Example usage for java.lang Double NEGATIVE_INFINITY

List of usage examples for java.lang Double NEGATIVE_INFINITY

Introduction

In this page you can find the example usage for java.lang Double NEGATIVE_INFINITY.

Prototype

double NEGATIVE_INFINITY

To view the source code for java.lang Double NEGATIVE_INFINITY.

Click Source Link

Document

A constant holding the negative infinity of type double .

Usage

From source file:ucar.unidata.idv.control.chart.ChartWrapper.java

/**
 * Get get list of Ranges for time subsetting. If there are none
 * then return null.//from  w  ww .j  a  v a 2  s  .co  m
 *
 * @return List of time ranges or null
 */
protected List getTimeFilterRanges() {
    List ranges = null;
    if ((minDate != Double.NEGATIVE_INFINITY) || (maxDate != Double.POSITIVE_INFINITY)) {
        if ((minDate != dataMinDate) || (maxDate != dataMaxDate)) {
            ranges = Misc.newList(new ucar.unidata.util.Range(minDate, maxDate));

        }
    }

    if (timeFilterSource != null) {
        List filterRanges = timeFilterSource.getTimeRanges();
        if (filterRanges != null) {
            if (ranges == null) {
                ranges = filterRanges;
            } else {
                ranges.addAll(filterRanges);
            }
        }
    }
    return ranges;
}

From source file:org.apache.drill.exec.fn.impl.TestNewMathFunctions.java

@Test
public void testLog10WithBigInt() throws Throwable {
    String json = "{" + "\"num1\": 0," + "\"num3\": 1," + "\"num5\": -1," + "\"num6\": 10" + "}";
    String query = "select " + "log10(num1) as num1, " + "log10(num3) as num3, " + "log10(num5) as num5, "
            + "log10(num6) as num6 " + "from dfs.`data.json`";
    File file = new File(dirTestWatcher.getRootDir(), "data.json");
    try {//www  .j  a  v a  2s  . co m
        FileUtils.writeStringToFile(file, json);

        setSessionOption(ExecConstants.JSON_READER_NAN_INF_NUMBERS, true);
        testBuilder().sqlQuery(query).ordered().baselineColumns("num1", "num3", "num5", "num6")
                .baselineValues(Double.NEGATIVE_INFINITY, 0d, Double.NaN, 1.0d).go();
    } finally {
        resetSessionOption(ExecConstants.JSON_READER_NAN_INF_NUMBERS);
        FileUtils.deleteQuietly(file);
    }
}

From source file:egat.replicatordynamics.SymmetricConstrainedTransformedAmoebaSearch.java

private void randomDirection(double[] current, int[] restricted, double[] gradient) {
    double max = Double.NEGATIVE_INFINITY;
    for (int i = 0; i < restricted.length; i++) {
        gradient[i] = Math.random() - current[restricted[i]];
        max = Math.max(max, Math.abs(gradient[i]));
    }/*from  w ww  . ja va  2s .  co  m*/

    for (int i = 0; i < restricted.length; i++) {
        gradient[i] /= max;
    }
}

From source file:edu.pitt.csb.mgm.IndTestMixedMultipleTTest.java

