Java Code Examples for org.apache.commons.math.MathRuntimeException#createInternalError()

The following examples show how to use org.apache.commons.math.MathRuntimeException#createInternalError() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HarmonicFitter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Fit an harmonic function to the observed points.
 * @return harmonic function best fitting the observed points
 * @throws OptimizationException if the sample is too short or if
 * the first guess cannot be computed
 */
public HarmonicFunction fit() throws OptimizationException {
    try {

        // shall we compute the first guess of the parameters ourselves ?
        if (parameters == null) {
            final WeightedObservedPoint[] observations = fitter.getObservations();
            if (observations.length < 4) {
                throw new OptimizationException("sample contains {0} observed points, at least {1} are required",
                                                observations.length, 4);
            }

            HarmonicCoefficientsGuesser guesser = new HarmonicCoefficientsGuesser(observations);
            guesser.guess();
            parameters = new double[] {
                             guesser.getGuessedAmplitude(),
                             guesser.getGuessedPulsation(),
                             guesser.getGuessedPhase()
                        };

        }

        double[] fitted = fitter.fit(new ParametricHarmonicFunction(), parameters);
        return new HarmonicFunction(fitted[0], fitted[1], fitted[2]);

    } catch (FunctionEvaluationException fee) {
        // this should never happen
        throw MathRuntimeException.createInternalError(fee);
    }
}
 
Example 2
Source File: PolynomialFitter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Get the polynomial fitting the weighted (x, y) points.
 * @return polynomial function best fitting the observed points
 * @exception OptimizationException if the algorithm failed to converge
 */
public PolynomialFunction fit()
    throws OptimizationException {
    try {
        return new PolynomialFunction(fitter.fit(new ParametricPolynomial(), new double[degree + 1]));
    } catch (FunctionEvaluationException fee) {
        // this should never happen
        throw MathRuntimeException.createInternalError(fee);
    }
}
 
Example 3
Source File: PolynomialFitter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Get the polynomial fitting the weighted (x, y) points.
 * @return polynomial function best fitting the observed points
 * @exception OptimizationException if the algorithm failed to converge
 */
public PolynomialFunction fit()
    throws OptimizationException {
    try {
        return new PolynomialFunction(fitter.fit(new ParametricPolynomial(), new double[degree + 1]));
    } catch (FunctionEvaluationException fee) {
        // this should never happen
        throw MathRuntimeException.createInternalError(fee);
    }
}
 
Example 4
Source File: NaturalRanking.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Resolve a sequence of ties, using the configured {@link TiesStrategy}.
 * The input <code>ranks</code> array is expected to take the same value
 * for all indices in <code>tiesTrace</code>.  The common value is recoded
 * according to the tiesStrategy. For example, if ranks = <5,8,2,6,2,7,1,2>,
 * tiesTrace = <2,4,7> and tiesStrategy is MINIMUM, ranks will be unchanged.
 * The same array and trace with tiesStrategy AVERAGE will come out
 * <5,8,3,6,3,7,1,3>.
 *
 * @param ranks array of ranks
 * @param tiesTrace list of indices where <code>ranks</code> is constant
 * -- that is, for any i and j in TiesTrace, <code> ranks[i] == ranks[j]
 * </code>
 */
private void resolveTie(double[] ranks, List<Integer> tiesTrace) {

    // constant value of ranks over tiesTrace
    final double c = ranks[tiesTrace.get(0)];

    // length of sequence of tied ranks
    final int length = tiesTrace.size();

    switch (tiesStrategy) {
        case  AVERAGE:  // Replace ranks with average
            fill(ranks, tiesTrace, (2 * c + length - 1) / 2d);
            break;
        case MAXIMUM:   // Replace ranks with maximum values
            fill(ranks, tiesTrace, c + length - 1);
            break;
        case MINIMUM:   // Replace ties with minimum
            fill(ranks, tiesTrace, c);
            break;
        case RANDOM:    // Fill with random integral values in [c, c + length - 1]
            Iterator<Integer> iterator = tiesTrace.iterator();
            long f = Math.round(c);
            while (iterator.hasNext()) {
                ranks[iterator.next()] =
                    randomData.nextLong(f, f + length - 1);
            }
            break;
        case SEQUENTIAL:  // Fill sequentially from c to c + length - 1
            // walk and fill
            iterator = tiesTrace.iterator();
            f = Math.round(c);
            int i = 0;
            while (iterator.hasNext()) {
                ranks[iterator.next()] = f + i++;
            }
            break;
        default: // this should not happen unless TiesStrategy enum is changed
            throw MathRuntimeException.createInternalError(null);
    }
}
 
