Example usage for java.util List indexOf

List of usage examples for java.util List indexOf

Introduction

In this page you can find the example usage for java.util List indexOf.

Prototype

int indexOf(Object o);

Source Link

Document

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

Usage

From source file:com.cloudera.oryx.rdf.common.pmml.DecisionForestPMML.java

/**
 * @param pmmlFile file to read PMML encoding from
 * @return a {@link DecisionForest} representation of the PMML encoded model
 *///  www  .  jav  a2s  . c o m
public static Pair<DecisionForest, Map<Integer, BiMap<String, Integer>>> read(File pmmlFile)
        throws IOException {

    PMML pmml;
    InputStream in = IOUtils.openMaybeDecompressing(pmmlFile);
    try {
        pmml = IOUtil.unmarshal(in);
    } catch (SAXException e) {
        throw new IOException(e);
    } catch (JAXBException e) {
        throw new IOException(e);
    } finally {
        in.close();
    }

    List<Model> models = pmml.getModels();
    Preconditions.checkNotNull(models);
    Preconditions.checkArgument(!models.isEmpty());
    Preconditions.checkArgument(models.get(0) instanceof MiningModel);
    MiningModel miningModel = (MiningModel) models.get(0);

    Segmentation segmentation = miningModel.getSegmentation();
    Preconditions.checkNotNull(segmentation);

    List<Segment> segments = segmentation.getSegments();
    Preconditions.checkNotNull(segments);
    Preconditions.checkArgument(!segments.isEmpty());

    Map<Integer, BiMap<String, Integer>> columnToCategoryNameToIDMapping = PMMLUtils
            .buildColumnCategoryMapping(pmml.getDataDictionary());
    InboundSettings settings = InboundSettings.create(ConfigUtils.getDefaultConfig());
    DecisionTree[] trees = new DecisionTree[segments.size()];
    double[] weights = new double[trees.length];
    for (int i = 0; i < trees.length; i++) {
        Segment segment = segments.get(i);
        weights[i] = segment.getWeight();
        TreeModel treeModel = (TreeModel) segment.getModel();
        TreeNode root = translateFromPMML(treeModel.getNode(), columnToCategoryNameToIDMapping, settings);
        trees[i] = new DecisionTree(root);
    }

    List<String> columnNames = settings.getColumnNames();
    List<MiningField> fields = miningModel.getMiningSchema().getMiningFields();
    double[] featureImportances = new double[fields.size()];
    for (MiningField field : fields) {
        Double importance = field.getImportance();
        if (importance != null) {
            int featureNumber = columnNames.indexOf(field.getName().getValue());
            featureImportances[featureNumber] = importance;
        }
    }

    return new Pair<DecisionForest, Map<Integer, BiMap<String, Integer>>>(
            new DecisionForest(trees, weights, featureImportances), columnToCategoryNameToIDMapping);
}

From source file:de.tudarmstadt.ukp.dkpro.tc.core.util.ReportUtils.java

/**
 * Creates a confusion matrix by collecting the results from the overall CV run stored in
 * {@code tempM}//w  w  w . ja va  2 s  .  co m
 * 
 * @param tempM
 * @param actualLabelsList
 *            the label powerset transformed list of actual/true labels
 * @param predictedLabelsList
 *            the label powerset transformed list of predicted labels
 * @return
 */
public static double[][] createConfusionMatrix(HashMap<String, Map<String, Integer>> tempM,
        List<String> actualLabelsList, List<String> predictedLabelsList) {
    double[][] matrix = new double[actualLabelsList.size()][predictedLabelsList.size()];

    Iterator<String> actualsIter = tempM.keySet().iterator();
    while (actualsIter.hasNext()) {
        String actual = actualsIter.next();
        Iterator<String> predsIter = tempM.get(actual).keySet().iterator();
        while (predsIter.hasNext()) {
            String pred = predsIter.next();
            int a = actualLabelsList.indexOf(actual);
            int p = predictedLabelsList.indexOf(pred);
            matrix[a][p] = tempM.get(actual).get(pred);
        }
    }
    return matrix;
}

