List of usage examples for com.google.common.collect TreeMultimap create
public static <K, V> TreeMultimap<K, V> create(Comparator<? super K> keyComparator, Comparator<? super V> valueComparator)
From source file:org.eclipse.ease.modules.incubation.SelectorService.java
protected void init() { if (selectors == null) { selectors = TreeMultimap.create(new Comparator<Integer>() { @Override// w ww . j av a 2 s. co m public int compare(final Integer o1, final Integer o2) { return o2.compareTo(o1); } }, new Comparator<SelectorWrapper>() { @Override public int compare(final SelectorWrapper o1, final SelectorWrapper o2) { return o1.compareTo(o2); } }); selectorsMap = new HashMap<String, SelectorWrapper>(); final IConfigurationElement[] config = Platform.getExtensionRegistry() .getConfigurationElementsFor(SELECTOR_EXT_POINT_ID); for (final IConfigurationElement e : config) { if ("Selector".equals(e.getName())) { String id = e.getAttribute("id"); try { ISelector newSelector = (ISelector) e.createExecutableExtension("impl"); String priorityS = e.getAttribute("priority"); int priority = Integer.parseInt(priorityS); SelectorWrapper oldSelector = selectorsMap.get(id); if (oldSelector != null) { selectorsMap.remove(id); Collection<SelectorWrapper> selects = selectors.get(priority); selects.remove(oldSelector); } Expression expression = null; for (IConfigurationElement child : e.getChildren()) { expression = ExpressionConverter.getDefault().perform(child); if (expression != null) { break; } } SelectorWrapper selectorWrapper = new SelectorWrapper(newSelector, expression, id); selectors.put(priority, selectorWrapper); selectorsMap.put(id, selectorWrapper); } catch (CoreException e1) { e1.printStackTrace(); Logger.logError("Unable to create the a selector from " + id); } } } } }
From source file:org.apache.hadoop.hbase.util.RegionSplitCalculator.java
/** * Generates a coverage multimap from split key to Regions that start with the * split key.// www .ja v a 2 s . co m * * @return coverage multimap */ public Multimap<byte[], R> calcCoverage() { // This needs to be sorted to force the use of the comparator on the values, // otherwise byte array comparison isn't used Multimap<byte[], R> regions = TreeMultimap.create(BYTES_COMPARATOR, rangeCmp); // march through all splits from the start points for (Entry<byte[], Collection<R>> start : starts.asMap().entrySet()) { byte[] key = start.getKey(); for (R r : start.getValue()) { regions.put(key, r); for (byte[] coveredSplit : splits.subSet(r.getStartKey(), specialEndKey(r))) { regions.put(coveredSplit, r); } } } return regions; }
From source file:org.cinchapi.concourse.server.storage.db.SearchRecord.java
/** * Return the Set of primary keys for records that match {@code query}. * /* w w w .jav a2 s . c o m*/ * @param query * @return the Set of PrimaryKeys */ public Set<PrimaryKey> search(Text query) { read.lock(); try { Multimap<PrimaryKey, Integer> reference = HashMultimap.create(); String[] toks = query.toString().toLowerCase() .split(TStrings.REGEX_GROUP_OF_ONE_OR_MORE_WHITESPACE_CHARS); boolean initial = true; int offset = 0; for (String tok : toks) { Multimap<PrimaryKey, Integer> temp = HashMultimap.create(); if (STOPWORDS.contains(tok)) { // When skipping a stop word, we must record an offset to // correctly determine if the next term match is in the // correct relative position to the previous term match offset++; continue; } Set<Position> positions = get(Text.wrap(tok)); for (Position position : positions) { PrimaryKey key = position.getPrimaryKey(); int pos = position.getIndex(); if (initial) { temp.put(key, pos); } else { for (int current : reference.get(key)) { if (pos == current + 1 + offset) { temp.put(key, pos); } } } } initial = false; reference = temp; offset = 0; } // Result Scoring: Scoring is simply the number of times the query // appears in a document [e.g. the number of Positions mapped from // key: #reference.get(key).size()]. The total number of positions // in #reference is equal to the total number of times a document // appears in the corpus [e.g. reference.asMap().values().size()]. Multimap<Integer, PrimaryKey> sorted = TreeMultimap.create(Collections.<Integer>reverseOrder(), PrimaryKey.Sorter.INSTANCE); for (Entry<PrimaryKey, Collection<Integer>> entry : reference.asMap().entrySet()) { sorted.put(entry.getValue().size(), entry.getKey()); } return Sets.newLinkedHashSet(sorted.values()); } finally { read.unlock(); } }
From source file:com.facebook.buck.android.WriteAppModuleMetadataStep.java
private static TreeMultimap<APKModule, String> sortModuleToStringsMultimap( ImmutableMultimap<APKModule, String> multimap) { TreeMultimap<APKModule, String> orderedMap = TreeMultimap .create((left, right) -> left.getName().compareTo(right.getName()), Ordering.natural()); orderedMap.putAll(multimap);/* w w w.j av a2 s .c o m*/ return orderedMap; }
From source file:com.opengamma.component.rest.DataComponentServerResource.java
@GET @Produces(value = MediaType.TEXT_HTML) public String getComponentInfosHtml(@Context ServletContext servletContext, @Context UriInfo uriInfo) { ComponentServer server = new ComponentServer(URI.create("components")); server.getComponentInfos().addAll(_remoteComponents); for (RestComponent component : _localComponents) { server.getComponentInfos().add(component.getInfo()); }/*from ww w. j a va 2 s .co m*/ server.setUri(uriInfo.getBaseUri()); Multimap<Class<?>, ComponentInfo> byType = TreeMultimap.create(ORDER_CLASS, ORDER_CLASSIFIER); for (ComponentInfo info : server.getComponentInfos()) { byType.put(info.getType(), info); } FreemarkerOutputter freemarker = new FreemarkerOutputter(servletContext); FlexiBean data = freemarker.createRootData(); data.put("componentServer", server); data.put("infosByType", byType); return freemarker.build("data/componentserver.ftl", data); }
From source file:org.geogit.api.plumbing.diff.DiffCounter.java
private DiffObjectCount countBucketsChildren(ImmutableSortedMap<Integer, Bucket> buckets, Iterator<Node> children, final NodeStorageOrder refOrder, final int depth) { final SortedSetMultimap<Integer, Node> treesByBucket; final SortedSetMultimap<Integer, Node> featuresByBucket; {/*from w w w.jav a2 s .c om*/ treesByBucket = TreeMultimap.create(Ordering.natural(), refOrder); // make sure values // are sorted // according to // refOrder featuresByBucket = TreeMultimap.create(Ordering.natural(), refOrder);// make sure values // are sorted // according to // refOrder while (children.hasNext()) { Node ref = children.next(); Integer bucket = refOrder.bucket(ref, depth); if (ref.getType().equals(TYPE.TREE)) { treesByBucket.put(bucket, ref); } else { featuresByBucket.put(bucket, ref); } } } DiffObjectCount count = new DiffObjectCount(); {// count full size of all buckets for which no children falls into final Set<Integer> loneleyBuckets = Sets.difference(buckets.keySet(), Sets.union(featuresByBucket.keySet(), treesByBucket.keySet())); for (Integer bucket : loneleyBuckets) { ObjectId bucketId = buckets.get(bucket).id(); count.add(sizeOfTree(bucketId)); } } {// count the full size of all children whose buckets don't exist on the buckets tree for (Integer bucket : Sets.difference(featuresByBucket.keySet(), buckets.keySet())) { SortedSet<Node> refs = featuresByBucket.get(bucket); count.addFeatures(refs.size()); } for (Integer bucket : Sets.difference(treesByBucket.keySet(), buckets.keySet())) { SortedSet<Node> refs = treesByBucket.get(bucket); count.add(aggregateSize(refs)); } } // find the number of diffs of the intersection final Set<Integer> commonBuckets = Sets.intersection(buckets.keySet(), Sets.union(featuresByBucket.keySet(), treesByBucket.keySet())); for (Integer bucket : commonBuckets) { Iterator<Node> refs = Iterators.concat(treesByBucket.get(bucket).iterator(), featuresByBucket.get(bucket).iterator()); final ObjectId bucketId = buckets.get(bucket).id(); final RevTree bucketTree = getTree(bucketId); if (bucketTree.isEmpty()) { // unlikely count.add(aggregateSize(refs)); } else if (!bucketTree.buckets().isPresent()) { count.add(countChildrenDiffs(bucketTree.children(), refs)); } else { final int deeperBucketsDepth = depth + 1; final ImmutableSortedMap<Integer, Bucket> deeperBuckets; deeperBuckets = bucketTree.buckets().get(); count.add(countBucketsChildren(deeperBuckets, refs, refOrder, deeperBucketsDepth)); } } return count; }
From source file:uk.ac.ebi.atlas.web.controllers.page.BaselineExperimentsController.java
@PostConstruct private void loadExperimentAccessionsBySpecies() { for (String experimentAccession : experimentTrader.getAllBaselineExperimentAccessions()) { String displayName = null; try {//from w w w . j a v a 2s . c o m displayName = experimentTrader.getPublicExperiment(experimentAccession).getDisplayName(); } catch (RuntimeException e) { // we don't want the entire application to crash just because one magetab file may be offline because a curator is modifying it LOGGER.error(e.getMessage(), e); displayName = experimentAccession; } int numberOfAssays = ((BaselineExperiment) experimentTrader.getPublicExperiment(experimentAccession)) .getExperimentRunAccessions().size(); experimentDisplayNames.put(experimentAccession, displayName + " (" + numberOfAssays + " assays)"); } Comparator<String> keyComparator = new Comparator<String>() { @Override public int compare(String o1, String o2) { // Services review: Alvis' edict for Homo sapiens experiments to always come up on top of baseline landing page if (o1.equals("Homo sapiens") && !o2.equals("Homo sapiens")) return -1; else if (o2.equals("Homo sapiens") && !o1.equals("Homo sapiens")) return 1; else return o1.compareTo(o2); } }; // experiments should be sorted by their display name, not accession Comparator<String> valueComparator = new Comparator<String>() { @Override public int compare(String o1, String o2) { // Services review: Alvis' edict for proteomics experiments to always come up at the bottom of // the list of experiments within each species if (o1.indexOf("-PROT-") != -1 && o2.indexOf("-PROT-") == -1) return 1; else if (o2.indexOf("-PROT-") != -1 && o1.indexOf("-PROT-") == -1) return -1; else return experimentDisplayNames.get(o1).compareTo(experimentDisplayNames.get(o2)); } }; experimentAccessionsBySpecies = TreeMultimap.create(keyComparator, valueComparator); for (String experimentAccession : experimentTrader.getAllBaselineExperimentAccessions()) { try { BaselineExperiment experiment = (BaselineExperiment) experimentTrader .getPublicExperiment(experimentAccession); for (String specie : experiment.getOrganisms()) { experimentAccessionsBySpecies.put(specie, experimentAccession); if (experiment.getOrganisms().size() > 1) { experimentLinks.put(experimentAccession + specie, "?serializedFilterFactors=ORGANISM:" + specie); } else { experimentLinks.put(experimentAccession + specie, ""); } } } catch (RuntimeException e) { // we don't want the entire application to crash just because one magetab file may be offline because a curator is modifying it LOGGER.error(e.getMessage(), e); } } }
From source file:org.terasology.crafting.ui.workstation.StationAvailableRecipesWidget.java
public void loadRecipes() { availableRecipes.clear();//w ww.ja va 2 s . c om displayedOpenCategories.clear(); displayedOpenCategories.addAll(openCategories); Multimap<String, CraftingStationRecipe.CraftingStationResult> withoutCategory = LinkedHashMultimap.create(); Multimap<String, String> categoryRelationships = TreeMultimap.create(Ordering.natural(), Ordering.natural()); Set<String> topLevelCategories = new TreeSet<>(); Map<String, Multimap<String, CraftingStationRecipe.CraftingStationResult>> categoryRecipesMap = Maps .newHashMap(); WorkstationComponent workstation = station.getComponent(WorkstationComponent.class); for (WorkstationProcess workstationProcess : registry .getWorkstationProcesses(workstation.supportedProcessTypes.keySet())) { if (workstationProcess instanceof CraftingWorkstationProcess) { String recipeId = workstationProcess.getId(); List<? extends CraftingStationRecipe.CraftingStationResult> results = ((CraftingWorkstationProcess) workstationProcess) .getCraftingWorkstationRecipe().getMatchingRecipeResultsForDisplay(station); if (results != null) { for (CraftingStationRecipe.CraftingStationResult result : results) { availableRecipes.put(recipeId, result.getResultParameters()); String category = getCategory(recipeId); if (category == null) { withoutCategory.put(recipeId, result); } else { Multimap<String, CraftingStationRecipe.CraftingStationResult> categoryRecipes = categoryRecipesMap .get(category); if (categoryRecipes == null) { categoryRecipes = LinkedHashMultimap.create(); categoryRecipesMap.put(category, categoryRecipes); } categoryRecipes.put(recipeId, result); String topLevel = fillRelationships(categoryRelationships, category); topLevelCategories.add(topLevel); } } } } } for (String topLevelCategory : topLevelCategories) { int level = 0; appendCategory(categoryRelationships, categoryRecipesMap, topLevelCategory, level); } appendRecipes(0, withoutCategory.entries()); }
From source file:com.mgmtp.perfload.perfalyzer.reporting.ReportCreator.java
public void createReport(final List<PerfAlyzerFile> files) throws IOException { Function<PerfAlyzerFile, String> classifier = perfAlyzerFile -> { String marker = perfAlyzerFile.getMarker(); return marker == null ? "Overall" : marker; };/*from w w w. j av a 2 s .co m*/ Supplier<Map<String, List<PerfAlyzerFile>>> mapFactory = () -> new TreeMap<>(Ordering.explicit(tabNames)); Map<String, List<PerfAlyzerFile>> filesByMarker = files.stream() .collect(Collectors.groupingBy(classifier, mapFactory, toList())); Map<String, SortedSetMultimap<String, PerfAlyzerFile>> contentItemFiles = new LinkedHashMap<>(); for (Entry<String, List<PerfAlyzerFile>> entry : filesByMarker.entrySet()) { SortedSetMultimap<String, PerfAlyzerFile> contentItemFilesByMarker = contentItemFiles.computeIfAbsent( entry.getKey(), s -> TreeMultimap.create(new ItemComparator(reportContentsConfigMap.get("priorities")), Ordering.natural())); for (PerfAlyzerFile perfAlyzerFile : entry.getValue()) { File file = perfAlyzerFile.getFile(); String groupKey = removeExtension(file.getPath()); boolean excluded = false; for (Pattern pattern : reportContentsConfigMap.get("exclusions")) { Matcher matcher = pattern.matcher(groupKey); if (matcher.matches()) { excluded = true; log.debug("Excluded from report: {}", groupKey); break; } } if (!excluded) { contentItemFilesByMarker.put(groupKey, perfAlyzerFile); } } } // explicitly copy it because it is otherwise filtered from the report in order to only show in the overview String loadProfilePlot = new File("console", "[loadprofile].png").getPath(); copyFile(new File(soureDir, loadProfilePlot), new File(destDir, loadProfilePlot)); Map<String, List<ContentItem>> tabItems = new LinkedHashMap<>(); Map<String, QuickJump> quickJumps = new HashMap<>(); Set<String> tabNames = contentItemFiles.keySet(); for (Entry<String, SortedSetMultimap<String, PerfAlyzerFile>> tabEntry : contentItemFiles.entrySet()) { String tab = tabEntry.getKey(); SortedSetMultimap<String, PerfAlyzerFile> filesForTab = tabEntry.getValue(); List<ContentItem> contentItems = tabItems.computeIfAbsent(tab, list -> new ArrayList<>()); Map<String, String> quickJumpMap = new LinkedHashMap<>(); quickJumps.put(tab, new QuickJump(tab, quickJumpMap)); int itemIndex = 0; for (Entry<String, Collection<PerfAlyzerFile>> itemEntry : filesForTab.asMap().entrySet()) { String title = itemEntry.getKey(); Collection<PerfAlyzerFile> itemFiles = itemEntry.getValue(); TableData tableData = null; String plotSrc = null; for (PerfAlyzerFile file : itemFiles) { if ("png".equals(getExtension(file.getFile().getName()))) { plotSrc = file.getFile().getPath(); copyFile(new File(soureDir, plotSrc), new File(destDir, plotSrc)); } else { tableData = createTableData(file.getFile()); } } // strip off potential marker title = substringBefore(title, "{"); String[] titleParts = split(title, SystemUtils.FILE_SEPARATOR); StringBuilder sb = new StringBuilder(50); String separator = " - "; sb.append(resourceBundle.getString(titleParts[0])); sb.append(separator); sb.append(resourceBundle.getString(titleParts[1])); List<String> fileNameParts = extractFileNameParts(titleParts[1], true); if (titleParts[1].contains("[distribution]")) { String operation = fileNameParts.get(1); sb.append(separator); sb.append(operation); } else if ("comparison".equals(titleParts[0])) { String operation = fileNameParts.get(1); sb.append(separator); sb.append(operation); } else if (titleParts[1].contains("[gclog]")) { if (fileNameParts.size() > 1) { sb.append(separator); sb.append(fileNameParts.get(1)); } } title = sb.toString(); ContentItem item = new ContentItem(tab, itemIndex, title, tableData, plotSrc, resourceBundle.getString("report.topLink")); contentItems.add(item); quickJumpMap.put(tab + "_" + itemIndex, title); itemIndex++; } } NavBar navBar = new NavBar(tabNames, quickJumps); String testName = removeExtension(testMetadata.getTestPlanFile()); OverviewItem overviewItem = new OverviewItem(testMetadata, resourceBundle, locale); Content content = new Content(tabItems); String perfAlyzerVersion; try { perfAlyzerVersion = Resources.toString(Resources.getResource("perfAlyzer.version"), Charsets.UTF_8); } catch (IOException ex) { log.error("Could not read perfAlyzer version from classpath resource 'perfAlyzer.version'", ex); perfAlyzerVersion = ""; } String dateTimeString = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withLocale(locale) .format(ZonedDateTime.now()); String createdString = String.format(resourceBundle.getString("footer.created"), perfAlyzerVersion, dateTimeString); HtmlSkeleton html = new HtmlSkeleton(testName, createdString, navBar, overviewItem, content); writeReport(html); }
From source file:de.hzi.helmholtz.Compare.PathwayComparisonWithModules.java
public Multimap<Double, String> SubsetsMatching(final PathwayWithModules firstPathway, final PathwayWithModules secondPathway, BiMap<Integer, Integer> newSourceGeneIdToPositionMap, BiMap<Integer, Integer> newTargetGeneIdToPositionMap, int Yes) { Multimap<Double, String> resultPerfect = TreeMultimap.create(Ordering.natural().reverse(), Ordering.natural());//from w w w . j a v a 2 s .c om PathwayWithModules firstPathwayCopy = new PathwayWithModules(firstPathway);// Copy of the Query pathway PathwayWithModules secondPathwayCopy = new PathwayWithModules(secondPathway);// Copy of the Target pathway' // PathwayWithModules secondPathwayCopy1 = new PathwayWithModules(secondPathway); int currentQueryGene = 0; Iterator<ModuleGene> sourceGeneIt = firstPathway.moduleGeneIterator(); List<Integer> QueryToRemove = new ArrayList<Integer>(); List<Integer> TargetToRemove = new ArrayList<Integer>(); while (sourceGeneIt.hasNext()) { currentQueryGene++; ModuleGene queryGene = sourceGeneIt.next(); int currentTargetGene = 0; Multiset<String> qfunction = LinkedHashMultiset.create(); List<String> qfunctionList = new ArrayList<String>(); List<String> qactivity = new ArrayList<String>(); List<Set<String>> qsubstrate = new ArrayList<Set<String>>(); for (Module m : queryGene.getModule()) { for (Domain d : m.getDomains()) { qfunction.add(d.getDomainFunctionString()); qfunctionList.add(d.getDomainFunctionString()); qactivity.add(d.getStatus().toString()); qsubstrate.add(d.getSubstrates()); } } Iterator<ModuleGene> targetGeneIt = secondPathway.moduleGeneIterator(); while (targetGeneIt.hasNext()) { currentTargetGene++; ModuleGene targetGene = targetGeneIt.next(); Multiset<String> tfunction = LinkedHashMultiset.create(); List<String> tfunctionList = new ArrayList<String>(); List<String> tactivity = new ArrayList<String>(); List<Set<String>> tsubstrate = new ArrayList<Set<String>>(); for (Module m : targetGene.getModule()) { for (Domain d : m.getDomains()) { tfunctionList.add(d.getDomainFunctionString()); tfunction.add(d.getDomainFunctionString()); tactivity.add(d.getStatus().toString()); tsubstrate.add(d.getSubstrates()); } } Multiset<String> DomainsCovered = Multisets.intersection(qfunction, tfunction); if (DomainsCovered.size() == qfunction.size() && DomainsCovered.size() == tfunction.size()) { Multimap<Double, Multimap<String, Integer>> activityscores = myFunction.calculate(qactivity, tactivity); Multimap<String, Integer> Functionscores = ArrayListMultimap.create(); int TranspositionDomains = LevenshteinDistance.computeLevenshteinDistance(qfunctionList, tfunctionList); if (TranspositionDomains > 0) { TranspositionDomains = 1; } Functionscores.put(qfunction.size() + "-0", TranspositionDomains); Multimap<Double, Multimap<String, Integer>> substratescore = myFunction .calculate(getSubstrateList(qsubstrate), getSubstrateList(tsubstrate)); Object activityScore = activityscores.asMap().keySet().toArray()[0]; Object substrateScore = substratescore.asMap().keySet().toArray()[0]; double finalScore = Math .round((((2.9 * 1.0) + (0.05 * Double.parseDouble(activityScore.toString().trim())) + (0.05 * Double.parseDouble(substrateScore.toString().trim()))) / 3) * 100.0) / 100.0; String ConvertedGeneIDs = ""; if (Yes == 0) { ConvertedGeneIDs = reconstructWithGeneId(Integer.toString(currentQueryGene), newSourceGeneIdToPositionMap) + "->" + reconstructWithGeneId(Integer.toString(currentTargetGene), newTargetGeneIdToPositionMap); } else { ConvertedGeneIDs = reconstructWithGeneId(Integer.toString(currentTargetGene), newTargetGeneIdToPositionMap) + "->" + reconstructWithGeneId(Integer.toString(currentQueryGene), newSourceGeneIdToPositionMap); } resultPerfect.put(finalScore, ConvertedGeneIDs); ScoreFunctionMatchMisMatch.put(ConvertedGeneIDs, Functionscores); ScoreStatusMatchMisMatch.putAll(ConvertedGeneIDs, activityscores.values()); ScoreSubstrateMatchMisMatch.putAll(ConvertedGeneIDs, substratescore.values()); TargetToRemove.add(currentTargetGene); QueryToRemove.add(currentQueryGene); } } } for (int i : TargetToRemove) { secondPathwayCopy.removeGene(i); } for (int i : QueryToRemove) { firstPathwayCopy.removeGene(i); } if (firstPathwayCopy.size() > 0 && secondPathwayCopy.size() > 0) { // Re-construct the bimaps newSourceGeneIdToPositionMap = HashBiMap.create(); int temp = 0; for (ModuleGene e : firstPathwayCopy.getModulegenes()) { temp = temp + 1; newSourceGeneIdToPositionMap.put(e.getGeneId(), temp); } newTargetGeneIdToPositionMap = HashBiMap.create(); temp = 0; for (ModuleGene e : secondPathwayCopy.getModulegenes()) { temp = temp + 1; newTargetGeneIdToPositionMap.put(e.getGeneId(), temp); } resultPerfect.putAll(SubsetIdentification(firstPathwayCopy, secondPathwayCopy, newSourceGeneIdToPositionMap, newTargetGeneIdToPositionMap, Yes)); } System.out.println(resultPerfect); return resultPerfect; }