private double[] dependencePvalsLogit(Node x, Node y, List<Node> z) {
    if (!variablesPerNode.containsKey(x)) {
        throw new IllegalArgumentException("Unrecogized node: " + x);
    }/* www.j  av a  2  s . co  m*/

    if (!variablesPerNode.containsKey(y)) {
        throw new IllegalArgumentException("Unrecogized node: " + y);
    }

    for (Node node : z) {
        if (!variablesPerNode.containsKey(node)) {
            throw new IllegalArgumentException("Unrecogized node: " + node);
        }
    }

    List<Double> pValues = new ArrayList<Double>();

    int[] _rows = getNonMissingRows(x, y, z);
    logisticRegression.setRows(_rows);

    List<Node> yzDumList = new ArrayList<>();
    List<Node> yzList = new ArrayList<>();
    yzList.add(y);
    yzList.addAll(z);
    //List<Node> zList = new ArrayList<>();

    yzDumList.addAll(variablesPerNode.get(y));
    for (Node _z : z) {
        yzDumList.addAll(variablesPerNode.get(_z));
        //zList.addAll(variablesPerNode.get(_z));
    }

    //double[][] coeffsDep = new double[variablesPerNode.get(x).size()][];
    //DoubleMatrix2D coeffsNull = DoubleFactory2D.dense.make(zList.size(), variablesPerNode.get(x).size());
    //DoubleMatrix2D coeffsDep = DoubleFactory2D.dense.make(yzDumList.size()+1, variablesPerNode.get(x).size());
    double[] sumLnP = new double[yzList.size()];
    for (int i = 0; i < sumLnP.length; i++)
        sumLnP[i] = 0.0;

    for (int i = 0; i < variablesPerNode.get(x).size(); i++) {
        Node _x = variablesPerNode.get(x).get(i);

        LogisticRegression.Result result1 = logisticRegression.regress((DiscreteVariable) _x, yzDumList);

        int n = originalData.getNumRows();
        int k = yzDumList.size();

        //skip intercept at index 0
        int coefIndex = 1;
        for (int j = 0; j < yzList.size(); j++) {
            for (int dum = 0; dum < variablesPerNode.get(yzList.get(j)).size(); dum++) {

                double wald = Math.abs(result1.getCoefs()[coefIndex] / result1.getStdErrs()[coefIndex]);
                //double val = (1.0 - new NormalDistribution(0,1).cumulativeProbability(wald))*2;//two-tailed test
                //double val = 1-result1.getProbs()[i+1];

                //this is exactly the same test as the linear case
                double val = (1.0 - ProbUtils.tCdf(wald, n - k)) * 2;
                //System.out.println(_x.getName() + "\t" + yzDumList.get(coefIndex-1).getName() + "\t" + val + "\t" + (n-k));
                //if(val <= 0) System.out.println("Zero p-val t-test: p " + val + " stat " + wald + " k " + k + " n " + n);
                sumLnP[j] += Math.log(val);
                coefIndex++;
            }
        }
    }

    double[] pVec = new double[sumLnP.length];
    for (int i = 0; i < pVec.length; i++) {
        if (sumLnP[i] == Double.NEGATIVE_INFINITY)
            pVec[i] = 0.0;
        else {
            int df = 2 * variablesPerNode.get(x).size() * variablesPerNode.get(yzList.get(i)).size();
            pVec[i] = 1.0 - new ChiSquaredDistribution(df).cumulativeProbability(-2 * sumLnP[i]);
        }
    }

    return pVec;
}

From source file:beast.evolution.operators.GMRFMultilocusSkyrideBlockUpdateOperator.java