From source file:it.eng.spagobi.engines.worksheet.bo.WorkSheetDefinition.java

public static Map<String, List<String>> mergeDomainValuesFilters(List<Attribute> globalFilters,
        List<Attribute> sheetFilters) throws WrongConfigurationForFiltersOnDomainValuesException {
    Iterator<Attribute> globalFiltersIt = globalFilters.iterator();
    Map<String, List<String>> toReturn = new HashMap<String, List<String>>();
    while (globalFiltersIt.hasNext()) {
        Attribute aGlobalFilter = globalFiltersIt.next();
        if (sheetFilters.contains(aGlobalFilter)) { // the filter is defined globally and also on sheets
            // wins the more restrictive filter
            int index = sheetFilters.indexOf(aGlobalFilter);
            Attribute sheetsFilter = sheetFilters.get(index);
            List<String> aGlobalFilterValues = aGlobalFilter.getValuesAsList();
            List<String> sheetsFilterValues = sheetsFilter.getValuesAsList();
            if (aGlobalFilterValues.containsAll(sheetsFilterValues)) {
                // the sheets filters are less or equal to the global filters (this should always happen)
                toReturn.put(aGlobalFilter.getEntityId(), sheetsFilterValues);
            } else {
                logger.error("The global filter on field " + aGlobalFilter.getAlias()
                        + " is overridden by the sheet.");
                throw new WrongConfigurationForFiltersOnDomainValuesException(
                        "The global filter on field " + aGlobalFilter.getAlias()
                                + " is overridden by the sheet. Please expand the global filter's values.");
            }//from   w w  w . java 2  s.co  m
        } else {
            toReturn.put(aGlobalFilter.getEntityId(), aGlobalFilter.getValuesAsList());
        }
    }
    Iterator<Attribute> sheetFiltersIt = sheetFilters.iterator();
    while (sheetFiltersIt.hasNext()) {
        Attribute aSheetsFilter = sheetFiltersIt.next();
        if (toReturn.containsKey(aSheetsFilter.getEntityId())) {
            // conflict already solved
            continue;
        }
        toReturn.put(aSheetsFilter.getEntityId(), aSheetsFilter.getValuesAsList());
    }
    return toReturn;
}

From source file:edu.cmu.tetrad.search.IndTestMultiFisherZ.java

/**
 * Returns the submatrix of m with variables in the order of the x variables.
 *//*from   w w  w  .java  2 s  . com*/
public static TetradMatrix subMatrix(ICovarianceMatrix m, List<Node> x, List<Node> y, List<Node> z) {
    List<Node> variables = m.getVariables();
    TetradMatrix _covMatrix = m.getMatrix();

    // Create index array for the given variables.
    int[] indices = new int[x.size() + y.size() + z.size()];

    for (int i = 0; i < x.size(); i++) {
        indices[i] = variables.indexOf(x.get(i));
    }

    for (int i = 0; i < y.size(); i++) {
        indices[x.size() + i] = variables.indexOf(y.get(i));
    }

    for (int i = 0; i < z.size(); i++) {
        indices[x.size() + y.size() + i] = variables.indexOf(z.get(i));
    }

    // Extract submatrix of correlation matrix using this index array.
    TetradMatrix submatrix = _covMatrix.getSelection(indices, indices);

    return submatrix;
}

From source file:net.minecraftforge.fml.relauncher.libraries.LibraryManager.java

public static List<Artifact> flattenLists(File mcDir) {
    List<Artifact> merged = new ArrayList<>();
    for (ModList list : ModList.getBasicLists(mcDir)) {
        for (Artifact art : list.flatten()) {
            Optional<Artifact> old = merged.stream().filter(art::matchesID).findFirst();
            if (!old.isPresent()) {
                merged.add(art);//from   w w w .  java2 s .com
            } else if (old.get().getVersion().compareTo(art.getVersion()) < 0) {
                merged.add(merged.indexOf(old.get()), art);
                merged.remove(old.get());
            }
        }
    }
    return merged;
}