Example 5
Source File: HarmonicFitter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Fit an harmonic function to the observed points.
 * @return harmonic function best fitting the observed points
 * @throws OptimizationException if the sample is too short or if
 * the first guess cannot be computed
 */
public HarmonicFunction fit() throws OptimizationException {
    try {

        // shall we compute the first guess of the parameters ourselves ?
        if (parameters == null) {
            final WeightedObservedPoint[] observations = fitter.getObservations();
            if (observations.length < 4) {
                throw new OptimizationException("sample contains {0} observed points, at least {1} are required",
                                                observations.length, 4);
            }

            HarmonicCoefficientsGuesser guesser = new HarmonicCoefficientsGuesser(observations);
            guesser.guess();
            parameters = new double[] {
                             guesser.getGuessedAmplitude(),
                             guesser.getGuessedPulsation(),
                             guesser.getGuessedPhase()
                        };

        }

        double[] fitted = fitter.fit(new ParametricHarmonicFunction(), parameters);
        return new HarmonicFunction(fitted[0], fitted[1], fitted[2]);

    } catch (FunctionEvaluationException fee) {
        // this should never happen
        throw MathRuntimeException.createInternalError(fee);
    }
}
 
Example 6
Source File: PolynomialFitter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Get the polynomial fitting the weighted (x, y) points.
 * @return polynomial function best fitting the observed points
 * @exception OptimizationException if the algorithm failed to converge
 */
public PolynomialFunction fit()
    throws OptimizationException {
    try {
        return new PolynomialFunction(fitter.fit(new ParametricPolynomial(), new double[degree + 1]));
    } catch (FunctionEvaluationException fee) {
        // this should never happen
        throw MathRuntimeException.createInternalError(fee);
    }
}
 
Example 7
Source File: PolynomialFitter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Get the polynomial fitting the weighted (x, y) points.
 * @return polynomial function best fitting the observed points
 * @exception OptimizationException if the algorithm failed to converge
 */
public PolynomialFunction fit()
    throws OptimizationException {
    try {
        return new PolynomialFunction(fitter.fit(new ParametricPolynomial(), new double[degree + 1]));
    } catch (FunctionEvaluationException fee) {
        // this should never happen
        throw MathRuntimeException.createInternalError(fee);
    }
}
 
Example 8
Source File: NaturalRanking.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Resolve a sequence of ties, using the configured {@link TiesStrategy}.
 * The input <code>ranks</code> array is expected to take the same value
 * for all indices in <code>tiesTrace</code>.  The common value is recoded
 * according to the tiesStrategy. For example, if ranks = <5,8,2,6,2,7,1,2>,
 * tiesTrace = <2,4,7> and tiesStrategy is MINIMUM, ranks will be unchanged.
 * The same array and trace with tiesStrategy AVERAGE will come out
 * <5,8,3,6,3,7,1,3>.
 *
 * @param ranks array of ranks
 * @param tiesTrace list of indices where <code>ranks</code> is constant
 * -- that is, for any i and j in TiesTrace, <code> ranks[i] == ranks[j]
 * </code>
 */
private void resolveTie(double[] ranks, List<Integer> tiesTrace) {

    // constant value of ranks over tiesTrace
    final double c = ranks[tiesTrace.get(0)];

    // length of sequence of tied ranks
    final int length = tiesTrace.size();

    switch (tiesStrategy) {
        case  AVERAGE:  // Replace ranks with average
            fill(ranks, tiesTrace, (2 * c + length - 1) / 2d);
            break;
        case MAXIMUM:   // Replace ranks with maximum values
            fill(ranks, tiesTrace, c + length - 1);
            break;
        case MINIMUM:   // Replace ties with minimum
            fill(ranks, tiesTrace, c);
            break;
        case RANDOM:    // Fill with random integral values in [c, c + length - 1]
            Iterator<Integer> iterator = tiesTrace.iterator();
            long f = Math.round(c);
            while (iterator.hasNext()) {
                ranks[iterator.next()] =
                    randomData.nextLong(f, f + length - 1);
            }
            break;
        case SEQUENTIAL:  // Fill sequentially from c to c + length - 1
            // walk and fill
            iterator = tiesTrace.iterator();
            f = Math.round(c);
            int i = 0;
            while (iterator.hasNext()) {
                ranks[iterator.next()] = f + i++;
            }
            break;
        default: // this should not happen unless TiesStrategy enum is changed
            throw MathRuntimeException.createInternalError(null);
    }
}
 
