task_type
stringclasses 4
values | code_task
stringclasses 15
values | start_line
int64 4
1.79k
| end_line
int64 4
1.8k
| before
stringlengths 79
76.1k
| between
stringlengths 17
806
| after
stringlengths 2
72.6k
| reason_categories_output
stringlengths 2
2.24k
| horizon_categories_output
stringlengths 83
3.99k
⌀ | reason_freq_analysis
stringclasses 150
values | horizon_freq_analysis
stringlengths 23
185
⌀ |
---|---|---|---|---|---|---|---|---|---|---|
infilling_java | RNGTester | 174 | 176 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {'] | [' super(mySeed);', ' params = myParams;', ' }'] | [' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Variable 'mySeed' used at line 174 is defined at line 173 and has a Short-Range dependency.
Variable 'myParams' used at line 175 is defined at line 173 and has a Short-Range dependency.
Global_Variable 'params' used at line 175 is defined at line 171 and has a Short-Range dependency. | {} | {'Variable Short-Range': 2, 'Global_Variable Short-Range': 1} |
infilling_java | RNGTester | 179 | 181 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {'] | [' super(prng);', ' params = myParams;', ' }'] | ['', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Variable 'prng' used at line 179 is defined at line 178 and has a Short-Range dependency.
Variable 'myParams' used at line 180 is defined at line 178 and has a Short-Range dependency.
Global_Variable 'params' used at line 180 is defined at line 171 and has a Short-Range dependency. | {} | {'Variable Short-Range': 2, 'Global_Variable Short-Range': 1} |
infilling_java | RNGTester | 191 | 192 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {'] | [' myArray[i] = genUniform (0, 1.0); ', ' }'] | [' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 191}, {'reason_category': 'Loop Body', 'usage_line': 192}] | Function 'genUniform' used at line 191 is defined at line 531 and has a Long-Range dependency.
Variable 'myArray' used at line 191 is defined at line 189 and has a Short-Range dependency.
Variable 'i' used at line 191 is defined at line 190 and has a Short-Range dependency. | {'Loop Body': 2} | {'Function Long-Range': 1, 'Variable Short-Range': 2} |
infilling_java | RNGTester | 206 | 208 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {'] | [' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }'] | [' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 206}, {'reason_category': 'Loop Body', 'usage_line': 207}, {'reason_category': 'Loop Body', 'usage_line': 208}] | Variable 'curPosInProbs' used at line 206 is defined at line 202 and has a Short-Range dependency.
Global_Variable 'params' used at line 207 is defined at line 171 and has a Long-Range dependency.
Function 'getItem' used at line 207 is defined at line 47 and has a Long-Range dependency.
Variable 'curPosInProbs' used at line 207 is defined at line 202 and has a Short-Range dependency.
Variable 'totProbSoFar' used at line 207 is defined at line 203 and has a Short-Range dependency. | {'Loop Body': 3} | {'Variable Short-Range': 3, 'Global_Variable Long-Range': 1, 'Function Long-Range': 1} |
infilling_java | RNGTester | 205 | 210 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {'] | [' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }'] | [' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 205}, {'reason_category': 'Loop Body', 'usage_line': 205}, {'reason_category': 'Loop Body', 'usage_line': 206}, {'reason_category': 'Loop Body', 'usage_line': 207}, {'reason_category': 'Loop Body', 'usage_line': 208}, {'reason_category': 'Loop Body', 'usage_line': 209}, {'reason_category': 'Loop Body', 'usage_line': 210}] | Variable 'myArray' used at line 205 is defined at line 189 and has a Medium-Range dependency.
Variable 'i' used at line 205 is defined at line 204 and has a Short-Range dependency.
Variable 'totProbSoFar' used at line 205 is defined at line 203 and has a Short-Range dependency.
Variable 'curPosInProbs' used at line 206 is defined at line 202 and has a Short-Range dependency.
Global_Variable 'params' used at line 207 is defined at line 171 and has a Long-Range dependency.
Function 'getItem' used at line 207 is defined at line 47 and has a Long-Range dependency.
Variable 'curPosInProbs' used at line 207 is defined at line 202 and has a Short-Range dependency.
Variable 'totProbSoFar' used at line 207 is defined at line 203 and has a Short-Range dependency.
Variable 'returnVal' used at line 209 is defined at line 198 and has a Medium-Range dependency.
Variable 'curPosInProbs' used at line 209 is defined at line 202 and has a Short-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 6} | {'Variable Medium-Range': 2, 'Variable Short-Range': 6, 'Global_Variable Long-Range': 1, 'Function Long-Range': 1} |
infilling_java | RNGTester | 229 | 231 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {'] | [' numTrials = numTrialsIn;', ' probs = probsIn;', ' }'] | [' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Variable 'numTrialsIn' used at line 229 is defined at line 228 and has a Short-Range dependency.
Global_Variable 'numTrials' used at line 229 is defined at line 225 and has a Short-Range dependency.
Variable 'probsIn' used at line 230 is defined at line 228 and has a Short-Range dependency.
Global_Variable 'probs' used at line 230 is defined at line 226 and has a Short-Range dependency. | {} | {'Variable Short-Range': 2, 'Global_Variable Short-Range': 2} |
infilling_java | RNGTester | 234 | 235 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {'] | [' return numTrials;', ' }'] | [' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Global_Variable 'numTrials' used at line 234 is defined at line 225 and has a Short-Range dependency. | {} | {'Global_Variable Short-Range': 1} |
infilling_java | RNGTester | 238 | 239 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {'] | [' return probs;', ' }'] | ['}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Global_Variable 'probs' used at line 238 is defined at line 226 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 1} |
infilling_java | RNGTester | 252 | 256 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {'] | [' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }'] | [' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Variable 'shapeIn' used at line 252 is defined at line 251 and has a Short-Range dependency.
Global_Variable 'shape' used at line 252 is defined at line 248 and has a Short-Range dependency.
Variable 'scaleIn' used at line 253 is defined at line 251 and has a Short-Range dependency.
Global_Variable 'scale' used at line 253 is defined at line 248 and has a Short-Range dependency.
Variable 'leftmostStepIn' used at line 254 is defined at line 251 and has a Short-Range dependency.
Global_Variable 'leftmostStep' used at line 254 is defined at line 248 and has a Short-Range dependency.
Variable 'numStepsIn' used at line 255 is defined at line 251 and has a Short-Range dependency.
Global_Variable 'numSteps' used at line 255 is defined at line 249 and has a Short-Range dependency. | {} | {'Variable Short-Range': 4, 'Global_Variable Short-Range': 4} |
infilling_java | RNGTester | 259 | 260 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {'] | [' return shape;', ' }'] | [' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Global_Variable 'shape' used at line 259 is defined at line 248 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 1} |
infilling_java | RNGTester | 263 | 264 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {'] | [' return scale;', ' }'] | [' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Global_Variable 'scale' used at line 263 is defined at line 248 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 1} |
infilling_java | RNGTester | 267 | 268 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {'] | [' return leftmostStep;', ' }'] | [' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Global_Variable 'leftmostStep' used at line 267 is defined at line 248 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 1} |
infilling_java | RNGTester | 271 | 272 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {'] | [' return numSteps;', ' }'] | ['}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Global_Variable 'numSteps' used at line 271 is defined at line 249 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 1} |
infilling_java | RNGTester | 288 | 291 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {'] | [' super (prng);', ' params = myParams;', ' setup ();', ' }'] | [' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Variable 'prng' used at line 288 is defined at line 287 and has a Short-Range dependency.
Variable 'myParams' used at line 289 is defined at line 287 and has a Short-Range dependency.
Global_Variable 'params' used at line 289 is defined at line 281 and has a Short-Range dependency.
Function 'setup' used at line 290 is defined at line 299 and has a Short-Range dependency. | {} | {'Variable Short-Range': 2, 'Global_Variable Short-Range': 1, 'Function Short-Range': 1} |
infilling_java | RNGTester | 294 | 297 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {'] | [' super (mySeed);', ' params = myParams;', ' setup ();', ' }'] | [' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Variable 'mySeed' used at line 294 is defined at line 293 and has a Short-Range dependency.
Variable 'myParams' used at line 295 is defined at line 293 and has a Short-Range dependency.
Global_Variable 'params' used at line 295 is defined at line 281 and has a Medium-Range dependency.
Function 'setup' used at line 296 is defined at line 299 and has a Short-Range dependency. | {} | {'Variable Short-Range': 2, 'Global_Variable Medium-Range': 1, 'Function Short-Range': 1} |
infilling_java | RNGTester | 303 | 306 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {'] | [' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }'] | [' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [{'reason_category': 'If Body', 'usage_line': 303}, {'reason_category': 'If Body', 'usage_line': 304}, {'reason_category': 'If Body', 'usage_line': 305}, {'reason_category': 'If Body', 'usage_line': 306}] | Class 'UnitGamma' used at line 303 is defined at line 588 and has a Long-Range dependency.
Function 'getPRNG' used at line 303 is defined at line 508 and has a Long-Range dependency.
Class 'GammaParam' used at line 303 is defined at line 246 and has a Long-Range dependency.
Global_Variable 'gammaShapeOne' used at line 303 is defined at line 284 and has a Medium-Range dependency.
Global_Variable 'params' used at line 304 is defined at line 281 and has a Medium-Range dependency.
Global_Variable 'params' used at line 305 is defined at line 281 and has a Medium-Range dependency. | {'If Body': 4} | {'Class Long-Range': 2, 'Function Long-Range': 1, 'Global_Variable Medium-Range': 3} |
infilling_java | RNGTester | 309 | 312 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {'] | [' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }'] | [' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [{'reason_category': 'If Body', 'usage_line': 309}, {'reason_category': 'If Body', 'usage_line': 310}, {'reason_category': 'If Body', 'usage_line': 311}, {'reason_category': 'If Body', 'usage_line': 312}] | Class 'UnitGamma' used at line 309 is defined at line 588 and has a Long-Range dependency.
Function 'getPRNG' used at line 309 is defined at line 508 and has a Long-Range dependency.
Class 'GammaParam' used at line 309 is defined at line 246 and has a Long-Range dependency.
Variable 'leftover' used at line 309 is defined at line 307 and has a Short-Range dependency.
Global_Variable 'gammaShapeLessThanOne' used at line 309 is defined at line 285 and has a Medium-Range dependency.
Global_Variable 'params' used at line 310 is defined at line 281 and has a Medium-Range dependency.
Global_Variable 'params' used at line 311 is defined at line 281 and has a Medium-Range dependency. | {'If Body': 4} | {'Class Long-Range': 2, 'Function Long-Range': 1, 'Variable Short-Range': 1, 'Global_Variable Medium-Range': 3} |
infilling_java | RNGTester | 321 | 322 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {'] | [' value += gammaShapeOne.getNext();', ' }'] | [' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 321}, {'reason_category': 'Loop Body', 'usage_line': 322}] | Global_Variable 'gammaShapeOne' used at line 321 is defined at line 284 and has a Long-Range dependency.
Variable 'value' used at line 321 is defined at line 319 and has a Short-Range dependency. | {'Loop Body': 2} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 1} |
infilling_java | RNGTester | 324 | 324 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)'] | [' value += gammaShapeLessThanOne.getNext ();'] | [' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [{'reason_category': 'If Body', 'usage_line': 324}] | Global_Variable 'gammaShapeLessThanOne' used at line 324 is defined at line 285 and has a Long-Range dependency.
Variable 'value' used at line 324 is defined at line 319 and has a Short-Range dependency. | {'If Body': 1} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 1} |
infilling_java | RNGTester | 341 | 344 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {'] | [' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }'] | [' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Variable 'shapesIn' used at line 341 is defined at line 340 and has a Short-Range dependency.
Global_Variable 'shapes' used at line 341 is defined at line 336 and has a Short-Range dependency.
Variable 'leftmostStepIn' used at line 342 is defined at line 340 and has a Short-Range dependency.
Global_Variable 'leftmostStep' used at line 342 is defined at line 337 and has a Short-Range dependency.
Variable 'numStepsIn' used at line 343 is defined at line 340 and has a Short-Range dependency.
Global_Variable 'numSteps' used at line 343 is defined at line 338 and has a Short-Range dependency. | {} | {'Variable Short-Range': 3, 'Global_Variable Short-Range': 3} |
infilling_java | RNGTester | 347 | 348 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {'] | [' return shapes;', ' }'] | [' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Global_Variable 'shapes' used at line 347 is defined at line 336 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 1} |
infilling_java | RNGTester | 351 | 352 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {'] | [' return leftmostStep;', ' }'] | [' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Global_Variable 'leftmostStep' used at line 351 is defined at line 337 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 1} |
infilling_java | RNGTester | 355 | 356 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {'] | [' return numSteps;', ' }'] | ['}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Global_Variable 'numSteps' used at line 355 is defined at line 338 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 1} |
infilling_java | RNGTester | 368 | 371 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {'] | [' super (mySeed);', ' params = myParams;', ' setup ();', ' }'] | [' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Variable 'mySeed' used at line 368 is defined at line 367 and has a Short-Range dependency.
Variable 'myParams' used at line 369 is defined at line 367 and has a Short-Range dependency.
Global_Variable 'params' used at line 369 is defined at line 365 and has a Short-Range dependency.
Function 'setup' used at line 370 is defined at line 299 and has a Long-Range dependency. | {} | {'Variable Short-Range': 2, 'Global_Variable Short-Range': 1, 'Function Long-Range': 1} |
infilling_java | RNGTester | 374 | 377 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {'] | [' super (prng);', ' params = myParams;', ' setup ();', ' }'] | [' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Variable 'prng' used at line 374 is defined at line 373 and has a Short-Range dependency.
Variable 'myParams' used at line 375 is defined at line 373 and has a Short-Range dependency.
Global_Variable 'params' used at line 375 is defined at line 365 and has a Short-Range dependency.
Function 'setup' used at line 376 is defined at line 299 and has a Long-Range dependency. | {} | {'Variable Short-Range': 2, 'Global_Variable Short-Range': 1, 'Function Long-Range': 1} |
infilling_java | RNGTester | 391 | 395 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {'] | [' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }'] | [' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 391}, {'reason_category': 'Loop Body', 'usage_line': 392}, {'reason_category': 'Loop Body', 'usage_line': 393}, {'reason_category': 'Loop Body', 'usage_line': 394}, {'reason_category': 'Loop Body', 'usage_line': 395}] | Variable 'shapes' used at line 391 is defined at line 386 and has a Short-Range dependency.
Variable 'i' used at line 391 is defined at line 387 and has a Short-Range dependency.
Global_Variable 'gammas' used at line 392 is defined at line 382 and has a Short-Range dependency.
Class 'Gamma' used at line 392 is defined at line 276 and has a Long-Range dependency.
Function 'getPRNG' used at line 392 is defined at line 508 and has a Long-Range dependency.
Class 'GammaParam' used at line 392 is defined at line 246 and has a Long-Range dependency.
Variable 'd' used at line 392 is defined at line 391 and has a Short-Range dependency.
Global_Variable 'params' used at line 393 is defined at line 365 and has a Medium-Range dependency.
Global_Variable 'params' used at line 394 is defined at line 365 and has a Medium-Range dependency. | {'Loop Body': 5} | {'Variable Short-Range': 3, 'Global_Variable Short-Range': 1, 'Class Long-Range': 2, 'Function Long-Range': 1, 'Global_Variable Medium-Range': 2} |
infilling_java | RNGTester | 415 | 416 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {'] | [' v.setItem(i++, g.getNext());', ' }'] | [' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 415}, {'reason_category': 'Loop Body', 'usage_line': 416}] | Variable 'v' used at line 415 is defined at line 409 and has a Short-Range dependency.
Variable 'i' used at line 415 is defined at line 411 and has a Short-Range dependency.
Variable 'g' used at line 415 is defined at line 414 and has a Short-Range dependency. | {'Loop Body': 2} | {'Variable Short-Range': 3} |
infilling_java | RNGTester | 449 | 451 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {'] | [' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }'] | [' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Variable 'mySeed' used at line 449 is defined at line 448 and has a Short-Range dependency.
Global_Variable 'seedValue' used at line 449 is defined at line 438 and has a Medium-Range dependency.
Library 'BigInteger' used at line 450 is defined at line 2 and has a Long-Range dependency.
Global_Variable 'seedValue' used at line 450 is defined at line 449 and has a Short-Range dependency.
Global_Variable 'X' used at line 450 is defined at line 442 and has a Short-Range dependency. | {} | {'Variable Short-Range': 1, 'Global_Variable Medium-Range': 1, 'Library Long-Range': 1, 'Global_Variable Short-Range': 2} |
infilling_java | RNGTester | 457 | 459 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {'] | [' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }'] | [' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Global_Variable 'X' used at line 457 is defined at line 442 and has a Medium-Range dependency.
Global_Variable 'a' used at line 457 is defined at line 439 and has a Medium-Range dependency.
Global_Variable 'c' used at line 457 is defined at line 440 and has a Medium-Range dependency.
Global_Variable 'm' used at line 457 is defined at line 441 and has a Medium-Range dependency.
Global_Variable 'X' used at line 458 is defined at line 457 and has a Short-Range dependency.
Global_Variable 'max' used at line 458 is defined at line 443 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 5, 'Global_Variable Short-Range': 1} |
infilling_java | RNGTester | 465 | 466 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {'] | [' X = new BigInteger (seedValue + "");', ' }'] | ['}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Library 'BigInteger' used at line 465 is defined at line 2 and has a Long-Range dependency.
Global_Variable 'seedValue' used at line 465 is defined at line 438 and has a Medium-Range dependency.
Global_Variable 'X' used at line 465 is defined at line 442 and has a Medium-Range dependency. | {} | {'Library Long-Range': 1, 'Global_Variable Medium-Range': 2} |
infilling_java | RNGTester | 472 | 476 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {'] | [' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }'] | ['}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 473}, {'reason_category': 'Loop Body', 'usage_line': 474}, {'reason_category': 'Loop Body', 'usage_line': 475}] | Class 'ChrisPRNG' used at line 472 is defined at line 433 and has a Long-Range dependency.
Variable 'i' used at line 473 is defined at line 473 and has a Short-Range dependency.
Function 'ChrisPRNG.next' used at line 474 is defined at line 456 and has a Medium-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 2} | {'Class Long-Range': 1, 'Variable Short-Range': 1, 'Function Medium-Range': 1} |
infilling_java | RNGTester | 474 | 475 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {'] | [' System.out.println (foo.next ());', ' }'] | [' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 474}, {'reason_category': 'Loop Body', 'usage_line': 475}] | Function 'ChrisPRNG.next' used at line 474 is defined at line 456 and has a Medium-Range dependency. | {'Loop Body': 2} | {'Function Medium-Range': 1} |
infilling_java | RNGTester | 500 | 501 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {'] | [' prng = new ChrisPRNG(mySeed); ', ' }'] | [' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Class 'ChrisPRNG' used at line 500 is defined at line 433 and has a Long-Range dependency.
Variable 'mySeed' used at line 500 is defined at line 499 and has a Short-Range dependency.
Global_Variable 'prng' used at line 500 is defined at line 496 and has a Short-Range dependency. | {} | {'Class Long-Range': 1, 'Variable Short-Range': 1, 'Global_Variable Short-Range': 1} |
infilling_java | RNGTester | 505 | 506 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {'] | [' prng = useMe;', ' }'] | ['', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Variable 'useMe' used at line 505 is defined at line 504 and has a Short-Range dependency.
Global_Variable 'prng' used at line 505 is defined at line 496 and has a Short-Range dependency. | {} | {'Variable Short-Range': 1, 'Global_Variable Short-Range': 1} |
infilling_java | RNGTester | 509 | 510 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {'] | [' return prng;', ' }'] | [' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Global_Variable 'prng' used at line 509 is defined at line 496 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 1} |
infilling_java | RNGTester | 525 | 526 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {'] | [' prng.startOver();', ' }'] | ['', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Global_Variable 'prng' used at line 525 is defined at line 496 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 1} |
infilling_java | RNGTester | 532 | 536 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {'] | [' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }'] | ['', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Global_Variable 'prng' used at line 532 is defined at line 496 and has a Long-Range dependency.
Variable 'high' used at line 533 is defined at line 531 and has a Short-Range dependency.
Variable 'low' used at line 533 is defined at line 531 and has a Short-Range dependency.
Variable 'r' used at line 533 is defined at line 532 and has a Short-Range dependency.
Variable 'low' used at line 534 is defined at line 531 and has a Short-Range dependency.
Variable 'r' used at line 534 is defined at line 533 and has a Short-Range dependency.
Variable 'r' used at line 535 is defined at line 534 and has a Short-Range dependency. | {} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 6} |
infilling_java | RNGTester | 562 | 563 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {'] | [' return genUniform(params.getLow(), params.getHigh());', ' }'] | [' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Function 'genUniform' used at line 562 is defined at line 531 and has a Long-Range dependency.
Global_Variable 'params' used at line 562 is defined at line 546 and has a Medium-Range dependency. | {} | {'Function Long-Range': 1, 'Global_Variable Medium-Range': 1} |
infilling_java | RNGTester | 572 | 586 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' '] | [' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}'] | ['', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Variable 'lowIn' used at line 575 is defined at line 574 and has a Short-Range dependency.
Global_Variable 'low' used at line 575 is defined at line 572 and has a Short-Range dependency.
Variable 'highIn' used at line 576 is defined at line 574 and has a Short-Range dependency.
Global_Variable 'high' used at line 576 is defined at line 572 and has a Short-Range dependency.
Global_Variable 'low' used at line 580 is defined at line 572 and has a Short-Range dependency.
Global_Variable 'high' used at line 584 is defined at line 572 and has a Medium-Range dependency. | {} | {'Variable Short-Range': 2, 'Global_Variable Short-Range': 3, 'Global_Variable Medium-Range': 1} |
infilling_java | RNGTester | 575 | 577 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {'] | [' low = lowIn;', ' high = highIn;', ' }'] | [' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Variable 'lowIn' used at line 575 is defined at line 574 and has a Short-Range dependency.
Global_Variable 'low' used at line 575 is defined at line 572 and has a Short-Range dependency.
Variable 'highIn' used at line 576 is defined at line 574 and has a Short-Range dependency.
Global_Variable 'high' used at line 576 is defined at line 572 and has a Short-Range dependency. | {} | {'Variable Short-Range': 2, 'Global_Variable Short-Range': 2} |
infilling_java | RNGTester | 580 | 581 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {'] | [' return low;', ' }'] | [' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Global_Variable 'low' used at line 580 is defined at line 572 and has a Short-Range dependency. | {} | {'Global_Variable Short-Range': 1} |
infilling_java | RNGTester | 584 | 585 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {'] | [' return high;', ' }'] | ['}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Global_Variable 'high' used at line 584 is defined at line 572 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 1} |
infilling_java | RNGTester | 602 | 605 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { '] | [' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }'] | ['', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Class 'UniformParam' used at line 602 is defined at line 570 and has a Long-Range dependency.
Variable 'xmin' used at line 602 is defined at line 600 and has a Short-Range dependency.
Variable 'xmax' used at line 602 is defined at line 600 and has a Short-Range dependency.
Global_Variable 'xRegion' used at line 602 is defined at line 596 and has a Short-Range dependency.
Class 'UniformParam' used at line 603 is defined at line 570 and has a Long-Range dependency.
Variable 'ymin' used at line 603 is defined at line 601 and has a Short-Range dependency.
Variable 'ymax' used at line 603 is defined at line 601 and has a Short-Range dependency.
Global_Variable 'yRegion' used at line 603 is defined at line 597 and has a Short-Range dependency.
Variable 'xmax' used at line 604 is defined at line 600 and has a Short-Range dependency.
Variable 'xmin' used at line 604 is defined at line 600 and has a Short-Range dependency.
Variable 'ymax' used at line 604 is defined at line 601 and has a Short-Range dependency.
Variable 'ymin' used at line 604 is defined at line 601 and has a Short-Range dependency.
Global_Variable 'area' used at line 604 is defined at line 598 and has a Short-Range dependency. | {} | {'Class Long-Range': 2, 'Variable Short-Range': 8, 'Global_Variable Short-Range': 3} |
infilling_java | RNGTester | 612 | 612 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {'] | [' return x;'] | [' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [{'reason_category': 'If Body', 'usage_line': 612}] | Variable 'x' used at line 612 is defined at line 608 and has a Short-Range dependency. | {'If Body': 1} | {'Variable Short-Range': 1} |
infilling_java | RNGTester | 614 | 615 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {'] | [' return null;', ' }'] | [' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [{'reason_category': 'Else Reasoning', 'usage_line': 614}] | null | {'Else Reasoning': 1} | null |
infilling_java | RNGTester | 633 | 635 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {'] | [' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }'] | ['', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Global_Variable 'params' used at line 633 is defined at line 593 and has a Long-Range dependency.
Variable 'x' used at line 634 is defined at line 632 and has a Short-Range dependency.
Variable 'k' used at line 634 is defined at line 633 and has a Short-Range dependency. | {} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 2} |
infilling_java | RNGTester | 657 | 660 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {'] | [' super(prng);', ' params = myParams;', ' setup ();', ' } '] | [' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [] | Variable 'prng' used at line 657 is defined at line 656 and has a Short-Range dependency.
Variable 'myParams' used at line 658 is defined at line 656 and has a Short-Range dependency.
Global_Variable 'params' used at line 658 is defined at line 593 and has a Long-Range dependency.
Function 'setup' used at line 659 is defined at line 637 and has a Medium-Range dependency. | {} | {'Variable Short-Range': 2, 'Global_Variable Long-Range': 1, 'Function Medium-Range': 1} |
infilling_java | RNGTester | 676 | 685 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {'] | [' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }', ' }'] | [' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 676}, {'reason_category': 'If Condition', 'usage_line': 677}, {'reason_category': 'Loop Body', 'usage_line': 677}, {'reason_category': 'Loop Body', 'usage_line': 678}, {'reason_category': 'If Body', 'usage_line': 678}, {'reason_category': 'Loop Body', 'usage_line': 679}, {'reason_category': 'If Body', 'usage_line': 679}, {'reason_category': 'If Condition', 'usage_line': 680}, {'reason_category': 'Loop Body', 'usage_line': 680}, {'reason_category': 'If Body', 'usage_line': 680}, {'reason_category': 'If Body', 'usage_line': 681}, {'reason_category': 'Loop Body', 'usage_line': 681}, {'reason_category': 'If Body', 'usage_line': 682}, {'reason_category': 'Loop Body', 'usage_line': 682}, {'reason_category': 'If Body', 'usage_line': 683}, {'reason_category': 'Loop Body', 'usage_line': 683}, {'reason_category': 'Loop Body', 'usage_line': 684}, {'reason_category': 'Loop Body', 'usage_line': 685}] | Variable 's' used at line 676 is defined at line 675 and has a Short-Range dependency.
Variable 'area' used at line 676 is defined at line 674 and has a Short-Range dependency.
Variable 'area' used at line 677 is defined at line 676 and has a Short-Range dependency.
Variable 'step' used at line 677 is defined at line 673 and has a Short-Range dependency.
Variable 's' used at line 679 is defined at line 675 and has a Short-Range dependency.
Variable 'x' used at line 680 is defined at line 679 and has a Short-Range dependency.
Variable 'x' used at line 681 is defined at line 679 and has a Short-Range dependency. | {'Loop Body': 10, 'If Condition': 2, 'If Body': 6} | {'Variable Short-Range': 7} |
infilling_java | RNGTester | 679 | 684 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler'] | [' Double x = s.tryNext();', ' if (x != null) {', ' return x;', ' }', ' break;', ' }'] | [' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 679}, {'reason_category': 'If Body', 'usage_line': 679}, {'reason_category': 'If Condition', 'usage_line': 680}, {'reason_category': 'Loop Body', 'usage_line': 680}, {'reason_category': 'If Body', 'usage_line': 680}, {'reason_category': 'If Body', 'usage_line': 681}, {'reason_category': 'Loop Body', 'usage_line': 681}, {'reason_category': 'If Body', 'usage_line': 682}, {'reason_category': 'Loop Body', 'usage_line': 682}, {'reason_category': 'If Body', 'usage_line': 683}, {'reason_category': 'Loop Body', 'usage_line': 683}, {'reason_category': 'Loop Body', 'usage_line': 684}] | Variable 's' used at line 679 is defined at line 675 and has a Short-Range dependency.
Variable 'x' used at line 680 is defined at line 679 and has a Short-Range dependency.
Variable 'x' used at line 681 is defined at line 679 and has a Short-Range dependency. | {'Loop Body': 6, 'If Body': 5, 'If Condition': 1} | {'Variable Short-Range': 3} |
infilling_java | RNGTester | 681 | 681 | ['import junit.framework.TestCase;', 'import java.math.BigInteger;', 'import java.util.ArrayList;', 'import java.util.Arrays;', 'import java.util.Random;', 'import java.util.ArrayList;', '', '/**', ' * Interface to a pseudo random number generator that generates', ' * numbers between 0.0 and 1.0 and can start over to regenerate', ' * exactly the same sequence of values.', ' */', '', 'interface IPRNG {', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' double next();', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' void startOver();', '}', '', '/**', ' * This is the interface for a vector of double-precision floating point values.', ' */', 'interface IDoubleVector {', ' ', ' /** ', ' * Adds another double vector to the contents of this one. ', ' * Will throw OutOfBoundsException if the two vectors', " * don't have exactly the same sizes.", ' * ', ' * @param addThisOne the double vector to add in', ' */', ' public void addMyselfToHim (IDoubleVector addToHim) throws OutOfBoundsException;', ' ', ' /**', ' * Returns a particular item in the double vector. Will throw OutOfBoundsException if the index passed', ' * in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public double getItem (int whichOne) throws OutOfBoundsException;', '', ' /** ', ' * Add a value to all elements of the vector.', ' *', ' * @param addMe the value to be added to all elements', ' */', ' public void addToAll (double addMe);', ' ', ' /** ', ' * Returns a particular item in the double vector, rounded to the nearest integer. Will throw ', ' * OutOfBoundsException if the index passed in is beyond the end of the vector.', ' * ', ' * @param whichOne the index of the item to return', ' * @return the value at the specified index', ' */', ' public long getRoundedItem (int whichOne) throws OutOfBoundsException;', ' ', ' /**', ' * This forces the sum of all of the items in the vector to be one, by dividing each item by the', ' * total over all items.', ' */', ' public void normalize ();', ' ', ' /**', ' * Sets a particular item in the vector. ', ' * Will throw OutOfBoundsException if we are trying to set an item', ' * that is past the end of the vector.', ' * ', ' * @param whichOne the index of the item to set', ' * @param setToMe the value to set the item to', ' */', ' public void setItem (int whichOne, double setToMe) throws OutOfBoundsException;', '', ' /**', ' * Returns the length of the vector.', ' * ', ' * @return the vector length', ' */', ' public int getLength ();', ' ', ' /**', ' * Returns the L1 norm of the vector (this is just the sum of the absolute value of all of the entries)', ' * ', ' * @return the L1 norm', ' */', ' public double l1Norm ();', ' ', ' /**', ' * Constructs and returns a new "pretty" String representation of the vector.', ' * ', ' * @return the string representation', ' */', ' public String toString ();', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates outputs an object of type OutputType.', ' * Every concrete class that implements this interface should have a public ', ' * constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'interface IRandomGenerationAlgorithm <OutputType> {', ' ', ' /**', ' * Generate another random object', ' */', ' OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' void startOver ();', ' ', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class PRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private Random rng;', '', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public PRNG(long mySeed) {', ' seedValue = mySeed;', ' rng = new Random(seedValue);', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' return rng.nextDouble();', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' rng.setSeed(seedValue);', ' }', '}', '', '', 'class Multinomial extends ARandomGenerationAlgorithm <IDoubleVector> {', ' ', ' /**', ' * Parameters', ' */', ' private MultinomialParam params;', '', ' public Multinomial (long mySeed, MultinomialParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Multinomial (IPRNG prng, MultinomialParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' ', " // get an array of doubles; we'll put one random number in each slot", ' Double [] myArray = new Double[params.getNumTrials ()];', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' myArray[i] = genUniform (0, 1.0); ', ' }', ' ', ' // now sort them', ' Arrays.sort (myArray);', ' ', ' // get the output result', ' SparseDoubleVector returnVal = new SparseDoubleVector (params.getProbs ().getLength (), 0.0);', ' ', ' try {', ' // now loop through the probs and the observed doubles, and do a merge', ' int curPosInProbs = -1;', ' double totProbSoFar = 0.0;', ' for (int i = 0; i < params.getNumTrials (); i++) {', ' while (myArray[i] > totProbSoFar) {', ' curPosInProbs++;', ' totProbSoFar += params.getProbs ().getItem (curPosInProbs);', ' }', ' returnVal.setItem (curPosInProbs, returnVal.getItem (curPosInProbs) + 1.0);', ' }', ' return returnVal;', ' } catch (OutOfBoundsException e) {', ' System.err.println ("Somehow, within the multinomial sampler, I went out of bounds as I was contructing the output array");', ' return null;', ' }', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the multinomial distribution', ' */', 'class MultinomialParam {', ' ', ' int numTrials;', ' IDoubleVector probs;', ' ', ' public MultinomialParam (int numTrialsIn, IDoubleVector probsIn) {', ' numTrials = numTrialsIn;', ' probs = probsIn;', ' }', ' ', ' public int getNumTrials () {', ' return numTrials;', ' }', ' ', ' public IDoubleVector getProbs () {', ' return probs;', ' }', '}', '', '', '/*', ' * This holds a parameterization for the gamma distribution', ' */', 'class GammaParam {', ' ', ' private double shape, scale, leftmostStep;', ' private int numSteps;', ' ', ' public GammaParam (double shapeIn, double scaleIn, double leftmostStepIn, int numStepsIn) {', ' shape = shapeIn;', ' scale = scaleIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn; ', ' }', ' ', ' public double getShape () {', ' return shape;', ' }', ' ', ' public double getScale () {', ' return scale;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Gamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' long numShapeOnesToUse;', ' private UnitGamma gammaShapeOne;', ' private UnitGamma gammaShapeLessThanOne;', '', ' public Gamma(IPRNG prng, GammaParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Gamma(long mySeed, GammaParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' private void setup () {', ' ', ' numShapeOnesToUse = (long) Math.floor(params.getShape());', ' if (numShapeOnesToUse >= 1) {', ' gammaShapeOne = new UnitGamma(getPRNG(), new GammaParam(1.0, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' double leftover = params.getShape() - (double) numShapeOnesToUse;', ' if (leftover > 0.0) {', ' gammaShapeLessThanOne = new UnitGamma(getPRNG(), new GammaParam(leftover, 1.0,', ' params.getLeftmostStep(), ', ' params.getNumSteps()));', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' Double value = 0.0;', ' for (int i = 0; i < numShapeOnesToUse; i++) {', ' value += gammaShapeOne.getNext();', ' }', ' if (gammaShapeLessThanOne != null)', ' value += gammaShapeLessThanOne.getNext ();', ' ', ' return value * params.getScale ();', ' }', '', '}', '', '/*', ' * This holds a parameterization for the Dirichlet distribution', ' */', 'class DirichletParam {', ' ', ' private IDoubleVector shapes;', ' private double leftmostStep;', ' private int numSteps;', ' ', ' public DirichletParam (IDoubleVector shapesIn, double leftmostStepIn, int numStepsIn) {', ' shapes = shapesIn;', ' leftmostStep = leftmostStepIn;', ' numSteps = numStepsIn;', ' }', ' ', ' public IDoubleVector getShapes () {', ' return shapes;', ' }', ' ', ' public double getLeftmostStep () {', ' return leftmostStep;', ' }', ' ', ' public int getNumSteps () {', ' return numSteps;', ' }', '}', '', '', 'class Dirichlet extends ARandomGenerationAlgorithm <IDoubleVector> {', '', ' /**', ' * Parameters', ' */', ' private DirichletParam params;', '', ' public Dirichlet (long mySeed, DirichletParam myParams) {', ' super (mySeed);', ' params = myParams;', ' setup ();', ' }', ' ', ' public Dirichlet (IPRNG prng, DirichletParam myParams) {', ' super (prng);', ' params = myParams;', ' setup ();', ' }', ' ', ' /**', ' * List of gammas that compose the Dirichlet', ' */', ' private ArrayList<Gamma> gammas = new ArrayList<Gamma>();', '', ' public void setup () {', '', ' IDoubleVector shapes = params.getShapes();', ' int i = 0;', '', ' try {', ' for (; i<shapes.getLength(); i++) {', ' Double d = shapes.getItem(i);', ' gammas.add(new Gamma(getPRNG(), new GammaParam(d, 1.0, ', ' params.getLeftmostStep(),', ' params.getNumSteps())));', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet constructor Error: out of bounds access (%d) to shapes\\n", i);', ' params = null;', ' gammas = null;', ' return;', ' }', ' }', '', ' /**', ' * Generate another random object', ' */', ' public IDoubleVector getNext () {', ' int length = params.getShapes().getLength();', ' IDoubleVector v = new DenseDoubleVector(length, 0.0);', '', ' int i = 0;', '', ' try {', ' for (Gamma g : gammas) {', ' v.setItem(i++, g.getNext());', ' }', ' } catch (OutOfBoundsException e) {', ' System.err.format("Dirichlet getNext Error: out of bounds access (%d) to result vector\\n", i);', ' return null;', ' }', '', ' v.normalize();', '', ' return v;', ' }', '', '}', '', '/**', ' * Wrap the Java random number generator.', ' */', '', 'class ChrisPRNG implements IPRNG {', '', ' /**', ' * Java random number generator', ' */', ' private long seedValue;', ' private BigInteger a = new BigInteger ("6364136223846793005");', ' private BigInteger c = new BigInteger ("1442695040888963407");', ' private BigInteger m = new BigInteger ("2").pow (64);', ' private BigInteger X = new BigInteger ("0");', ' private double max = Math.pow (2.0, 32);', ' ', ' /**', ' * Build a new pseudo random number generator with the given seed.', ' */', ' public ChrisPRNG(long mySeed) {', ' seedValue = mySeed;', ' X = new BigInteger (seedValue + "");', ' }', ' ', ' /**', ' * Return the next double value between 0.0 and 1.0', ' */', ' public double next() {', ' X = X.multiply (a).add (c).mod (m);', ' return X.shiftRight (32).intValue () / max + 0.5;', ' }', ' ', ' /**', ' * Reset the PRNG to the original seed', ' */', ' public void startOver() {', ' X = new BigInteger (seedValue + "");', ' }', '}', '', 'class Main {', '', ' public static void main (String [] args) {', ' IPRNG foo = new ChrisPRNG (0);', ' for (int i = 0; i < 10; i++) {', ' System.out.println (foo.next ());', ' }', ' }', '}', '', '/** ', ' * Encapsulates the idea of a random object generation algorithm. The random', ' * variable that the algorithm simulates is parameterized using an object of', ' * type InputType. Every concrete class that implements this interface should', ' * have a constructor of the form:', ' * ', ' * ConcreteClass (Seed mySeed, ParamType myParams)', ' * ', ' */', 'abstract class ARandomGenerationAlgorithm <OutputType> implements IRandomGenerationAlgorithm <OutputType> {', '', ' /**', ' * There are two ways that this guy gets random numbers. Either he gets them from a "parent" (this is', ' * the ARandomGenerationAlgorithm object who created him) or he manufctures them himself if he has been', ' * created by someone other than another ARandomGenerationAlgorithm object.', ' */', ' ', ' private IPRNG prng;', ' ', ' // this constructor is called when we want an ARandomGenerationAlgorithm who uses his own rng', ' protected ARandomGenerationAlgorithm(long mySeed) {', ' prng = new ChrisPRNG(mySeed); ', ' }', ' ', ' // this one is called when we want a ARandomGenerationAlgorithm who uses someone elses rng', ' protected ARandomGenerationAlgorithm(IPRNG useMe) {', ' prng = useMe;', ' }', '', ' protected IPRNG getPRNG() {', ' return prng;', ' }', ' ', ' /**', ' * Generate another random object', ' */', ' abstract public OutputType getNext ();', ' ', ' /**', ' * Resets the sequence of random objects that are created. The net effect', ' * is that if we create the IRandomGenerationAlgorithm object, ', ' * then call getNext a bunch of times, and then call startOver (), then ', ' * call getNext a bunch of times, we will get exactly the same sequence ', ' * of random values the second time around.', ' */', ' public void startOver () {', ' prng.startOver();', ' }', '', ' /**', ' * Generate a random number uniformly between low and high', ' */', ' protected double genUniform(double low, double high) {', ' double r = prng.next();', ' r *= high - low;', ' r += low;', ' return r;', ' }', '', '}', '', '', 'class Uniform extends ARandomGenerationAlgorithm <Double> {', ' ', ' /**', ' * Parameters', ' */', ' private UniformParam params;', '', ' public Uniform(long mySeed, UniformParam myParams) {', ' super(mySeed);', ' params = myParams;', ' }', ' ', ' public Uniform(IPRNG prng, UniformParam myParams) {', ' super(prng);', ' params = myParams;', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' return genUniform(params.getLow(), params.getHigh());', ' }', ' ', '}', '', '/**', ' * This holds a parameterization for the uniform distribution', ' */', 'class UniformParam {', ' ', ' double low, high;', ' ', ' public UniformParam (double lowIn, double highIn) {', ' low = lowIn;', ' high = highIn;', ' }', ' ', ' public double getLow () {', ' return low;', ' }', ' ', ' public double getHigh () {', ' return high;', ' }', '}', '', 'class UnitGamma extends ARandomGenerationAlgorithm <Double> {', '', ' /**', ' * Parameters', ' */', ' private GammaParam params;', '', ' private class RejectionSampler {', ' private UniformParam xRegion;', ' private UniformParam yRegion;', ' private double area;', '', ' protected RejectionSampler(double xmin, double xmax, ', ' double ymin, double ymax) { ', ' xRegion = new UniformParam(xmin, xmax);', ' yRegion = new UniformParam(ymin, ymax);', ' area = (xmax - xmin) * (ymax - ymin);', ' }', '', ' protected Double tryNext() {', ' Double x = genUniform (xRegion.getLow (), xRegion.getHigh ());', ' Double y = genUniform (yRegion.getLow (), yRegion.getHigh ());', ' ', ' if (y <= fofx(x)) {', ' return x;', ' } else {', ' return null;', ' }', ' }', '', ' protected double getArea() {', ' return area;', ' }', ' }', ' ', ' /**', ' * Uniform generators', ' */', ' // Samplers for each step', ' private ArrayList<RejectionSampler> samplers = new ArrayList<RejectionSampler>();', '', ' // Total area of all envelopes', ' private double totalArea;', '', ' private double fofx(double x) {', ' double k = params.getShape();', ' return Math.pow(x, k-1) * Math.exp(-x);', ' }', '', ' private void setup () {', ' if (params.getShape() > 1.0 || params.getScale () > 1.0000000001 || params.getScale () < .999999999 ) {', ' System.err.println("UnitGamma must have shape <= 1.0 and a scale of one");', ' params = null;', ' samplers = null;', ' return;', ' }', '', ' totalArea = 0.0;', ' ', '', ' for (int i=0; i<params.getNumSteps(); i++) {', ' double left = params.getLeftmostStep() * Math.pow (2.0, i);', ' double fx = fofx(left);', ' samplers.add(new RejectionSampler(left, left*2.0, 0, fx));', ' totalArea += (left*2.0 - left) * fx;', ' }', ' }', ' ', ' public UnitGamma(IPRNG prng, GammaParam myParams) {', ' super(prng);', ' params = myParams;', ' setup ();', ' } ', ' ', ' public UnitGamma(long mySeed, GammaParam myParams) {', ' super(mySeed);', ' params = myParams;', ' setup ();', ' }', '', ' /**', ' * Generate another random object', ' */', ' public Double getNext () {', ' while (true) {', ' double step = genUniform(0.0, totalArea);', ' double area = 0.0;', ' for (RejectionSampler s : samplers) {', ' area += s.getArea();', ' if (area >= step) {', ' // Found the right sampler', ' Double x = s.tryNext();', ' if (x != null) {'] | [' return x;'] | [' }', ' break;', ' }', ' }', ' }', ' }', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class RNGTester extends TestCase {', ' ', ' ', ' // checks to see if two values are close enough', ' private void checkCloseEnough (double observed, double goal, double tolerance, String whatCheck, String dist) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * tolerance; ', ' if (allowedError < tolerance) ', ' allowedError = tolerance; ', ' ', ' // print the result', ' System.out.println ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist);', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' fail ("Got " + observed + ", expected " + goal + " when I was checking the " + whatCheck + " of the " + dist); ', ' } ', ' ', ' /**', ' * This routine checks whether the observed mean for a one-dim RNG is close enough to the expected mean.', ' * Note the weird "runTest" parameter. If this is set to true, the test for correctness is actually run.', ' * If it is set to false, the test is not run, and only the observed mean is returned to the caller.', ' * This is done so that we can "turn off" the correctness check, when we are only using this routine ', " * to compute an observed mean in order to check if the seeding is working. This way, we don't check", ' * too many things in one single test.', ' */', ' private double checkMean (IRandomGenerationAlgorithm<Double> myRNG, double expectedMean, boolean runTest, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' total += myRNG.getNext (); ', ' }', ' ', ' if (runTest)', ' checkCloseEnough (total / numTrials, expectedMean, 10e-3, "mean", dist);', ' ', ' return total / numTrials;', ' }', ' ', ' /**', ' * This checks whether the standard deviation for a one-dim RNG is close enough to the expected std dev.', ' */', ' private void checkStdDev (IRandomGenerationAlgorithm<Double> myRNG, double expectedVariance, String dist) {', ' ', ' int numTrials = 100000;', ' double total = 0.0;', ' double totalSquares = 0.0;', ' for (int i = 0; i < numTrials; i++) {', ' double next = myRNG.getNext ();', ' total += next;', ' totalSquares += next * next;', ' }', ' ', ' double observedVar = -(total / numTrials) * (total / numTrials) + totalSquares / numTrials;', ' ', ' checkCloseEnough (Math.sqrt(observedVar), Math.sqrt(expectedVariance), 10e-3, "standard deviation", dist);', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */', ' public void testUniformReset () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for uniform reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */', ' public void testUniformSeeding () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Uniform (745664, new UniformParam (low, high));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Uniform (2334, new UniformParam (low, high));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for uniform seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform1 () {', ' ', ' double low = 0.5;', ' double high = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUniform2 () {', '', ' double low = -123456.0;', ' double high = 233243.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Uniform (745664, new UniformParam (low, high));', ' checkMean (myRNG, low / 2.0 + high / 2.0, true, "Uniform (" + low + ", " + high + ")");', ' checkStdDev (myRNG, (high - low) * (high - low) / 12.0, "Uniform (" + low + ", " + high + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testUnitGammaReset () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for unit gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testUnitGammaSeeding () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new UnitGamma (232, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for unit gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma1 () {', ' ', ' double shape = 0.5;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (745664, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testUnitGamma2 () {', ' ', ' double shape = 0.05;', ' double scale = 1.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new UnitGamma (6755, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testGammaReset () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG, 0, false, "");', ' myRNG.startOver ();', ' double result2 = checkMean (myRNG, 0, false, "");', ' assertTrue ("Failed check for gamma reset capability", Math.abs (result1 - result2) < 10e-10);', ' }', ' ', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testGammaSeeding () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG1 = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' IRandomGenerationAlgorithm<Double> myRNG2 = new Gamma (297, new GammaParam (shape, scale, 10e-40, 150));', ' double result1 = checkMean (myRNG1, 0, false, "");', ' double result2 = checkMean (myRNG2, 0, false, "");', ' assertTrue ("Failed check for gamma seeding correctness", Math.abs (result1 - result2) > 10e-10);', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma1 () {', ' ', ' double shape = 5.88;', ' double scale = 34.0;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testGamma2 () {', ' ', ' double shape = 15.09;', ' double scale = 3.53;', ' IRandomGenerationAlgorithm<Double> myRNG = new Gamma (27, new GammaParam (shape, scale, 10e-40, 150));', ' checkMean (myRNG, shape * scale, true, "Gamma (" + shape + ", " + scale + ")");', ' checkStdDev (myRNG, shape * scale * scale, "Gamma (" + shape + ", " + scale + ")");', ' }', ' ', ' /**', ' * This checks the sub of the absolute differences between the entries of two vectors; if it is too large, then', ' * a jUnit error is generated', ' */', ' public void checkTotalDiff (IDoubleVector actual, IDoubleVector expected, double error, String test, String dist) throws OutOfBoundsException {', ' double totError = 0.0;', ' for (int i = 0; i < actual.getLength (); i++) {', ' totError += Math.abs (actual.getItem (i) - expected.getItem (i));', ' }', ' checkCloseEnough (totError, 0.0, error, test, dist);', ' }', ' ', ' /**', ' * Computes the difference between the observed mean of a multi-dim random variable, and the expected mean.', ' * The difference is returned as the sum of the parwise absolute values in the two vectors. This is used', ' * for the seeding and startOver tests for the two multi-dim random variables.', ' */', ' public double computeDiffFromMean (IRandomGenerationAlgorithm<IDoubleVector> myRNG, IDoubleVector expectedMean, int numTrials) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' }', ' ', ' // compute the total difference from the mean', ' double returnVal = 0;', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' returnVal += Math.abs (meanObs.getItem (i) / numTrials - expectedMean.getItem (i));', ' }', ' ', ' // and return it', ' return returnVal;', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' return 0.0;', ' }', ' }', ' ', ' /**', ' * Checks the observed mean and variance for a multi-dim random variable versus the theoretically expected values', ' * for these quantities. If the observed differs substantially from the expected, the test case is failed. This', ' * is used for checking the correctness of the multi-dim random variables.', ' */', ' public void checkMeanAndVar (IRandomGenerationAlgorithm<IDoubleVector> myRNG, ', ' IDoubleVector expectedMean, IDoubleVector expectedStdDev, double errorMean, double errorStdDev, int numTrials, String dist) {', ' ', ' // set up the total so far', ' try {', ' IDoubleVector firstOne = myRNG.getNext ();', ' DenseDoubleVector meanObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' DenseDoubleVector stdDevObs = new DenseDoubleVector (firstOne.getLength (), 0.0);', ' ', ' // add in a bunch more', ' for (int i = 0; i < numTrials; i++) {', ' IDoubleVector next = myRNG.getNext ();', ' next.addMyselfToHim (meanObs);', ' for (int j = 0; j < next.getLength (); j++) {', ' stdDevObs.setItem (j, stdDevObs.getItem (j) + next.getItem (j) * next.getItem (j)); ', ' }', ' }', ' ', ' // divide by the number of trials to get the mean', ' for (int i = 0; i < meanObs.getLength (); i++) {', ' meanObs.setItem (i, meanObs.getItem (i) / numTrials);', ' stdDevObs.setItem (i, Math.sqrt (stdDevObs.getItem (i) / numTrials - meanObs.getItem (i) * meanObs.getItem (i)));', ' }', ' ', ' // see if the mean and var are acceptable', ' checkTotalDiff (meanObs, expectedMean, errorMean, "total distance from true mean", dist);', ' checkTotalDiff (stdDevObs, expectedStdDev, errorStdDev, "total distance from true standard deviation", dist);', ' ', ' } catch (OutOfBoundsException e) {', ' fail ("I got an OutOfBoundsException when running getMean... bad vector length back?"); ', ' }', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testMultinomialReset () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testMultinomialSeeding () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Multinomial (27, new MultinomialParam (1024, probs));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Multinomial (2777, new MultinomialParam (1024, probs));', ' ', ' // and check the mean...', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for multinomial seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial1 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 100;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i += 2) {', ' probs.setItem (i, i); ', ' }', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (1024, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 1024);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 1024 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 5.0, 5.0, 5000, "multinomial number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */ ', ' public void testMultinomial2 () {', ' ', ' try {', ' // first set up a vector of probabilities', ' int len = 1000;', ' SparseDoubleVector probs = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 1; i ++) {', ' probs.setItem (i, 0.0001); ', ' }', ' probs.setItem (len - 1, 100);', ' probs.normalize ();', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Multinomial (27, new MultinomialParam (10, probs));', ' ', ' // and check the mean... we repeatedly double the prob vector to multiply it by 1024', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, probs.getItem (i) * 10);', ' expectedStdDev.setItem (i, Math.sqrt (probs.getItem (i) * 10 * (1.0 - probs.getItem (i))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.05, 5.0, 5000, "multinomial number two");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the multinomial."); ', ' }', ' ', ' }', ' ', ' /**', ' * Tests whether the startOver routine works correctly. To do this, it generates a sequence of random', ' * numbers, and computes the mean of them. Then it calls startOver, and generates the mean once again.', ' * If the means are very, very close to one another, then the test case passes.', ' */ ', ' public void testDirichletReset () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG, expectedMean, 500);', ' myRNG.startOver ();', ' double res2 = computeDiffFromMean (myRNG, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet reset", Math.abs (res1 - res2) < 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /** ', ' * Tests whether seeding is correctly used. This is run just like the startOver test above, except', ' * that here we create two sequences using two different seeds, and then we verify that the observed', ' * means were different from one another.', ' */ ', ' public void testDirichletSeeding () {', ' ', ' try {', ' ', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG1 = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG2 = new Dirichlet (92, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' }', ' ', ' double res1 = computeDiffFromMean (myRNG1, expectedMean, 500);', ' double res2 = computeDiffFromMean (myRNG2, expectedMean, 500);', ' ', ' assertTrue ("Failed check for Dirichlet seeding", Math.abs (res1 - res2) > 10e-10);', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', '', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet1 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 100;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.1, 0.3, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', ' /**', ' * Generates a bunch of random variables, and then uses the know formulas for the mean and variance of those', ' * variables to verify that the observed mean and variance are reasonable; if they are, this is a strong ', ' * indication that the variables are being generated correctly', ' */', ' public void testDirichlet2 () {', ' ', ' try {', ' // first set up a vector of shapes', ' int len = 300;', ' SparseDoubleVector shapes = new SparseDoubleVector (len, 0.0);', ' for (int i = 0; i < len - 10; i++) {', ' shapes.setItem (i, 0.05); ', ' }', ' for (int i = len - 9; i < len; i++) {', ' shapes.setItem (i, 100.0); ', ' }', ' ', ' // now, set up a distribution', ' IRandomGenerationAlgorithm<IDoubleVector> myRNG = new Dirichlet (27, new DirichletParam (shapes, 10e-40, 150));', ' ', ' // compute the expected mean and var', ' DenseDoubleVector expectedMean = new DenseDoubleVector (len, 0.0);', ' DenseDoubleVector expectedStdDev = new DenseDoubleVector (len, 0.0);', ' double norm = shapes.l1Norm ();', ' for (int i = 0; i < len; i++) {', ' expectedMean.setItem (i, shapes.getItem (i) / norm);', ' expectedStdDev.setItem (i, Math.sqrt (shapes.getItem (i) * (norm - shapes.getItem (i)) / ', ' (norm * norm * (1.0 + norm))));', ' }', ' ', ' checkMeanAndVar (myRNG, expectedMean, expectedStdDev, 0.01, 0.01, 5000, "Dirichlet number one");', ' ', ' } catch (Exception e) {', ' fail ("Got some sort of exception when I was testing the Dirichlet."); ', ' }', ' ', ' }', ' ', '}', ''] | [{'reason_category': 'If Body', 'usage_line': 681}, {'reason_category': 'Loop Body', 'usage_line': 681}] | Variable 'x' used at line 681 is defined at line 679 and has a Short-Range dependency. | {'If Body': 1, 'Loop Body': 1} | {'Variable Short-Range': 1} |
infilling_java | TopKTester | 167 | 169 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {'] | [' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }'] | [' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [] | Global_Variable 'left' used at line 167 is defined at line 136 and has a Long-Range dependency.
Global_Variable 'right' used at line 167 is defined at line 137 and has a Medium-Range dependency.
Global_Variable 'left' used at line 168 is defined at line 136 and has a Long-Range dependency.
Global_Variable 'right' used at line 168 is defined at line 137 and has a Long-Range dependency. | {} | {'Global_Variable Long-Range': 3, 'Global_Variable Medium-Range': 1} |
infilling_java | TopKTester | 190 | 196 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree'] | [' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }'] | [' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Else Reasoning', 'usage_line': 190}, {'reason_category': 'If Body', 'usage_line': 190}, {'reason_category': 'Else Reasoning', 'usage_line': 191}, {'reason_category': 'If Body', 'usage_line': 191}, {'reason_category': 'Else Reasoning', 'usage_line': 192}, {'reason_category': 'If Body', 'usage_line': 192}, {'reason_category': 'Else Reasoning', 'usage_line': 193}, {'reason_category': 'If Body', 'usage_line': 193}, {'reason_category': 'Else Reasoning', 'usage_line': 194}, {'reason_category': 'If Body', 'usage_line': 194}, {'reason_category': 'Else Reasoning', 'usage_line': 195}, {'reason_category': 'If Body', 'usage_line': 195}, {'reason_category': 'Else Reasoning', 'usage_line': 196}, {'reason_category': 'If Body', 'usage_line': 196}] | Class 'AVLNode' used at line 190 is defined at line 28 and has a Long-Range dependency.
Global_Variable 'left' used at line 190 is defined at line 136 and has a Long-Range dependency.
Class 'AVLNode' used at line 191 is defined at line 28 and has a Long-Range dependency.
Global_Variable 'right' used at line 191 is defined at line 180 and has a Medium-Range dependency.
Variable 'oldLeft' used at line 192 is defined at line 190 and has a Short-Range dependency.
Global_Variable 'left' used at line 192 is defined at line 136 and has a Long-Range dependency.
Class 'Occupied' used at line 193 is defined at line 134 and has a Long-Range dependency.
Global_Variable 'val' used at line 193 is defined at line 138 and has a Long-Range dependency.
Variable 'oldLeft' used at line 193 is defined at line 190 and has a Short-Range dependency.
Global_Variable 'right' used at line 193 is defined at line 180 and has a Medium-Range dependency.
Variable 'oldLeft' used at line 194 is defined at line 190 and has a Short-Range dependency.
Global_Variable 'val' used at line 194 is defined at line 138 and has a Long-Range dependency.
Function 'setHeight' used at line 195 is defined at line 35 and has a Long-Range dependency. | {'Else Reasoning': 7, 'If Body': 7} | {'Class Long-Range': 3, 'Global_Variable Long-Range': 4, 'Global_Variable Medium-Range': 2, 'Variable Short-Range': 3, 'Function Long-Range': 1} |
infilling_java | TopKTester | 215 | 215 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)'] | [' height = one;'] | [' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Body', 'usage_line': 215}] | Variable 'one' used at line 215 is defined at line 212 and has a Short-Range dependency.
Global_Variable 'height' used at line 215 is defined at line 139 and has a Long-Range dependency. | {'If Body': 1} | {'Variable Short-Range': 1, 'Global_Variable Long-Range': 1} |
infilling_java | TopKTester | 217 | 217 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else'] | [' height = other;'] | [' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Else Reasoning', 'usage_line': 217}] | Variable 'other' used at line 217 is defined at line 213 and has a Short-Range dependency.
Global_Variable 'height' used at line 217 is defined at line 215 and has a Short-Range dependency. | {'Else Reasoning': 1} | {'Variable Short-Range': 1, 'Global_Variable Short-Range': 1} |
infilling_java | TopKTester | 212 | 219 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' '] | [' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }'] | [' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Condition', 'usage_line': 214}, {'reason_category': 'If Body', 'usage_line': 215}, {'reason_category': 'Else Reasoning', 'usage_line': 216}, {'reason_category': 'Else Reasoning', 'usage_line': 217}] | Global_Variable 'left' used at line 212 is defined at line 136 and has a Long-Range dependency.
Global_Variable 'right' used at line 213 is defined at line 137 and has a Long-Range dependency.
Variable 'one' used at line 214 is defined at line 212 and has a Short-Range dependency.
Variable 'other' used at line 214 is defined at line 213 and has a Short-Range dependency.
Variable 'one' used at line 215 is defined at line 212 and has a Short-Range dependency.
Global_Variable 'height' used at line 215 is defined at line 139 and has a Long-Range dependency.
Variable 'other' used at line 217 is defined at line 213 and has a Short-Range dependency.
Global_Variable 'height' used at line 217 is defined at line 215 and has a Short-Range dependency.
Global_Variable 'height' used at line 218 is defined at line 215 and has a Short-Range dependency. | {'If Condition': 1, 'If Body': 1, 'Else Reasoning': 2} | {'Global_Variable Long-Range': 3, 'Variable Short-Range': 4, 'Global_Variable Short-Range': 2} |
infilling_java | TopKTester | 233 | 237 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;'] | [' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }'] | [' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [] | Variable 'oldLeft' used at line 233 is defined at line 231 and has a Short-Range dependency.
Global_Variable 'left' used at line 233 is defined at line 136 and has a Long-Range dependency.
Class 'Occupied' used at line 234 is defined at line 134 and has a Long-Range dependency.
Global_Variable 'val' used at line 234 is defined at line 138 and has a Long-Range dependency.
Variable 'oldLeft' used at line 234 is defined at line 231 and has a Short-Range dependency.
Global_Variable 'right' used at line 234 is defined at line 137 and has a Long-Range dependency.
Variable 'oldLeft' used at line 235 is defined at line 231 and has a Short-Range dependency.
Global_Variable 'val' used at line 235 is defined at line 138 and has a Long-Range dependency.
Function 'setHeight' used at line 236 is defined at line 210 and has a Medium-Range dependency. | {} | {'Variable Short-Range': 3, 'Global_Variable Long-Range': 4, 'Class Long-Range': 1, 'Function Medium-Range': 1} |
infilling_java | TopKTester | 235 | 237 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);'] | [' val = oldLeft.getVal ();', ' setHeight ();', ' }'] | [' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [] | Variable 'oldLeft' used at line 235 is defined at line 231 and has a Short-Range dependency.
Global_Variable 'val' used at line 235 is defined at line 138 and has a Long-Range dependency.
Function 'setHeight' used at line 236 is defined at line 210 and has a Medium-Range dependency. | {} | {'Variable Short-Range': 1, 'Global_Variable Long-Range': 1, 'Function Medium-Range': 1} |
infilling_java | TopKTester | 247 | 251 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;'] | [' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }'] | [' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [] | Class 'Occupied' used at line 247 is defined at line 134 and has a Long-Range dependency.
Global_Variable 'val' used at line 247 is defined at line 138 and has a Long-Range dependency.
Variable 'oldLeft' used at line 247 is defined at line 245 and has a Short-Range dependency.
Variable 'oldRight' used at line 247 is defined at line 246 and has a Short-Range dependency.
Global_Variable 'left' used at line 247 is defined at line 136 and has a Long-Range dependency.
Variable 'oldRight' used at line 248 is defined at line 246 and has a Short-Range dependency.
Global_Variable 'right' used at line 248 is defined at line 137 and has a Long-Range dependency.
Variable 'oldRight' used at line 249 is defined at line 246 and has a Short-Range dependency.
Global_Variable 'val' used at line 249 is defined at line 138 and has a Long-Range dependency.
Function 'setHeight' used at line 250 is defined at line 210 and has a Long-Range dependency. | {} | {'Class Long-Range': 1, 'Global_Variable Long-Range': 4, 'Variable Short-Range': 4, 'Function Long-Range': 1} |
infilling_java | TopKTester | 271 | 277 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' '] | [' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }'] | [' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [] | Class 'AVLNode' used at line 271 is defined at line 28 and has a Long-Range dependency.
Global_Variable 'left' used at line 271 is defined at line 136 and has a Long-Range dependency.
Class 'AVLNode' used at line 272 is defined at line 28 and has a Long-Range dependency.
Global_Variable 'right' used at line 272 is defined at line 137 and has a Long-Range dependency.
Variable 'oldLeft' used at line 273 is defined at line 271 and has a Short-Range dependency.
Global_Variable 'left' used at line 273 is defined at line 136 and has a Long-Range dependency.
Class 'Occupied' used at line 274 is defined at line 134 and has a Long-Range dependency.
Global_Variable 'val' used at line 274 is defined at line 138 and has a Long-Range dependency.
Variable 'oldLeft' used at line 274 is defined at line 271 and has a Short-Range dependency.
Variable 'oldRight' used at line 274 is defined at line 272 and has a Short-Range dependency.
Global_Variable 'right' used at line 274 is defined at line 137 and has a Long-Range dependency.
Variable 'oldLeft' used at line 275 is defined at line 271 and has a Short-Range dependency.
Global_Variable 'val' used at line 275 is defined at line 138 and has a Long-Range dependency.
Function 'setHeight' used at line 276 is defined at line 210 and has a Long-Range dependency. | {} | {'Class Long-Range': 3, 'Global_Variable Long-Range': 6, 'Variable Short-Range': 4, 'Function Long-Range': 1} |
infilling_java | TopKTester | 281 | 285 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {'] | [' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }'] | [' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [] | Variable 'valIn' used at line 281 is defined at line 280 and has a Short-Range dependency.
Global_Variable 'val' used at line 281 is defined at line 138 and has a Long-Range dependency.
Variable 'leftIn' used at line 282 is defined at line 280 and has a Short-Range dependency.
Global_Variable 'left' used at line 282 is defined at line 136 and has a Long-Range dependency.
Variable 'rightIn' used at line 283 is defined at line 280 and has a Short-Range dependency.
Global_Variable 'right' used at line 283 is defined at line 137 and has a Long-Range dependency.
Function 'setHeight' used at line 284 is defined at line 210 and has a Long-Range dependency. | {} | {'Variable Short-Range': 3, 'Global_Variable Long-Range': 3, 'Function Long-Range': 1} |
infilling_java | TopKTester | 290 | 290 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {'] | [' left = left.insert (myKey, myVal); '] | [' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Body', 'usage_line': 290}] | Global_Variable 'left' used at line 290 is defined at line 136 and has a Long-Range dependency.
Variable 'myKey' used at line 290 is defined at line 287 and has a Short-Range dependency.
Variable 'myVal' used at line 290 is defined at line 287 and has a Short-Range dependency. | {'If Body': 1} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 2} |
infilling_java | TopKTester | 292 | 293 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {'] | [' right = right.insert (myKey, myVal); ', ' }'] | [' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Else Reasoning', 'usage_line': 292}, {'reason_category': 'Else Reasoning', 'usage_line': 293}] | Global_Variable 'right' used at line 292 is defined at line 137 and has a Long-Range dependency.
Variable 'myKey' used at line 292 is defined at line 287 and has a Short-Range dependency.
Variable 'myVal' used at line 292 is defined at line 287 and has a Short-Range dependency. | {'Else Reasoning': 2} | {'Global_Variable Long-Range': 1, 'Variable Short-Range': 2} |
infilling_java | TopKTester | 296 | 296 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)'] | [' raiseLeft ();'] | [' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Body', 'usage_line': 296}] | Function 'raiseLeft' used at line 296 is defined at line 225 and has a Long-Range dependency. | {'If Body': 1} | {'Function Long-Range': 1} |
infilling_java | TopKTester | 298 | 298 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)'] | [' raiseRight ();'] | [' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Elif Body', 'usage_line': 298}] | Function 'raiseRight' used at line 298 is defined at line 239 and has a Long-Range dependency. | {'Elif Body': 1} | {'Function Long-Range': 1} |
infilling_java | TopKTester | 300 | 302 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' '] | [' setHeight ();', ' return this;', ' }'] | ['}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [] | Function 'setHeight' used at line 300 is defined at line 210 and has a Long-Range dependency. | {} | {'Function Long-Range': 1} |
infilling_java | TopKTester | 314 | 317 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {'] | [' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }'] | [' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [] | Global_Variable 'root' used at line 315 is defined at line 307 and has a Short-Range dependency.
Variable 'temp' used at line 315 is defined at line 314 and has a Short-Range dependency.
Variable 'temp' used at line 316 is defined at line 314 and has a Short-Range dependency. | {} | {'Global_Variable Short-Range': 1, 'Variable Short-Range': 2} |
infilling_java | TopKTester | 320 | 321 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {'] | [' root = root.removeBig ();', ' }'] | [' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [] | Global_Variable 'root' used at line 320 is defined at line 307 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 1} |
infilling_java | TopKTester | 353 | 353 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')"] | [' startPos++;'] | [' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 353}] | Variable 'startPos' used at line 353 is defined at line 351 and has a Short-Range dependency. | {'Loop Body': 1} | {'Variable Short-Range': 1} |
infilling_java | TopKTester | 368 | 368 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')"] | [' lParens++;'] | [" else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Body', 'usage_line': 368}, {'reason_category': 'Loop Body', 'usage_line': 368}] | Variable 'lParens' used at line 368 is defined at line 362 and has a Short-Range dependency. | {'If Body': 1, 'Loop Body': 1} | {'Variable Short-Range': 1} |
infilling_java | TopKTester | 370 | 370 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')"] | [' rParens++;'] | [' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 370}, {'reason_category': 'Elif Body', 'usage_line': 370}] | Variable 'rParens' used at line 370 is defined at line 363 and has a Short-Range dependency. | {'Loop Body': 1, 'Elif Body': 1} | {'Variable Short-Range': 1} |
infilling_java | TopKTester | 377 | 380 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {'] | [' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;'] | [' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 377}, {'reason_category': 'If Body', 'usage_line': 377}, {'reason_category': 'Loop Body', 'usage_line': 378}, {'reason_category': 'If Body', 'usage_line': 378}, {'reason_category': 'Loop Body', 'usage_line': 379}, {'reason_category': 'If Body', 'usage_line': 379}, {'reason_category': 'If Body', 'usage_line': 380}, {'reason_category': 'Loop Body', 'usage_line': 380}] | Function 'checkHeight' used at line 377 is defined at line 348 and has a Medium-Range dependency.
Variable 'checkMe' used at line 377 is defined at line 348 and has a Medium-Range dependency.
Variable 'startPos' used at line 377 is defined at line 351 and has a Medium-Range dependency.
Variable 'i' used at line 377 is defined at line 364 and has a Medium-Range dependency.
Variable 'leftDepth' used at line 377 is defined at line 356 and has a Medium-Range dependency.
Variable 'i' used at line 378 is defined at line 364 and has a Medium-Range dependency.
Variable 'startPos' used at line 378 is defined at line 351 and has a Medium-Range dependency.
Variable 'lParens' used at line 379 is defined at line 362 and has a Medium-Range dependency.
Variable 'rParens' used at line 380 is defined at line 363 and has a Medium-Range dependency. | {'Loop Body': 4, 'If Body': 4} | {'Function Medium-Range': 1, 'Variable Medium-Range': 8} |
infilling_java | TopKTester | 384 | 387 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {'] | [' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }'] | [' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 384}, {'reason_category': 'Else Reasoning', 'usage_line': 384}, {'reason_category': 'Loop Body', 'usage_line': 385}, {'reason_category': 'Else Reasoning', 'usage_line': 385}, {'reason_category': 'Loop Body', 'usage_line': 386}, {'reason_category': 'Else Reasoning', 'usage_line': 386}, {'reason_category': 'Loop Body', 'usage_line': 387}, {'reason_category': 'Else Reasoning', 'usage_line': 387}] | Function 'checkHeight' used at line 384 is defined at line 348 and has a Long-Range dependency.
Variable 'checkMe' used at line 384 is defined at line 348 and has a Long-Range dependency.
Variable 'startPos' used at line 384 is defined at line 378 and has a Short-Range dependency.
Variable 'i' used at line 384 is defined at line 364 and has a Medium-Range dependency.
Variable 'rightDepth' used at line 384 is defined at line 359 and has a Medium-Range dependency.
Variable 'i' used at line 385 is defined at line 364 and has a Medium-Range dependency.
Variable 'startPos' used at line 385 is defined at line 378 and has a Short-Range dependency. | {'Loop Body': 4, 'Else Reasoning': 4} | {'Function Long-Range': 1, 'Variable Long-Range': 1, 'Variable Short-Range': 2, 'Variable Medium-Range': 3} |
infilling_java | TopKTester | 376 | 388 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree'] | [' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }'] | [' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 376}, {'reason_category': 'If Body', 'usage_line': 376}, {'reason_category': 'If Condition', 'usage_line': 376}, {'reason_category': 'Loop Body', 'usage_line': 377}, {'reason_category': 'If Body', 'usage_line': 377}, {'reason_category': 'Loop Body', 'usage_line': 378}, {'reason_category': 'If Body', 'usage_line': 378}, {'reason_category': 'Loop Body', 'usage_line': 379}, {'reason_category': 'If Body', 'usage_line': 379}, {'reason_category': 'If Body', 'usage_line': 380}, {'reason_category': 'Loop Body', 'usage_line': 380}, {'reason_category': 'Loop Body', 'usage_line': 381}, {'reason_category': 'Loop Body', 'usage_line': 382}, {'reason_category': 'Loop Body', 'usage_line': 383}, {'reason_category': 'Else Reasoning', 'usage_line': 383}, {'reason_category': 'Loop Body', 'usage_line': 384}, {'reason_category': 'Else Reasoning', 'usage_line': 384}, {'reason_category': 'Loop Body', 'usage_line': 385}, {'reason_category': 'Else Reasoning', 'usage_line': 385}, {'reason_category': 'Loop Body', 'usage_line': 386}, {'reason_category': 'Else Reasoning', 'usage_line': 386}, {'reason_category': 'Loop Body', 'usage_line': 387}, {'reason_category': 'Else Reasoning', 'usage_line': 387}, {'reason_category': 'Loop Body', 'usage_line': 388}] | Variable 'leftDepth' used at line 376 is defined at line 356 and has a Medium-Range dependency.
Function 'checkHeight' used at line 377 is defined at line 348 and has a Medium-Range dependency.
Variable 'checkMe' used at line 377 is defined at line 348 and has a Medium-Range dependency.
Variable 'startPos' used at line 377 is defined at line 351 and has a Medium-Range dependency.
Variable 'i' used at line 377 is defined at line 364 and has a Medium-Range dependency.
Variable 'leftDepth' used at line 377 is defined at line 356 and has a Medium-Range dependency.
Variable 'i' used at line 378 is defined at line 364 and has a Medium-Range dependency.
Variable 'startPos' used at line 378 is defined at line 351 and has a Medium-Range dependency.
Variable 'lParens' used at line 379 is defined at line 362 and has a Medium-Range dependency.
Variable 'rParens' used at line 380 is defined at line 363 and has a Medium-Range dependency.
Function 'checkHeight' used at line 384 is defined at line 348 and has a Long-Range dependency.
Variable 'checkMe' used at line 384 is defined at line 348 and has a Long-Range dependency.
Variable 'startPos' used at line 384 is defined at line 378 and has a Short-Range dependency.
Variable 'i' used at line 384 is defined at line 364 and has a Medium-Range dependency.
Variable 'rightDepth' used at line 384 is defined at line 359 and has a Medium-Range dependency.
Variable 'i' used at line 385 is defined at line 364 and has a Medium-Range dependency.
Variable 'startPos' used at line 385 is defined at line 378 and has a Short-Range dependency. | {'Loop Body': 13, 'If Body': 5, 'If Condition': 1, 'Else Reasoning': 5} | {'Variable Medium-Range': 12, 'Function Medium-Range': 1, 'Function Long-Range': 1, 'Variable Long-Range': 1, 'Variable Short-Range': 2} |
infilling_java | TopKTester | 397 | 397 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')"] | [' startPos++;'] | [' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 397}] | Variable 'startPos' used at line 397 is defined at line 351 and has a Long-Range dependency. | {'Loop Body': 1} | {'Variable Long-Range': 1} |
infilling_java | TopKTester | 401 | 401 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)'] | [' return leftDepth + 1;'] | [' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Body', 'usage_line': 401}] | Variable 'leftDepth' used at line 401 is defined at line 356 and has a Long-Range dependency. | {'If Body': 1} | {'Variable Long-Range': 1} |
infilling_java | TopKTester | 403 | 403 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else'] | [' return rightDepth + 1;'] | [' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Else Reasoning', 'usage_line': 403}] | Variable 'rightDepth' used at line 403 is defined at line 359 and has a Long-Range dependency. | {'Else Reasoning': 1} | {'Variable Long-Range': 1} |
infilling_java | TopKTester | 426 | 430 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {'] | [' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }'] | [' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Body', 'usage_line': 426}, {'reason_category': 'If Body', 'usage_line': 427}, {'reason_category': 'If Condition', 'usage_line': 428}, {'reason_category': 'If Body', 'usage_line': 428}, {'reason_category': 'If Body', 'usage_line': 429}, {'reason_category': 'If Body', 'usage_line': 430}] | Global_Variable 'myTree' used at line 426 is defined at line 413 and has a Medium-Range dependency.
Variable 'score' used at line 426 is defined at line 424 and has a Short-Range dependency.
Variable 'value' used at line 426 is defined at line 424 and has a Short-Range dependency.
Global_Variable 'spaceLeft' used at line 427 is defined at line 412 and has a Medium-Range dependency.
Global_Variable 'spaceLeft' used at line 428 is defined at line 412 and has a Medium-Range dependency.
Global_Variable 'myTree' used at line 429 is defined at line 413 and has a Medium-Range dependency.
Global_Variable 'cutoff' used at line 429 is defined at line 414 and has a Medium-Range dependency. | {'If Body': 5, 'If Condition': 1} | {'Global_Variable Medium-Range': 5, 'Variable Short-Range': 2} |
infilling_java | TopKTester | 429 | 429 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)'] | [' cutoff = myTree.getBig ();'] | [' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Body', 'usage_line': 429}] | Global_Variable 'myTree' used at line 429 is defined at line 413 and has a Medium-Range dependency.
Global_Variable 'cutoff' used at line 429 is defined at line 414 and has a Medium-Range dependency. | {'If Body': 1} | {'Global_Variable Medium-Range': 2} |
infilling_java | TopKTester | 433 | 436 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {'] | [' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }'] | [' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Body', 'usage_line': 433}, {'reason_category': 'If Body', 'usage_line': 434}, {'reason_category': 'If Body', 'usage_line': 435}, {'reason_category': 'If Body', 'usage_line': 436}] | Global_Variable 'myTree' used at line 433 is defined at line 413 and has a Medium-Range dependency.
Global_Variable 'myTree' used at line 434 is defined at line 413 and has a Medium-Range dependency.
Global_Variable 'cutoff' used at line 434 is defined at line 429 and has a Short-Range dependency.
Global_Variable 'spaceLeft' used at line 435 is defined at line 412 and has a Medium-Range dependency. | {'If Body': 4} | {'Global_Variable Medium-Range': 3, 'Global_Variable Short-Range': 1} |
infilling_java | TopKTester | 442 | 443 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {'] | [' return cutoff; ', ' }'] | [' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [] | Global_Variable 'cutoff' used at line 442 is defined at line 414 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 1} |
infilling_java | TopKTester | 450 | 451 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {'] | [' return myTree.toList (); ', ' }'] | [' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [] | Global_Variable 'myTree' used at line 450 is defined at line 413 and has a Long-Range dependency. | {} | {'Global_Variable Long-Range': 1} |
infilling_java | TopKTester | 468 | 472 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {'] | [' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }'] | [' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 468}, {'reason_category': 'Loop Body', 'usage_line': 469}, {'reason_category': 'Loop Body', 'usage_line': 470}, {'reason_category': 'Loop Body', 'usage_line': 471}, {'reason_category': 'Loop Body', 'usage_line': 472}] | Variable 'i' used at line 468 is defined at line 467 and has a Short-Range dependency.
Global_Variable 'shuffler' used at line 468 is defined at line 465 and has a Short-Range dependency.
Variable 'list' used at line 468 is defined at line 466 and has a Short-Range dependency.
Variable 'list' used at line 469 is defined at line 466 and has a Short-Range dependency.
Variable 'i' used at line 469 is defined at line 467 and has a Short-Range dependency.
Variable 'list' used at line 470 is defined at line 466 and has a Short-Range dependency.
Variable 'pos' used at line 470 is defined at line 468 and has a Short-Range dependency.
Variable 'i' used at line 470 is defined at line 467 and has a Short-Range dependency.
Variable 'temp' used at line 471 is defined at line 469 and has a Short-Range dependency.
Variable 'list' used at line 471 is defined at line 470 and has a Short-Range dependency.
Variable 'pos' used at line 471 is defined at line 468 and has a Short-Range dependency. | {'Loop Body': 5} | {'Variable Short-Range': 10, 'Global_Variable Short-Range': 1} |
infilling_java | TopKTester | 487 | 487 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) '] | [' reverseOrNot = controlTest[1];'] | [' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Body', 'usage_line': 487}] | Variable 'controlTest' used at line 487 is defined at line 481 and has a Short-Range dependency.
Variable 'reverseOrNot' used at line 487 is defined at line 484 and has a Short-Range dependency. | {'If Body': 1} | {'Variable Short-Range': 2} |
infilling_java | TopKTester | 494 | 494 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)'] | [' list[i] = numInserts - 1 - i;'] | [' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Body', 'usage_line': 494}, {'reason_category': 'Loop Body', 'usage_line': 494}] | Variable 'numInserts' used at line 494 is defined at line 481 and has a Medium-Range dependency.
Variable 'i' used at line 494 is defined at line 492 and has a Short-Range dependency.
Variable 'list' used at line 494 is defined at line 491 and has a Short-Range dependency. | {'If Body': 1, 'Loop Body': 1} | {'Variable Medium-Range': 1, 'Variable Short-Range': 2} |
infilling_java | TopKTester | 501 | 501 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)'] | [' shuffle (list);'] | [' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Body', 'usage_line': 501}] | Function 'shuffle' used at line 501 is defined at line 466 and has a Long-Range dependency.
Variable 'list' used at line 501 is defined at line 491 and has a Short-Range dependency. | {'If Body': 1} | {'Function Long-Range': 1, 'Variable Short-Range': 1} |
infilling_java | TopKTester | 541 | 541 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)'] | [' k = numInserts;'] | [' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Body', 'usage_line': 541}] | Variable 'numInserts' used at line 541 is defined at line 481 and has a Long-Range dependency.
Variable 'k' used at line 541 is defined at line 481 and has a Long-Range dependency. | {'If Body': 1} | {'Variable Long-Range': 2} |
infilling_java | TopKTester | 559 | 559 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) '] | [' reverseOrNot = controlTest[1];'] | [' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Body', 'usage_line': 559}] | Variable 'controlTest' used at line 559 is defined at line 553 and has a Short-Range dependency.
Variable 'reverseOrNot' used at line 559 is defined at line 556 and has a Short-Range dependency. | {'If Body': 1} | {'Variable Short-Range': 2} |
infilling_java | TopKTester | 566 | 566 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)'] | [' list[i] = numInserts - 1 - i;'] | [' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Loop Body', 'usage_line': 566}, {'reason_category': 'If Body', 'usage_line': 566}] | Variable 'numInserts' used at line 566 is defined at line 553 and has a Medium-Range dependency.
Variable 'i' used at line 566 is defined at line 564 and has a Short-Range dependency.
Variable 'list' used at line 566 is defined at line 563 and has a Short-Range dependency. | {'Loop Body': 1, 'If Body': 1} | {'Variable Medium-Range': 1, 'Variable Short-Range': 2} |
infilling_java | TopKTester | 568 | 568 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else'] | [' list[i] = i; '] | [' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'Else Reasoning', 'usage_line': 568}, {'reason_category': 'Loop Body', 'usage_line': 568}] | Variable 'i' used at line 568 is defined at line 564 and has a Short-Range dependency.
Variable 'list' used at line 568 is defined at line 566 and has a Short-Range dependency. | {'Else Reasoning': 1, 'Loop Body': 1} | {'Variable Short-Range': 2} |
infilling_java | TopKTester | 573 | 573 | ['import junit.framework.TestCase;', 'import java.util.Random;', 'import java.util.Collections;', 'import java.util.ArrayList;', '', '// This simple interface allows us to get the top K objects out of a large set', '// (that is, the K objects that are inserted having the **lowest** score vales)', '// The idea is that you would create an ITopKMachine using a specific K. Then,', '// you insert the vlaues one-by-one into the machine using the "insert" method.', '// Whenever you want to obtain the current top K, you call "getTopK", which puts', '// the top K into the array list. In addition, the machine can be queried to', '// see what is the current worst score that will still put a value into the top K.', 'interface ITopKMachine <T> {', '', ' // insert a new value into the machine. If its score is greater than the current', ' // cutoff, it is ignored. If its score is smaller than the current cutoff, the', ' // insertion will evict the value with the worst score.', ' void insert (double score, T value);', ' ', ' // get the current top K in an array list', ' ArrayList <T> getTopK ();', ' ', ' // let the caller know the current cutoff value that will get one into the top K list', ' double getCurrentCutoff ();', ' ', '}', '', 'abstract class AVLNode <T> {', ' abstract AVLNode <T> insert (double myKey, T myVal);', ' abstract AVLNode <T> removeBig ();', ' abstract AVLNode <T> getLeft ();', ' abstract AVLNode <T> getRight ();', ' abstract Data <T> getVal ();', ' abstract int getHeight ();', ' abstract void setHeight ();', ' abstract void raiseRight ();', ' abstract void raiseLeft ();', ' abstract void makeLeftDeep ();', ' abstract void makeRightDeep ();', ' abstract void checkBalanced ();', ' abstract boolean isBalanced ();', ' abstract String print ();', ' abstract void toList (ArrayList <T> myList);', ' abstract double getBig ();', '}', '', '', 'class EmptyNode <T> extends AVLNode <T> {', ' ', ' void toList (ArrayList <T> myList) {}', '', ' double getBig () {', ' return Double.NEGATIVE_INFINITY; ', ' }', ' ', ' String print () {', ' return "()"; ', ' }', ' ', ' void checkBalanced () { ', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' return new Occupied <T> (new Data <T> (myKey, myVal), new EmptyNode <T> (), new EmptyNode <T> ()); ', ' }', ' ', ' AVLNode <T> removeBig () {', ' return null; ', ' }', ' ', ' AVLNode <T> getLeft () {', ' return null; ', ' }', ' ', ' AVLNode <T> getRight () {', ' return null; ', ' }', ' ', ' Data <T> getVal () {', ' return null; ', ' }', ' ', ' int getHeight () {', ' return 0; ', ' }', ' ', ' boolean isBalanced () {', ' return true;', ' }', ' ', ' void setHeight () {', ' throw new RuntimeException ("set height on empty node");', ' }', ' ', ' ', ' void raiseRight ( ){', ' throw new RuntimeException ("raise right on empty node");', ' } ', ' ', ' void raiseLeft () {', ' throw new RuntimeException ("raise left on empty node");', ' }', ' ', ' void makeLeftDeep () {', ' throw new RuntimeException ("make left deep on empty node");', ' }', ' ', ' void makeRightDeep () {', ' throw new RuntimeException ("make right deep on empty node");', ' }', ' ', '}', '', 'class Data <T> {', '', ' private double score;', ' private T val;', ' ', ' double getScore () {', ' return score;', ' }', ' ', ' T getVal () {', ' return val;', ' }', ' ', ' Data (double scoreIn, T valIn) {', ' score = scoreIn;', ' val = valIn;', ' }', '}', '', '', 'class Occupied <T> extends AVLNode <T> {', ' ', ' private AVLNode <T> left;', ' private AVLNode <T> right;', ' private Data <T> val;', ' private int height;', '', ' double getBig () {', ' double big = right.getBig ();', ' if (val.getScore () > big)', ' return val.getScore ();', ' else', ' return big;', ' }', ' ', ' void toList (ArrayList <T> myList) {', ' left.toList (myList);', ' myList.add (val.getVal ());', ' right.toList (myList);', ' }', ' ', ' String print () {', ' return "(" + left.print () + val.getVal () + right.print () + ")"; ', ' }', ' ', ' void checkBalanced () {', ' if (!isBalanced ())', ' throw new RuntimeException (left.getHeight () + " " + right.getHeight ());', ' left.checkBalanced ();', ' right.checkBalanced ();', ' }', ' ', ' boolean isBalanced () {', ' return (!(left.getHeight () - right.getHeight () >= 2 ||', ' left.getHeight () - right.getHeight () <= -2));', ' }', ' ', ' Data <T> getVal () {', ' return val; ', ' }', ' ', ' AVLNode <T> removeBig () {', ' AVLNode <T> newRight = right.removeBig ();', ' if (newRight == null) {', ' return left; ', ' } else {', ' right = newRight;', ' setHeight ();', ' ', ' // if we are not balanced, the RHS shrank', ' if (!isBalanced ()) {', ' ', ' // make sure the LHS is left deep', ' left.makeLeftDeep ();', ' ', ' // and now reconstruct the tree', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' return this;', ' }', ' }', ' ', ' AVLNode <T> getLeft () {', ' return left;', ' }', ' ', ' AVLNode <T> getRight () {', ' return right;', ' }', ' ', ' void setHeight () {', ' ', ' int one = left.getHeight ();', ' int other = right.getHeight ();', ' if (one > other)', ' height = one;', ' else', ' height = other;', ' height++;', ' }', ' ', ' int getHeight () {', ' return height; ', ' }', ' ', ' void raiseLeft () {', ' ', ' // make sure we are left deep first', ' left.makeLeftDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), right);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' void raiseRight () {', ' ', ' // make sure we are right deep first', ' right.makeRightDeep ();', ' ', ' // and then balance the thing', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeLeftDeep () {', ' ', ' if (left.getHeight () >= right.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = new Occupied <T> (val, oldLeft, oldRight.getLeft ());', ' right = oldRight.getRight ();', ' val = oldRight.getVal ();', ' setHeight ();', ' }', ' ', ' void makeRightDeep () {', ' ', ' if (right.getHeight () >= left.getHeight ())', ' return;', ' ', ' AVLNode <T> oldLeft = left;', ' AVLNode <T> oldRight = right;', ' left = oldLeft.getLeft ();', ' right = new Occupied <T> (val, oldLeft.getRight (), oldRight);', ' val = oldLeft.getVal ();', ' setHeight ();', ' }', ' ', ' ', ' Occupied (Data <T> valIn, AVLNode <T> leftIn, AVLNode <T> rightIn) {', ' val = valIn;', ' left = leftIn;', ' right = rightIn;', ' setHeight ();', ' }', ' ', ' AVLNode <T> insert (double myKey, T myVal) {', ' ', ' if (myKey <= val.getScore ()) {', ' left = left.insert (myKey, myVal); ', ' } else {', ' right = right.insert (myKey, myVal); ', ' }', ' ', ' if (left.getHeight () - right.getHeight () > 1)', ' raiseLeft ();', ' else if (right.getHeight () - left.getHeight () > 1)', ' raiseRight ();', ' ', ' setHeight ();', ' return this;', ' }', '}', '', 'class ChrisAVLTree <T> {', '', ' AVLNode <T> root = new EmptyNode <T> ();', ' ', ' void insert (double val, T insertMe) {', ' root = root.insert (val, insertMe);', ' }', ' ', ' public ArrayList <T> toList () {', ' ArrayList <T> temp = new ArrayList <T> ();', ' root.toList (temp);', ' return temp;', ' }', ' ', ' void removeBig () {', ' root = root.removeBig ();', ' }', ' ', ' public double getBig () {', ' return root.getBig (); ', ' }', ' ', ' String print () {', ' return root.print ();', ' }', ' ', ' void checkBalanced () {', ' root.checkBalanced ();', ' }', '} ', '', '', '// this little class processes a printed version of a BST to see if it is balanced', '// enough to be an AVL tree. We assume that an empty tree is encoded as "()". And', '// we assume that a non-empty tree is encoded as "(<left tree> value <right tree>)".', '// So, for example, "(((()0(()1()))2((()3())4(()5())))6())" encodes one tree, and', '// "((()0(()1()))2(()3()))" encodes another tree. This second one has a 2 at the', '// root, with a 3 to the right of the root and a 1 to the left of the root. To the', '// left of the one is a 0. Everything else is empty.', 'class IsBalanced {', ' ', ' // returns the height of the tree encoded in the string; throws an exception if it', ' // is not balanced', ' int checkHeight (String checkMe) {', ' ', " // find the position of the first '('", ' int startPos = 0;', " while (checkMe.charAt (startPos) != '(')", ' startPos++;', ' ', ' // this is the depth at the left', ' int leftDepth = -1;', ' ', ' // and the depth at the right', ' int rightDepth = -1;', ' ', ' // now, find where the number of parens on each side is equal', ' int lParens = 0;', ' int rParens = 0;', ' for (int i = startPos + 1; i < checkMe.length (); i++) {', ' ', ' // count each ) or ( in the string', " if (checkMe.charAt (i) == '(')", ' lParens++;', " else if (checkMe.charAt (i) == ')')", ' rParens++;', ' ', ' // if the number of ) and ( are equal', ' if (lParens == rParens && lParens > 0) {', ' ', ' // in this case, we just completed the left tree', ' if (leftDepth == -1) {', ' leftDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' lParens = 0;', ' rParens = 0;', ' ', ' // in this case, we just completed the right tree', ' } else {', ' rightDepth = checkHeight (checkMe.substring (startPos + 1, i + 1));', ' startPos = i + 1;', ' break;', ' }', ' }', ' }', ' ', ' // check to see if this is not a valid AVL tree', ' if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2)', ' throw new RuntimeException ("this tree is not balanced! Left: " + leftDepth + " Right: " + rightDepth);', ' ', ' // search for the closing )', " while (checkMe.charAt (startPos) != ')')", ' startPos++;', ' ', ' // and we are outta here', ' if (leftDepth > rightDepth)', ' return leftDepth + 1;', ' else', ' return rightDepth + 1;', ' ', ' }', ' ', ' ', '}', '', 'class AVLTopKMachine <T> implements ITopKMachine <T> {', ' ', ' private int spaceLeft;', ' private ChrisAVLTree <T> myTree = new ChrisAVLTree <T> ();', ' private double cutoff = Double.POSITIVE_INFINITY;', ' ', ' public AVLTopKMachine (int kIn) {', ' if (kIn < 0)', ' throw new RuntimeException ("K must be at least zero.");', ' if (kIn == 0)', ' cutoff = Double.NEGATIVE_INFINITY;', ' spaceLeft = kIn;', ' }', ' ', ' public void insert (double score, T value) {', ' if (spaceLeft > 0 || score < cutoff) {', ' myTree.insert (score, value);', ' spaceLeft--;', ' if (spaceLeft == 0)', ' cutoff = myTree.getBig ();', ' }', ' ', ' if (spaceLeft < 0) {', ' myTree.removeBig ();', ' cutoff = myTree.getBig ();', ' spaceLeft++;', ' }', ' ', ' ', ' }', ' ', ' public double getCurrentCutoff () {', ' return cutoff; ', ' }', ' ', ' public String toString () {', ' return myTree.print (); ', ' }', ' ', ' public ArrayList <T> getTopK () {', ' return myTree.toList (); ', ' }', ' ', ' ', '}', '', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class TopKTester extends TestCase {', ' ', ' // this simple method randomly shuffles the items in an array', ' Random shuffler = new Random (324234);', ' void shuffle (Integer [] list) {', ' for (Integer i = 0; i < list.length; i++) {', ' Integer pos = i + shuffler.nextInt (list.length - i);', ' Integer temp = list[i];', ' list[i] = list[pos];', ' list[pos] = temp;', ' }', ' }', ' ', ' // the first param is the number of inserts to try. The second is k. If the third param is true, ', ' // then we do a random order of inserts. If the third param is false, then we do inserts in order,', ' // and the method expects a fourth boolean param that tells us whether we do reverse or forward ', ' // inserts. So testInserts (100, 5, false, true) will do 100 reverse order inserts, with a k of 5.', ' // testInserts (100, 5, false, false) will do 100 in order inserts. testInserts (100, 5, true) will', ' // do 100 random inserts.', ' private void testInserts (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)', ' shuffle (list);', ' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) {', ' ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // if we are not random, check to see that the cutoff is correct', ' if (!randomOrNot) {', ' ', ' double score = testMe.getCurrentCutoff ();', ' ', " // if we don't have k inserts, then we should have an extreme cutoff", ' if (j + 1 < k) {', ' if (score != Double.POSITIVE_INFINITY && score != Double.NEGATIVE_INFINITY)', ' fail ("at insert number " + j + 1 + " expected positive or negative infinity; found " + score);', ' ', ' // otherwise, check the cutoff', ' } else {', ' ', ' // for reverse order inserts, we have one cutoff...', ' if (reverseOrNot) {', ' ', ' assertEquals ("when checking cutoff during reverse inserts", (i + k - 1) * 1.343432, score);', ' ', ' // and for in-order, we have another', ' } else {', ' assertEquals ("when checking cutoff during in order inserts", (k - 1) * 1.343432, score);', ' }', ' }', ' }', ' }', ' ', ' // and make sure top k are correct', ' ArrayList <Integer> retVal = testMe.getTopK ();', ' Collections.sort (retVal);', ' ', " // don'e go past the size of the list", ' if (k > numInserts)', ' k = numInserts;', ' ', ' // make sure the list is the right size', ' assertEquals (retVal.size (), k);', ' ', ' // and check its contents', ' for (int i = 0; i < k; i++) {', ' assertEquals ("when checking values returned getting top k", i, (int) retVal.get (i));', ' }', ' }', ' ', ' // this checks for balance.. it does NOT check for the right answer... params ae same as above', ' private void testBalance (int numInserts, int k, boolean... controlTest) {', ' ', ' // see what kind of test to do', ' boolean reverseOrNot = false;', ' boolean randomOrNot = controlTest[0];', ' if (!randomOrNot) ', ' reverseOrNot = controlTest[1];', ' ', ' // create a list of random ints', ' ITopKMachine <Integer> testMe = new AVLTopKMachine <Integer> (k);', ' Integer [] list = new Integer [numInserts];', ' for (int i = 0; i < numInserts; i++) {', ' if (reverseOrNot)', ' list[i] = numInserts - 1 - i;', ' else', ' list[i] = i; ', ' }', ' ', ' // if we are looking for randomness, shuffle the list', ' if (randomOrNot)'] | [' shuffle (list);'] | [' ', ' // now add the ints', ' for (int j = 0; j < list.length; j++) { ', ' Integer i = list[j];', ' testMe.insert (i * 1.343432, i);', ' ', ' // and check for balance', ' if (j % 10 == 0) {', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' }', ' ', ' // check for balance one last time', ' IsBalanced temp = new IsBalanced ();', ' try {', ' temp.checkHeight (testMe.toString ());', ' } catch (Exception e) {', ' fail ("the tree was found to not be balanced"); ', ' }', ' } ', '', ' }', ' ', ' ', ' /**', ' * A test method.', ' * (Replace "X" with a name describing the test. You may write as', ' * many "testSomething" methods in this class as you wish, and each', ' * one will be called when running JUnit over this class.)', ' */', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK () {', ' testInserts (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK () {', ' testInserts (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK () {', ' testInserts (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK () {', ' testInserts (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK () {', ' testInserts (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK () {', ' testInserts (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK () {', ' testInserts (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK () {', ' testInserts (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK () {', ' testInserts (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK () {', ' testInserts (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK () {', ' testInserts (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK () {', ' testInserts (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK () {', ' testInserts (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK () {', ' testInserts (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK () {', ' testInserts (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK () {', ' testInserts (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK () {', ' testInserts (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK () {', ' testInserts (100000, 100, false, true);', ' }', ' ', ' /***************************', ' * Now check for balance!!! *', ' **************************/', ' ', ' /******************************', ' * These do RANDOM inserts *', ' ******************************/', ' ', ' public void testAFewRandomInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, true);', ' }', ' ', ' public void testALotOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, true);', ' }', ' ', ' public void testAFewRandomInsertsBigK_CheckBalance_CheckBalance () {', ' testBalance (10, 100, true);', ' }', ' ', ' public void testALotOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100, 100, true);', ' }', ' ', ' public void testAHugeNumberOfRandomInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, true);', ' }', ' ', ' /******************************', ' * These do ORDERED inserts *', ' ******************************/', ' ', ' public void testAFewOrderedInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, false);', ' }', ' ', ' public void testAFewOrderedInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, false);', ' }', ' ', ' public void testALotOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, false);', ' }', ' ', ' public void testAHugeNumberOfOrderedInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, false);', ' }', ' ', ' /******************************', ' * These do REVERSE inserts *', ' ******************************/', ' ', ' public void testAFewReverseInsertsSmallK_CheckBalance () {', ' testBalance (10, 5, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100, 5, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsSmallK_CheckBalance () {', ' testBalance (100000, 5, false, true);', ' }', ' ', ' public void testAFewReverseInsertsBigK_CheckBalance () {', ' testBalance (10, 100, false, true);', ' }', ' ', ' public void testALotOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100, 100, false, true);', ' }', ' ', ' public void testAHugeNumberOfReverseInsertsBigK_CheckBalance () {', ' testBalance (100000, 100, false, true);', ' }', ' ', '}'] | [{'reason_category': 'If Loop', 'usage_line': 573}] | Function 'shuffle' used at line 573 is defined at line 466 and has a Long-Range dependency.
Variable 'list' used at line 573 is defined at line 563 and has a Short-Range dependency. | {} | {'Function Long-Range': 1, 'Variable Short-Range': 1} |
infilling_java | SparseArrayTester | 58 | 62 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {'] | [' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }'] | ['', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [] | Global_Variable 'curIdx' used at line 58 is defined at line 52 and has a Short-Range dependency.
Variable 'numElements' used at line 59 is defined at line 57 and has a Short-Range dependency.
Global_Variable 'numElements' used at line 59 is defined at line 53 and has a Short-Range dependency.
Variable 'indices' used at line 60 is defined at line 57 and has a Short-Range dependency.
Global_Variable 'indices' used at line 60 is defined at line 54 and has a Short-Range dependency.
Variable 'data' used at line 61 is defined at line 57 and has a Short-Range dependency.
Global_Variable 'data' used at line 61 is defined at line 55 and has a Short-Range dependency. | {} | {'Global_Variable Short-Range': 4, 'Variable Short-Range': 3} |
infilling_java | SparseArrayTester | 65 | 66 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {'] | [' return (curIdx+1) < numElements;', ' }'] | ['', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [] | Global_Variable 'curIdx' used at line 65 is defined at line 52 and has a Medium-Range dependency.
Global_Variable 'numElements' used at line 65 is defined at line 53 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 2} |
infilling_java | SparseArrayTester | 69 | 71 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {'] | [' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }'] | [' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [] | Global_Variable 'curIdx' used at line 69 is defined at line 52 and has a Medium-Range dependency.
Global_Variable 'indices' used at line 70 is defined at line 54 and has a Medium-Range dependency.
Global_Variable 'curIdx' used at line 70 is defined at line 69 and has a Short-Range dependency.
Global_Variable 'data' used at line 70 is defined at line 55 and has a Medium-Range dependency. | {} | {'Global_Variable Medium-Range': 3, 'Global_Variable Short-Range': 1} |
infilling_java | SparseArrayTester | 74 | 75 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {'] | [' throw new UnsupportedOperationException();', ' }'] | ['}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [] | null | {} | null |
infilling_java | SparseArrayTester | 89 | 90 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {'] | [' temp[i] = indices[i]; ', ' }'] | [' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'Loop Body', 'usage_line': 89}, {'reason_category': 'Loop Body', 'usage_line': 90}] | Global_Variable 'indices' used at line 89 is defined at line 79 and has a Short-Range dependency.
Variable 'i' used at line 89 is defined at line 88 and has a Short-Range dependency.
Variable 'temp' used at line 89 is defined at line 87 and has a Short-Range dependency. | {'Loop Body': 2} | {'Global_Variable Short-Range': 1, 'Variable Short-Range': 2} |
infilling_java | SparseArrayTester | 86 | 93 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {'] | [' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }'] | [' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'Define Stop Criteria', 'usage_line': 88}, {'reason_category': 'Loop Body', 'usage_line': 89}, {'reason_category': 'Loop Body', 'usage_line': 90}] | Global_Variable 'data' used at line 86 is defined at line 80 and has a Short-Range dependency.
Global_Variable 'lastSlot' used at line 86 is defined at line 82 and has a Short-Range dependency.
Global_Variable 'lastSlot' used at line 87 is defined at line 82 and has a Short-Range dependency.
Variable 'i' used at line 88 is defined at line 88 and has a Short-Range dependency.
Global_Variable 'numElements' used at line 88 is defined at line 81 and has a Short-Range dependency.
Global_Variable 'indices' used at line 89 is defined at line 79 and has a Short-Range dependency.
Variable 'i' used at line 89 is defined at line 88 and has a Short-Range dependency.
Variable 'temp' used at line 89 is defined at line 87 and has a Short-Range dependency.
Variable 'temp' used at line 91 is defined at line 87 and has a Short-Range dependency.
Global_Variable 'indices' used at line 91 is defined at line 79 and has a Medium-Range dependency.
Global_Variable 'lastSlot' used at line 92 is defined at line 82 and has a Short-Range dependency. | {'Define Stop Criteria': 1, 'Loop Body': 2} | {'Global_Variable Short-Range': 6, 'Variable Short-Range': 4, 'Global_Variable Medium-Range': 1} |
infilling_java | SparseArrayTester | 111 | 113 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {'] | [' data.add (element);', ' indices[numElements] = position;', ' '] | [" // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'If Body', 'usage_line': 111}, {'reason_category': 'If Body', 'usage_line': 112}, {'reason_category': 'If Body', 'usage_line': 113}] | Global_Variable 'data' used at line 111 is defined at line 80 and has a Long-Range dependency.
Variable 'element' used at line 111 is defined at line 107 and has a Short-Range dependency.
Variable 'position' used at line 112 is defined at line 107 and has a Short-Range dependency.
Global_Variable 'indices' used at line 112 is defined at line 79 and has a Long-Range dependency.
Global_Variable 'numElements' used at line 112 is defined at line 81 and has a Long-Range dependency. | {'If Body': 3} | {'Global_Variable Long-Range': 3, 'Variable Short-Range': 2} |
infilling_java | SparseArrayTester | 120 | 122 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {'] | [' data.setElementAt (element, i);', ' return;', ' }'] | [' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'Else Reasoning', 'usage_line': 120}, {'reason_category': 'Loop Body', 'usage_line': 120}, {'reason_category': 'If Body', 'usage_line': 120}, {'reason_category': 'Else Reasoning', 'usage_line': 121}, {'reason_category': 'Loop Body', 'usage_line': 121}, {'reason_category': 'If Body', 'usage_line': 121}, {'reason_category': 'Else Reasoning', 'usage_line': 122}, {'reason_category': 'Loop Body', 'usage_line': 122}, {'reason_category': 'If Body', 'usage_line': 122}] | Global_Variable 'data' used at line 120 is defined at line 80 and has a Long-Range dependency.
Variable 'element' used at line 120 is defined at line 107 and has a Medium-Range dependency.
Variable 'i' used at line 120 is defined at line 118 and has a Short-Range dependency. | {'Else Reasoning': 3, 'Loop Body': 3, 'If Body': 3} | {'Global_Variable Long-Range': 1, 'Variable Medium-Range': 1, 'Variable Short-Range': 1} |
infilling_java | SparseArrayTester | 128 | 129 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {'] | [' indices[pos] = indices[pos - 1];', ' }'] | [' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) ', ' doubleCapacity ();', ' }', '', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'Else Reasoning', 'usage_line': 128}, {'reason_category': 'Loop Body', 'usage_line': 128}, {'reason_category': 'Else Reasoning', 'usage_line': 129}, {'reason_category': 'Loop Body', 'usage_line': 129}] | Global_Variable 'indices' used at line 128 is defined at line 112 and has a Medium-Range dependency.
Variable 'pos' used at line 128 is defined at line 127 and has a Short-Range dependency. | {'Else Reasoning': 2, 'Loop Body': 2} | {'Global_Variable Medium-Range': 1, 'Variable Short-Range': 1} |
infilling_java | SparseArrayTester | 136 | 137 | ['import junit.framework.TestCase;', 'import java.util.Calendar;', 'import java.util.*;', '', '', '/**', ' * An interface to an indexed element with an integer index into its', ' * enclosing container and data of parameterized type T.', ' */', 'interface IIndexedData<T> {', ' /**', ' * Get index of this item.', ' *', ' * @return index in enclosing container', ' */', ' int getIndex();', '', ' /**', ' * Get data.', ' *', ' * @return data element', ' */', ' T getData();', '}', '', 'interface ISparseArray<T> extends Iterable<IIndexedData<T>> {', ' /**', ' * Add element to the array at position.', ' * ', ' * @param position position in the array', ' * @param element data to place in the array', ' */', ' void put (int position, T element);', '', ' /**', ' * Get element at the given position.', ' *', ' * @param position position in the array', ' * @return element at that position or null if there is none', ' */', ' T get (int position);', '', ' /**', ' * Create an iterator over the array.', ' *', ' * @return an iterator over the sparse array', ' */', ' Iterator<IIndexedData<T>> iterator ();', '}', '', 'class LinearIndexedIterator<T> implements Iterator<IIndexedData<T>> {', ' private int curIdx;', ' private int numElements;', ' private int [] indices;', ' private Vector<T> data;', '', ' public LinearIndexedIterator (int [] indices, Vector<T> data, int numElements) {', ' this.curIdx = -1;', ' this.numElements = numElements;', ' this.indices = indices;', ' this.data = data;', ' }', '', ' public boolean hasNext() {', ' return (curIdx+1) < numElements;', ' }', '', ' public IndexedData<T> next() {', ' curIdx++;', ' return new IndexedData<T> (indices[curIdx], data.get(curIdx));', ' }', ' ', ' public void remove() throws UnsupportedOperationException {', ' throw new UnsupportedOperationException();', ' }', '}', '', 'class LinearSparseArray<T> implements ISparseArray<T> {', ' private int [] indices;', ' private Vector <T> data;', ' private int numElements;', ' private int lastSlot;', ' private int lastSlotReturned;', '', ' private void doubleCapacity () {', ' data.ensureCapacity (lastSlot * 2);', ' int [] temp = new int [lastSlot * 2];', ' for (int i = 0; i < numElements; i++) {', ' temp[i] = indices[i]; ', ' }', ' indices = temp;', ' lastSlot *= 2;', ' }', ' ', ' public LinearIndexedIterator<T> iterator () {', ' return new LinearIndexedIterator<T> (indices, data, numElements);', ' }', ' ', ' public LinearSparseArray(int initialSize) {', ' indices = new int[initialSize];', ' data = new Vector<T> (initialSize);', ' numElements = 0;', ' lastSlotReturned = -1;', ' lastSlot = initialSize;', ' }', '', ' public void put (int position, T element) {', ' ', ' // first see if it is OK to just append', ' if (numElements == 0 || position > indices[numElements - 1]) {', ' data.add (element);', ' indices[numElements] = position;', ' ', " // if the one ew are adding is not the largest, can't just append", ' } else {', '', ' // first check to see if we have data at that position', ' for (int i = 0; i < numElements; i++) {', ' if (indices[i] == position) {', ' data.setElementAt (element, i);', ' return;', ' }', ' }', ' ', ' // if we made it here, there is no data at the position', ' int pos;', ' for (pos = numElements; pos > 0 && indices[pos - 1] > position; pos--) {', ' indices[pos] = indices[pos - 1];', ' }', ' indices[pos] = position;', ' data.add (pos, element);', ' }', ' ', ' numElements++;', ' if (numElements == lastSlot) '] | [' doubleCapacity ();', ' }'] | ['', ' public T get (int position) {', '', ' // first we find an index value that is less than or equal to the position we want', ' for (; lastSlotReturned >= 0 && indices[lastSlotReturned] >= position; lastSlotReturned--);', ' ', ' // now we go up, and find the first one that is bigger than what we want', ' for (; lastSlotReturned + 1 < numElements && indices[lastSlotReturned + 1] <= position; lastSlotReturned++);', ' ', ' // now there are three cases... if we are at position -1, then we have a very small guy', ' if (lastSlotReturned == -1)', ' return null;', ' ', " // if the guy where we are is less than what we want, we didn't find it", ' if (indices[lastSlotReturned] != position)', ' return null;', ' ', ' // otherwise, we got it!', ' return data.get(lastSlotReturned);', ' }', '}', '', 'class TreeSparseArray<T> implements ISparseArray<T> {', ' private TreeMap<Integer, T> array;', '', ' public TreeSparseArray() {', ' array = new TreeMap<Integer, T>();', ' }', '', ' public void put (int position, T element) {', ' array.put(position, element);', ' }', '', ' public T get (int position) {', ' return array.get(position);', ' }', '', ' public IndexedIterator<T> iterator () {', ' return new IndexedIterator<T> (array);', ' }', '}', '', '/**', ' * A JUnit test case class.', ' * Every method starting with the word "test" will be called when running', ' * the test with JUnit.', ' */', 'public class SparseArrayTester extends TestCase {', ' ', ' /**', ' * Checks to see if an observed value is close enough to the expected value', ' */', ' private void checkCloseEnough (double observed, double goal, int pos) { ', ' ', ' // first compute the allowed error ', ' double allowedError = goal * 10e-5; ', ' if (allowedError < 10e-5) ', ' allowedError = 10e-5; ', ' ', ' // if it is too large, then fail ', ' if (!(observed > goal - allowedError && observed < goal + allowedError)) ', ' if (pos != -1) ', ' fail ("Got " + observed + " at pos " + pos + ", expected " + goal); ', ' else ', ' fail ("Got " + observed + ", expected " + goal); ', ' } ', ' ', ' /**', ' * This does a bunch of inserts to the array that is being tested, then', ' * it does a scan through the array. The duration of the test in msec is', ' * returned to the caller', ' */', ' private long doInsertThenScan (ISparseArray <Double> myArray) {', ' ', ' // This test tries to simulate how a spare array might be used ', ' // when it is embedded inside of a sparse double vector. Someone first', ' // adds a bunch of data into specific slots in the sparse double vector, and', ' // then they scan through the sparse double vector from start to finish. This', ' // has the effect of generating a bunch of calls to "get" in the underlying ', ' // sparse array, in sequence. ', ' ', ' // get the time', ' long msec = Calendar.getInstance().getTimeInMillis();', ' ', ' // add a bunch of stuff into it', ' System.out.println ("Doing the inserts...");', ' for (int i = 0; i < 1000000; i++) {', ' if (i % 100000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 100000);', ' ', ' // put one item at an even position', ' myArray.put (i * 10, i * 1.0);', ' ', ' // and put another one at an odd position', ' myArray.put (i * 10 + 3, i * 1.1);', ' }', ' ', ' // now, iterate through the list', ' System.out.println ("\\nDoing the lookups...");', ' double total = 0.0;', ' ', ' // note that we are only going to look at the data in the even positions', ' for (int i = 0; i < 20000000; i += 2) {', ' if (i % 2000000 == 0)', ' System.out.format ("%d%% done ", i * 10 / 2000000);', ' Double temp = myArray.get (i);', ' ', ' // if we got back a null, there was no data there', ' if (temp != null)', ' total += temp;', ' }', ' ', ' System.out.println ();', ' ', ' // get the time again', ' msec = Calendar.getInstance().getTimeInMillis() - msec;', ' ', ' // and vertify the total', ' checkCloseEnough (total, 1000000.0 * 1000001.0 / 2.0, -1);', ' ', ' // and return the time', ' return msec; ', ' }', ' ', ' /**', ' * Make sure that a single value can be correctly stored and extracted.', ' */', ' private void superSimpleTester (ISparseArray <Double> myArray) {', ' myArray.put (12, 3.4);', ' if (myArray.get (0) != null || myArray.get (14) != null) ', ' fail ("Expected a null!");', ' checkCloseEnough (myArray.get (12), 3.4, 12);', ' }', '', ' /**', ' * This puts some data in ascending order, then puts some data in the front', ' * of the array in ascending order, and then makes sure it can all come', ' * out once again.', ' */', ' private void moreComplexTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 100; i < 10000; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 10, i * 1.0);', ' }', ' ', ' for (int i = 0; i < 10000; i++) {', ' if (myArray.get (i * 10 + 1) != null)', ' fail ("Expected a null at pos " + i * 10 + 1);', ' }', ' ', ' for (int i = 100; i < 10000; i++) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' for (int i = 99; i >= 0; i--) {', ' checkCloseEnough (myArray.get (i * 10), i * 1.0, i * 10);', ' }', ' ', ' }', ' ', ' /**', ' * This puts data in using a weird order, and then extracts it using another ', ' * weird order', ' */', ' private void strangeOrderTester (ISparseArray <Double> myArray) {', ' ', ' for (int i = 0; i < 500; i++) {', ' myArray.put (500 + i, (500 + i) * 4.99);', ' myArray.put (499 - i, (499 - i) * 5.99);', ' }', ' ', ' for (int i = 0; i < 500; i++) {', ' checkCloseEnough (myArray.get (i), i * 5.99, i);', ' checkCloseEnough (myArray.get (999 - i), (999 - i) * 4.99, 999 - i);', ' }', ' }', ' ', ' /**', ' * Adds 1000 values into the array, and then sees if they are correctly extracted', ' * using an iterator.', ' */', ' private void iteratorTester (ISparseArray <Double> myArray) {', ' ', ' // put a bunch of values in', ' for (int i = 0; i < 1000; i++) {', ' myArray.put (i * 100, i * 23.45); ', ' }', ' ', ' // then create an iterator and make sure we can extract them once again', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' int counter = 0;', ' while (myIter.hasNext ()) {', ' IIndexedData <Double> curOne = myIter.next ();', ' if (curOne.getIndex () != counter * 100)', ' fail ("I was using an iterator; expected index " + counter * 100 + " but got " + curOne.getIndex ());', ' checkCloseEnough (curOne.getData (), counter * 23.45, counter * 100);', ' counter++;', ' }', ' }', ' ', ' /** ', ' * Used to see if the array can correctly accept writes and rewrites of ', ' * the same slots, and get the re-written values back', ' */', ' private void rewriteTester (ISparseArray <Double> myArray) {', ' for (int i = 0; i < 100; i++) {', ' myArray.put (i * 4, i * 9.34); ', ' }', ' for (int i = 99; i >= 0; i--) {', ' myArray.put (i * 4, i * 19.34); ', ' }', ' for (int i = 0; i < 100; i++) {', ' checkCloseEnough (myArray.get (i * 4), i * 19.34, i * 4);', ' } ', ' }', ' ', ' /**', ' * Checks both arrays to make sure that if there is no data, you can', ' * still correctly create and use an iterator.', ' */', ' public void testEmptyIterator () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' Iterator <IIndexedData <Double>> myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The linear sparse array should have had no data!");', ' }', ' myArray = new TreeSparseArray <Double> ();', ' myIter = myArray.iterator ();', ' if (myIter.hasNext ()) {', ' fail ("The tree sparse array should have had no data!");', ' }', ' }', ' ', ' /**', ' * Checks to see if you can put a bunch of data in, and then get it out', ' * again using an iterator.', ' */', ' public void testIteratorLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' iteratorTester (myArray);', ' }', ' ', ' public void testIteratorTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' iteratorTester (myArray);', ' }', ' ', ' /**', ' * Tests whether one can write data into the array, then write over it with', ' * new data, and get the re-written values out once again', ' */', ' public void testRewriteLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' rewriteTester (myArray);', ' }', ' ', ' public void testRewriteTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' rewriteTester (myArray);', ' }', ' ', ' /** Inserts in ascending and then in descending order, and then does a lot', ' * of gets to check to make sure the correct data is in there', ' */', ' public void testMoreComplexLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' moreComplexTester (myArray);', ' }', ' ', ' public void testMoreComplexTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' moreComplexTester (myArray);', ' }', ' ', ' /**', ' * Tests a single insert; tries to retreive that insert, and checks a couple', ' * of slots for null.', ' */', ' public void testSuperSimpleInsertTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' superSimpleTester (myArray);', ' }', ' ', ' public void testSuperSimpleInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' superSimpleTester (myArray);', ' }', ' ', ' /**', ' * This does a bunch of backwards-order puts and gets into a linear sparse array', ' */', ' public void testBackwardsInsertLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' ', ' for (int i = 1000; i < 0; i--)', ' myArray.put (i, i * 2.0);', ' ', ' for (int i = 1000; i < 0; i--)', ' checkCloseEnough (myArray.get (i), i * 2.0, i);', ' }', ' ', ' /**', ' * These do a bunch of gets in puts in a non-linear order', ' */', ' public void testStrageOrderLinear () {', ' ISparseArray <Double> myArray = new LinearSparseArray <Double> (2000);', ' strangeOrderTester (myArray);', ' }', ' ', ' public void testStrageOrdeTree () {', ' ISparseArray <Double> myArray = new TreeSparseArray <Double> ();', ' strangeOrderTester (myArray);', ' }', ' ', ' /**', ' * Used to check the raw speed of sequential access in the implementation', ' */', ' public void speedCheck (double goal) {', ' ', ' // create two sparse arrays', ' ISparseArray <Double> myArray1 = new SparseArray <Double> ();', ' ISparseArray <Double> myArray2 = new LinearSparseArray <Double> (2000);', ' ', ' // test the first one', ' System.out.println ("**************** SPEED TEST ******************");', ' System.out.println ("Testing the provided, tree-based sparse array.");', ' long firstTime = doInsertThenScan (myArray1);', ' ', ' // test the second one', ' System.out.println ("Testing the linear sparse array.");', ' long secTime = doInsertThenScan (myArray2);', ' ', ' System.out.format ("The linear took %g%% as long as the tree-based\\n", (secTime * 100.0) / firstTime);', ' System.out.format ("The goal is %g%% or less.\\n", goal);', ' ', ' if ((secTime * 100.0) / firstTime > goal)', ' fail ("Not fast enough to pass the speed check!");', ' ', ' System.out.println ("**********************************************");', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 2/3 of the time comapred to SparseArray', ' */', ' public void testSpeedMedium () {', ' speedCheck (66.67); ', ' }', ' ', ' /**', ' * See if the linear sparse array takes less than 1/2 of the time comapred to SparseArray', ' */', ' public void testSpeedFast () {', ' speedCheck (50.0); ', ' }', '}', ''] | [{'reason_category': 'If Body', 'usage_line': 136}] | Function 'doubleCapacity' used at line 136 is defined at line 85 and has a Long-Range dependency. | {'If Body': 1} | {'Function Long-Range': 1} |