From source file:com.bluexml.side.m2.repositoryBuilder.Builder.java

private static void applyOptionalJob(File rootPlugins, String option, String filePath)
        throws Exception, IOException {
    if (option.equals("-makeDot")) {
        writeDotFile(rootPlugins, filePath);
        System.out.println("graph dot file generated :" + filePath);
    } else if (option.equals("-patchPom")) {
        List<ModuleConstraint> res = Builder.getModulesConstraint(rootPlugins);
        // add dependency plugin used by SIDE
        ModuleConstraint McForMavenDependeciesPlugins = new ModuleConstraint(
                "org.apache.maven.plugins.maven-dependency-plugin", null, "maven-plugin", "2.0", "2.0");
        res.add(McForMavenDependeciesPlugins);

        File file = new File(filePath);
        if (!file.exists()) {
            System.err.println("File do not exist :" + file);
        }/*from  w  w w  .j av  a  2s. c  o m*/
        List<File> poms = new ArrayList<File>();
        for (ModuleConstraint moduleConstraint : res) {
            File destFile = new File(file.getParent(), res.indexOf(moduleConstraint) + "_.pom");
            FileUtils.copyFile(file, destFile);
            List<ModuleConstraint> res_ = new ArrayList<ModuleConstraint>();
            res_.add(moduleConstraint);
            writePomFile(destFile, res_);
            System.out.println("pom Patched" + destFile);
            poms.add(destFile);
        }
        // write pom.sh script that call go-offline for each patched poms
        Builder.writeShellScript(new File(file.getParent(), "pom.sh"), poms);
    }
}

From source file:com.mh.commons.utils.Reflections.java

/**
 * ?? trim() /*www .ja va2s.  c o m*/
 * ?? trim();  ??
 * @param obj
 * @param escapeList ??trim()
 * @return
 */