@Override
public double proposal() {

    double currentPrecision = precisionParameter.getValue(0);
    double proposedPrecision = this.getNewPrecision(currentPrecision, scaleFactor);

    double currentLambda = this.lambdaParameter.getValue(0);
    double proposedLambda = this.getNewLambda(currentLambda, lambdaScaleFactor);

    precisionParameter.setValue(0, proposedPrecision);
    lambdaParameter.setValue(0, proposedLambda);

    Double[] Values = gmrfField.getPopSizeParameter().getValues();
    double[] values = new double[Values.length];
    for (int i = 0; i < values.length; i++) {
        values[i] = Values[i];/*from w  w w.  ja  va  2  s .  com*/
    }
    DenseVector currentGamma = new DenseVector(values);
    DenseVector proposedGamma;

    SymmTridiagMatrix currentQ = gmrfField.getStoredScaledWeightMatrix(currentPrecision, currentLambda);
    SymmTridiagMatrix proposedQ = gmrfField.getScaledWeightMatrix(proposedPrecision, proposedLambda);

    double[] wNative = gmrfField.getSufficientStatistics();
    double[] numCoalEv = gmrfField.getNumCoalEvents();

    UpperSPDBandMatrix forwardQW = new UpperSPDBandMatrix(proposedQ, 1);
    UpperSPDBandMatrix backwardQW = new UpperSPDBandMatrix(currentQ, 1);

    BandCholesky forwardCholesky = new BandCholesky(wNative.length, 1, true);
    BandCholesky backwardCholesky = new BandCholesky(wNative.length, 1, true);

    DenseVector diagonal1 = new DenseVector(fieldLength);
    DenseVector diagonal2 = new DenseVector(fieldLength);
    DenseVector diagonal3 = new DenseVector(fieldLength);

    DenseVector modeForward;
    try {
        modeForward = newtonRaphson(numCoalEv, wNative, currentGamma, proposedQ.copy());
    } catch (MathException e) {
        return Double.NEGATIVE_INFINITY;
    }

    for (int i = 0; i < fieldLength; i++) {
        diagonal1.set(i, wNative[i] * Math.exp(-modeForward.get(i)));
        diagonal2.set(i, modeForward.get(i) + 1);

        forwardQW.set(i, i, diagonal1.get(i) + forwardQW.get(i, i));
        //diagonal1.set(i, diagonal1.get(i) * diagonal2.get(i) - 1);
        diagonal1.set(i, diagonal1.get(i) * diagonal2.get(i) - numCoalEv[i]);
    }

    forwardCholesky.factor(forwardQW.copy());

    DenseVector forwardMean = getMultiNormalMean(diagonal1, forwardCholesky);

    DenseVector stand_norm = new DenseVector(zeros);

    for (int i = 0; i < zeros.length; i++)
        stand_norm.set(i, Randomizer.nextGaussian());

    proposedGamma = getMultiNormal(stand_norm, forwardMean, forwardCholesky);

    /*
    double hRatio = 0;
    for (int i = 0; i < fieldLength; i++) {
    diagonal1.set(i, proposedGamma.get(i) - forwardMean.get(i));
    }
    diagonal3.zero();
    forwardQW.mult(diagonal1, diagonal3);
            
    hRatio -= logGeneralizedDeterminant(forwardCholesky.getU() ) - 0.5 * diagonal1.dot(diagonal3);
    */

    for (int i = 0; i < fieldLength; i++)
        popSizeParameter.setValue(i, proposedGamma.get(i));

    //((Parameter.Abstract) popSizeParameter).fireParameterChangedEvent();

    double hRatio = 0;

    diagonal1.zero();
    diagonal2.zero();
    diagonal3.zero();

    DenseVector modeBackward;
    try {
        modeBackward = newtonRaphson(numCoalEv, wNative, proposedGamma, currentQ.copy());
    } catch (MathException e) {
        return Double.NEGATIVE_INFINITY;
    }

    for (int i = 0; i < fieldLength; i++) {
        diagonal1.set(i, wNative[i] * Math.exp(-modeBackward.get(i)));
        diagonal2.set(i, modeBackward.get(i) + 1);

        backwardQW.set(i, i, diagonal1.get(i) + backwardQW.get(i, i));
        //diagonal1.set(i, diagonal1.get(i) * diagonal2.get(i) - 1);
        diagonal1.set(i, diagonal1.get(i) * diagonal2.get(i) - numCoalEv[i]);
    }

    backwardCholesky.factor(backwardQW.copy());

    DenseVector backwardMean = getMultiNormalMean(diagonal1, backwardCholesky);

    for (int i = 0; i < fieldLength; i++) {
        diagonal1.set(i, currentGamma.get(i) - backwardMean.get(i));
    }

    backwardQW.mult(diagonal1, diagonal3);

    hRatio += logGeneralizedDeterminant(backwardCholesky.getU()) - 0.5 * diagonal1.dot(diagonal3);
    hRatio -= logGeneralizedDeterminant(forwardCholesky.getU()) - 0.5 * stand_norm.dot(stand_norm);

    return hRatio;
}

From source file:io.github.gjyaiya.stetho.realm.Database.java

