List of usage examples for com.google.common.collect Multimaps index
public static <K, V> ImmutableListMultimap<K, V> index(Iterator<V> values, Function<? super V, K> keyFunction)
From source file:org.summer.dsl.xbase.typesystem.override.ResolvedOperations.java
protected ListMultimap<String, IResolvedOperation> computeIndex() { // produces an immutable index which is what we want to have return Multimaps.index(getAllOperations(), new Function<IResolvedOperation, String>() { public String apply(IResolvedOperation input) { return input.getResolvedErasureSignature(); }// w w w . ja va2 s.co m }); }
From source file:com.facebook.buck.core.cell.AbstractCellConfig.java
/** * Translates the 'cell name'->override map into a 'Path'->override map. * * @param pathMapping a map containing paths to all of the cells we want to query. * @return 'Path'->override map/*from w ww .ja v a 2 s . c om*/ */ public ImmutableMap<Path, RawConfig> getOverridesByPath(ImmutableMap<CellName, Path> pathMapping) throws InvalidCellOverrideException { ImmutableSet<CellName> relativeNamesOfCellsWithOverrides = FluentIterable.from(getValues().keySet()) .filter(Predicates.not(CellName.ALL_CELLS_SPECIAL_NAME::equals)).toSet(); ImmutableSet.Builder<Path> pathsWithOverrides = ImmutableSet.builder(); for (CellName cellWithOverride : relativeNamesOfCellsWithOverrides) { if (!pathMapping.containsKey(cellWithOverride)) { throw new InvalidCellOverrideException( String.format("Trying to override settings for unknown cell %s", cellWithOverride)); } pathsWithOverrides.add(pathMapping.get(cellWithOverride)); } ImmutableMultimap<Path, CellName> pathToRelativeName = Multimaps.index(pathMapping.keySet(), Functions.forMap(pathMapping)); for (Path pathWithOverrides : pathsWithOverrides.build()) { ImmutableList<CellName> namesForPath = RichStream.from(pathToRelativeName.get(pathWithOverrides)) .filter(name -> name.getLegacyName().isPresent()).toImmutableList(); if (namesForPath.size() > 1) { throw new InvalidCellOverrideException( String.format("Configuration override is ambiguous: cell rooted at %s is reachable " + "as [%s]. Please override the config by placing a .buckconfig.local file in the " + "cell's root folder.", pathWithOverrides, Joiner.on(',').join(namesForPath))); } } Map<Path, RawConfig> overridesByPath = new HashMap<>(); for (Map.Entry<CellName, Path> entry : pathMapping.entrySet()) { CellName cellRelativeName = entry.getKey(); Path cellPath = entry.getValue(); RawConfig configFromOtherRelativeName = overridesByPath.get(cellPath); RawConfig config = getForCell(cellRelativeName); if (configFromOtherRelativeName != null) { // Merge configs RawConfig mergedConfig = RawConfig.builder().putAll(configFromOtherRelativeName).putAll(config) .build(); overridesByPath.put(cellPath, mergedConfig); } else { overridesByPath.put(cellPath, config); } } return ImmutableMap.copyOf(overridesByPath); }
From source file:org.mskcc.shenkers.control.track.gene.GTFGeneModelProvider.java
@Override public Iterable<GeneModel> query(String chr, int start, int end) { CloseableTribbleIterator<GTFContext> query = null; try {//from w w w .j a v a 2 s.c o m query = features.query(chr, start, end); Stream<GTFContext> filter = StreamSupport .stream(Spliterators.spliteratorUnknownSize(query, Spliterator.CONCURRENT), true) .filter(c -> c.getTranscriptId() != null); ImmutableListMultimap<String, GTFContext> transcript_id_multimap = Multimaps.index(filter.iterator(), GTFContext::getTranscriptId); Stream<GeneModel> map = transcript_id_multimap.keySet().stream().map(key -> { System.out.println(key); ImmutableListMultimap<String, GTFContext> transcript_features = Multimaps .index(transcript_id_multimap.get(key), GTFContext::getFeature); Map<String, RangeSet<Integer>> collect = transcript_features.keySet().stream() .collect(Collectors.toMap(s -> s, feature -> { return transcript_features.get(feature).stream() .map(c -> Range.closed(c.getStart(), c.getEnd())) .collect(new RangeSetCollector()); })); GeneModel model = new GeneModel(collect.get("transcript").span(), Optional.ofNullable(collect.get("exon")), Optional.ofNullable(collect.get("CDS")).map(c -> c.span())); return model; }); return map::iterator; } catch (IOException ex) { logger.error("exception reading gene models ", ex); throw new RuntimeException(ex); } finally { query.close(); } }
From source file:eu.itesla_project.ucte.network.ext.UcteNetworkExt.java
private UndirectedGraph<UcteNodeCode, Object> createSubstationGraph(UcteNetwork network) { UndirectedGraph<UcteNodeCode, Object> graph = new Pseudograph<>(Object.class); for (UcteNode node : network.getNodes()) { graph.addVertex(node.getCode()); }/*from w ww . j a va 2s . c om*/ // in the same substation... // ...nodes with same geographical spot Multimap<String, UcteNode> nodesByGeographicalSpot = Multimaps.index(network.getNodes(), new Function<UcteNode, String>() { @Override public String apply(UcteNode node) { return node.getCode().getGeographicalSpot(); } }); for (Map.Entry<String, Collection<UcteNode>> entry : nodesByGeographicalSpot.asMap().entrySet()) { for (UcteNode n1 : entry.getValue()) { for (UcteNode n2 : entry.getValue()) { if (n1 != n2) { graph.addEdge(n1.getCode(), n2.getCode()); } } } } // ...nodes connected by a transformer for (UcteTransformer tfo : network.getTransformers()) { UcteNodeCode nodeCode1 = tfo.getId().getNodeCode1(); UcteNodeCode nodeCode2 = tfo.getId().getNodeCode2(); graph.addEdge(nodeCode1, nodeCode2); } // ...nodes connected by a coupler or by a low impedance line for (UcteLine l : network.getLines()) { UcteNodeCode nodeCode1 = l.getId().getNodeCode1(); UcteNodeCode nodeCode2 = l.getId().getNodeCode2(); if (l.getStatus() == UcteElementStatus.BUSBAR_COUPLER_IN_OPERATION || l.getStatus() == UcteElementStatus.BUSBAR_COUPLER_OUT_OF_OPERATION) { graph.addEdge(nodeCode1, nodeCode2); } else { double z = Math.hypot(l.getResistance(), l.getReactance()); if (z < lineMinZ) { graph.addEdge(nodeCode1, nodeCode2); } } } return graph; }
From source file:com.google.testing.compile.Compilation.java
private static ImmutableListMultimap<Diagnostic.Kind, Diagnostic<? extends JavaFileObject>> sortDiagnosticsByKind( Iterable<Diagnostic<? extends JavaFileObject>> diagnostics) { return Multimaps.index(diagnostics, new Function<Diagnostic<?>, Diagnostic.Kind>() { @Override//from w w w. jav a2s . c om public Diagnostic.Kind apply(Diagnostic<?> input) { return input.getKind(); } }); }
From source file:com.qcadoo.mes.productionCounting.hooks.helpers.OperationProductsExtractor.java
/** * This method takes production tracking entity and returns all matching products wrapped in tracking operation components. * Results will be grouped by their model name, so you can easily distinct inputs products from output ones. * /* w w w.j av a 2s. co m*/ * @param productionTracking * production tracking for which you want to extract products. * * @return object representing tracking operation components grouped by their model name. */ public TrackingOperationProducts getProductsByModelName(final Entity productionTracking) { Entity order = productionTracking.getBelongsToField(ProductionTrackingFields.ORDER); Iterable<Entity> allProducts = getProductsFromOrderOperation(productionTracking, order); return new TrackingOperationProducts(Multimaps.index(allProducts, EXTRACT_MODEL_NAME)); }
From source file:dk.ilios.spanner.internal.ConsoleOutput.java
/** * Prints a summary of a successful trial result. *///from w w w. j a v a2 s. c o m void processTrial(Trial.Result result) { Trial baseline = result.getExperiment().getBaseline(); trialsCompleted++; stdout.printf("Trial Report (%d of %d):%n Experiment %s%n", trialsCompleted, numberOfTrials, result.getExperiment()); if (!result.getTrialMessages().isEmpty()) { stdout.println(" Messages:"); for (String message : result.getTrialMessages()) { stdout.print(" "); stdout.println(message); } } Trial trial = result.getTrial(); // Group measurements by their description // TODO Why? All measurements for a single trial should have the same description ImmutableListMultimap<String, Measurement> measurementsIndex = new ImmutableListMultimap.Builder<String, Measurement>() .orderKeysBy(Ordering.natural()) .putAll(Multimaps.index(trial.measurements(), new Function<Measurement, String>() { @Override public String apply(Measurement input) { return input.description(); } })).build(); stdout.println(" Results:"); for (Map.Entry<String, Collection<Measurement>> entry : measurementsIndex.asMap().entrySet()) { Collection<Measurement> measurements = entry.getValue(); String unit = measurements.iterator().next().value().unit(); double[] weightedValues = new double[measurements.size()]; int i = 0; for (Measurement measurement : measurements) { weightedValues[i] = measurement.value().magnitude() / measurement.weight(); i++; } Percentile percentile = new Percentile(); percentile.setData(weightedValues); DescriptiveStatistics descriptiveStatistics = new DescriptiveStatistics(weightedValues); stdout.printf(" %s%s: min=%.2f, 1st qu.=%.2f, median=%.2f (%s), mean=%.2f, 3rd qu.=%.2f, max=%.2f%n", entry.getKey(), unit.isEmpty() ? "" : "(" + unit + ")", descriptiveStatistics.getMin(), percentile.evaluate(25), percentile.evaluate(50), calculateDiff(percentile.evaluate(50), baseline), descriptiveStatistics.getMean(), percentile.evaluate(75), descriptiveStatistics.getMax()); } instrumentSpecs.add(trial.instrumentSpec()); Scenario scenario = trial.scenario(); benchmarkSpecs.add(scenario.benchmarkSpec()); numMeasurements += trial.measurements().size(); }
From source file:com.google.caliper.runner.ConsoleOutput.java
/** * Prints a summary of a successful trial result. *///from w w w. j a v a 2s. com void processTrial(TrialResult result) { trialsCompleted++; stdout.printf("Trial Report (%d of %d):%n Experiment %s%n", trialsCompleted, numberOfTrials, result.getExperiment()); if (!result.getTrialMessages().isEmpty()) { stdout.println(" Messages:"); for (String message : result.getTrialMessages()) { stdout.print(" "); stdout.println(message); } } Trial trial = result.getTrial(); ImmutableListMultimap<String, Measurement> measurementsIndex = new ImmutableListMultimap.Builder<String, Measurement>() .orderKeysBy(Ordering.natural()) .putAll(Multimaps.index(trial.measurements(), new Function<Measurement, String>() { @Override public String apply(Measurement input) { return input.description(); } })).build(); stdout.println(" Results:"); for (Entry<String, Collection<Measurement>> entry : measurementsIndex.asMap().entrySet()) { Collection<Measurement> measurements = entry.getValue(); ImmutableSet<String> units = FluentIterable.from(measurements) .transform(new Function<Measurement, String>() { @Override public String apply(Measurement input) { return input.value().unit(); } }).toSet(); double[] weightedValues = new double[measurements.size()]; int i = 0; for (Measurement measurement : measurements) { weightedValues[i] = measurement.value().magnitude() / measurement.weight(); i++; } Percentile percentile = new Percentile(); percentile.setData(weightedValues); DescriptiveStatistics descriptiveStatistics = new DescriptiveStatistics(weightedValues); String unit = Iterables.getOnlyElement(units); stdout.printf(" %s%s: min=%.2f, 1st qu.=%.2f, median=%.2f, mean=%.2f, 3rd qu.=%.2f, max=%.2f%n", entry.getKey(), unit.isEmpty() ? "" : "(" + unit + ")", descriptiveStatistics.getMin(), percentile.evaluate(25), percentile.evaluate(50), descriptiveStatistics.getMean(), percentile.evaluate(75), descriptiveStatistics.getMax()); } instrumentSpecs.add(trial.instrumentSpec()); Scenario scenario = trial.scenario(); vmSpecs.add(scenario.vmSpec()); benchmarkSpecs.add(scenario.benchmarkSpec()); numMeasurements += trial.measurements().size(); }
From source file:com.facebook.buck.config.AbstractCellConfig.java
/** * Translates the 'cell name'->override map into a 'Path'->override map. * @param pathMapping a map containing paths to all of the cells we want to query. * @return 'Path'->override map/*from ww w .ja v a 2 s . c o m*/ */ public ImmutableMap<Path, RawConfig> getOverridesByPath(ImmutableMap<RelativeCellName, Path> pathMapping) throws MalformedOverridesException { ImmutableSet<RelativeCellName> relativeNamesOfCellsWithOverrides = FluentIterable.from(getValues().keySet()) .filter(Predicates.not(ALL_CELLS_OVERRIDE::equals)).toSet(); ImmutableSet.Builder<Path> pathsWithOverrides = ImmutableSet.builder(); for (RelativeCellName cellWithOverride : relativeNamesOfCellsWithOverrides) { if (!pathMapping.containsKey(cellWithOverride)) { throw new MalformedOverridesException( String.format("Trying to override settings for unknown cell %s", cellWithOverride)); } pathsWithOverrides.add(pathMapping.get(cellWithOverride)); } ImmutableMultimap<Path, RelativeCellName> pathToRelativeName = Multimaps.index(pathMapping.keySet(), Functions.forMap(pathMapping)); for (Path pathWithOverrides : pathsWithOverrides.build()) { ImmutableCollection<RelativeCellName> namesForPath = pathToRelativeName.get(pathWithOverrides); if (namesForPath.size() > 1) { throw new MalformedOverridesException( String.format("Configuration override is ambiguous: cell rooted at %s is reachable " + "as [%s]. Please override the config by placing a .buckconfig.local file in the " + "cell's root folder.", pathWithOverrides, Joiner.on(',').join(namesForPath))); } } Map<Path, RawConfig> overridesByPath = new HashMap<>(); for (Map.Entry<RelativeCellName, Path> entry : pathMapping.entrySet()) { RelativeCellName cellRelativeName = entry.getKey(); Path cellPath = entry.getValue(); RawConfig configFromOtherRelativeName = overridesByPath.get(cellPath); RawConfig config = getForCell(cellRelativeName); if (configFromOtherRelativeName != null) { Preconditions.checkState(configFromOtherRelativeName.equals(config), "Attempting to create cell %s at %s with conflicting overrides [%s] vs [%s].", cellRelativeName, cellPath, configFromOtherRelativeName, config); } else { overridesByPath.put(cellPath, config); } } return ImmutableMap.copyOf(overridesByPath); }
From source file:com.qcadoo.mes.productionPerShift.dates.ProgressDatesService.java
@Transactional public void setUpDatesFor(final Entity order) { for (OrderDates orderDates : resolveOrderDates(order).asSet()) { List<Entity> progressesForDays = progressForDayDataProvider.findForOrder(order, ProgressForDayDataProvider.DEFAULT_SEARCH_ORDER); Multimap<Long, Entity> progressesByOperationId = Multimaps.index(progressesForDays, EXTRACT_TECHNOLOGY_OPERATION_ID); for (Collection<Entity> progresses : progressesByOperationId.asMap().values()) { setupDatesFor(progresses, orderDates); }//from w w w .ja va 2 s . c o m } }