List of usage examples for com.google.common.collect SortedSetMultimap get
@Override SortedSet<V> get(@Nullable K key);
From source file:com.analog.lyric.dimple.solvers.lp.LPTableFactor.java
/** * Computes constraint equations for this factor table and adds to {@code constraints}. * @return the total number of non-zero terms in added constraints. * <p>//ww w . j av a2 s .co m * Call after {@link #computeObjectiveFunction}. */ int computeConstraints(List<IntegerEquation> constraints) { if (_nLpVars <= 0) { return 0; } final DiscreteFactor factor = getModelObject(); final IFactorTable factorTable = factor.getFactorTable(); final int[][] rows = factorTable.getIndicesSparseUnsafe(); final int nRows = rows.length; final LPDiscrete[] svariables = getSVariables(); // Table of the marginal constraints for this factor where key is the index of the LP variable for // the marginal variable value, and the associated values are the indexes of the LP // variables in this factor that have the same variable value. final SortedSetMultimap<Integer, Integer> marginalConstraints = TreeMultimap.create(); final BitSet invalidAssignments = _invalidAssignments; for (int i = 0, lpFactor = _lpVarIndex; i < nRows; ++i, ++lpFactor) { if (invalidAssignments != null && nRows <= (i = invalidAssignments.nextClearBit(i))) { break; } int[] indices = rows[i]; for (int j = 0, endj = indices.length; j < endj; ++j) { LPDiscrete svar = svariables[j]; if (svar.hasLPVariable()) { // Only build marginal constraints for variables that have LP variables // (i.e. don't have fixed values). int valueIndex = indices[j]; int lpVar = svar.domainIndexToLPVar(valueIndex); marginalConstraints.put(lpVar, lpFactor); } } } int nTerms = 0; for (int lpVar : marginalConstraints.keySet()) { // This expresses the constraint that the marginal probability of a particular variable value // is equal to the sum of the non-zero factor table entries for the same variable value. SortedSet<Integer> lpFactorVars = marginalConstraints.get(lpVar); int[] lpVars = new int[1 + lpFactorVars.size()]; lpVars[0] = lpVar; int i = 0; for (int lpFactorVar : lpFactorVars) { lpVars[++i] = lpFactorVar; } constraints.add(new LPFactorMarginalConstraint(this, lpVars)); nTerms += lpVars.length; } return nTerms; }
From source file:com.google.idea.blaze.android.rendering.BlazeRenderErrorContributor.java
/** * Blaze doesn't resolve class dependencies from resources until building the final * android_binary, so we could end up with resources that ultimately build correctly, but fail to * find their class dependencies during rendering in the layout editor. */// www. ja v a 2 s. c om private void reportResourceTargetShouldDependOnClassTarget(TargetIdeInfo target, TargetMap targetMap, ArtifactLocationDecoder decoder) { Collection<String> missingClasses = logger.getMissingClasses(); if (missingClasses == null || missingClasses.isEmpty()) { return; } // Sorted entries for deterministic error message. SortedSetMultimap<String, TargetKey> missingClassToTargetMap = TreeMultimap.create(); SourceToTargetMap sourceToTargetMap = SourceToTargetMap.getInstance(project); ImmutableCollection transitiveDependencies = TransitiveDependencyMap.getInstance(project) .getTransitiveDependencies(target.key); for (String missingClass : missingClasses) { File sourceFile = getSourceFileForClass(missingClass); if (sourceFile == null) { continue; } ImmutableCollection<TargetKey> sourceTargets = sourceToTargetMap.getRulesForSourceFile(sourceFile); if (sourceTargets.stream().noneMatch(sourceTarget -> sourceTarget.equals(target.key) || transitiveDependencies.contains(sourceTarget))) { missingClassToTargetMap.putAll(missingClass, sourceTargets); } } if (missingClassToTargetMap.isEmpty()) { return; } HtmlBuilder builder = new HtmlBuilder(); addTargetLink(builder, target, decoder).add(" contains resource files that reference these classes:") .beginList(); for (String missingClass : missingClassToTargetMap.keySet()) { builder.listItem().addLink(missingClass, getLinkManager().createOpenClassUrl(missingClass)) .add(" from "); for (TargetKey targetKey : missingClassToTargetMap.get(missingClass)) { addTargetLink(builder, targetMap.get(targetKey), decoder).add(" "); } } builder.endList().add("Please fix your dependencies so that "); addTargetLink(builder, target, decoder).add(" correctly depends on these classes, ") .addLink("then ", "sync the project", " ", getLinkManager().createSyncProjectUrl()) .addLink("and ", "refresh the layout", ".", getLinkManager().createRefreshRenderUrl()).newline() .newline() .addBold("NOTE: blaze can still build with the incorrect dependencies " + "due to the way it handles resources, " + "but the layout editor needs them to be correct."); addIssue().setSeverity(HighlightSeverity.ERROR, HIGH_PRIORITY + 1) // Reported above missing classes. .setSummary("Missing class dependencies").setHtmlContent(builder).build(); }
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; {/* ww w . j a v a 2s .co m*/ 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:com.publictransitanalytics.scoregenerator.datalayer.directories.GTFSReadingStopTimesDirectory.java
private void parseStopTimesFile(final ImmutableSetMultimap<String, FrequencyRecord> frequencyRecordMap, final Reader stopTimesReader) throws FileNotFoundException, IOException, InterruptedException { final CSVParser parser = new CSVParser(stopTimesReader, CSVFormat.DEFAULT.withHeader()); final SortedSetMultimap<String, RawTripStop> rawTripMap = TreeMultimap.create(Comparator.naturalOrder(), (stop1, stop2) -> Integer.compare(stop1.getSequence(), stop2.getSequence())); final Iterator<CSVRecord> stopTimesIter = parser.iterator(); while (stopTimesIter.hasNext()) { final CSVRecord record = stopTimesIter.next(); final String rawTripId = record.get("trip_id"); final int stopSequence = Integer.valueOf(record.get("stop_sequence")); final String stopId = record.get("stop_id"); final String arrivalTimeString = record.get("arrival_time"); final TransitTime arrivalTime = (arrivalTimeString == null) ? null : TransitTime.parse(arrivalTimeString); final String departureTimeString = record.get("departure_time"); final TransitTime departureTime = (departureTimeString == null) ? null : TransitTime.parse(arrivalTimeString); if (frequencyRecordMap.containsKey(rawTripId)) { final RawTripStop rawTripStop = new RawTripStop(arrivalTime, departureTime, stopId, rawTripId, stopSequence);//from ww w . jav a2 s . c o m rawTripMap.put(rawTripId, rawTripStop); } else { final TripId tripId = new TripId(rawTripId); final TripStop tripStop = new TripStop(arrivalTime, stopId, tripId, stopSequence); try { final TripIdKey tripIdKey = new TripIdKey(rawTripId); tripsStore.put(tripIdKey, tripId); tripSequenceStore.put(new TripSequenceKey(tripIdKey, arrivalTime, stopSequence), tripStop); stopTimesStore.put(StopTimeKey.getWriteKey(stopId, arrivalTime), tripStop); } catch (final BitvantageStoreException e) { throw new ScoreGeneratorFatalException(e); } } } for (final String rawTripId : rawTripMap.keySet()) { final ImmutableSet<FrequencyRecord> frequencyRecords = frequencyRecordMap.get(rawTripId); for (final FrequencyRecord frequencyRecord : frequencyRecords) { TransitTime recurringTime = frequencyRecord.getStartTime(); while (recurringTime.isBefore(frequencyRecord.getEndTime())) { final TransitTime baseArrivalTime = rawTripMap.get(rawTripId).first().getArrivalTime(); final TripId tripId = new TripId(rawTripId, recurringTime.toString()); for (final RawTripStop rawTripStop : rawTripMap.get(rawTripId)) { final TransitTime arrivalTime = recurringTime .plus(TransitTime.durationBetween(baseArrivalTime, rawTripStop.getArrivalTime())); final int stopSequence = rawTripStop.getSequence(); final String stopId = rawTripStop.getStopId(); final TripStop tripStop = new TripStop(arrivalTime, stopId, tripId, stopSequence); final TripIdKey tripIdKey = new TripIdKey(tripId.getRawTripId(), tripId.getQualifier()); try { tripsStore.put(tripIdKey, tripId); tripSequenceStore.put(new TripSequenceKey(tripIdKey, arrivalTime, stopSequence), tripStop); stopTimesStore.put(StopTimeKey.getWriteKey(stopId, arrivalTime), tripStop); } catch (final BitvantageStoreException e) { throw new ScoreGeneratorFatalException(e); } } recurringTime = recurringTime.plus(frequencyRecord.getInterval()); } } } }
From source file:ome.services.graphs.GraphPathReport.java
/** * Process the Hibernate domain object model and write a report of the mapped objects. * @throws IOException if there was a problem in writing to the output file *//*from www. j ava2 s .c o m*/ private static void report() throws IOException { /* note all the direct superclasses and subclasses */ final Map<String, String> superclasses = new HashMap<String, String>(); final SortedSetMultimap<String, String> subclasses = TreeMultimap.create(); @SuppressWarnings("unchecked") final Map<String, ClassMetadata> classesMetadata = sessionFactory.getAllClassMetadata(); for (final String className : classesMetadata.keySet()) { try { final Class<?> actualClass = Class.forName(className); if (IObject.class.isAssignableFrom(actualClass)) { @SuppressWarnings("unchecked") final Set<String> subclassNames = sessionFactory.getEntityPersister(className) .getEntityMetamodel().getSubclassEntityNames(); for (final String subclassName : subclassNames) { if (!subclassName.equals(className)) { final Class<?> actualSubclass = Class.forName(subclassName); if (actualSubclass.getSuperclass() == actualClass) { superclasses.put(subclassName, className); subclasses.put(getSimpleName(className), getSimpleName(subclassName)); } } } } else { System.err.println("error: mapped class " + className + " is not a " + IObject.class.getName()); } } catch (ClassNotFoundException e) { System.err.println("error: could not instantiate class: " + e); } } /* queue for processing all the properties of all the mapped entities: name, type, nullability */ final Queue<PropertyDetails> propertyQueue = new LinkedList<PropertyDetails>(); final Map<String, Set<String>> allPropertyNames = new HashMap<String, Set<String>>(); for (final Map.Entry<String, ClassMetadata> classMetadata : classesMetadata.entrySet()) { final String className = classMetadata.getKey(); final ClassMetadata metadata = classMetadata.getValue(); final String[] propertyNames = metadata.getPropertyNames(); final Type[] propertyTypes = metadata.getPropertyTypes(); final boolean[] propertyNullabilities = metadata.getPropertyNullability(); for (int i = 0; i < propertyNames.length; i++) { if (!ignoreProperty(propertyNames[i])) { final List<String> propertyPath = Collections.singletonList(propertyNames[i]); propertyQueue.add(new PropertyDetails(className, propertyPath, propertyTypes[i], propertyNullabilities[i])); } } final Set<String> propertyNamesSet = new HashSet<String>(propertyNames.length); propertyNamesSet.addAll(Arrays.asList(propertyNames)); allPropertyNames.put(className, propertyNamesSet); } /* for linkedBy, X -> Y, Z: class X is linked to by class Y with Y's property Z */ final SetMultimap<String, Map.Entry<String, String>> linkedBy = HashMultimap.create(); final SetMultimap<String, String> linkers = HashMultimap.create(); final SortedMap<String, SortedMap<String, String>> classPropertyReports = new TreeMap<String, SortedMap<String, String>>(); /* process each property to note entity linkages */ while (!propertyQueue.isEmpty()) { final PropertyDetails property = propertyQueue.remove(); /* if the property has a component type, queue the parts for processing */ if (property.type instanceof ComponentType) { final ComponentType componentType = (ComponentType) property.type; final String[] componentPropertyNames = componentType.getPropertyNames(); final Type[] componentPropertyTypes = componentType.getSubtypes(); final boolean[] componentPropertyNullabilities = componentType.getPropertyNullability(); for (int i = 0; i < componentPropertyNames.length; i++) { if (!ignoreProperty(componentPropertyNames[i])) { final List<String> componentPropertyPath = new ArrayList<String>(property.path.size() + 1); componentPropertyPath.addAll(property.path); componentPropertyPath.add(componentPropertyNames[i]); propertyQueue.add(new PropertyDetails(property.holder, componentPropertyPath, componentPropertyTypes[i], componentPropertyNullabilities[i])); } } } else { /* determine if this property links to another entity */ final boolean isAssociatedEntity; if (property.type instanceof CollectionType) { final CollectionType ct = (CollectionType) property.type; isAssociatedEntity = sessionFactory.getCollectionPersister(ct.getRole()).getElementType() .isEntityType(); } else { isAssociatedEntity = property.type instanceof AssociationType; } /* determine the class and property name for reporting */ final String holderSimpleName = getSimpleName(property.holder); final String propertyPath = Joiner.on('.').join(property.path); /* build a report line for this property */ final StringBuffer sb = new StringBuffer(); final String valueClassName; if (isAssociatedEntity) { /* entity linkages by non-inherited properties are recorded */ final String valueName = ((AssociationType) property.type) .getAssociatedEntityName(sessionFactory); final String valueSimpleName = getSimpleName(valueName); final Map.Entry<String, String> classPropertyName = Maps.immutableEntry(holderSimpleName, propertyPath); linkers.put(holderSimpleName, propertyPath); linkedBy.put(valueSimpleName, classPropertyName); valueClassName = linkTo(valueSimpleName); } else { /* find a Sphinx representation for this property value type */ final UserType userType; if (property.type instanceof CustomType) { userType = ((CustomType) property.type).getUserType(); } else { userType = null; } if (property.type instanceof EnumType) { valueClassName = "enumeration"; } else if (userType instanceof GenericEnumType) { @SuppressWarnings("unchecked") final Class<? extends Unit> unitQuantityClass = ((GenericEnumType) userType) .getQuantityClass(); valueClassName = "enumeration of " + linkToJavadoc(unitQuantityClass.getName()); } else if (property.type instanceof ListType || userType instanceof ListAsSQLArrayUserType) { valueClassName = "list"; } else if (property.type instanceof MapType) { valueClassName = "map"; } else { valueClassName = "``" + property.type.getName() + "``"; } } sb.append(valueClassName); if (property.type.isCollectionType()) { sb.append(" (multiple)"); } else if (property.isNullable) { sb.append(" (optional)"); } /* determine from which class the property is inherited, if at all */ String superclassWithProperty = null; String currentClass = property.holder; while (true) { currentClass = superclasses.get(currentClass); if (currentClass == null) { break; } else if (allPropertyNames.get(currentClass).contains(property.path.get(0))) { superclassWithProperty = currentClass; } } /* check if the property actually comes from an interface */ final String declaringClassName = superclassWithProperty == null ? property.holder : superclassWithProperty; final Class<? extends IObject> interfaceForProperty = getInterfaceForProperty(declaringClassName, property.path.get(0)); /* report where the property is declared */ if (superclassWithProperty != null) { sb.append(" from "); sb.append(linkTo(getSimpleName(superclassWithProperty))); } else { if (interfaceForProperty != null) { sb.append(", see "); sb.append(linkToJavadoc(interfaceForProperty.getName())); } } SortedMap<String, String> byProperty = classPropertyReports.get(holderSimpleName); if (byProperty == null) { byProperty = new TreeMap<String, String>(); classPropertyReports.put(holderSimpleName, byProperty); } byProperty.put(propertyPath, sb.toString()); } } /* the information is gathered, now write the report */ out.write("Glossary of all OMERO Model Objects\n"); out.write("===================================\n\n"); out.write("Overview\n"); out.write("--------\n\n"); out.write("Reference\n"); out.write("---------\n\n"); for (final Map.Entry<String, SortedMap<String, String>> byClass : classPropertyReports.entrySet()) { /* label the class heading */ final String className = byClass.getKey(); out.write(".. _" + labelFor(className) + ":\n\n"); out.write(className + "\n"); final char[] underline = new char[className.length()]; for (int i = 0; i < underline.length; i++) { underline[i] = '"'; } out.write(underline); out.write("\n\n"); /* note the class' relationships */ final SortedSet<String> superclassOf = new TreeSet<String>(); for (final String subclass : subclasses.get(className)) { superclassOf.add(linkTo(subclass)); } final SortedSet<String> linkerText = new TreeSet<String>(); for (final Map.Entry<String, String> linker : linkedBy.get(className)) { linkerText.add(linkTo(linker.getKey(), linker.getValue())); } if (!(superclassOf.isEmpty() && linkerText.isEmpty())) { /* write the class' relationships */ /* out.write("Relationships\n"); out.write("^^^^^^^^^^^^^\n\n"); */ if (!superclassOf.isEmpty()) { out.write("Subclasses: " + Joiner.on(", ").join(superclassOf) + "\n\n"); } if (!linkerText.isEmpty()) { out.write("Used by: " + Joiner.on(", ").join(linkerText) + "\n\n"); } } /* write the class' properties */ /* out.write("Properties\n"); out.write("^^^^^^^^^^\n\n"); */ out.write("Properties:\n"); for (final Map.Entry<String, String> byProperty : byClass.getValue().entrySet()) { final String propertyName = byProperty.getKey(); // if (linkers.containsEntry(className, propertyName)) { // /* label properties that have other entities as values */ // out.write(".. _" + labelFor(className, propertyName) + ":\n\n"); // } out.write(" | " + propertyName + ": " + byProperty.getValue() + "\n" /* \n */); } out.write("\n"); } }