public static Object trim(Object obj, List<String> escapeList) {
    if (obj == null)
        return null;
    try {
        Field[] fields = obj.getClass().getDeclaredFields();
        if (fields != null && fields.length > 0) {
            for (Field field : fields) {
                if (field.getModifiers() < 15 && field.getType().toString().equals("class java.lang.String")) {
                    Object val = FieldUtils.readField(field, obj, true);
                    if (val != null) {
                        if (escapeList != null && escapeList.indexOf(field.getName()) != -1)
                            continue;
                        FieldUtils.writeField(field, obj, val.toString().trim(), true);
                    }
                }
            }
        }
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    return obj;
}

From source file:de.tudarmstadt.ukp.similarity.experiments.coling2012.util.Evaluator.java

@SuppressWarnings("unchecked")
public static void runEvaluationMetric(WekaClassifier wekaClassifier, EvaluationMetric metric, Dataset dataset)
        throws IOException {
    StringBuilder sb = new StringBuilder();

    List<String> gold = ColingUtils.readGoldstandard(dataset);
    List<String> exp = FileUtils.readLines(
            new File(OUTPUT_DIR + "/" + dataset.toString() + "/" + wekaClassifier.toString() + "/output.csv"));

    if (metric.equals(EvaluationMetric.Accuracy)) {
        double acc = 0.0;

        for (int i = 0; i < gold.size(); i++) {
            if (gold.get(i).equals(exp.get(i)))
                acc++;/*w w  w . j  ava 2  s.  c  om*/
        }

        acc /= gold.size();

        sb.append(acc);
    } else if (metric.equals(EvaluationMetric.AverageF1)) {
        // Get all classes
        Set<String> classesSet = new HashSet<String>();
        for (String cl : gold)
            classesSet.add(cl);

        // Order the classes
        List<String> classes = new ArrayList<String>(classesSet);

        // Initialize confusion matrix
        // exp\class   A   B
        // A         x1   x2
        // B         x3   x4         
        int[][] matrix = new int[classes.size()][classes.size()];

        // Initialize matrix
        for (int i = 0; i < classes.size(); i++)
            for (int j = 0; j < classes.size(); j++)
                matrix[i][j] = 0;

        // Construct confusion matrix
        for (int i = 0; i < gold.size(); i++) {
            int goldIndex = classes.indexOf(gold.get(i));
            int expIndex = classes.indexOf(exp.get(i));

            matrix[goldIndex][expIndex] += 1;
        }

        // Compute precision and recall per class
        double[] prec = new double[classes.size()];
        double[] rec = new double[classes.size()];

        for (int i = 0; i < classes.size(); i++) {
            double tp = matrix[i][i];
            double fp = 0.0;
            double fn = 0.0;

            // FP
            for (int j = 0; j < classes.size(); j++) {
                if (i == j)
                    continue;

                fp += matrix[j][i];
            }

            // FN
            for (int j = 0; j < classes.size(); j++) {
                if (i == j)
                    continue;

                fn += matrix[i][j];
            }

            // Save
            prec[i] = tp / (tp + fp);
            rec[i] = tp / (tp + fn);
        }

        // Compute average F1 score across all classes
        double f1 = 0.0;

        for (int i = 0; i < classes.size(); i++) {
            double f1PerClass = (2 * prec[i] * rec[i]) / (prec[i] + rec[i]);
            f1 += f1PerClass;
        }

        f1 = f1 / classes.size();

        // Output
        sb.append(f1);
    }

    FileUtils.writeStringToFile(new File(OUTPUT_DIR + "/" + dataset.toString() + "/" + wekaClassifier.toString()
            + "/" + metric.toString() + ".txt"), sb.toString());
}

From source file:edu.wpi.checksims.algorithm.similaritymatrix.SimilarityMatrix.java

/**
 * Generate a similarity matrix from a given set of submissions.
 *
 * @param inputSubmissions Submissions to generate from
 * @param results Results to build from. Must contain results for every possible unordered pair of input submissions
 * @return Similarity Matrix built from given results
 * @throws InternalAlgorithmError Thrown on missing results, or results containing a submission not in the input
 *///from   w  w w. j av  a  2  s. c om
public static SimilarityMatrix generateMatrix(Set<Submission> inputSubmissions, Set<AlgorithmResults> results)
        throws InternalAlgorithmError {
    checkNotNull(inputSubmissions);
    checkNotNull(results);
    checkArgument(!inputSubmissions.isEmpty(), "Must provide at least 1 submission to build matrix from");
    checkArgument(!results.isEmpty(), "Must provide at least 1 AlgorithmResults to build matrix from!");

    // Generate the matrix we'll use
    MatrixEntry[][] matrix = new MatrixEntry[inputSubmissions.size()][inputSubmissions.size()];

    // Order the submissions
    List<Submission> orderedSubmissions = Ordering.natural().immutableSortedCopy(inputSubmissions);

    // Generate the matrix

    // Start with the diagonal, filling with 100% similarity
    for (int i = 0; i < orderedSubmissions.size(); i++) {
        Submission s = orderedSubmissions.get(i);

        matrix[i][i] = new MatrixEntry(s, s, s.getNumTokens());
    }

    // Now go through all the results, and build appropriate two MatrixEntry objects for each
    for (AlgorithmResults result : results) {
        int aIndex = orderedSubmissions.indexOf(result.a);
        int bIndex = orderedSubmissions.indexOf(result.b);

        if (aIndex == -1) {
            throw new InternalAlgorithmError(
                    "Processed Algorithm Result with submission not in given input submissions with name \""
                            + result.a.getName() + "\"");
        } else if (bIndex == -1) {
            throw new InternalAlgorithmError(
                    "Processed Algorithm Result with submission not in given input submissions with name \""
                            + result.b.getName() + "\"");
        }

        matrix[aIndex][bIndex] = new MatrixEntry(result.a, result.b, result.identicalTokensA);
        matrix[bIndex][aIndex] = new MatrixEntry(result.b, result.a, result.identicalTokensB);
    }

    // Verification pass: Go through and ensure that the entire array was populated
    for (int x = 0; x < orderedSubmissions.size(); x++) {
        for (int y = 0; y < orderedSubmissions.size(); y++) {
            if (matrix[x][y] == null) {
                throw new InternalAlgorithmError("Missing Algorithm Results for comparison of submissions \""
                        + orderedSubmissions.get(x).getName() + "\" and \""
                        + orderedSubmissions.get(y).getName() + "\"");
            }
        }
    }

    return new SimilarityMatrix(matrix, orderedSubmissions, orderedSubmissions, results);
}

From source file:net.lldp.checksims.algorithm.similaritymatrix.SimilarityMatrix.java

/**
 * Generate a similarity matrix from a given set of submissions.
 *
 * @param inputSubmissions Submissions to generate from
 * @param results Results to build from. Must contain results for every possible unordered pair of input submissions
 * @return Similarity Matrix built from given results
 * @throws InternalAlgorithmError Thrown on missing results, or results containing a submission not in the input
 */// ww  w . j a  v a  2s . com
public static SimilarityMatrix generateMatrix(Set<Submission> inputSubmissions, Set<AlgorithmResults> results)
        throws InternalAlgorithmError {
    checkNotNull(inputSubmissions);
    checkNotNull(results);
    checkArgument(!inputSubmissions.isEmpty(), "Must provide at least 1 submission to build matrix from");
    checkArgument(!results.isEmpty(), "Must provide at least 1 AlgorithmResults to build matrix from!");

    // Generate the matrix we'll use
    AlgorithmResults[][] matrix = new AlgorithmResults[inputSubmissions.size()][inputSubmissions.size()];

    //Ordering sortBy = Ordering.natural();
    Ordering<Submission> sortBy = Ordering.from(new Comparator<Submission>() {
        public int compare(Submission a, Submission b) {
            return ((Double) b.getTotalCopyScore()).compareTo(a.getTotalCopyScore());
        }
    });

    // Order the submissions
    List<Submission> orderedSubmissions = sortBy.immutableSortedCopy(inputSubmissions);

    // Generate the matrix

    // Start with the diagonal, filling with 100% similarity
    for (int i = 0; i < orderedSubmissions.size(); i++) {
        Submission s = orderedSubmissions.get(i);

        matrix[i][i] = new AlgorithmResults(Pair.of(s, s), Real.ONE, Real.ONE);
    }

    // Now go through all the results, and build appropriate two MatrixEntry objects for each
    for (AlgorithmResults result : results) {
        int aIndex = orderedSubmissions.indexOf(result.a);
        int bIndex = orderedSubmissions.indexOf(result.b);

        if (aIndex == -1) {
            if (!result.a.testFlag("invalid")) {
                throw new InternalAlgorithmError(
                        "Processed Algorithm Result with submission not in given input submissions with name \""
                                + result.a.getName() + "\"");
            }
        } else if (bIndex == -1) {
            if (!result.b.testFlag("invalid")) {
                throw new InternalAlgorithmError(
                        "Processed Algorithm Result with submission not in given input submissions with name \""
                                + result.b.getName() + "\"");
            }
        } else {
            matrix[aIndex][bIndex] = result.inverse();
            matrix[bIndex][aIndex] = result;
        }
    }

    // Verification pass: Go through and ensure that the entire array was populated
    for (int x = 0; x < orderedSubmissions.size(); x++) {
        for (int y = 0; y < orderedSubmissions.size(); y++) {
            if (matrix[x][y] == null) {
                throw new InternalAlgorithmError("Missing Algorithm Results for comparison of submissions \""
                        + orderedSubmissions.get(x).getName() + "\" and \""
                        + orderedSubmissions.get(y).getName() + "\"");
            }
        }
    }

    return new SimilarityMatrix(matrix, orderedSubmissions, orderedSubmissions, results);
}