Example usage for java.lang Double compare

List of usage examples for java.lang Double compare

Introduction

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

Prototype

public static int compare(double d1, double d2) 

Source Link

Document

Compares the two specified double values.

Usage

From source file:org.projectbuendia.client.models.ObsValue.java

/**
 * Compares ObsValue instances according to a total ordering such that:
 * - All non-null values are greater than null.
 * - The lowest value is the "false" Boolean value (encoded as the coded concept for "No").
 * - Next are all coded values, ordered from least severe to most severe (if they can
 *   be interpreted as having a severity); or from first to last (if they can
 *   be interpreted as having a typical temporal sequence).
 * - Next is the "true" Boolean value (encoded as the coded concept for "Yes").
 * - Next are all numeric values, ordered from least to greatest.
 * - Next are all text values, ordered lexicographically from A to Z.
 * - Next are all date values, ordered from least to greatest.
 * - Next are all instant values, ordered from least to greatest.
 * @param other The other Value to compare to.
 * @return/*from   w w w. j  a v a2 s.com*/
 */
@Override
public int compareTo(@Nullable ObsValue other) {
    if (other == null)
        return 1;
    int result = 0;
    result = Integer.compare(getTypeOrdering(), other.getTypeOrdering());
    if (result != 0)
        return result;
    if (uuid != null) {
        result = Integer.compare(getUuidOrdering(), other.getUuidOrdering());
        if (result != 0)
            return result;
        result = uuid.compareTo(other.uuid);
    } else if (number != null) {
        result = Double.compare(number, other.number);
    } else if (text != null) {
        result = text.compareTo(other.text);
    } else if (date != null) {
        result = date.compareTo(other.date);
    } else if (instant != null) {
        result = instant.compareTo(other.instant);
    }
    return result;
}

From source file:org.commoncrawl.service.parser.client.ParserNode.java

@Override
public int compareTo(ParserNode o) {
    if (_status != null && o._status != null) {
        int result = Double.compare(Math.floor(_status.getLoad()), Math.floor(o._status.getLoad()));
        if (result == 0) {
            result = (_status.getQueuedDocs() < o._status.getQueuedDocs()) ? -1
                    : (_status.getQueuedDocs() > o._status.getQueuedDocs()) ? 1 : 0;
            if (result == 0) {
                result = (_status.getActiveDocs() < o._status.getActiveDocs()) ? -1
                        : (_status.getActiveDocs() > o._status.getActiveDocs()) ? 1 : 0;

                if (result == 0) {
                    result = (_lastTouched < o._lastTouched) ? -1 : (_lastTouched > o._lastTouched) ? 1 : 0;
                }//www. j  a  va 2 s .co  m
            }

        }
        return result;
    } else if (_status != null && o._status == null) {
        return -1;
    } else if (_status == null && o._status != null) {
    } else {
        return (_lastTouched < o._lastTouched) ? -1 : (_lastTouched > o._lastTouched) ? 1 : 0;
    }

    return 0;
}

From source file:com.act.biointerpretation.sarinference.ProductScorer.java

/**
 * Reads in scored SARs, checks them against a prediction corpus and positive inchi list to get a product ranking.
 * This method is static because it does not rely on any properties of the enclosing class to construct the job.
 * TODO: It would probably make more sense to make this its own class, i.e. <ProductScorer implements JavaRunnable>
 * TODO: improve the data structure used to store scored products- using an L2PredictionCorpus is pretty ugly
 *
 * @param predictionCorpus The prediction corpus to score.
 * @param scoredSars The scored SARs to use.
 * @param lcmsFile The set of positive LCMS inchis, to use in scoring.
 * @return A JavaRunnable to run the product scoring.
 *//*ww w . j a  v  a  2  s .c  o  m*/