private List<Object> flattenRows(Table table, long limit, boolean addRowIndex) {
    Util.throwIfNot(limit >= 0);
    final List<Object> flatList = new ArrayList<>();
    long numColumns = table.getColumnCount();

    final RowFetcher rowFetcher = RowFetcher.getInstance();
    final long tableSize = table.size();
    for (long index = 0; index < limit && index < tableSize; index++) {
        final long row = ascendingOrder ? index : (tableSize - index - 1);
        final RowWrapper rowData = RowWrapper.wrap(rowFetcher.getRow(table, row));
        if (addRowIndex) {
            flatList.add(rowData.getIndex());
        }//from  w w w  .j  ava 2 s. co m
        for (int column = 0; column < numColumns; column++) {
            switch (rowData.getColumnType(column)) {
            case INTEGER:
                if (rowData.isNull(column)) {
                    flatList.add(NULL);
                } else {
                    flatList.add(rowData.getLong(column));
                }
                break;
            case BOOLEAN:
                if (rowData.isNull(column)) {
                    flatList.add(NULL);
                } else {
                    flatList.add(rowData.getBoolean(column));
                }
                break;
            case STRING:
                if (rowData.isNull(column)) {
                    flatList.add(NULL);
                } else {
                    flatList.add(rowData.getString(column));
                }
                break;
            case BINARY:
                if (rowData.isNull(column)) {
                    flatList.add(NULL);
                } else {
                    flatList.add(rowData.getBinaryByteArray(column));
                }
                break;
            case FLOAT:
                if (rowData.isNull(column)) {
                    flatList.add(NULL);
                } else {
                    final float aFloat = rowData.getFloat(column);
                    if (Float.isNaN(aFloat)) {
                        flatList.add("NaN");
                    } else if (aFloat == Float.POSITIVE_INFINITY) {
                        flatList.add("Infinity");
                    } else if (aFloat == Float.NEGATIVE_INFINITY) {
                        flatList.add("-Infinity");
                    } else {
                        flatList.add(aFloat);
                    }
                }
                break;
            case DOUBLE:
                if (rowData.isNull(column)) {
                    flatList.add(NULL);
                } else {
                    final double aDouble = rowData.getDouble(column);
                    if (Double.isNaN(aDouble)) {
                        flatList.add("NaN");
                    } else if (aDouble == Double.POSITIVE_INFINITY) {
                        flatList.add("Infinity");
                    } else if (aDouble == Double.NEGATIVE_INFINITY) {
                        flatList.add("-Infinity");
                    } else {
                        flatList.add(aDouble);
                    }
                }
                break;
            case OLD_DATE:
            case DATE:
                if (rowData.isNull(column)) {
                    flatList.add(NULL);
                } else {
                    flatList.add(formatDate(rowData.getDate(column)));
                }
                break;
            case OBJECT:
                if (rowData.isNullLink(column)) {
                    flatList.add(NULL);
                } else {
                    flatList.add(rowData.getLink(column));
                }
                break;
            case LIST:
                // LIST never be null
                flatList.add(formatList(rowData.getLinkList(column)));
                break;
            default:
                flatList.add("unknown column type: " + rowData.getColumnType(column));
                break;
            }
        }
    }

    if (limit < table.size()) {
        for (int column = 0; column < numColumns; column++) {
            flatList.add("{truncated}");
        }
    }

    return flatList;
}

From source file:io.warp10.continuum.gts.GTSOutliersHelper.java

/**
 * Applying generalized extreme Studentized deviate test using mean/std or median/mad
 * @see http://www.itl.nist.gov/div898/handbook/eda/section3/eda35h3.htm
 * /*ww  w.j a v  a  2 s.c  o  m*/
 * @param gts
 * @param k       Upper bound of suspected number of outliers
 * @param useMedian     Should the test use median/mad instead of mean/std
 * @param alpha   Significance level with which to accept or reject anomalies. Default is 0.05
 * 
 * @return anomalous_ticks
 * 
 * @throws WarpScriptException
 */
public static List<Long> ESDTest(GeoTimeSerie gts, int k, boolean useMedian, double alpha)
        throws WarpScriptException {
    doubleCheck(gts);

    // Clone GTS (not necessary but simplifies implementation) -> copy only needed fields
    //GeoTimeSerie clone = gts.clone();
    GeoTimeSerie clone = new GeoTimeSerie();
    clone.type = gts.type;
    clone.values = gts.values;
    clone.doubleValues = Arrays.copyOf(gts.doubleValues, gts.values);
    clone.ticks = Arrays.copyOf(gts.ticks, gts.values);

    List<Long> anomalous_ticks = new ArrayList<Long>();

    int greater_j_test_passed = -1;
    for (int j = 0; j < k; j++) {

        int N = clone.values;
        if (N < 3) {
            // In this case there are no more outlier left
            break;
        }

        double[] musigma = madsigma(clone, useMedian);
        double m = musigma[0];
        double std = musigma[1];

        if (0.0D == std) {
            // In this case there are no more outlier left
            break;
        }

        double z = 0.0D;
        double max = Double.NEGATIVE_INFINITY;
        int suspicious_idx = 0;

        for (int i = 0; i < N; i++) {
            z = Math.abs((clone.doubleValues[i] - m) / std);
            if (z > max) {
                max = z;
                suspicious_idx = i;
            }
        }

        //
        // Calculate critical value
        //

        double p = 1 - alpha / (2 * N);
        double t = new TDistribution(N - 2).inverseCumulativeProbability(p);

        //
        // Calculate threshold
        //

        double lambda = (N - 1) * t / Math.sqrt((N - 2 + t * t) * N);

        //
        // Test
        //

        if (max > lambda) {
            greater_j_test_passed = j;
        }

        //
        // Removing potential outlier before next loop
        //

        clone.values--;

        // We swap it with last point
        long tmp_tick = clone.ticks[suspicious_idx];
        clone.ticks[suspicious_idx] = clone.ticks[clone.values];
        clone.ticks[clone.values] = tmp_tick;

        // We don't need to keep the value of the potential outlier
        clone.doubleValues[suspicious_idx] = clone.doubleValues[clone.values];
    }

    // adding to output
    for (int j = 0; j <= greater_j_test_passed; j++) {
        anomalous_ticks.add(clone.ticks[gts.values - 1 - j]);
    }

    return anomalous_ticks;
}

