Example usage for com.google.common.base Functions forMap

List of usage examples for com.google.common.base Functions forMap

Introduction

In this page you can find the example usage for com.google.common.base Functions forMap.

Prototype

public static <K, V> Function<K, V> forMap(Map<K, V> map) 

Source Link

Document

Returns a function which performs a map lookup.

Usage

From source file:org.sosy_lab.cpachecker.util.predicates.AbstractionManager.java

public Region buildRegionFromFormula(BooleanFormula pF) {
    return rmgr.fromFormula(pF, fmgr, Functions.compose(new Function<AbstractionPredicate, Region>() {
        @Override/*from w w  w. ja v a2 s . co m*/
        public Region apply(AbstractionPredicate pInput) {
            return pInput.getAbstractVariable();
        }
    }, Functions.forMap(atomToPredicate)));
}

From source file:ch.uzh.ifi.attempto.acewiki.gf.GfGrammar.java

/**
 * <p>Returns the {@code k} largest categories in the order of size.
 * The size is in terms of the number of producer functions that are
 * not consumer functions.</p>/*from   w  ww . j  a v a2s  .  c o m*/
 */
public List<String> getLargestCategories(int k) {
    return Ordering.natural().onResultOf(Functions.forMap(mCatToSize)).greatestOf(mCatToSize.keySet(), k);
}

From source file:org.apache.ctakes.relationextractor.eval.SHARPXMI.java

public static <T extends Evaluation_ImplBase> void evaluate(EvaluationOptions options,
        ParameterSettings bestSettings, List<ParameterSettings> gridOfSettings,
        Function<ParameterSettings, T> getEvaluation) throws Exception {
    // define the set of possible training parameters
    List<ParameterSettings> possibleParams;
    if (options.getGridSearch()) {
        possibleParams = gridOfSettings;
    } else {/*w ww  .  j a v  a  2s.  c  o m*/
        possibleParams = Lists.newArrayList(bestSettings);
    }

    // run an evaluation for each set of parameters
    Map<ParameterSettings, Double> scoredParams = new HashMap<>();
    for (ParameterSettings params : possibleParams) {
        Evaluation_ImplBase evaluation = getEvaluation.apply(params);

        List<File> trainFiles, devFiles, testFiles;
        switch (options.getEvaluteOn()) {
        case TRAIN:
            // run n-fold cross-validation on the training set
            trainFiles = getTrainTextFiles(options.getBatchesDirectory());
            trainFiles = toXMIFiles(options, trainFiles);
            List<AnnotationStatistics<String>> foldStats = evaluation.crossValidation(trainFiles, 2);
            params.stats = AnnotationStatistics.addAll(foldStats);
            break;
        case DEV:
            // train on the training set and evaluate on the dev set
            trainFiles = getTrainTextFiles(options.getBatchesDirectory());
            trainFiles = toXMIFiles(options, trainFiles);
            devFiles = getDevTextFiles(options.getBatchesDirectory());
            devFiles = toXMIFiles(options, devFiles);
            params.stats = evaluation.trainAndTest(trainFiles, devFiles);
            break;
        case TEST:
            // train on the training set + dev set and evaluate on the test set
            List<File> allTrainFiles = new ArrayList<>();
            allTrainFiles.addAll(getTrainTextFiles(options.getBatchesDirectory()));
            allTrainFiles.addAll(getDevTextFiles(options.getBatchesDirectory()));
            allTrainFiles = toXMIFiles(options, allTrainFiles);
            testFiles = getTestTextFiles(options.getBatchesDirectory());
            testFiles = toXMIFiles(options, testFiles);
            params.stats = evaluation.trainAndTest(allTrainFiles, testFiles);
            break;
        case OTHER:
            // train on train + dev + specified train xmis and test on specified test xmi files
            // these files should have the necessary preprocessing in the initial view
            // and gold standard relation annotations in the gold view
            // the path to the xmi files must be specified from command line 
            List<File> trainAndDevFiles = new ArrayList<>();
            trainAndDevFiles.addAll(getTrainTextFiles(options.getBatchesDirectory()));
            trainAndDevFiles.addAll(getDevTextFiles(options.getBatchesDirectory()));
            trainAndDevFiles = toXMIFiles(options, trainAndDevFiles);

            // if path to additional train xmis is specified, add them to the training set
            if (options.getTrainXmiDir() != null) {
                for (File trainXmiFile : options.getTrainXmiDir().listFiles()) {
                    trainAndDevFiles.add(trainXmiFile);
                }
            }

            // now read the xmis we will use for evaluation
            List<File> testXmiFiles = new ArrayList<>();
            for (File testXmiFile : options.getTestXmiDir().listFiles()) {
                testXmiFiles.add(testXmiFile);
            }
            params.stats = evaluation.trainAndTest(trainAndDevFiles, testXmiFiles);
            break;
        default:
            throw new IllegalArgumentException("Invalid EvaluateOn: " + options.getEvaluteOn());
        }
        scoredParams.put(params, params.stats.f1());
    }

    // print parameters sorted by F1
    List<ParameterSettings> list = new ArrayList<>(scoredParams.keySet());
    Function<ParameterSettings, Double> getCount = Functions.forMap(scoredParams);
    Collections.sort(list, Ordering.natural().onResultOf(getCount));

    // print performance of each set of parameters
    if (list.size() > 1) {
        System.err.println("Summary");
        for (ParameterSettings params : list) {
            System.err.printf("F1=%.3f P=%.3f R=%.3f %s\n", params.stats.f1(), params.stats.precision(),
                    params.stats.recall(), params);
        }
        System.err.println();
    }

    // print overall best model
    if (!list.isEmpty()) {
        ParameterSettings lastParams = list.get(list.size() - 1);
        System.err.println("Best model:");
        System.err.print(lastParams.stats);
        System.err.println(lastParams);
        System.err.println(lastParams.stats.confusions());
        System.err.println();
    }
}