public static JavaRunnable getProductScorer(File predictionCorpus, File scoredSars, File lcmsFile,
        File outputFile) {

    return new JavaRunnable() {
        @Override
        public void run() throws IOException {
            // Verify files
            FileChecker.verifyInputFile(predictionCorpus);
            FileChecker.verifyInputFile(scoredSars);
            FileChecker.verifyInputFile(lcmsFile);
            FileChecker.verifyAndCreateOutputFile(outputFile);

            // Build SAR node list and best sar finder
            SarTreeNodeList nodeList = new SarTreeNodeList();
            nodeList.loadFromFile(scoredSars);
            BestSarFinder sarFinder = new BestSarFinder(nodeList);

            // Build prediction corpus
            L2PredictionCorpus predictions = L2PredictionCorpus.readPredictionsFromJsonFile(predictionCorpus);

            // Build LCMS results
            IonAnalysisInterchangeModel lcmsResults = new IonAnalysisInterchangeModel();
            lcmsResults.loadResultsFromFile(lcmsFile);

            /**
             * Build map from predictions to their scores based on SAR
             * For each prediction, we add on auxiliary info about its SARs and score to its projector name.
             * TODO: build data structure to store a scored prediction, instead of hijacking the projector name.
             */
            Map<L2Prediction, Double> predictionToScoreMap = new HashMap<>();
            LOGGER.info("Scoring predictions.");
            for (L2Prediction prediction : predictions.getCorpus()) {
                String nameAppendage = lcmsResults.getLcmsDataForPrediction(prediction).toString(); // Always tack LCMS result onto name

                Optional<SarTreeNode> maybeBestSar = sarFinder.apply(prediction);

                if (maybeBestSar.isPresent()) {
                    // If a SAR was matched, add info about it to the projector name, and put its score into the map
                    SarTreeNode bestSar = maybeBestSar.get();
                    nameAppendage += ":" + bestSar.getHierarchyId() + ":" + bestSar.getRankingScore();
                    prediction.setProjectorName(prediction.getProjectorName() + nameAppendage);
                    predictionToScoreMap.put(prediction, bestSar.getRankingScore());
                } else {
                    // If no SAR is found, append "NO_SAR" to the prediction, and give it a ranking score of 0
                    nameAppendage += "NO_SAR";
                    prediction.setProjectorName(prediction.getProjectorName() + nameAppendage);
                    predictionToScoreMap.put(prediction, 0D);
                }
            }

            LOGGER.info("Sorting predictions in decreasing order of best associated SAR rank.");
            List<L2Prediction> predictionList = new ArrayList<>(predictionToScoreMap.keySet());
            predictionList
                    .sort((a, b) -> -Double.compare(predictionToScoreMap.get(a), predictionToScoreMap.get(b)));

            // Wrap results in a corpus and write to file.
            L2PredictionCorpus finalCorpus = new L2PredictionCorpus(predictionList);
            finalCorpus.writePredictionsToJsonFile(outputFile);
            LOGGER.info("Complete!.");
        }

        @Override
        public String toString() {
            return "ProductScorer:" + scoredSars.getName();
        }
    };
}

From source file:org.deeplearning4j.util.StringGrid.java

public void sortColumnsByWordLikelihoodIncluded(final int column) {
    final Counter<String> counter = new Counter<>();
    List<String> col = getColumn(column);

    for (String s : col) {
        StringTokenizer tokenizer = new StringTokenizer(s);
        while (tokenizer.hasMoreTokens()) {
            counter.incrementCount(tokenizer.nextToken(), 1.0);
        }/*from   w ww. j  a  va 2s .co m*/
    }

    if (counter.totalCount() <= 0.0) {
        log.warn("Unable to calculate probability; nothing found");
        return;
    }

    //laplace smoothing
    counter.incrementAll(counter.keySet(), 1.0);
    Set<String> remove = new HashSet<>();
    for (String key : counter.keySet())
        if (key.length() < 2 || key.matches("[a-z]+"))
            remove.add(key);
    for (String key : remove)
        counter.removeKey(key);

    counter.pruneKeysBelowThreshold(4.0);

    final double totalCount = counter.totalCount();

    Collections.sort(this, new Comparator<List<String>>() {

        @Override
        public int compare(List<String> o1, List<String> o2) {
            double c1 = sumOverTokens(counter, o1.get(column), totalCount);
            double c2 = sumOverTokens(counter, o2.get(column), totalCount);
            return Double.compare(c1, c2);
        }

    });
}

From source file:org.zanata.action.ProjectHomeAction.java

