List of usage examples for com.google.common.collect Multimaps invertFrom
public static <K, V, M extends Multimap<K, V>> M invertFrom(Multimap<? extends V, ? extends K> source, M dest)
From source file:org.pau.assetmanager.viewmodel.MonthlyReportViewModel.java
/** * @param annotations//from w w w .j a v a 2 s .co m * @return the multimap 'Year of Annotaion' --> 'Annotations Involved' */ private static Multimap<Integer, Annotation> getYearToAnnotationMultimapFromAnnotations( Collection<Annotation> annotations) { ImmutableMap<Annotation, Integer> annotationToYear = Maps.toMap(annotations, new Function<Annotation, Integer>() { @Override public Integer apply(Annotation input) { Calendar calendar = GregorianCalendar.getInstance(); calendar.setTime(input.getDate()); return calendar.get(Calendar.YEAR); } }); ListMultimap<Integer, Annotation> yearToAnnotationMultimap = Multimaps .invertFrom(Multimaps.forMap(annotationToYear), ArrayListMultimap.<Integer, Annotation>create()); return yearToAnnotationMultimap; }
From source file:de.cau.cs.kieler.klay.layered.intermediate.SplineSelfLoopPreProcessor.java
/** * Finds a set of connected edges. Two edges are connected if they share a port, or if there * is a path between them, only containing self-loops. * //www .j av a2 s. com * @param portsToEdges A Multimap holding all connections between the ports. * ATTENTION: THIS PARAMETER GETS ALTERED: * All edges included in the return value are removed from the Multimap. * @param node The node we are currently working on. * @param isFixedOrder True, if the port-order of the node is at least {@code fixedOrder}. * @return A set of connected edges. */ private static ConnectedSelfLoopComponent findAConnectedComponent(final Multimap<LPort, LEdge> portsToEdges, final LNode node, final boolean isFixedOrder) { final Multimap<LEdge, LPort> edgeToPort = ArrayListMultimap.create(); Multimaps.invertFrom(portsToEdges, edgeToPort); // The connected components element we are constructing. final ConnectedSelfLoopComponent connectedComponent = new ConnectedSelfLoopComponent(node); // Create a list of ports we have to check for connected ports. Initially add an arbitrary port. final List<LPort> portsToProcess = Lists.newArrayList(); portsToProcess.add(portsToEdges.keys().iterator().next()); final List<LPort> portsProcessed = Lists.newArrayList(); // Check ports for connection to current connected component till no port to check is left. while (!portsToProcess.isEmpty()) { final LPort currentPort = portsToProcess.iterator().next(); portsProcessed.add(currentPort); final Collection<LEdge> allEdgesOnCurrentPort = portsToEdges.removeAll(currentPort); for (final LEdge currentEdge : allEdgesOnCurrentPort) { if (connectedComponent.tryAddEdge(currentEdge, isFixedOrder)) { final Collection<LPort> portsOfCurrentEdge = edgeToPort.removeAll(currentEdge); for (final LPort port : portsOfCurrentEdge) { if (!portsProcessed.contains(port)) { portsToProcess.add(port); } } } } portsToProcess.remove(currentPort); } return connectedComponent; }
From source file:com.google.javascript.jscomp.deps.SortedDependencies.java
private static <T> List<T> topologicalStableSort(List<T> items, Multimap<T, T> deps) { if (items.isEmpty()) { // Priority queue blows up if we give it a size of 0. Since we need // to special case this either way, just bail out. return new ArrayList<>(); }//from ww w. j a v a 2 s. co m final Map<T, Integer> originalIndex = new HashMap<>(); for (int i = 0; i < items.size(); i++) { originalIndex.put(items.get(i), i); } PriorityQueue<T> inDegreeZero = new PriorityQueue<>(items.size(), new Comparator<T>() { @Override public int compare(T a, T b) { return originalIndex.get(a).intValue() - originalIndex.get(b).intValue(); } }); List<T> result = new ArrayList<>(); Multiset<T> inDegree = HashMultiset.create(); Multimap<T, T> reverseDeps = ArrayListMultimap.create(); Multimaps.invertFrom(deps, reverseDeps); // First, add all the inputs with in-degree 0. for (T item : items) { Collection<T> itemDeps = deps.get(item); inDegree.add(item, itemDeps.size()); if (itemDeps.isEmpty()) { inDegreeZero.add(item); } } // Then, iterate to a fixed point over the reverse dependency graph. while (!inDegreeZero.isEmpty()) { T item = inDegreeZero.remove(); result.add(item); for (T inWaiting : reverseDeps.get(item)) { inDegree.remove(inWaiting, 1); if (inDegree.count(inWaiting) == 0) { inDegreeZero.add(inWaiting); } } } return result; }
From source file:cpw.mods.fml.common.Loader.java
/** * Sort the mods into a sorted list, using dependency information from the * containers. The sorting is performed using a {@link TopologicalSort} * based on the pre- and post- dependency information provided by the mods. *//*w w w.java 2s.c o m*/ private void sortModList() { FMLLog.finer("Verifying mod requirements are satisfied"); try { BiMap<String, ArtifactVersion> modVersions = HashBiMap.create(); for (ModContainer mod : getActiveModList()) { modVersions.put(mod.getModId(), mod.getProcessedVersion()); } ArrayListMultimap<String, String> reqList = ArrayListMultimap.create(); for (ModContainer mod : getActiveModList()) { if (!mod.acceptableMinecraftVersionRange().containsVersion(minecraft.getProcessedVersion())) { FMLLog.severe( "The mod %s does not wish to run in Minecraft version %s. You will have to remove it to play.", mod.getModId(), getMCVersionString()); throw new WrongMinecraftVersionException(mod); } Map<String, ArtifactVersion> names = Maps.uniqueIndex(mod.getRequirements(), new ArtifactVersionNameFunction()); Set<ArtifactVersion> versionMissingMods = Sets.newHashSet(); Set<String> missingMods = Sets.difference(names.keySet(), modVersions.keySet()); if (!missingMods.isEmpty()) { FMLLog.severe("The mod %s (%s) requires mods %s to be available", mod.getModId(), mod.getName(), missingMods); for (String modid : missingMods) { versionMissingMods.add(names.get(modid)); } throw new MissingModsException(versionMissingMods); } reqList.putAll(mod.getModId(), names.keySet()); ImmutableList<ArtifactVersion> allDeps = ImmutableList.<ArtifactVersion>builder() .addAll(mod.getDependants()).addAll(mod.getDependencies()).build(); for (ArtifactVersion v : allDeps) { if (modVersions.containsKey(v.getLabel())) { if (!v.containsVersion(modVersions.get(v.getLabel()))) { versionMissingMods.add(v); } } } if (!versionMissingMods.isEmpty()) { FMLLog.severe("The mod %s (%s) requires mod versions %s to be available", mod.getModId(), mod.getName(), versionMissingMods); throw new MissingModsException(versionMissingMods); } } FMLLog.finer("All mod requirements are satisfied"); reverseDependencies = Multimaps.invertFrom(reqList, ArrayListMultimap.<String, String>create()); ModSorter sorter = new ModSorter(getActiveModList(), namedMods); try { FMLLog.finer("Sorting mods into an ordered list"); List<ModContainer> sortedMods = sorter.sort(); // Reset active list to the sorted list modController.getActiveModList().clear(); modController.getActiveModList().addAll(sortedMods); // And inject the sorted list into the overall list mods.removeAll(sortedMods); sortedMods.addAll(mods); mods = sortedMods; FMLLog.finer("Mod sorting completed successfully"); } catch (ModSortingException sortException) { FMLLog.severe( "A dependency cycle was detected in the input mod set so an ordering cannot be determined"); SortingExceptionData<ModContainer> exceptionData = sortException.getExceptionData(); FMLLog.severe("The first mod in the cycle is %s", exceptionData.getFirstBadNode()); FMLLog.severe("The mod cycle involves"); for (ModContainer mc : exceptionData.getVisitedNodes()) { FMLLog.severe("%s : before: %s, after: %s", mc.toString(), mc.getDependants(), mc.getDependencies()); } FMLLog.log(Level.ERROR, sortException, "The full error"); throw sortException; } } finally { FMLLog.fine("Mod sorting data"); int unprintedMods = mods.size(); for (ModContainer mod : getActiveModList()) { if (!mod.isImmutable()) { FMLLog.fine("\t%s(%s:%s): %s (%s)", mod.getModId(), mod.getName(), mod.getVersion(), mod.getSource().getName(), mod.getSortingRules()); unprintedMods--; } } if (unprintedMods == mods.size()) { FMLLog.fine("No user mods found to sort"); } } }
From source file:de.fau.osr.bl.Tracker.java
/** * relation CommitId - ReqId of VCS + Database * @return set of the relations//from w w w .jav a 2 s. co m * @throws IOException */ public SetMultimap<String, String> getAllCommitReqRelations() throws IOException { SetMultimap<String, String> result = HashMultimap.create(); Multimaps.invertFrom(getAllReqCommitRelations(), result); return result; }
From source file:net.minecraftforge.fml.common.Loader.java
/** * Sort the mods into a sorted list, using dependency information from the * containers. The sorting is performed using a {@link TopologicalSort} * based on the pre- and post- dependency information provided by the mods. */// w ww . ja va2s . co m private void sortModList() { FMLLog.finer("Verifying mod requirements are satisfied"); try { BiMap<String, ArtifactVersion> modVersions = HashBiMap.create(); for (ModContainer mod : Iterables.concat(getActiveModList(), ModAPIManager.INSTANCE.getAPIList())) { modVersions.put(mod.getModId(), mod.getProcessedVersion()); } ArrayListMultimap<String, String> reqList = ArrayListMultimap.create(); for (ModContainer mod : getActiveModList()) { if (!mod.acceptableMinecraftVersionRange().containsVersion(minecraft.getProcessedVersion())) { FMLLog.severe( "The mod %s does not wish to run in Minecraft version %s. You will have to remove it to play.", mod.getModId(), getMCVersionString()); throw new WrongMinecraftVersionException(mod); } Map<String, ArtifactVersion> names = Maps.uniqueIndex(mod.getRequirements(), new ArtifactVersionNameFunction()); Set<ArtifactVersion> versionMissingMods = Sets.newHashSet(); Set<String> missingMods = Sets.difference(names.keySet(), modVersions.keySet()); if (!missingMods.isEmpty()) { FMLLog.severe("The mod %s (%s) requires mods %s to be available", mod.getModId(), mod.getName(), missingMods); for (String modid : missingMods) { versionMissingMods.add(names.get(modid)); } throw new MissingModsException(versionMissingMods, mod.getModId(), mod.getName()); } reqList.putAll(mod.getModId(), names.keySet()); ImmutableList<ArtifactVersion> allDeps = ImmutableList.<ArtifactVersion>builder() .addAll(mod.getDependants()).addAll(mod.getDependencies()).build(); for (ArtifactVersion v : allDeps) { if (modVersions.containsKey(v.getLabel())) { if (!v.containsVersion(modVersions.get(v.getLabel()))) { versionMissingMods.add(v); } } } if (!versionMissingMods.isEmpty()) { FMLLog.severe("The mod %s (%s) requires mod versions %s to be available", mod.getModId(), mod.getName(), versionMissingMods); throw new MissingModsException(versionMissingMods, mod.getModId(), mod.getName()); } } FMLLog.finer("All mod requirements are satisfied"); reverseDependencies = Multimaps.invertFrom(reqList, ArrayListMultimap.<String, String>create()); ModSorter sorter = new ModSorter(getActiveModList(), namedMods); try { FMLLog.finer("Sorting mods into an ordered list"); List<ModContainer> sortedMods = sorter.sort(); // Reset active list to the sorted list modController.getActiveModList().clear(); modController.getActiveModList().addAll(sortedMods); // And inject the sorted list into the overall list mods.removeAll(sortedMods); sortedMods.addAll(mods); mods = sortedMods; FMLLog.finer("Mod sorting completed successfully"); } catch (ModSortingException sortException) { FMLLog.severe( "A dependency cycle was detected in the input mod set so an ordering cannot be determined"); SortingExceptionData<ModContainer> exceptionData = sortException.getExceptionData(); FMLLog.severe("The first mod in the cycle is %s", exceptionData.getFirstBadNode()); FMLLog.severe("The mod cycle involves"); for (ModContainer mc : exceptionData.getVisitedNodes()) { FMLLog.severe("%s : before: %s, after: %s", mc.toString(), mc.getDependants(), mc.getDependencies()); } FMLLog.log(Level.ERROR, sortException, "The full error"); throw sortException; } } finally { FMLLog.fine("Mod sorting data"); int unprintedMods = mods.size(); for (ModContainer mod : getActiveModList()) { if (!mod.isImmutable()) { FMLLog.fine("\t%s(%s:%s): %s (%s)", mod.getModId(), mod.getName(), mod.getVersion(), mod.getSource().getName(), mod.getSortingRules()); unprintedMods--; } } if (unprintedMods == mods.size()) { FMLLog.fine("No user mods found to sort"); } } }
From source file:ai.grakn.graql.internal.query.QueryOperationExecutor.java
/** * Produce a valid ordering of the properties by using the given dependency information. * * <p>//w ww . j av a 2 s .co m * This method uses a topological sort (Kahn's algorithm) in order to find a valid ordering. * </p> */ private ImmutableList<VarAndProperty> sortProperties() { ImmutableList.Builder<VarAndProperty> sorted = ImmutableList.builder(); // invertedDependencies is intended to just be a 'view' on dependencies, so when dependencies is modified // we should always also modify invertedDependencies (and vice-versa). Multimap<VarAndProperty, VarAndProperty> dependencies = HashMultimap.create(this.dependencies); Multimap<VarAndProperty, VarAndProperty> invertedDependencies = HashMultimap.create(); Multimaps.invertFrom(dependencies, invertedDependencies); Queue<VarAndProperty> propertiesWithoutDependencies = new ArrayDeque<>( Sets.filter(properties, property -> dependencies.get(property).isEmpty())); VarAndProperty property; // Retrieve the next property without any dependencies while ((property = propertiesWithoutDependencies.poll()) != null) { sorted.add(property); // We copy this into a new list because the underlying collection gets modified during iteration Collection<VarAndProperty> dependents = Lists.newArrayList(invertedDependencies.get(property)); for (VarAndProperty dependent : dependents) { // Because the property has been removed, the dependent no longer needs to depend on it dependencies.remove(dependent, property); invertedDependencies.remove(property, dependent); boolean hasNoDependencies = dependencies.get(dependent).isEmpty(); if (hasNoDependencies) { propertiesWithoutDependencies.add(dependent); } } } if (!dependencies.isEmpty()) { // This means there must have been a loop. Pick an arbitrary remaining var to display Var var = dependencies.keys().iterator().next().var(); throw GraqlQueryException.insertRecursive(printableRepresentation(var)); } return sorted.build(); }
From source file:org.eclipse.sirius.diagram.sequence.business.internal.layout.horizontal.SequenceHorizontalLayout.java
private void populateFrames() { Collection<AbstractFrame> allFrames = Lists.newArrayList(); allFrames.addAll(sequenceDiagram.getAllInteractionUses()); allFrames.addAll(sequenceDiagram.getAllCombinedFragments()); for (AbstractFrame frame : allFrames) { Collection<Lifeline> coveredLifelines = frame.computeCoveredLifelines(); if (!coveredLifelines.isEmpty()) { frames.add(frame);//w w w . j av a2 s .com coverage.putAll(frame, coveredLifelines); ranges.put(frame, frame.getVerticalRange()); } } for (AbstractFrame frame : frames) { getOrComputeMaxChildrenDepth(frame, Collections.singletonList(frame)); } Multimaps.invertFrom(coverage, invCoverage); }
From source file:grakn.core.graql.executor.WriteExecutor.java
/** * Produce a valid ordering of the properties by using the given dependency information. * This method uses a topological sort (Kahn's algorithm) in order to find a valid ordering. *///from w w w . j ava2 s . co m private ImmutableList<Writer> sortedWriters() { ImmutableList.Builder<Writer> sorted = ImmutableList.builder(); // invertedDependencies is intended to just be a 'view' on dependencies, so when dependencies is modified // we should always also modify invertedDependencies (and vice-versa). Multimap<Writer, Writer> dependencies = HashMultimap.create(this.dependencies); Multimap<Writer, Writer> invertedDependencies = HashMultimap.create(); Multimaps.invertFrom(dependencies, invertedDependencies); Queue<Writer> writerWithoutDependencies = new ArrayDeque<>( Sets.filter(writers, property -> dependencies.get(property).isEmpty())); Writer property; // Retrieve the next property without any dependencies while ((property = writerWithoutDependencies.poll()) != null) { sorted.add(property); // We copy this into a new list because the underlying collection gets modified during iteration Collection<Writer> dependents = Lists.newArrayList(invertedDependencies.get(property)); for (Writer dependent : dependents) { // Because the property has been removed, the dependent no longer needs to depend on it dependencies.remove(dependent, property); invertedDependencies.remove(property, dependent); boolean hasNoDependencies = dependencies.get(dependent).isEmpty(); if (hasNoDependencies) { writerWithoutDependencies.add(dependent); } } } if (!dependencies.isEmpty()) { // This means there must have been a loop. Pick an arbitrary remaining var to display Variable var = dependencies.keys().iterator().next().var(); throw GraqlSemanticException.insertRecursive(printableRepresentation(var)); } return sorted.build(); }
From source file:com.twitter.aurora.scheduler.http.SchedulerzJob.java
private static Map<String, SchedulingDetails> buildSchedulingTable(Iterable<IAssignedTask> tasks) { Map<Integer, ITaskConfig> byInstance = Maps .transformValues(Maps.uniqueIndex(tasks, Tasks.ASSIGNED_TO_INSTANCE_ID), Tasks.ASSIGNED_TO_INFO); Map<Integer, SchedulingDetails> detailsByInstance = Maps.transformValues(byInstance, CONFIG_TO_DETAILS); Multimap<SchedulingDetails, Integer> instancesByDetails = Multimaps .invertFrom(Multimaps.forMap(detailsByInstance), HashMultimap.<SchedulingDetails, Integer>create()); Map<SchedulingDetails, String> instanceStringsByDetails = Maps.transformValues(instancesByDetails.asMap(), TransformationUtils.INSTANCES_TOSTRING); return HashBiMap.create(instanceStringsByDetails).inverse(); }