Example 9
Source File: PolynomialFitter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Get the polynomial fitting the weighted (x, y) points.
 * @return polynomial function best fitting the observed points
 * @exception OptimizationException if the algorithm failed to converge
 */
public PolynomialFunction fit()
    throws OptimizationException {
    try {
        return new PolynomialFunction(fitter.fit(new ParametricPolynomial(), new double[degree + 1]));
    } catch (FunctionEvaluationException fee) {
        // this should never happen
        throw MathRuntimeException.createInternalError(fee);
    }
}
 
Example 10
Source File: HarmonicFitter.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Fit an harmonic function to the observed points.
 * @return harmonic function best fitting the observed points
 * @throws OptimizationException if the sample is too short or if
 * the first guess cannot be computed
 */
public HarmonicFunction fit() throws OptimizationException {
    try {

        // shall we compute the first guess of the parameters ourselves ?
        if (parameters == null) {
            final WeightedObservedPoint[] observations = fitter.getObservations();
            if (observations.length < 4) {
                throw new OptimizationException("sample contains {0} observed points, at least {1} are required",
                                                observations.length, 4);
            }

            HarmonicCoefficientsGuesser guesser = new HarmonicCoefficientsGuesser(observations);
            guesser.guess();
            parameters = new double[] {
                             guesser.getGuessedAmplitude(),
                             guesser.getGuessedPulsation(),
                             guesser.getGuessedPhase()
                        };

        }

        double[] fitted = fitter.fit(new ParametricHarmonicFunction(), parameters);
        return new HarmonicFunction(fitted[0], fitted[1], fitted[2]);

    } catch (FunctionEvaluationException fee) {
        // this should never happen
        throw MathRuntimeException.createInternalError(fee);
    }
}
 
Example 11
Source File: RandomDataImpl.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * <strong>Algorithm Description:</strong> hex strings are generated in
 * 40-byte segments using a 3-step process.
 * <ol>
 * <li>
 * 20 random bytes are generated using the underlying
 * <code>SecureRandom</code>.</li>
 * <li>
 * SHA-1 hash is applied to yield a 20-byte binary digest.</li>
 * <li>
 * Each byte of the binary digest is converted to 2 hex digits.</li>
 * </ol>
 * </p>
 *
 * @param len
 *            the length of the generated string
 * @return the random string
 */
public String nextSecureHexString(int len) {
    if (len <= 0) {
        throw MathRuntimeException.createIllegalArgumentException(
              "length must be positive ({0})", len);
    }

    // Get SecureRandom and setup Digest provider
    SecureRandom secRan = getSecRan();
    MessageDigest alg = null;
    try {
        alg = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException ex) {
        // this should never happen
        throw MathRuntimeException.createInternalError(ex);
    }
    alg.reset();

    // Compute number of iterations required (40 bytes each)
    int numIter = (len / 40) + 1;

    StringBuffer outBuffer = new StringBuffer();
    for (int iter = 1; iter < numIter + 1; iter++) {
        byte[] randomBytes = new byte[40];
        secRan.nextBytes(randomBytes);
        alg.update(randomBytes);

        // Compute hash -- will create 20-byte binary hash
        byte hash[] = alg.digest();

        // Loop over the hash, converting each byte to 2 hex digits
        for (int i = 0; i < hash.length; i++) {
            Integer c = Integer.valueOf(hash[i]);

            /*
             * Add 128 to byte value to make interval 0-255 This guarantees
             * <= 2 hex digits from toHexString() toHexString would
             * otherwise add 2^32 to negative arguments
             */
            String hex = Integer.toHexString(c.intValue() + 128);

            // Keep strings uniform length -- guarantees 40 bytes
            if (hex.length() == 1) {
                hex = "0" + hex;
            }
            outBuffer.append(hex);
        }
    }
    return outBuffer.toString().substring(0, len);
}
 