public String getCopyVersionCompletePercent(String projectSlug, String versionSlug) {
    CopyVersionTaskHandle handler = copyVersionManager.getCopyVersionProcessHandle(projectSlug, versionSlug);
    if (handler != null) {
        double completedPercent = (double) handler.getCurrentProgress() / (double) handler.getMaxProgress()
                * 100;//from  w ww .  j a  v a 2 s  .  co  m
        if (Double.compare(completedPercent, 100) == 0) {
            setMessage(msgs.format("jsf.copyVersion.Completed", versionSlug));
        }
        return String.format("%1$,.2f", completedPercent);
    } else {
        return "0";
    }
}

From source file:eu.planets_project.pp.plato.evaluation.evaluators.FITSEvaluator.java

public HashMap<MeasurementInfoUri, Value> evaluate(Alternative alternative, SampleObject sample,
        DigitalObject result, List<MeasurementInfoUri> measurementInfoUris, IStatusListener listener)
        throws EvaluatorException {

    FloatFormatter formatter = new FloatFormatter();

    HashMap<MeasurementInfoUri, Value> results = new HashMap<MeasurementInfoUri, Value>();

    String fitsXMLResult = result.getFitsXMLString();
    String fitsXMLSample = sample.getFitsXMLString();

    XmlExtractor extractor = new XmlExtractor();
    extractor.setNamespaceContext(new FitsNamespaceContext());
    if ((fitsXMLResult != null) && (fitsXMLSample != null)) {
        // so we have a fits xml, lets analyse it:
        try {// ww w .  j  av a  2s.c o  m
            StringReader reader = new StringReader(fitsXMLResult);
            Document fitsDocResult = extractor.getDocument(new InputSource(reader));
            reader = new StringReader(fitsXMLSample);
            Document fitsDocSample = extractor.getDocument(new InputSource(reader));

            String sampleImageCompressionScheme = extractor.extractText(fitsDocSample,
                    "//fits:compressionScheme/text()");
            String resultImageCompressionScheme = extractor.extractText(fitsDocResult,
                    "//fits:compressionScheme/text()");

            for (MeasurementInfoUri measurementInfoUri : measurementInfoUris) {
                Value v = null;
                String propertyURI = measurementInfoUri.getAsURI();
                Scale scale = descriptor.getMeasurementScale(measurementInfoUri);
                if (scale == null) {
                    // This means that I am not entitled to evaluate this measurementInfo and therefore supposed to skip it:
                    continue;
                }
                if (OBJECT_FORMAT_CORRECT_WELLFORMED.equals(propertyURI)) {
                    v = extractor.extractValue(fitsDocResult, scale,
                            "//fits:well-formed[@status='SINGLE_RESULT']/text()",
                            "//fits:filestatus/fits:message/text()");
                } else if (OBJECT_FORMAT_CORRECT_VALID.equals(propertyURI)) {
                    v = extractor.extractValue(fitsDocResult, scale,
                            "//fits:filestatus/fits:valid[@status='SINGLE_RESULT']/text()",
                            "//fits:filestatus/fits:message/text()");
                }
                if (OBJECT_COMPRESSION_SCHEME.equals(propertyURI)) {
                    v = extractor.extractValue(fitsDocResult, scale, "//fits:compressionScheme/text()", null);
                }

                if ((v != null) && (v.getComment() == null || "".equals(v.getComment()))) {
                    v.setComment(SOURCE);
                    results.put(measurementInfoUri, v);
                    listener.updateStatus(String.format("%s: measurement: %s = %s", NAME,
                            measurementInfoUri.getAsURI(), v.toString()));
                    // this leaf has been processed
                    continue;
                }

                if (OBJECT_FORMAT_CORRECT_CONFORMS.equals(propertyURI)) {
                    if (alternative.getAction() != null) {
                        String puid = "UNDEFINED";
                        FormatInfo info = alternative.getAction().getTargetFormatInfo();
                        if (info != null) {
                            puid = info.getPuid();
                        }
                        String fitsText = extractor.extractText(fitsDocResult,
                                "//fits:externalIdentifier[@type='puid']/text()");
                        v = identicalValues(puid, fitsText, scale);
                    }
                } else if ((OBJECT_IMAGE_DIMENSION_WIDTH + "#equal").equals(propertyURI)) {
                    String sampleValue = extractor.extractText(fitsDocSample, "//fits:imageWidth/text()");
                    String resultValue = extractor.extractText(fitsDocResult, "//fits:imageWidth/text()");
                    v = identicalValues(sampleValue, resultValue, scale);
                } else if ((OBJECT_IMAGE_DIMENSION_HEIGHT + "#equal").equals(propertyURI)) {
                    String sampleValue = extractor.extractText(fitsDocSample, "//fits:imageHeight/text()");
                    String resultValue = extractor.extractText(fitsDocResult, "//fits:imageHeight/text()");
                    v = identicalValues(sampleValue, resultValue, scale);
                } else if ((OBJECT_IMAGE_DIMENSION_ASPECTRATIO + "#equal").equals(propertyURI)) {
                    try {
                        int sampleHeight = Integer
                                .parseInt(extractor.extractText(fitsDocSample, "//fits:imageHeight/text()"));
                        int resultHeight = Integer
                                .parseInt(extractor.extractText(fitsDocResult, "//fits:imageHeight/text()"));
                        int sampleWidth = Integer
                                .parseInt(extractor.extractText(fitsDocSample, "//fits:imageWidth/text()"));
                        int resultWidth = Integer
                                .parseInt(extractor.extractText(fitsDocResult, "//fits:imageWidth/text()"));

                        double sampleRatio = ((double) sampleWidth) / sampleHeight;
                        double resultRatio = ((double) resultWidth) / resultHeight;
                        v = scale.createValue();
                        ((BooleanValue) v).bool(0 == Double.compare(sampleRatio, resultRatio));
                        v.setComment(String.format("Reference value: %s\nActual value: %s",
                                formatter.formatFloat(sampleRatio), formatter.formatFloat(resultRatio)));
                    } catch (NumberFormatException e) {
                        // not all values are available - aspectRatio cannot be calculated 
                        v = scale.createValue();
                        v.setComment(
                                "Image width and/or height are not available - aspectRatio cannot be calculated");
                    }
                } else if ((OBJECT_COMPRESSION_SCHEME + "#equal").equals(propertyURI)) {
                    v = identicalValues(sampleImageCompressionScheme, resultImageCompressionScheme, scale);
                } else if (OBJECT_COMPRESSION_LOSSLESS.equals(propertyURI)) {
                    // At the moment we only handle compression schemes of images
                    if ((resultImageCompressionScheme != null) && (!"".equals(resultImageCompressionScheme))) {
                        v = scale.createValue();
                        ((BooleanValue) v)
                                .bool(FITS_COMPRESSIONSCHEME_UNCOMPRESSED.equals(resultImageCompressionScheme));
                    }
                } else if (OBJECT_COMPRESSION_LOSSY.equals(propertyURI)) {
                    // At the moment we only handle compression schemes of images
                    if ((resultImageCompressionScheme != null) && (!"".equals(resultImageCompressionScheme))) {
                        v = scale.createValue();
                        ((BooleanValue) v).bool(
                                !FITS_COMPRESSIONSCHEME_UNCOMPRESSED.equals(resultImageCompressionScheme));
                    }
                } else if ((OBJECT_IMAGE_COLORENCODING_BITSPERSAMPLE + "#equal").equals(propertyURI)) {
                    String sampleValue = extractor.extractText(fitsDocSample, "//fits:bitsPerSample/text()");
                    String resultValue = extractor.extractText(fitsDocResult, "//fits:bitsPerSample/text()");
                    v = identicalValues(sampleValue, resultValue, scale);
                } else if ((OBJECT_IMAGE_COLORENCODING_SAMPLESPERPIXEL + "#equal").equals(propertyURI)) {
                    String sampleValue = extractor.extractText(fitsDocSample, "//fits:samplesPerPixel/text()");
                    String resultValue = extractor.extractText(fitsDocResult, "//fits:samplesPerPixel/text()");
                    v = identicalValues(sampleValue, resultValue, scale);
                } else if ((OBJECT_IMAGE_PHOTOMETRICINTERPRETATION_COLORSPACE + "#equal").equals(propertyURI)) {
                    String sampleValue = extractor.extractText(fitsDocSample, "//fits:colorSpace/text()");
                    String resultValue = extractor.extractText(fitsDocResult, "//fits:colorSpace/text()");
                    v = identicalValues(sampleValue, resultValue, scale);
                } else if ((OBJECT_IMAGE_PHOTOMETRICINTERPRETATION_COLORPROFILE_ICCPROFILE + "#equal")
                        .equals(propertyURI)) {
                    String sampleValue = extractor.extractText(fitsDocSample, "//fits:iccProfileName/text()");
                    String resultValue = extractor.extractText(fitsDocResult, "//fits:iccProfileName/text()");
                    v = identicalValues(sampleValue, resultValue, scale);
                } else if ((OBJECT_IMAGE_SPATIALMETRICS_SAMPLINGFREQUENCYUNIT + "#equal").equals(propertyURI)) {
                    String sampleValue = extractor.extractText(fitsDocSample,
                            "//fits:samplingFrequencyUnit/text()");
                    String resultValue = extractor.extractText(fitsDocResult,
                            "//fits:samplingFrequencyUnit/text()");
                    v = identicalValues(sampleValue, resultValue, scale);
                } else if ((OBJECT_IMAGE_SPATIALMETRICS_XSAMPLINGFREQUENCY + "#equal").equals(propertyURI)) {
                    String sampleValue = extractor.extractText(fitsDocSample,
                            "//fits:xSamplingFrequency/text()");
                    String resultValue = extractor.extractText(fitsDocResult,
                            "//fits:xSamplingFrequency/text()");
                    v = identicalValues(sampleValue, resultValue, scale);
                } else if ((OBJECT_IMAGE_SPATIALMETRICS_YSAMPLINGFREQUENCY + "#equal").equals(propertyURI)) {
                    String sampleValue = extractor.extractText(fitsDocSample,
                            "//fits:ySamplingFrequency/text()");
                    String resultValue = extractor.extractText(fitsDocResult,
                            "//fits:ySamplingFrequency/text()");
                    v = identicalValues(sampleValue, resultValue, scale);

                } else if ((OBJECT_IMAGE_METADATA + "#equal").equals(propertyURI)) {
                    // we use the equal metric. reserve PRESERVED metric for later and get it right.
                    HashMap<String, String> sampleMetadata = extractor.extractValues(fitsDocSample,
                            "//fits:exiftool/*[local-name() != 'rawdata']");
                    HashMap<String, String> resultMetadata = extractor.extractValues(fitsDocResult,
                            "//fits:exiftool/*[local-name() != 'rawdata']");
                    v = preservedValues(sampleMetadata, resultMetadata, scale);
                } else if ((OBJECT_IMAGE_METADATA_PRODUCER + "#equal").equals(propertyURI)) {
                    String sampleValue = extractor.extractText(fitsDocSample,
                            "//fits:ImageCreation/ImageProducer/text()");
                    String resultValue = extractor.extractText(fitsDocResult,
                            "//fits:ImageCreation/ImageProducer/text()");
                    v = identicalValues(sampleValue, resultValue, scale);
                } else if ((OBJECT_IMAGE_METADATA_SOFTWARE + "#equal").equals(propertyURI)) {
                    String sampleValue = extractor.extractText(fitsDocSample,
                            "//fits:creatingApplicationName/text()");
                    String resultValue = extractor.extractText(fitsDocResult,
                            "//fits:creatingApplicationName/text()");
                    v = identicalValues(sampleValue, resultValue, scale);
                } else if ((OBJECT_IMAGE_METADATA_CREATIONDATE + "#equal").equals(propertyURI)) {
                    String sampleValue = extractor.extractText(fitsDocSample,
                            "//fits:ImageCreation/DateTimeCreated/text()");
                    String resultValue = extractor.extractText(fitsDocResult,
                            "//fits:ImageCreation/DateTimeCreated/text()");
                    v = identicalValues(sampleValue, resultValue, scale);
                } else if ((OBJECT_IMAGE_METADATA_LASTMODIFIED + "#equal").equals(propertyURI)) {
                    String sampleValue = extractor.extractText(fitsDocSample,
                            "//fits:fileinfo/lastmodified/text()");
                    String resultValue = extractor.extractText(fitsDocResult,
                            "//fits:fileinfo/lastmodified/text()");
                    v = identicalValues(sampleValue, resultValue, scale);
                } else if ((OBJECT_IMAGE_METADATA_DESCRIPTION + "#equal").equals(propertyURI)) {
                    String sampleValue = extractor.extractText(fitsDocSample,
                            "//fits:exiftool/ImageDescription/text()");
                    String resultValue = extractor.extractText(fitsDocResult,
                            "//fits:exiftool/ImageDescription/text()");
                    v = identicalValues(sampleValue, resultValue, scale);
                } else if ((OBJECT_IMAGE_METADATA_ORIENTATION + "#equal").equals(propertyURI)) {
                    String sampleValue = extractor.extractText(fitsDocSample,
                            "//fits:exiftool/Orientation/text()");
                    String resultValue = extractor.extractText(fitsDocResult,
                            "//fits:exiftool/Orientation/text()");
                    v = identicalValues(sampleValue, resultValue, scale);
                }

                if (v != null) {
                    v.setComment(v.getComment() + SOURCE);
                    results.put(measurementInfoUri, v);
                    listener.updateStatus(String.format("%s: evaluated measurement: %s = %s", NAME,
                            measurementInfoUri.getAsURI(), v.toString()));
                } else {
                    listener.updateStatus(String.format("%s: no evaluator found for measurement: %s", NAME,
                            measurementInfoUri.getAsURI()));
                }
            }
        } catch (IOException e) {
            listener.updateStatus(" - could not read FITS xml");
        } catch (SAXException e) {
            listener.updateStatus(" - invalid FITS xml found");
        } catch (ParserConfigurationException e) {
            listener.updateStatus(" - invalid FITS xml found");
        }
    } else {
        listener.updateStatus(" - no FITS xml found");
    }
    return results;
}