From source file:de.julielab.jcore.ae.lingpipegazetteer.chunking.ChunkerProviderImplAlt.java

public void load(DataResource resource) throws ResourceInitializationException {
    LOGGER.info("Loading configuration file from URI \"{}\" (URL: \"{}\").", resource.getUri(),
            resource.getUrl());/*  w  w  w  .jav  a  2 s .c  om*/
    Properties properties = new Properties();
    try {
        InputStream is;
        try {
            is = resource.getInputStream();
        } catch (NullPointerException e) {
            LOGGER.info("Couldn't get InputStream from UIMA. Trying to load the resource by classpath lookup.");
            String cpAddress = resource.getUri().toString();
            is = getClass().getResourceAsStream(cpAddress.startsWith("/") ? cpAddress : "/" + cpAddress);
            if (null == is) {
                String err = "Couldn't find the resource at \"" + resource.getUri()
                        + "\" neither as an UIMA external resource file nor as a classpath resource.";
                LOGGER.error(err);
                throw new ResourceInitializationException(new IllegalArgumentException(err));
            }
        }
        properties.load(is);
    } catch (IOException e) {
        LOGGER.error("Error while loading properties file", e);
        throw new ResourceInitializationException(e);
    }

    LOGGER.info("Creating dictionary chunker with " + resource.getUrl() + " properties file.");

    dictionaryFilePath = properties.getProperty(PARAM_DICTIONARY_FILE);
    if (dictionaryFilePath == null)
        throw new ResourceInitializationException(ResourceInitializationException.CONFIG_SETTING_ABSENT,
                new Object[] { PARAM_DICTIONARY_FILE });

    stopwordFilePath = properties.getProperty(PARAM_STOPWORD_FILE);
    if (stopwordFilePath == null)
        throw new ResourceInitializationException(ResourceInitializationException.CONFIG_SETTING_ABSENT,
                new Object[] { PARAM_STOPWORD_FILE });

    String generateVariantsString = properties.getProperty(PARAM_MAKE_VARIANTS);
    generateVariants = true;
    if (generateVariantsString != null)
        generateVariants = new Boolean(generateVariantsString);
    LOGGER.info("Generate variants: {}", generateVariants);

    String normalizeString = properties.getProperty(PARAM_NORMALIZE_TEXT);
    normalize = false;
    if (normalizeString != null)
        normalize = new Boolean(normalizeString);
    LOGGER.info("Normalize dictionary entries (i.e. completely strip dashes, parenthesis etc): {}", normalize);

    String transliterateString = properties.getProperty(PARAM_TRANSLITERATE_TEXT);
    transliterate = false;
    if (transliterateString != null)
        transliterate = new Boolean(transliterateString);
    LOGGER.info("Transliterate dictionary entries (i.e. transform accented characters to their base forms): {}",
            transliterate);

    String caseSensitiveString = properties.getProperty(PARAM_CASE_SENSITIVE);
    caseSensitive = false;
    if (caseSensitiveString != null)
        caseSensitive = new Boolean(caseSensitiveString);
    LOGGER.info("Case sensitive: {}", caseSensitive);

    String useApproximateMatchingString = properties.getProperty(PARAM_USE_APPROXIMATE_MATCHING);
    useApproximateMatching = false;
    if (useApproximateMatchingString != null)
        useApproximateMatching = new Boolean(useApproximateMatchingString);
    LOGGER.info("Use approximate matching: {}", useApproximateMatching);

    if (normalize && generateVariants)
        throw new ResourceInitializationException(new IllegalStateException(
                "MakeVariants and NormalizeText are both activated which is invalid. The two options work towards the same goal in two different ways, i.e. to recognize dictionary entry variants not given explicitly. However, the approaches are not compatible and you have to choose a single one."));

    dictFile = readStreamFromFileSystemOrClassPath(dictionaryFilePath);
    stopFile = readStreamFromFileSystemOrClassPath(stopwordFilePath);

    try {
        initStopWords(stopFile);
        readDictionary(dictFile);

        LOGGER.info("Now creating chunker.");
        long time = System.currentTimeMillis();
        if (useApproximateMatching) {
            final Set<Character> charsToDelete = new HashSet<>();
            charsToDelete.add('-');
            // charsToDelete.add('+');
            // charsToDelete.add(',');
            // charsToDelete.add('.');
            // charsToDelete.add(':');
            // charsToDelete.add(';');
            // charsToDelete.add('?');
            // charsToDelete.add('!');
            // charsToDelete.add('*');
            // charsToDelete.add('');
            // charsToDelete.add('$');
            // charsToDelete.add('%');
            // charsToDelete.add('&');
            // charsToDelete.add('/');
            // charsToDelete.add('\\');
            // charsToDelete.add('(');
            // charsToDelete.add(')');
            // charsToDelete.add('<');
            // charsToDelete.add('>');
            // charsToDelete.add('[');
            // charsToDelete.add(']');
            // charsToDelete.add('=');
            // charsToDelete.add('\'');
            // charsToDelete.add('`');
            // charsToDelete.add('');
            // charsToDelete.add('"');
            // charsToDelete.add('#');

            WeightedEditDistance editDistance = ApproxDictionaryChunker.TT_DISTANCE;
            editDistance = new WeightedEditDistance() {

                @Override
                public double deleteWeight(char cDeleted) {
                    double ret;
                    if (cDeleted == '-')
                        ret = -5.0;
                    else if (cDeleted == ' ' || charsToDelete.contains(cDeleted))
                        ret = -10.0;
                    else
                        ret = -110.0;
                    return ret;
                }

                @Override
                public double insertWeight(char cInserted) {
                    return deleteWeight(cInserted);
                }

                @Override
                public double matchWeight(char cMatched) {
                    return 0.0;
                }

                @Override
                public double substituteWeight(char cDeleted, char cInserted) {
                    if (cDeleted == ' ' && cInserted == '-')
                        return -2.0;
                    if (cDeleted == '-' && cInserted == ' ')
                        return -2.0;
                    if (cDeleted == ' ' && charsToDelete.contains(cInserted))
                        return -10.0;
                    if (charsToDelete.contains(cDeleted) && cInserted == ' ')
                        return -10.0;
                    return -110.0;
                }

                @Override
                public double transposeWeight(char c1, char c2) {
                    return Double.NEGATIVE_INFINITY;
                }
            };

            dictChunker = new ApproxDictionaryChunker((TrieDictionary<String>) dict,
                    IndoEuropeanTokenizerFactory.INSTANCE, editDistance, APPROX_MATCH_THRESHOLD_SCORE);
        } else {
            dictChunker = new ExactDictionaryChunker(dict, IndoEuropeanTokenizerFactory.INSTANCE, false,
                    caseSensitive);
        }
        time = System.currentTimeMillis() - time;
        LOGGER.info("Building the actual chunker from the dictionary took {}ms ({}s).", time, time / 1000);

    } catch (Exception e) {
        LOGGER.error("Exception while creating chunker instance", e);
    }
}