Example 12
Source File: NaturalRanking.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Rank <code>data</code> using the natural ordering on Doubles, with
 * NaN values handled according to <code>nanStrategy</code> and ties
 * resolved using <code>tiesStrategy.</code>
 *
 * @param data array to be ranked
 * @return array of ranks
 */
public double[] rank(double[] data) {

    // Array recording initial positions of data to be ranked
    IntDoublePair[] ranks = new IntDoublePair[data.length];
    for (int i = 0; i < data.length; i++) {
        ranks[i] = new IntDoublePair(data[i], i);
    }

    // Recode, remove or record positions of NaNs
    List<Integer> nanPositions = null;
    switch (nanStrategy) {
        case MAXIMAL: // Replace NaNs with +INFs
            recodeNaNs(ranks, Double.POSITIVE_INFINITY);
            break;
        case MINIMAL: // Replace NaNs with -INFs
            recodeNaNs(ranks, Double.NEGATIVE_INFINITY);
            break;
        case REMOVED: // Drop NaNs from data
            ranks = removeNaNs(ranks);
            break;
        case FIXED:   // Record positions of NaNs
            nanPositions = getNanPositions(ranks);
            break;
        default: // this should not happen unless NaNStrategy enum is changed
            throw MathRuntimeException.createInternalError(null);
    }

    // Sort the IntDoublePairs
    Arrays.sort(ranks);

    // Walk the sorted array, filling output array using sorted positions,
    // resolving ties as we go
    double[] out = new double[ranks.length];
    int pos = 1;  // position in sorted array
    out[ranks[0].getPosition()] = pos;
    List<Integer> tiesTrace = new ArrayList<Integer>();
    tiesTrace.add(ranks[0].getPosition());
    for (int i = 1; i < ranks.length; i++) {
        if (Double.compare(ranks[i].getValue(), ranks[i - 1].getValue()) > 0) {
            // tie sequence has ended (or had length 1)
            pos = i + 1;
            if (tiesTrace.size() > 1) {  // if seq is nontrivial, resolve
                resolveTie(out, tiesTrace);
            }
            tiesTrace = new ArrayList<Integer>();
            tiesTrace.add(ranks[i].getPosition());
        } else {
            // tie sequence continues
            tiesTrace.add(ranks[i].getPosition());
        }
        out[ranks[i].getPosition()] = pos;
    }
    if (tiesTrace.size() > 1) {  // handle tie sequence at end
        resolveTie(out, tiesTrace);
    }
    if (nanStrategy == NaNStrategy.FIXED) {
        restoreNaNs(out, nanPositions);
    }
    return out;
}
 
Example 13
Source File: RandomDataImpl.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * <strong>Algorithm Description:</strong> hex strings are generated in
 * 40-byte segments using a 3-step process.
 * <ol>
 * <li>
 * 20 random bytes are generated using the underlying
 * <code>SecureRandom</code>.</li>
 * <li>
 * SHA-1 hash is applied to yield a 20-byte binary digest.</li>
 * <li>
 * Each byte of the binary digest is converted to 2 hex digits.</li>
 * </ol>
 * </p>
 *
 * @param len
 *            the length of the generated string
 * @return the random string
 */
public String nextSecureHexString(int len) {
    if (len <= 0) {
        throw MathRuntimeException.createIllegalArgumentException(
              "length must be positive ({0})", len);
    }

    // Get SecureRandom and setup Digest provider
    SecureRandom secRan = getSecRan();
    MessageDigest alg = null;
    try {
        alg = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException ex) {
        // this should never happen
        throw MathRuntimeException.createInternalError(ex);
    }
    alg.reset();

    // Compute number of iterations required (40 bytes each)
    int numIter = (len / 40) + 1;

    StringBuffer outBuffer = new StringBuffer();
    for (int iter = 1; iter < numIter + 1; iter++) {
        byte[] randomBytes = new byte[40];
        secRan.nextBytes(randomBytes);
        alg.update(randomBytes);

        // Compute hash -- will create 20-byte binary hash
        byte hash[] = alg.digest();

        // Loop over the hash, converting each byte to 2 hex digits
        for (int i = 0; i < hash.length; i++) {
            Integer c = Integer.valueOf(hash[i]);

            /*
             * Add 128 to byte value to make interval 0-255 This guarantees
             * <= 2 hex digits from toHexString() toHexString would
             * otherwise add 2^32 to negative arguments
             */
            String hex = Integer.toHexString(c.intValue() + 128);

            // Keep strings uniform length -- guarantees 40 bytes
            if (hex.length() == 1) {
                hex = "0" + hex;
            }
            outBuffer.append(hex);
        }
    }
    return outBuffer.toString().substring(0, len);
}
 