From source file:org.devathon.contest2016.npc.NPCController.java

public void updateEquipment() {
    for (ArmorCategory category : ArmorCategory.values()) {
        List<Pair<ItemStack, Double>> weighted = itemStacks.stream()
                .map(itemStack -> Pair.of(itemStack, getGenericDefense(category, itemStack.getType())))
                .filter(pair -> pair.getRight() > 0).collect(Collectors.toList());

        weighted.sort((a, b) -> -Double.compare(a.getRight(), b.getRight()));

        if (weighted.size() > 0) {
            category.applyTo(getBukkitEntity(), weighted.get(0).getLeft());
        }/*from  ww  w .  j  a  va2 s  . co m*/
    }

    List<Pair<ItemStack, Double>> weighted = itemStacks.stream()
            .map(itemStack -> Pair.of(itemStack, getGenericAttackDamage(itemStack.getType())))
            .filter(pair -> pair.getRight() > 0).collect(Collectors.toList());

    weighted.sort((a, b) -> -Double.compare(a.getRight(), b.getRight()));

    if (weighted.size() > 0) {
        getBukkitEntity().getEquipment().setItemInMainHand(weighted.get(0).getLeft());
    }
}

From source file:org.orekit.time.TimeComponents.java

/** {@inheritDoc} */
public int compareTo(final TimeComponents other) {
    return Double.compare(getSecondsInDay(), other.getSecondsInDay());
}