From source file:hu.ppke.itk.nlpg.purepos.decoder.AbstractDecoder.java

private Map<NGram<Integer>, Map<Integer, Pair<Double, Double>>> getNextForGuessedVocToken(
        final Set<NGram<Integer>> prevTagsSet, String lWord, Collection<Integer> anals,
        ISuffixGuesser<String, Integer> guesser) {

    Map<NGram<Integer>, Map<Integer, Pair<Double, Double>>> ret = new HashMap<NGram<Integer>, Map<Integer, Pair<Double, Double>>>();
    Map<Integer, Pair<Double, Double>> tagProbs;
    Collection<Integer> possibleTags;
    possibleTags = anals;/*from   ww w  .  j  av a 2  s .  c o  m*/
    tagProbs = new HashMap<Integer, Pair<Double, Double>>();
    for (Integer tag : possibleTags) {
        Double emissionProb = 0.0;

        Double transitionProb;
        Integer newTag = guesser.getMapper().map(tag);
        if (newTag > model.getTagVocabulary().getMaximalIndex()) {
            emissionProb = UNKNOWN_TAG_WEIGHT;
            // TODO: RESEARCH: new tags should handled better
            transitionProb = UNKOWN_TAG_TRANSITION;
            tagProbs.put(tag, new ImmutablePair<Double, Double>(transitionProb, emissionProb));
            for (NGram<Integer> prevTags : prevTagsSet) {
                ret.put(prevTags, tagProbs);
            }
        } else {
            Double aprioriProb = model.getAprioriTagProbs().get(newTag);
            Double logAprioriPorb = Math.log(aprioriProb);
            double tagLogProbability = guesser.getTagLogProbability(lWord, tag);
            if (tagLogProbability == Double.NEGATIVE_INFINITY)
                emissionProb = UNKNOWN_TAG_WEIGHT;
            else
                emissionProb = tagLogProbability - logAprioriPorb;
            for (NGram<Integer> prevTags : prevTagsSet) {
                transitionProb = model.getTagTransitionModel().getLogProb(prevTags.toList(), tag);
                tagProbs.put(tag, new ImmutablePair<Double, Double>(transitionProb, emissionProb));
                ret.put(prevTags, tagProbs);
            }
        }

    }
    return ret;
}