Example 14
Source File: NaturalRanking.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Rank <code>data</code> using the natural ordering on Doubles, with
 * NaN values handled according to <code>nanStrategy</code> and ties
 * resolved using <code>tiesStrategy.</code>
 *
 * @param data array to be ranked
 * @return array of ranks
 */
public double[] rank(double[] data) {

    // Array recording initial positions of data to be ranked
    IntDoublePair[] ranks = new IntDoublePair[data.length];
    for (int i = 0; i < data.length; i++) {
        ranks[i] = new IntDoublePair(data[i], i);
    }

    // Recode, remove or record positions of NaNs
    List<Integer> nanPositions = null;
    switch (nanStrategy) {
        case MAXIMAL: // Replace NaNs with +INFs
            recodeNaNs(ranks, Double.POSITIVE_INFINITY);
            break;
        case MINIMAL: // Replace NaNs with -INFs
            recodeNaNs(ranks, Double.NEGATIVE_INFINITY);
            break;
        case REMOVED: // Drop NaNs from data
            ranks = removeNaNs(ranks);
            break;
        case FIXED:   // Record positions of NaNs
            nanPositions = getNanPositions(ranks);
            break;
        default: // this should not happen unless NaNStrategy enum is changed
            throw MathRuntimeException.createInternalError(null);
    }

    // Sort the IntDoublePairs
    Arrays.sort(ranks);

    // Walk the sorted array, filling output array using sorted positions,
    // resolving ties as we go
    double[] out = new double[ranks.length];
    int pos = 1;  // position in sorted array
    out[ranks[0].getPosition()] = pos;
    List<Integer> tiesTrace = new ArrayList<Integer>();
    tiesTrace.add(ranks[0].getPosition());
    for (int i = 1; i < ranks.length; i++) {
        if (Double.compare(ranks[i].getValue(), ranks[i - 1].getValue()) > 0) {
            // tie sequence has ended (or had length 1)
            pos = i + 1;
            if (tiesTrace.size() > 1) {  // if seq is nontrivial, resolve
                resolveTie(out, tiesTrace);
            }
            tiesTrace = new ArrayList<Integer>();
            tiesTrace.add(ranks[i].getPosition());
        } else {
            // tie sequence continues
            tiesTrace.add(ranks[i].getPosition());
        }
        out[ranks[i].getPosition()] = pos;
    }
    if (tiesTrace.size() > 1) {  // handle tie sequence at end
        resolveTie(out, tiesTrace);
    }
    if (nanStrategy == NaNStrategy.FIXED) {
        restoreNaNs(out, nanPositions);
    }
    return out;
}
 
Example 15
Source File: NaturalRanking.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Rank <code>data</code> using the natural ordering on Doubles, with
 * NaN values handled according to <code>nanStrategy</code> and ties
 * resolved using <code>tiesStrategy.</code>
 *
 * @param data array to be ranked
 * @return array of ranks
 */
public double[] rank(double[] data) {

    // Array recording initial positions of data to be ranked
    IntDoublePair[] ranks = new IntDoublePair[data.length];
    for (int i = 0; i < data.length; i++) {
        ranks[i] = new IntDoublePair(data[i], i);
    }

    // Recode, remove or record positions of NaNs
    List<Integer> nanPositions = null;
    switch (nanStrategy) {
        case MAXIMAL: // Replace NaNs with +INFs
            recodeNaNs(ranks, Double.POSITIVE_INFINITY);
            break;
        case MINIMAL: // Replace NaNs with -INFs
            recodeNaNs(ranks, Double.NEGATIVE_INFINITY);
            break;
        case REMOVED: // Drop NaNs from data
            ranks = removeNaNs(ranks);
            break;
        case FIXED:   // Record positions of NaNs
            nanPositions = getNanPositions(ranks);
            break;
        default: // this should not happen unless NaNStrategy enum is changed
            throw MathRuntimeException.createInternalError(null);
    }

    // Sort the IntDoublePairs
    Arrays.sort(ranks);

    // Walk the sorted array, filling output array using sorted positions,
    // resolving ties as we go
    double[] out = new double[ranks.length];
    int pos = 1;  // position in sorted array
    out[ranks[0].getPosition()] = pos;
    List<Integer> tiesTrace = new ArrayList<Integer>();
    tiesTrace.add(ranks[0].getPosition());
    for (int i = 1; i < ranks.length; i++) {
        if (Double.compare(ranks[i].getValue(), ranks[i - 1].getValue()) > 0) {
            // tie sequence has ended (or had length 1)
            pos = i + 1;
            if (tiesTrace.size() > 1) {  // if seq is nontrivial, resolve
                resolveTie(out, tiesTrace);
            }
            tiesTrace = new ArrayList<Integer>();
            tiesTrace.add(ranks[i].getPosition());
        } else {
            // tie sequence continues
            tiesTrace.add(ranks[i].getPosition());
        }
        out[ranks[i].getPosition()] = pos;
    }
    if (tiesTrace.size() > 1) {  // handle tie sequence at end
        resolveTie(out, tiesTrace);
    }
    if (nanStrategy == NaNStrategy.FIXED) {
        restoreNaNs(out, nanPositions);
    }
    return out;
}
 