From source file:uk.org.rbc1b.roms.controller.volunteer.VolunteersController.java

/**
 * @return reference map for all skills.
 *//*from  w ww  .  j a v  a2 s .c  o m*/
private Map<Integer, DepartmentSkillNameModel> findSkills() {

    List<Department> departments = departmentDao.findDepartments();
    Map<Integer, String> departmentNames = new HashMap<Integer, String>();
    for (Department department : departments) {
        departmentNames.put(department.getDepartmentId(), department.getName());
    }

    List<Skill> skills = skillDao.findSkills(new SkillSearchCriteria());
    Map<Integer, DepartmentSkillNameModel> skillNames = new HashMap<Integer, DepartmentSkillNameModel>(
            skills.size());
    for (Skill skill : skills) {
        String departmentName = departmentNames.get(skill.getDepartment().getDepartmentId());

        skillNames.put(skill.getSkillId(), new DepartmentSkillNameModel(departmentName, skill.getName()));
    }

    // return the map, sorted by the value (department + skill name)
    return ImmutableSortedMap.copyOf(skillNames, Ordering.natural().onResultOf(Functions.forMap(skillNames)));
}

From source file:org.eclipse.sirius.diagram.ui.internal.edit.commands.DistributeCommand.java

/**
 * Must be called only when <code>wrappedCommand</code> is initialized.
 *
 * @param partsToBounds//from   w w  w .j  ava2s.c o  m
 *            List of parts to distribute associated with their bounds (the
 *            bounds of their figure).
 */
private void distributeHorizontallyWithUniformGaps(final HashMap<IGraphicalEditPart, Rectangle> partsToBounds) {
    GetNewBoundsFunction setXFunction = new GetNewBoundsFunction() {
        @Override
        public Rectangle apply(IGraphicalEditPart input) {
            return partsToBounds.get(input).getCopy().setX(previousPartBounds.getRight().x + gap);
        };
    };
    distributeWithUniformGaps(partsToBounds.keySet(), new GetLeftFunction(partsToBounds),
            new GetTopFunction(partsToBounds), new GetRightFunction(partsToBounds),
            new GetBottomFunction(partsToBounds), new GetWidthFunction(partsToBounds),
            new PartByCenter(partsToBounds), setXFunction, Functions.forMap(partsToBounds));
}

From source file:com.isotrol.impe3.pms.core.obj.ConnectorsObject.java

/**
 * Starts the connectors collection, in order.
 * @param model Model to apply./*from  w  w  w .j a  va2 s.c  om*/
 * @return The started connectors.
 */
public StartedConnectors start(ImpeIAModel model) {
    Map<UUID, StartedModule<?>> started = Maps.newHashMap();
    Function<UUID, StartedModule<?>> f = Functions.forMap(started);
    List<StartedModule<?>> connectorStop = Lists.newLinkedList();
    for (ConnectorObject c : getInstantiationOrder()) {
        final StartedModule<?> sm = c.starter(model, f).start(null);
        started.put(c.getId(), sm);
        connectorStop.add(0, sm);
    }
    return new StartedConnectors(started, connectorStop);
}

From source file:edu.uci.ics.jung.samples.PluggableRendererDemo.java

/**
 * Generates a mixed-mode random graph, runs VoltageRanker on it, and
 * returns the resultant graph./*from   www .j  a va2s.c o  m*/
 * @return the generated graph
 */