From source file:NumberUtils.java

/**
 * Compares the first number to the second one numerically and 
 * returns an integer depending on the comparison result:
 * a negative value if the first number is the smaller one,
 * a zero value if they are equal, and//from  www . j  av  a2s.  co  m
 * a positive value if the first number is the larger one.
 *
 * The main strategy goes like follows:
 * 1. If one of the arguments is <code>null</code> or 'not a number',
 *    throw an exception.
 * 2. If both values are 'long compatible', compare their <code>longValue()</code>
 *    using the usual comparison operators for primitive types (&lt;, ==, &gt;).
 * 3. If both values are 'double compatible', compare their <code>doubleValue()</code>
 *    using the usual comparison operators for primitive types (&lt;, ==, &gt;).
 * 4. If one of the values is infinite (and the other is finite),
 *    determine the result depending on the sign of the infinite value.
 * 5. Otherwise convert both values to <code>java.math.BigDecimal</code> and
 *    return the result of the <code>BigDecimal.compareTo(BigDecimal)</code> method.
 *
 * As a consequence, the method is not suitable to implement a
 * <code>java.util.Comparator</code> for numbers. To achieve this,
 * one had to accept 'not a number' arguments and place them somewhere
 * in the row of numbers (probably at the upper end, i.e. larger than
 * positive infinity, as <code>Double.compare(double, double)</code>
 * does it).
 * So the behavior of this method is like that of the comparison
 * operator for primitive types and not like that of the related
 * <code>compareTo(...)</code> methods. Besides the handling of
 * 'not a number' values this makes a difference, when comparing
 * the float or double values <code>-0.0</code> and <code>0.0</code>:
 * again, like the operators, we consider them as equal (whereas
 * according to <code>Double.compareTo(...)</code> <code>-0.0</code>
 * is less than <code>0.0</code>).
 *
 * @param first
 * @param second
 * @return int
 * @throws ArithmeticException One or both of the given numbers is <code>null</code> or 'not a number'.
 */
public static int compare(Number first, Number second) throws ArithmeticException {
    if (first == null || second == null || isNaN(first) || isNaN(second))
        throw new ArithmeticException("Arguments must not be null or NaN.");

    int result = -2;

    if (isLongCompatible(first) && isLongCompatible(second)) {
        long v1 = first.longValue(), v2 = second.longValue();
        result = v1 < v2 ? -1 : v1 == v2 ? 0 : v1 > v2 ? 1 : 2;
    } else if (isDoubleCompatible(first) && isDoubleCompatible(second)) {
        double v1 = first.doubleValue(), v2 = second.doubleValue();
        result = v1 < v2 ? -1 : v1 == v2 ? 0 : v1 > v2 ? 1 : 2;
    }

    if (result == 2) // should not happen
        throw new ArithmeticException("Arguments " + first + " and " + second + " are not comparable.");
    if (result > -2)
        return result;

    if (isInfinite(first)) // => second is finite
        return first.doubleValue() == Double.NEGATIVE_INFINITY ? -1 : 1;
    if (isInfinite(second)) // => first is finite
        return second.doubleValue() == Double.POSITIVE_INFINITY ? -1 : 1;

    return toBigDecimal(first).compareTo(toBigDecimal(second));
}