Example 16
Source File: RandomDataImpl.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * <strong>Algorithm Description:</strong> hex strings are generated in
 * 40-byte segments using a 3-step process.
 * <ol>
 * <li>
 * 20 random bytes are generated using the underlying
 * <code>SecureRandom</code>.</li>
 * <li>
 * SHA-1 hash is applied to yield a 20-byte binary digest.</li>
 * <li>
 * Each byte of the binary digest is converted to 2 hex digits.</li>
 * </ol>
 * </p>
 *
 * @param len
 *            the length of the generated string
 * @return the random string
 */
public String nextSecureHexString(int len) {
    if (len <= 0) {
        throw MathRuntimeException.createIllegalArgumentException(
              "length must be positive ({0})", len);
    }

    // Get SecureRandom and setup Digest provider
    SecureRandom secRan = getSecRan();
    MessageDigest alg = null;
    try {
        alg = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException ex) {
        // this should never happen
        throw MathRuntimeException.createInternalError(ex);
    }
    alg.reset();

    // Compute number of iterations required (40 bytes each)
    int numIter = (len / 40) + 1;

    StringBuffer outBuffer = new StringBuffer();
    for (int iter = 1; iter < numIter + 1; iter++) {
        byte[] randomBytes = new byte[40];
        secRan.nextBytes(randomBytes);
        alg.update(randomBytes);

        // Compute hash -- will create 20-byte binary hash
        byte hash[] = alg.digest();

        // Loop over the hash, converting each byte to 2 hex digits
        for (int i = 0; i < hash.length; i++) {
            Integer c = Integer.valueOf(hash[i]);

            /*
             * Add 128 to byte value to make interval 0-255 This guarantees
             * <= 2 hex digits from toHexString() toHexString would
             * otherwise add 2^32 to negative arguments
             */
            String hex = Integer.toHexString(c.intValue() + 128);

            // Keep strings uniform length -- guarantees 40 bytes
            if (hex.length() == 1) {
                hex = "0" + hex;
            }
            outBuffer.append(hex);
        }
    }
    return outBuffer.toString().substring(0, len);
}
 
Example 17
Source File: NaturalRanking.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Rank <code>data</code> using the natural ordering on Doubles, with
 * NaN values handled according to <code>nanStrategy</code> and ties
 * resolved using <code>tiesStrategy.</code>
 *
 * @param data array to be ranked
 * @return array of ranks
 */
