List of usage examples for com.google.common.collect Multimap asMap
Map<K, Collection<V>> asMap();
From source file:dollar.internal.runtime.script.parser.scope.ScriptScope.java
private ScriptScope(@NotNull Scope parent, @NotNull String id, boolean parameterScope, @NotNull Map<VarKey, Variable> variables, @NotNull List<Value> errorHandlers, @NotNull Multimap<VarKey, Listener> listeners, @NotNull String source, @NotNull Parser<Value> parser, boolean root, boolean classScope) { this.parent = parent; this.id = id; this.parameterScope = parameterScope; this.classScope = classScope; this.variables.putAll(variables); this.errorHandlers.addAll(errorHandlers); for (Map.Entry<VarKey, Collection<Listener>> entry : listeners.asMap().entrySet()) { this.listeners.putAll(entry.getKey(), entry.getValue()); }/* w w w. java 2s . c o m*/ this.source = source; this.parser = parser; this.root = root; checkPure(parent); }
From source file:org.apache.hadoop.hive.ql.exec.tez.CustomPartitionVertex.java
private void processAllSideEvents(String inputName, Multimap<Integer, InputSplit> bucketToGroupedSplitMap) throws IOException { List<InputDataInformationEvent> taskEvents = new ArrayList<InputDataInformationEvent>(); LOG.info("We have a routing table and we are going to set the destination tasks for the" + " multi mr inputs. " + bucketToTaskMap); Integer[] numSplitsForTask = new Integer[taskCount]; Arrays.fill(numSplitsForTask, 0); Multimap<Integer, ByteBuffer> bucketToSerializedSplitMap = LinkedListMultimap.create(); // Create the list of serialized splits for each bucket. for (Entry<Integer, Collection<InputSplit>> entry : bucketToGroupedSplitMap.asMap().entrySet()) { for (InputSplit split : entry.getValue()) { MRSplitProto serializedSplit = MRInputHelpers.createSplitProto(split); ByteBuffer bs = serializedSplit.toByteString().asReadOnlyByteBuffer(); bucketToSerializedSplitMap.put(entry.getKey(), bs); }/*from www . j a v a 2 s . c om*/ } for (Entry<Integer, Collection<ByteBuffer>> entry : bucketToSerializedSplitMap.asMap().entrySet()) { Collection<Integer> destTasks = bucketToTaskMap.get(entry.getKey()); if ((destTasks == null) || (destTasks.isEmpty())) { continue; } for (Integer task : destTasks) { int count = 0; for (ByteBuffer buf : entry.getValue()) { count++; InputDataInformationEvent diEvent = InputDataInformationEvent.createWithSerializedPayload(count, buf); diEvent.setTargetIndex(task); taskEvents.add(diEvent); } numSplitsForTask[task] = count; } } inputNameInputSpecMap.put(inputName, InputSpecUpdate.createPerTaskInputSpecUpdate(Arrays.asList(numSplitsForTask))); LOG.info("For input name: " + inputName + " task events size is " + taskEvents.size()); context.addRootInputEvents(inputName, taskEvents); }
From source file:org.openscience.cdk.smiles.smarts.SmartsAtomAtomMapFilter.java
SmartsAtomAtomMapFilter(IAtomContainer query, IAtomContainer target) { Multimap<Integer, Integer> reactInvMap = null; Multimap<Integer, Integer> prodInvMap = null; this.target = target; // transform query maps in to matchable data-structure final int numAtoms = query.getAtomCount(); for (int idx = 0; idx < numAtoms; idx++) { IAtom atom = query.getAtom(idx); final int mapidx = mapidx(atom); if (mapidx == 0) continue; switch (role(atom)) { case Reactant: if (reactInvMap == null) reactInvMap = ArrayListMultimap.create(); reactInvMap.put(mapidx, idx); break; case Product: if (prodInvMap == null) prodInvMap = ArrayListMultimap.create(); prodInvMap.put(mapidx, idx); break; }/* w ww . j a va 2 s . c o m*/ } if (reactInvMap != null && prodInvMap != null) { for (Map.Entry<Integer, Collection<Integer>> e : reactInvMap.asMap().entrySet()) { int[] reacMaps = Ints.toArray(e.getValue()); int[] prodMaps = Ints.toArray(prodInvMap.get(e.getKey())); if (prodMaps.length == 0) continue; // unpaired mapped.add(new MappedPairs(reacMaps, prodMaps)); } } }
From source file:com.facebook.swift.codec.metadata.ThriftStructMetadataBuilder.java
private void inferThriftFieldIds(Multimap<String, FieldMetadata> fieldsByName, Set<String> fieldsWithConflictingIds) { // for each name group, set the ids on the fields without ids for (Entry<String, Collection<FieldMetadata>> entry : fieldsByName.asMap().entrySet()) { Collection<FieldMetadata> fields = entry.getValue(); // skip all entries without a name or singleton groups... we'll deal with these later if (fields.size() <= 1) { continue; }//from w w w .j av a2 s .c om // all ids used by this named field Set<Short> ids = ImmutableSet.copyOf(Optional.presentInstances(transform(fields, getThriftFieldId()))); // multiple conflicting ids if (ids.size() > 1) { String fieldName = entry.getKey(); if (!fieldsWithConflictingIds.contains(fieldName)) { metadataErrors.addError("ThriftStruct '%s' field '%s' has multiple ids: %s", structName, fieldName, ids); fieldsWithConflictingIds.add(fieldName); } continue; } // single id, so set on all fields in this group (groups with no id are handled later) if (ids.size() == 1) { // propagate the id to all fields in this group short id = Iterables.getOnlyElement(ids); for (FieldMetadata field : fields) { field.setId(id); } } } }
From source file:net.shibboleth.idp.saml.impl.attribute.mapping.RequestedAttributesMapper.java
/** * Constructor to create the mapping from an existing resolver. <br/> * This code inverts the {@link AttributeEncoder} (internal attribute -> SAML Attributes) into * {@link AttributeMapper} (SAML [RequestedAttributes] -> internal [Requested] Attributes). <br/> * to generate the {@link AbstractSAMLAttributeMapper} (with no * {@link AbstractSAMLAttributeMapper#getAttributeIds(). These are accumulated into a {@link Multimap}, where the * key is the {@link AbstractSAMLAttributeMapper} and the values are the (IdP) attribute names. The collection of * {@link AttributeMapper}s can then be extracted from the map, and the appropriate internal names added (these * being the value of the {@link Multimap}) * /* w ww . j ava2 s .c om*/ * @param resolver The resolver */ public RequestedAttributesMapper(AttributeResolver resolver) { super(); setId(resolver.getId()); final Multimap<AbstractSAMLAttributeMapper<RequestedAttribute, IdPRequestedAttribute>, String> theMappers; theMappers = HashMultimap.create(); for (AttributeDefinition attributeDef : resolver.getAttributeDefinitions().values()) { for (AttributeEncoder encode : attributeDef.getAttributeEncoders()) { if (encode instanceof AttributeMapperFactory) { // There is an appropriate reverse mappers AttributeMapperFactory factory = (AttributeMapperFactory) encode; AbstractSAMLAttributeMapper<RequestedAttribute, IdPRequestedAttribute> mapper = factory .getRequestedMapper(); theMappers.put(mapper, attributeDef.getId()); } } } final List<AttributeMapper<RequestedAttribute, IdPRequestedAttribute>> mappers = new ArrayList<AttributeMapper<RequestedAttribute, IdPRequestedAttribute>>( theMappers.values().size()); for (Entry<AbstractSAMLAttributeMapper<RequestedAttribute, IdPRequestedAttribute>, Collection<String>> entry : theMappers .asMap().entrySet()) { AbstractSAMLAttributeMapper<RequestedAttribute, IdPRequestedAttribute> mapper = entry.getKey(); mapper.setAttributeIds(new ArrayList<String>(entry.getValue())); mappers.add(mapper); } setMappers(mappers); }
From source file:ai.grakn.graql.internal.reasoner.atom.binary.RelationAtom.java
/** * infer relation types that this relation atom can potentially have * NB: entity types and role types are treated separately as they behave differently: * entity types only play the explicitly defined roles (not the relevant part of the hierarchy of the specified role) * @return list of relation types this atom can have ordered by the number of compatible role types *//*from w w w . java2 s. com*/ public List<RelationType> inferPossibleRelationTypes(Answer sub) { if (getPredicate() != null) return Collections.singletonList(getOntologyConcept().asRelationType()); //look at available role types Multimap<RelationType, Role> compatibleTypesFromRoles = getCompatibleRelationTypesWithRoles( getExplicitRoleTypes(), new RoleTypeConverter()); //look at entity types Map<Var, OntologyConcept> varTypeMap = getParentQuery().getVarOntologyConceptMap(); //explicit types Set<OntologyConcept> types = getRolePlayers().stream().filter(varTypeMap::containsKey).map(varTypeMap::get) .collect(toSet()); //types deduced from substitution inferEntityTypes(sub).forEach(types::add); Multimap<RelationType, Role> compatibleTypesFromTypes = getCompatibleRelationTypesWithRoles(types, new OntologyConceptConverterImpl()); Multimap<RelationType, Role> compatibleTypes; //intersect relation types from roles and types if (compatibleTypesFromRoles.isEmpty()) { compatibleTypes = compatibleTypesFromTypes; } else if (!compatibleTypesFromTypes.isEmpty()) { compatibleTypes = multimapIntersection(compatibleTypesFromTypes, compatibleTypesFromRoles); } else { compatibleTypes = compatibleTypesFromRoles; } return compatibleTypes.asMap().entrySet().stream().sorted(Comparator.comparing(e -> -e.getValue().size())) .map(Map.Entry::getKey) .filter(t -> Sets.intersection(getSupers(t), compatibleTypes.keySet()).isEmpty()) .collect(Collectors.toList()); }
From source file:com.google.caliper.runner.ConsoleResultProcessor.java
private void displayResults(Instrument instrument) { System.out.printf("Results for %s:%n", instrument.className); processedResults = Maps.newHashMap(); for (Result result : run.results) { ScenarioName scenarioLocalName = new ScenarioName(result.scenarioLocalName); if (instrument.localName.equals(result.instrumentLocalName)) { ProcessedResult existingResult = processedResults.get(scenarioLocalName); if (existingResult == null) { processedResults.put(scenarioLocalName, new ProcessedResult(result)); } else { processedResults.put(scenarioLocalName, combineResults(existingResult, result)); }/*from w ww .j a va2 s .co m*/ } } double minOfMedians = Double.POSITIVE_INFINITY; double maxOfMedians = Double.NEGATIVE_INFINITY; for (ProcessedResult result : processedResults.values()) { minOfMedians = Math.min(minOfMedians, result.median); maxOfMedians = Math.max(maxOfMedians, result.median); } Multimap<AxisName, AxisValue> axisValues = LinkedHashMultimap.create(); for (Scenario scenario : run.scenarios) { ScenarioName scenarioName = new ScenarioName(scenario.localName); // only include scenarios with data for this instrument if (processedResults.keySet().contains(scenarioName)) { for (Entry<AxisName, AxisValue> entry : scenarioLocalVars.row(scenarioName).entrySet()) { axisValues.put(entry.getKey(), entry.getValue()); } } } List<Axis> axes = Lists.newArrayList(); for (Entry<AxisName, Collection<AxisValue>> entry : axisValues.asMap().entrySet()) { Axis axis = new Axis(entry.getKey(), entry.getValue()); axes.add(axis); } /* * Figure out how much influence each axis has on the measured value. * We sum the measurements taken with each value of each axis. For * axes that have influence on the measurement, the sums will differ * by value. If the axis has little influence, the sums will be similar * to one another and close to the overall average. We take the variance * across each axis' collection of sums. Higher variance implies higher * influence on the measured result. */ double sumOfAllMeasurements = 0; for (ProcessedResult result : processedResults.values()) { sumOfAllMeasurements += result.median; } for (Axis axis : axes) { int numValues = axis.numberOfValues(); double[] sumForValue = new double[numValues]; for (Entry<ScenarioName, ProcessedResult> entry : processedResults.entrySet()) { ScenarioName scenarioLocalName = entry.getKey(); ProcessedResult result = entry.getValue(); sumForValue[axis.index(scenarioLocalName)] += result.median; } double mean = sumOfAllMeasurements / sumForValue.length; double variance = 0; for (double value : sumForValue) { double distance = value - mean; variance += distance * distance; } axis.variance = variance / numValues; } this.sortedAxes = new VarianceOrdering().reverse().sortedCopy(axes); this.sortedScenarioNames = ImmutableSortedSet.copyOf(new ByAxisOrdering(), processedResults.keySet()); this.maxValue = maxOfMedians; this.minValue = minOfMedians; displayResults(); }
From source file:groovyx.gpars.benchmark.caliper.chart.ChartBuilder.java
private void displayResults(final Instrument instrument) { processedResults = Maps.newHashMap(); for (final Result result : run.results) { final ScenarioName scenarioLocalName = new ScenarioName(result.scenarioLocalName); if (instrument.localName.equals(result.instrumentLocalName)) { final ProcessedResult existingResult = processedResults.get(scenarioLocalName); if (existingResult == null) { processedResults.put(scenarioLocalName, new ProcessedResult(result)); } else { processedResults.put(scenarioLocalName, combineResults(existingResult, result)); }/* w w w .ja v a 2s. com*/ } } double minOfMedians = Double.POSITIVE_INFINITY; double maxOfMedians = Double.NEGATIVE_INFINITY; for (final ProcessedResult result : processedResults.values()) { minOfMedians = Math.min(minOfMedians, result.median); maxOfMedians = Math.max(maxOfMedians, result.median); } final Multimap<AxisName, AxisValue> axisValues = LinkedHashMultimap.create(); for (final Scenario scenario : run.scenarios) { final ScenarioName scenarioName = new ScenarioName(scenario.localName); // only include scenarios with data for this instrument if (processedResults.keySet().contains(scenarioName)) { for (final Entry<AxisName, AxisValue> entry : scenarioLocalVars.row(scenarioName).entrySet()) { axisValues.put(entry.getKey(), entry.getValue()); } } } final List<Axis> axes = Lists.newArrayList(); for (final Entry<AxisName, Collection<AxisValue>> entry : axisValues.asMap().entrySet()) { final Axis axis = new Axis(entry.getKey(), entry.getValue()); axes.add(axis); } /* * Figure out how much influence each axis has on the measured value. * We sum the measurements taken with each value of each axis. For * axes that have influence on the measurement, the sums will differ * by value. If the axis has little influence, the sums will be similar * to one another and close to the overall average. We take the variance * across each axis' collection of sums. Higher variance implies higher * influence on the measured result. */ double sumOfAllMeasurements = 0; for (final ProcessedResult result : processedResults.values()) { sumOfAllMeasurements += result.median; } for (final Axis axis : axes) { final int numValues = axis.numberOfValues(); final double[] sumForValue = new double[numValues]; for (final Entry<ScenarioName, ProcessedResult> entry : processedResults.entrySet()) { final ScenarioName scenarioLocalName = entry.getKey(); final ProcessedResult result = entry.getValue(); sumForValue[axis.index(scenarioLocalName)] += result.median; } final double mean = sumOfAllMeasurements / sumForValue.length; double variance = 0; for (final double value : sumForValue) { final double distance = value - mean; variance += distance * distance; } axis.variance = variance / numValues; } this.sortedAxes = new VarianceOrdering().reverse().sortedCopy(axes); this.sortedScenarioNames = ImmutableSortedSet.copyOf(new ByAxisOrdering(), processedResults.keySet()); this.maxValue = maxOfMedians; buildChart(); }
From source file:com.google.caliper.report.ReportGenerator.java
/** * /*from w ww. ja v a 2s.c om*/ * @param run * @param registry * @param arguments */ public ReportGenerator(SuiteRun run, RendererRegistry registry, CommandLineParser arguments) { this.run = run; this.arguments = arguments; rendererName = arguments.getReportType(); this.registry = registry; // File pluginFolder = arguments.getPluginFolder(); // this.registry = new DefaultRendererRegistry( // (null != pluginFolder) ? pluginFolder : new File(DEFAULT_PLUGIN_LOCATION), // arguments); unitMap.put(MeasurementType.TIME, arguments.getTimeUnit()); unitMap.put(MeasurementType.INSTANCE, arguments.getInstanceUnit()); unitMap.put(MeasurementType.MEMORY, arguments.getMemoryUnit()); if (arguments.getMeasureMemory()) { orderedMeasurementTypes = Arrays.asList(MeasurementType.values()); } else { orderedMeasurementTypes = Arrays.asList(MeasurementType.TIME); } if (arguments.getPrimaryMeasurementType() != null) { this.type = arguments.getPrimaryMeasurementType(); } else { this.type = MeasurementType.TIME; } double min = Double.POSITIVE_INFINITY; double max = 0; Multimap<String, String> nameToValues = LinkedHashMultimap.create(); List<Variable> variablesBuilder = new ArrayList<Variable>(); for (Entry<Scenario, ScenarioResult> entry : this.run.getMeasurements().entrySet()) { Scenario scenario = entry.getKey(); double d = entry.getValue().getMeasurementSet(type).medianUnits(); min = Math.min(min, d); max = Math.max(max, d); for (Entry<String, String> variable : scenario.getVariables().entrySet()) { String name = variable.getKey(); nameToValues.put(name, variable.getValue()); } } for (Entry<String, Collection<String>> entry : nameToValues.asMap().entrySet()) { Variable variable = new Variable(entry.getKey(), entry.getValue()); variablesBuilder.add(variable); } /* * Figure out how much influence each variable has on the measured value. * We sum the measurements taken with each value of each variable. For * variable that have influence on the measurement, the sums will differ * by value. If the variable has little influence, the sums will be similar * to one another and close to the overall average. We take the standard * deviation across each variable's collection of sums. Higher standard * deviation implies higher influence on the measured result. */ double sumOfAllMeasurements = 0; for (ScenarioResult measurement : this.run.getMeasurements().values()) { sumOfAllMeasurements += measurement.getMeasurementSet(type).medianUnits(); } for (Variable variable : variablesBuilder) { int numValues = variable.values.size(); double[] sumForValue = new double[numValues]; for (Entry<Scenario, ScenarioResult> entry : this.run.getMeasurements().entrySet()) { Scenario scenario = entry.getKey(); sumForValue[variable.index(scenario)] += entry.getValue().getMeasurementSet(type).medianUnits(); } double mean = sumOfAllMeasurements / sumForValue.length; double stdDeviationSquared = 0; for (double value : sumForValue) { double distance = value - mean; stdDeviationSquared += distance * distance; } variable.stdDeviation = Math.sqrt(stdDeviationSquared / numValues); } this.variables = new StandardDeviationOrdering().reverse().sortedCopy(variablesBuilder); this.scenarios = new ByVariablesOrdering().sortedCopy(this.run.getMeasurements().keySet()); this.maxValue = max; this.logMinValue = Math.log(min); this.logMaxValue = Math.log(max); EnumMap<MeasurementType, Integer> digitsBeforeDecimalMap = new EnumMap<MeasurementType, Integer>( MeasurementType.class); EnumMap<MeasurementType, Integer> decimalPointMap = new EnumMap<MeasurementType, Integer>( MeasurementType.class); for (MeasurementType measurementType : orderedMeasurementTypes) { double maxForType = 0; double minForType = Double.POSITIVE_INFINITY; for (Entry<Scenario, ScenarioResult> entry : this.run.getMeasurements().entrySet()) { double d = entry.getValue().getMeasurementSet(measurementType).medianUnits(); minForType = Math.min(minForType, d); maxForType = Math.max(maxForType, d); } unitMap.put(measurementType, getUnit(unitMap.get(measurementType), measurementType, minForType)); divideByMap.put(measurementType, (double) getUnits(measurementType).get(unitMap.get(measurementType))); int numDigitsInMin = ceil(Math.log10(minForType)); decimalDigitsMap.put(measurementType, ceil(Math.max(0, ceil(Math.log10(divideByMap.get(measurementType))) + 3 - numDigitsInMin))); digitsBeforeDecimalMap.put(measurementType, Math.max(1, ceil(Math.log10(maxForType / divideByMap.get(measurementType))))); decimalPointMap.put(measurementType, decimalDigitsMap.get(measurementType) > 0 ? 1 : 0); measurementColumnLengthMap.put(measurementType, Math.max(maxForType > 0 ? digitsBeforeDecimalMap.get(measurementType) + decimalPointMap.get(measurementType) + decimalDigitsMap.get(measurementType) : 1, unitMap.get(measurementType).trim().length())); } }
From source file:es.usc.citius.composit.core.composition.optimization.FunctionalDominanceOptimizer.java
public Collection<Collection<Operation<E>>> functionalInputEquivalence(ServiceMatchNetwork<E, T> network, int level) { // Identify providers for each service (all those services that provides one or more // inputs to the current service. Multimap<Set<Set<Operation<E>>>, Operation<E>> equivalentGroups = HashMultimap.create(); for (Operation<E> o : network.getOperationsAtLevel(level)) { // Calculate service providers for each input of this service. Set<Set<Operation<E>>> groupedInputProviders = new HashSet<Set<Operation<E>>>(); for (E input : o.getSignature().getInputs()) { // For each input, find compatible source elements that match that input Set<E> targets = network.getSourceElementsThatMatch(input).keySet(); Set<Operation<E>> inputProviders = new HashSet<Operation<E>>(); for (E target : targets) { inputProviders.addAll(Sets.newHashSet(network.getOperationsWithOutput(target))); }/*from w w w . j a v a2 s . c om*/ // Remove services that are not in the previous layers inputProviders.retainAll(network.getOperationsBeforeLevel(level)); groupedInputProviders.add(inputProviders); } equivalentGroups.get(groupedInputProviders).add(o); } return equivalentGroups.asMap().values(); }