From source file:de.dfki.madm.anomalydetection.operator.statistical_based.RobustPCAOperator.java

@Override
public void doWork() throws OperatorException {
    // check whether all attributes are numerical
    ExampleSet exampleSet = exampleSetInput.getData(ExampleSet.class);

    Tools.onlyNonMissingValues(exampleSet, "PCA");
    Tools.onlyNumericalAttributes(exampleSet, "PCA");

    // Get normal probability.
    double normProb = getParameterAsDouble(PARAMETER_OUTLIER_PROBABILITY);
    int olInst = exampleSet.size() - (int) Math.floor(exampleSet.size() * normProb);
    log("Ignoring " + olInst + " anomalyous instances for robustness.");

    // The robust estimate is based on removing top outliers first based on Mahalanobis distance (MD).
    // Since MD is the same as the outlier score when using all PCs, the PCA is done twice:
    // First with all examples, second with top-outliers removed (robust)

    // First PCA for outlier removal
    // create covariance matrix
    Matrix covarianceMatrix = CovarianceMatrix.getCovarianceMatrix(exampleSet);

    // EigenVector and EigenValues of the covariance matrix
    EigenvalueDecomposition eigenvalueDecomposition = covarianceMatrix.eig();

    // create and deliver results
    double[] eigenvalues = eigenvalueDecomposition.getRealEigenvalues();
    Matrix eigenvectorMatrix = eigenvalueDecomposition.getV();
    double[][] eigenvectors = eigenvectorMatrix.getArray();

    PCAModel model = new PCAModel(exampleSet, eigenvalues, eigenvectors);

    // Perform transformation
    ExampleSet res = model.apply((ExampleSet) exampleSet.clone());

    // Compute simple list with MDs and sort according to MD.
    List<double[]> l = new LinkedList<double[]>();
    double eIdx = 0;
    for (Example example : res) {
        double md = 0.0;
        int aNr = 0;
        for (Attribute attr : example.getAttributes()) {
            double pcscore = example.getValue(attr);
            md += (pcscore * pcscore) / model.getEigenvalue(aNr);
            aNr++;/*from   w w  w  .  jav a2s .c om*/
        }
        double[] x = { md, eIdx };
        l.add(x);
        eIdx++;
    }
    Collections.sort(l, new Comparator<double[]>() {
        public int compare(double[] first, double[] second) {
            return Double.compare(second[0], first[0]);
        }
    });
    // Out of the list, create array with outlier-indexes and array (mapping) with good instances. 
    Iterator<double[]> iter = l.iterator();
    int[] olMapping = new int[olInst];
    for (int i = 0; i < olInst; i++) {
        olMapping[i] = (int) ((double[]) iter.next())[1];
    }
    Arrays.sort(olMapping);
    int[] mapping = new int[exampleSet.size() - olInst];
    int olc = 0;
    int ctr = 0;
    for (int i = 0; i < exampleSet.size(); i++) {
        if (olc == olInst) { // Add last elements after last outlier
            mapping[ctr++] = i;
            continue;
        }
        if (olMapping[olc] != i) {
            mapping[ctr++] = i;
        } else {
            olc++;
        }
    }
    ExampleSet robustExampleSet = new MappedExampleSet(exampleSet, mapping); // creates a new example set without the top outliers.

    // ---
    // Second PCA (robust)
    covarianceMatrix = CovarianceMatrix.getCovarianceMatrix(robustExampleSet);
    eigenvalueDecomposition = covarianceMatrix.eig();

    // create and deliver results
    eigenvalues = eigenvalueDecomposition.getRealEigenvalues();
    eigenvectorMatrix = eigenvalueDecomposition.getV();
    eigenvectors = eigenvectorMatrix.getArray();

    // Apply on original set
    model = new PCAModel(exampleSet, eigenvalues, eigenvectors);

    // Perform transformation
    res = model.apply((ExampleSet) exampleSet.clone());

    // Sort eigenvalues
    Arrays.sort(eigenvalues);
    ArrayUtils.reverse(eigenvalues);

    // if necessary reduce nbr of dimensions ...
    int reductionType = getParameterAsInt(PARAMETER_REDUCTION_TYPE);
    List<Integer> pcList = new ArrayList<Integer>();
    if (reductionType == PCS_ALL) {
        for (int i = 0; i < exampleSet.getAttributes().size(); i++) {
            pcList.add(i);
        }
    }
    if (reductionType == PCS_TOP || reductionType == PCS_BOTH) {
        //top
        switch (getParameterAsInt(PARAMETER_TOP_METHODS)) {
        case PCS_TOP_FIX:
            for (int i = 0; i < getParameterAsInt(PARAMETER_NUMBER_OF_COMPONENTS_TOP); i++) {
                pcList.add(i);
            }
            break;
        case PCS_TOP_VAR:
            double var = getParameterAsDouble(PARAMETER_VARIANCE_THRESHOLD);
            boolean last = false;
            for (int i = 0; i < exampleSet.getAttributes().size(); i++) {
                if (model.getCumulativeVariance(i) < var) {
                    pcList.add(i);
                } else if (!last) { // we need to add another PC to meet the minimum requirement.
                    last = true;
                    pcList.add(i);
                }
            }
            break;
        }
    }
    if (reductionType == PCS_LOWER || reductionType == PCS_BOTH) {
        //lower
        switch (getParameterAsInt(PARAMETER_LOW_METHODS)) {
        case PCS_LOW_FIX:
            for (int i = exampleSet.getAttributes().size()
                    - getParameterAsInt(PARAMETER_NUMBER_OF_COMPONENTS_LOW); i < exampleSet.getAttributes()
                            .size(); i++) {
                pcList.add(i);
            }
            break;
        case PCS_LOW_VAL:
            double val = getParameterAsDouble(PARAMETER_VALUE_THRESHOLD);
            for (int i = 0; i < eigenvalues.length; i++) {
                if (eigenvalues[i] <= val) {
                    if (pcList.size() == 0) {
                        pcList.add(i);
                    } else if (pcList.get(pcList.size() - 1).intValue() < i) {
                        pcList.add(i);
                    }
                }
            }
            break;
        }
    }
    int[] opcs = ArrayUtils.toPrimitive(pcList.toArray(new Integer[pcList.size()]));

    if (opcs.length == 0) {
        throw new UserError(this,
                "Parameters thresholds are selected such that they did not match any principal component. Lower variance or increase eigenvalue threshold.");
    }
    if (opcs.length == exampleSet.getAttributes().size()) {
        log("Using all PCs for score.");
    } else {
        log("Using following PCs for score: " + Arrays.toString(opcs));
    }

    // Normalize by Chi-Dist with d degrees of freedom
    double scoreNormalizer = 1.0;
    ChiSquaredDistributionImpl chi = new ChiSquaredDistributionImpl(opcs.length);
    try {
        scoreNormalizer = chi.inverseCumulativeProbability(normProb);
    } catch (MathException e) {
        System.err.println(e);
    }
    log("Normalizing score with chi cumulative propability: " + scoreNormalizer);

    // compute scores
    Attribute scoreAttr = AttributeFactory.createAttribute("outlier", Ontology.REAL);
    exampleSet.getExampleTable().addAttribute(scoreAttr);
    exampleSet.getAttributes().setOutlier(scoreAttr);
    for (int exNr = 0; exNr < exampleSet.size(); exNr++) {
        Example orig = exampleSet.getExample(exNr);
        Example pc = res.getExample(exNr);
        double oscore = 0.0;
        int aNr = 0;
        ctr = 0;
        for (Attribute attr : pc.getAttributes()) {
            if (ctr < opcs.length && opcs[ctr] != aNr) { // we skip this dimension
                aNr++;
                continue;
            }
            double pcscore = pc.getValue(attr);
            oscore += (pcscore * pcscore) / model.getEigenvalue(aNr);
            aNr++;
            ctr++;
        }
        orig.setValue(scoreAttr, oscore / scoreNormalizer);
    }
    exampleSetOutput.deliver(exampleSet);
}

From source file:com.vsthost.rnd.commons.math.ext.linear.DMatrixUtils.java

/**
 * Get the order of the specified elements in descending or ascending order.
 *
 * @param values A vector of integer values.
 * @param indices The indices which will be considered for ordering.
 * @param descending Flag indicating if we go descending or not.
 * @return A vector of indices sorted in the provided order.
 *//* www . java2 s.  c om*/
public static int[] getOrder(int[] values, int[] indices, boolean descending) {
    // Create an index series:
    Integer[] opIndices = ArrayUtils.toObject(indices);

    // Sort indices:
    Arrays.sort(opIndices, new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {
            if (descending) {
                return Double.compare(values[o2], values[o1]);
            } else {
                return Double.compare(values[o1], values[o2]);
            }
        }
    });

    return ArrayUtils.toPrimitive(opIndices);
}