public double[] rank(double[] data) {

    // Array recording initial positions of data to be ranked
    IntDoublePair[] ranks = new IntDoublePair[data.length];
    for (int i = 0; i < data.length; i++) {
        ranks[i] = new IntDoublePair(data[i], i);
    }

    // Recode, remove or record positions of NaNs
    List<Integer> nanPositions = null;
    switch (nanStrategy) {
        case MAXIMAL: // Replace NaNs with +INFs
            recodeNaNs(ranks, Double.POSITIVE_INFINITY);
            break;
        case MINIMAL: // Replace NaNs with -INFs
            recodeNaNs(ranks, Double.NEGATIVE_INFINITY);
            break;
        case REMOVED: // Drop NaNs from data
            ranks = removeNaNs(ranks);
            break;
        case FIXED:   // Record positions of NaNs
            nanPositions = getNanPositions(ranks);
            break;
        default: // this should not happen unless NaNStrategy enum is changed
            throw MathRuntimeException.createInternalError(null);
    }

    // Sort the IntDoublePairs
    Arrays.sort(ranks);

    // Walk the sorted array, filling output array using sorted positions,
    // resolving ties as we go
    double[] out = new double[ranks.length];
    int pos = 1;  // position in sorted array
    out[ranks[0].getPosition()] = pos;
    List<Integer> tiesTrace = new ArrayList<Integer>();
    tiesTrace.add(ranks[0].getPosition());
    for (int i = 1; i < ranks.length; i++) {
        if (Double.compare(ranks[i].getValue(), ranks[i - 1].getValue()) > 0) {
            // tie sequence has ended (or had length 1)
            pos = i + 1;
            if (tiesTrace.size() > 1) {  // if seq is nontrivial, resolve
                resolveTie(out, tiesTrace);
            }
            tiesTrace = new ArrayList<Integer>();
            tiesTrace.add(ranks[i].getPosition());
        } else {
            // tie sequence continues
            tiesTrace.add(ranks[i].getPosition());
        }
        out[ranks[i].getPosition()] = pos;
    }
    if (tiesTrace.size() > 1) {  // handle tie sequence at end
        resolveTie(out, tiesTrace);
    }
    if (nanStrategy == NaNStrategy.FIXED) {
        restoreNaNs(out, nanPositions);
    }
    return out;
}
 
Example 18
Source File: NaturalRanking.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Rank <code>data</code> using the natural ordering on Doubles, with
 * NaN values handled according to <code>nanStrategy</code> and ties
 * resolved using <code>tiesStrategy.</code>
 *
 * @param data array to be ranked
 * @return array of ranks
 */
public double[] rank(double[] data) {

    // Array recording initial positions of data to be ranked
    IntDoublePair[] ranks = new IntDoublePair[data.length];
    for (int i = 0; i < data.length; i++) {
        ranks[i] = new IntDoublePair(data[i], i);
    }

    // Recode, remove or record positions of NaNs
    List<Integer> nanPositions = null;
    switch (nanStrategy) {
        case MAXIMAL: // Replace NaNs with +INFs
            recodeNaNs(ranks, Double.POSITIVE_INFINITY);
            break;
        case MINIMAL: // Replace NaNs with -INFs
            recodeNaNs(ranks, Double.NEGATIVE_INFINITY);
            break;
        case REMOVED: // Drop NaNs from data
            ranks = removeNaNs(ranks);
            break;
        case FIXED:   // Record positions of NaNs
            nanPositions = getNanPositions(ranks);
            break;
        default: // this should not happen unless NaNStrategy enum is changed
            throw MathRuntimeException.createInternalError(null);
    }

    // Sort the IntDoublePairs
    Arrays.sort(ranks);

    // Walk the sorted array, filling output array using sorted positions,
    // resolving ties as we go
    double[] out = new double[ranks.length];
    int pos = 1;  // position in sorted array
    out[ranks[0].getPosition()] = pos;
    List<Integer> tiesTrace = new ArrayList<Integer>();
    tiesTrace.add(ranks[0].getPosition());
    for (int i = 1; i < ranks.length; i++) {
        if (Double.compare(ranks[i].getValue(), ranks[i - 1].getValue()) > 0) {
            // tie sequence has ended (or had length 1)
            pos = i + 1;
            if (tiesTrace.size() > 1) {  // if seq is nontrivial, resolve
                resolveTie(out, tiesTrace);
            }
            tiesTrace = new ArrayList<Integer>();
            tiesTrace.add(ranks[i].getPosition());
        } else {
            // tie sequence continues
            tiesTrace.add(ranks[i].getPosition());
        }
        out[ranks[i].getPosition()] = pos;
    }
    if (tiesTrace.size() > 1) {  // handle tie sequence at end
        resolveTie(out, tiesTrace);
    }
    if (nanStrategy == NaNStrategy.FIXED) {
        restoreNaNs(out, nanPositions);
    }
    return out;
}
 
Example 19
Source File: NaturalRanking.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Rank <code>data</code> using the natural ordering on Doubles, with
 * NaN values handled according to <code>nanStrategy</code> and ties
 * resolved using <code>tiesStrategy.</code>
 *
 * @param data array to be ranked
 * @return array of ranks
 */