public Graph<Integer, Number> buildGraph() {
    Supplier<Graph<Integer, Number>> graphFactory = new Supplier<Graph<Integer, Number>>() {
        public Graph<Integer, Number> get() {
            return new SparseMultigraph<Integer, Number>();
        }
    };
    Supplier<Integer> vertexFactory = new Supplier<Integer>() {
        int count;

        public Integer get() {
            return count++;
        }
    };
    Supplier<Number> edgeFactory = new Supplier<Number>() {
        int count;

        public Number get() {
            return count++;
        }
    };
    Graph<Integer, Number> g = MixedRandomGraphGenerator.<Integer, Number>generateMixedRandomGraph(graphFactory,
            vertexFactory, edgeFactory, edge_weight, 20, seedVertices);
    es = new NumberFormattingTransformer<Number>(Functions.forMap(edge_weight));

    // collect the seeds used to define the random graph

    if (seedVertices.size() < 2)
        System.out.println("need at least 2 seeds (one source, one sink)");

    // use these seeds as source and sink vertices, run VoltageRanker
    boolean source = true;
    Set<Integer> sources = new HashSet<Integer>();
    Set<Integer> sinks = new HashSet<Integer>();
    for (Integer v : seedVertices) {
        if (source)
            sources.add(v);
        else
            sinks.add(v);
        source = !source;
    }
    VoltageScorer<Integer, Number> voltage_scores = new VoltageScorer<Integer, Number>(g,
            Functions.forMap(edge_weight), sources, sinks);
    voltage_scores.evaluate();
    voltages = new VertexScoreTransformer<Integer, Double>(voltage_scores);
    vs = new NumberFormattingTransformer<Integer>(voltages);

    Collection<Integer> verts = g.getVertices();

    // assign a transparency value of 0.9 to all vertices
    for (Integer v : verts) {
        transparency.put(v, new Double(0.9));
    }

    // add a couple of self-loops (sanity check on rendering)
    Integer v = verts.iterator().next();
    Number e = new Float(Math.random());
    edge_weight.put(e, e);
    g.addEdge(e, v, v);
    e = new Float(Math.random());
    edge_weight.put(e, e);
    g.addEdge(e, v, v);
    return g;
}

From source file:org.eclipse.sirius.diagram.ui.internal.edit.commands.DistributeCommand.java

/**
 * Must be called only when <code>wrappedCommand</code> is initialized.
 *
 * @param partsToBounds/*  ww  w.  ja v  a 2 s .  co m*/
 *            List of parts to distribute associated with their bounds.
 */
private void distributeVerticallyWithUniformGaps(final HashMap<IGraphicalEditPart, Rectangle> partsToBounds) {
    GetNewBoundsFunction setYFunction = new GetNewBoundsFunction() {
        @Override
        public Rectangle apply(IGraphicalEditPart input) {
            return partsToBounds.get(input).getCopy().setY(previousPartBounds.getBottom().y + gap);
        };
    };
    distributeWithUniformGaps(partsToBounds.keySet(), new GetTopFunction(partsToBounds),
            new GetLeftFunction(partsToBounds), new GetBottomFunction(partsToBounds),
            new GetRightFunction(partsToBounds), new GetHeightFunction(partsToBounds),
            new PartByMiddle(partsToBounds), setYFunction, Functions.forMap(partsToBounds));
}

From source file:com.palantir.atlasdb.transaction.impl.SerializableTransaction.java

private void verifyCells(Transaction ro) {
    for (String table : cellsRead.keySet()) {
        final ConcurrentNavigableMap<Cell, byte[]> readsForTable = getReadsForTable(table);
        for (Iterable<Cell> batch : Iterables.partition(cellsRead.get(table), 1000)) {
            if (writesByTable.get(table) != null) {
                // We don't want to verify any reads that we wrote to cause we will just read our own values.
                // NB: If the value has changed between read and write, our normal SI checking handles this case
                batch = Iterables.filter(batch,
                        Predicates.not(Predicates.in(writesByTable.get(table).keySet())));
            }//from ww w  . j a  v a2 s.  c o  m
            ImmutableSet<Cell> batchSet = ImmutableSet.copyOf(batch);
            Map<Cell, byte[]> currentBatch = ro.get(table, batchSet);
            ImmutableMap<Cell, byte[]> originalReads = Maps.toMap(
                    Sets.intersection(batchSet, readsForTable.keySet()), Functions.forMap(readsForTable));
            if (!areMapsEqual(currentBatch, originalReads)) {
                throw TransactionSerializableConflictException.create(table, getTimestamp(),
                        System.currentTimeMillis() - timeCreated);
            }
        }
    }
}

From source file:org.eclipse.sirius.diagram.ui.internal.edit.commands.DistributeCommand.java

/**
 * Must be called only when <code>wrappedCommand</code> is initialized.
 *
 * @param partsToBounds/*from  w w w.jav  a2  s . c om*/
 *            List of parts to distribute associated with their bounds.
 */
private void distributeCentersHorizontally(final HashMap<IGraphicalEditPart, Rectangle> partsToBounds) {
    GetNewBoundsFunction setCenterFunction = new GetNewBoundsFunction() {
        @Override
        public Rectangle apply(IGraphicalEditPart input) {
            Rectangle r = partsToBounds.get(input).getCopy();
            return r.setX(previousPartBounds.getCenter().x + gap - (r.width / 2));
        };
    };

    distributeCenters(partsToBounds.keySet(), new GetCenterFunction(partsToBounds),
            new GetTopFunction(partsToBounds), new GetBottomFunction(partsToBounds),
            new GetWidthFunction(partsToBounds), new PartByCenter(partsToBounds), setCenterFunction,
            Functions.forMap(partsToBounds));
}