public double[] rank(double[] data) {

    // Array recording initial positions of data to be ranked
    IntDoublePair[] ranks = new IntDoublePair[data.length];
    for (int i = 0; i < data.length; i++) {
        ranks[i] = new IntDoublePair(data[i], i);
    }

    // Recode, remove or record positions of NaNs
    List<Integer> nanPositions = null;
    switch (nanStrategy) {
        case MAXIMAL: // Replace NaNs with +INFs
            recodeNaNs(ranks, Double.POSITIVE_INFINITY);
            break;
        case MINIMAL: // Replace NaNs with -INFs
            recodeNaNs(ranks, Double.NEGATIVE_INFINITY);
            break;
        case REMOVED: // Drop NaNs from data
            ranks = removeNaNs(ranks);
            break;
        case FIXED:   // Record positions of NaNs
            nanPositions = getNanPositions(ranks);
            break;
        default: // this should not happen unless NaNStrategy enum is changed
            throw MathRuntimeException.createInternalError(null);
    }

    // Sort the IntDoublePairs
    Arrays.sort(ranks);

    // Walk the sorted array, filling output array using sorted positions,
    // resolving ties as we go
    double[] out = new double[ranks.length];
    int pos = 1;  // position in sorted array
    out[ranks[0].getPosition()] = pos;
    List<Integer> tiesTrace = new ArrayList<Integer>();
    tiesTrace.add(ranks[0].getPosition());
    for (int i = 1; i < ranks.length; i++) {
        if (Double.compare(ranks[i].getValue(), ranks[i - 1].getValue()) > 0) {
            // tie sequence has ended (or had length 1)
            pos = i + 1;
            if (tiesTrace.size() > 1) {  // if seq is nontrivial, resolve
                resolveTie(out, tiesTrace);
            }
            tiesTrace = new ArrayList<Integer>();
            tiesTrace.add(ranks[i].getPosition());
        } else {
            // tie sequence continues
            tiesTrace.add(ranks[i].getPosition());
        }
        out[ranks[i].getPosition()] = pos;
    }
    if (tiesTrace.size() > 1) {  // handle tie sequence at end
        resolveTie(out, tiesTrace);
    }
    if (nanStrategy == NaNStrategy.FIXED) {
        restoreNaNs(out, nanPositions);
    }
    return out;
}
 
Example 20
Source File: RandomDataImpl.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * <strong>Algorithm Description:</strong> hex strings are generated in
 * 40-byte segments using a 3-step process.
 * <ol>
 * <li>
 * 20 random bytes are generated using the underlying
 * <code>SecureRandom</code>.</li>
 * <li>
 * SHA-1 hash is applied to yield a 20-byte binary digest.</li>
 * <li>
 * Each byte of the binary digest is converted to 2 hex digits.</li>
 * </ol>
 * </p>
 *
 * @param len
 *            the length of the generated string
 * @return the random string
 */
public String nextSecureHexString(int len) {
    if (len <= 0) {
        throw MathRuntimeException.createIllegalArgumentException(
              "length must be positive ({0})", len);
    }

    // Get SecureRandom and setup Digest provider
    SecureRandom secRan = getSecRan();
    MessageDigest alg = null;
    try {
        alg = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException ex) {
        // this should never happen
        throw MathRuntimeException.createInternalError(ex);
    }
    alg.reset();

    // Compute number of iterations required (40 bytes each)
    int numIter = (len / 40) + 1;

    StringBuffer outBuffer = new StringBuffer();
    for (int iter = 1; iter < numIter + 1; iter++) {
        byte[] randomBytes = new byte[40];
        secRan.nextBytes(randomBytes);
        alg.update(randomBytes);

        // Compute hash -- will create 20-byte binary hash
        byte hash[] = alg.digest();

        // Loop over the hash, converting each byte to 2 hex digits
        for (int i = 0; i < hash.length; i++) {
            Integer c = Integer.valueOf(hash[i]);

            /*
             * Add 128 to byte value to make interval 0-255 This guarantees
             * <= 2 hex digits from toHexString() toHexString would
             * otherwise add 2^32 to negative arguments
             */
            String hex = Integer.toHexString(c.intValue() + 128);

            // Keep strings uniform length -- guarantees 40 bytes
            if (hex.length() == 1) {
                hex = "0" + hex;
            }
            outBuffer.append(hex);
        }
    }
    return outBuffer.toString().substring(0, len);
}