Java Code Examples for com.google.common.collect.ListMultimap#keySet()

The following examples show how to use com.google.common.collect.ListMultimap#keySet() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DiploidRatioSupplier.java    From hmftools with GNU General Public License v3.0 6 votes vote down vote up
DiploidRatioSupplier(@NotNull final ListMultimap<Chromosome, ReadRatio> normalRatios) {
    final ReferenceRatioStatistics stats = ReferenceRatioStatisticsFactory.fromReferenceRatio(normalRatios);

    for (Chromosome chromosome : normalRatios.keySet()) {
        final List<ReadRatio> ratios = normalRatios.get(chromosome);
        final List<ReadRatio> adjustedRatios;
        if (chromosome.equals(HumanChromosome._Y)) {
            adjustedRatios = ratios;
        } else {
            double expectedRatio = chromosome.equals(HumanChromosome._X) && !stats.containsTwoXChromosomes() ? 0.5 : 1;
            adjustedRatios = new DiploidRatioNormalization(expectedRatio,
                    ROLLING_MEDIAN_MAX_DISTANCE,
                    ROLLING_MEDIAN_MIN_COVERAGE,
                    ratios).get();
        }
        result.replaceValues(chromosome, adjustedRatios);
    }
}
 
Example 2
Source File: GroupRepository.java    From artemis with Apache License 2.0 6 votes vote down vote up
protected Map<Long, GroupTags> getServiceGroupTags() {
    Map<Long, GroupTags> newGroupTags = Maps.newHashMap();
    ListMultimap<Long, GroupTagModel> m = ArrayListMultimap.create();
    for (GroupTagModel model : groupTagDao.query()) {
        m.put(model.getGroupId(), model);
    }

    for (Long id : m.keySet()) {
        Map<String, String> tags = Maps.newHashMap();
        for (GroupTagModel tag : m.get(id)) {
            tags.put(tag.getTag(), tag.getValue());
        }
        newGroupTags.put(id, new GroupTags(id, tags));
    }
    return newGroupTags;
}
 
Example 3
Source File: ServiceCluster.java    From artemis with Apache License 2.0 6 votes vote down vote up
protected void updateClusterNodes() {
    ListMultimap<String, String> zoneIdNodeUrlsMap = _clusterNodesProperty.typedValue();
    _logger.info("ClusterNodes setting raw value: " + _clusterNodesProperty.value() + ", typedValue: "
            + zoneIdNodeUrlsMap);
    ListMultimap<Zone, ServiceNode> clusterNodes = ArrayListMultimap.create();
    for (String zoneId : zoneIdNodeUrlsMap.keySet()) {
        Zone zone = new Zone(_regionId, zoneId);
        for (String serviceUrl : zoneIdNodeUrlsMap.get(zoneId)) {
            if (StringValues.isNullOrWhitespace(serviceUrl))
                continue;
            ServiceNode peerNode = new ServiceNode(zone, serviceUrl);
            clusterNodes.put(zone, peerNode);
        }
    }

    if (clusterNodes.size() == 0) {
        _logger.warn("New ClusterNodes is empty. Skip to update");
        return;
    }

    _logger.info("ClusterNodes is updated. from: " + _clusterNodes + ", to: " + clusterNodes);
    _clusterNodes = clusterNodes;
}
 
Example 4
Source File: DataMerger.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the post blob load state to WRITTEN.
 *
 * After a load from the blob file, all items have their state set to nothing.
 * If the load mode is set to incrementalState then we want the items that are in the current
 * merge result to have their state be WRITTEN.
 *
 * This will allow further updates with {@link #mergeData(MergeConsumer, boolean)} to ignore the
 * state at load time and only apply the new changes.
 *
 * @see #loadFromBlob(File, boolean)
 * @see DataItem#isWritten()
 */
private void setPostBlobLoadStateToWritten() {
    ListMultimap<String, I> itemMap = ArrayListMultimap.create();

    // put all the sets into list per keys. The order is important as the lower sets are
    // overridden by the higher sets.
    for (S dataSet : mDataSets) {
        ListMultimap<String, I> map = dataSet.getDataMap();
        for (Map.Entry<String, Collection<I>> entry : map.asMap().entrySet()) {
            itemMap.putAll(entry.getKey(), entry.getValue());
        }
    }

    // the items that represent the current state is the last item in the list for each key.
    for (String key : itemMap.keySet()) {
        List<I> itemList = itemMap.get(key);
        itemList.get(itemList.size() - 1).resetStatusToWritten();
    }
}
 
Example 5
Source File: DataMerger.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the post blob load state to TOUCHED.
 *
 * After a load from the blob file, all items have their state set to nothing.
 * If the load mode is not set to incrementalState then we want the items that are in the
 * current merge result to have their state be TOUCHED.
 *
 * This will allow the first use of {@link #mergeData(MergeConsumer, boolean)} to add these
 * to the consumer as if they were new items.
 *
 * @see #loadFromBlob(File, boolean)
 * @see DataItem#isTouched()
 */
private void setPostBlobLoadStateToTouched() {
    ListMultimap<String, I> itemMap = ArrayListMultimap.create();

    // put all the sets into list per keys. The order is important as the lower sets are
    // overridden by the higher sets.
    for (S dataSet : mDataSets) {
        ListMultimap<String, I> map = dataSet.getDataMap();
        for (Map.Entry<String, Collection<I>> entry : map.asMap().entrySet()) {
            itemMap.putAll(entry.getKey(), entry.getValue());
        }
    }

    // the items that represent the current state is the last item in the list for each key.
    for (String key : itemMap.keySet()) {
        List<I> itemList = itemMap.get(key);
        itemList.get(itemList.size() - 1).resetStatusToTouched();
    }
}
 
Example 6
Source File: XtendJvmModelInferrer.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
protected void appendSyntheticDispatchMethods(XtendTypeDeclaration source, final JvmGenericType target) {
	ListMultimap<DispatchHelper.DispatchSignature, JvmOperation> methods = dispatchHelper.getDeclaredOrEnhancedDispatchMethods(target);
	for (DispatchHelper.DispatchSignature signature : methods.keySet()) {
		List<JvmOperation> operations = methods.get(signature);
		Iterable<JvmOperation> localOperations = Iterables.filter(operations, new Predicate<JvmOperation>() {
			@Override
			public boolean apply(JvmOperation input) {
				return target == input.eContainer();
			}
		});
		JvmOperation operation = deriveGenericDispatchOperationSignature(localOperations, target);
		if (operation != null) {
			dispatchHelper.markAsDispatcherFunction(operation);
			operation.setSimpleName(signature.getSimpleName());
			operation.setReturnType(jvmTypesBuilder.inferredType());
		}
	}
}
 
Example 7
Source File: AbstractResourceRepository.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
@NonNull
public Map<String, ResourceValue> getConfiguredResources(
        @NonNull Map<ResourceType, ListMultimap<String, ResourceItem>> itemMap,
        @NonNull ResourceType type,
        @NonNull FolderConfiguration referenceConfig) {
    // get the resource item for the given type
    ListMultimap<String, ResourceItem> items = itemMap.get(type);
    if (items == null) {
        return Maps.newHashMap();
    }

    Set<String> keys = items.keySet();

    // create the map
    Map<String, ResourceValue> map = Maps.newHashMapWithExpectedSize(keys.size());

    for (String key : keys) {
        List<ResourceItem> keyItems = items.get(key);

        // look for the best match for the given configuration
        // the match has to be of type ResourceFile since that's what the input list contains
        ResourceItem match = (ResourceItem) referenceConfig.findMatchingConfigurable(keyItems);
        if (match != null) {
            ResourceValue value = match.getResourceValue(mFramework);
            if (value != null) {
                map.put(match.getName(), value);
            }
        }
    }

    return map;
}
 
Example 8
Source File: StructuralVariantLegsFactory.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
private static Set<GenomePosition> findDuplicatePositions(@NotNull final Collection<ModifiableStructuralVariantLegs> legs) {
    final ListMultimap<GenomePosition, ModifiableStructuralVariantLegs> result = ArrayListMultimap.create();
    for (ModifiableStructuralVariantLegs leg : legs) {
        leg.start().ifPresent(x -> result.put(cnaPosition(x), leg));
        leg.end().ifPresent(x -> result.put(cnaPosition(x), leg));
    }

    result.keySet().removeIf(key -> result.get(key).size() <= 1);
    return result.keySet();
}
 
Example 9
Source File: RawResolvedFeatures.java    From xtext-extras with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public List<JvmFeature> getAllFeatures() {
	if (!allFeaturesComputed) {
		ListMultimap<String, JvmFeature> featureIndex = computeAllFeatures();
		for(String simpleName: featureIndex.keySet()) {
			this.featureIndex.put(simpleName, Lists.newArrayList(featureIndex.get(simpleName)));
		}
		allFeaturesComputed = true;
	}
	List<JvmFeature> result = Lists.newArrayList();
	for(List<JvmFeature> list: featureIndex.values()) {
		result.addAll(list);
	}
	return result;
}
 
Example 10
Source File: AbstractResourceRepository.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@NonNull
public Map<String, ResourceValue> getConfiguredResources(
        @NonNull Map<ResourceType, ListMultimap<String, ResourceItem>> itemMap,
        @NonNull ResourceType type,
        @NonNull FolderConfiguration referenceConfig) {
    // get the resource item for the given type
    ListMultimap<String, ResourceItem> items = itemMap.get(type);
    if (items == null) {
        return Maps.newHashMap();
    }

    Set<String> keys = items.keySet();

    // create the map
    Map<String, ResourceValue> map = Maps.newHashMapWithExpectedSize(keys.size());

    for (String key : keys) {
        List<ResourceItem> keyItems = items.get(key);

        // look for the best match for the given configuration
        // the match has to be of type ResourceFile since that's what the input list contains
        ResourceItem match = (ResourceItem) referenceConfig.findMatchingConfigurable(keyItems);
        if (match != null) {
            ResourceValue value = match.getResourceValue(mFramework);
            if (value != null) {
                map.put(match.getName(), value);
            }
        }
    }

    return map;
}
 
Example 11
Source File: DistcpFileSplitter.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Finds all split work units in the input collection and merges the file parts into the expected output files.
 * @param fs {@link FileSystem} where file parts exist.
 * @param workUnits Collection of {@link WorkUnitState}s possibly containing split work units.
 * @return The collection of {@link WorkUnitState}s where split work units for each file have been merged.
 * @throws IOException
 */
public static Collection<WorkUnitState> mergeAllSplitWorkUnits(FileSystem fs, Collection<WorkUnitState> workUnits)
    throws IOException {
  ListMultimap<CopyableFile, WorkUnitState> splitWorkUnitsMap = ArrayListMultimap.create();
  for (WorkUnitState workUnit : workUnits) {
    if (isSplitWorkUnit(workUnit)) {
      CopyableFile copyableFile = (CopyableFile) CopySource.deserializeCopyEntity(workUnit);
      splitWorkUnitsMap.put(copyableFile, workUnit);
    }
  }

  for (CopyableFile file : splitWorkUnitsMap.keySet()) {
    log.info(String.format("Merging split file %s.", file.getDestination()));

    WorkUnitState oldWorkUnit = splitWorkUnitsMap.get(file).get(0);
    Path outputDir = FileAwareInputStreamDataWriter.getOutputDir(oldWorkUnit);
    CopyEntity.DatasetAndPartition datasetAndPartition =
        file.getDatasetAndPartition(CopySource.deserializeCopyableDataset(oldWorkUnit));
    Path parentPath = FileAwareInputStreamDataWriter.getOutputFilePath(file, outputDir, datasetAndPartition)
        .getParent();

    WorkUnitState newWorkUnit = mergeSplits(fs, file, splitWorkUnitsMap.get(file), parentPath);

    for (WorkUnitState wu : splitWorkUnitsMap.get(file)) {
      // Set to committed so that task states will not fail
      wu.setWorkingState(WorkUnitState.WorkingState.COMMITTED);
      workUnits.remove(wu);
    }
    workUnits.add(newWorkUnit);
  }
  return workUnits;
}
 
Example 12
Source File: TaskDetailPrinter.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void print(StyledTextOutput output) {
    final List<Task> tasks = sort(selection.getTasks());

    output.text("Detailed task information for ").withStyle(UserInput).println(taskPath);
    final ListMultimap<Class, Task> classListMap = groupTasksByType(tasks);

    final Set<Class> classes = classListMap.keySet();
    boolean multipleClasses = classes.size() > 1;
    final List<Class> sortedClasses = sort(classes, new Comparator<Class>() {
        public int compare(Class o1, Class o2) {
            return o1.getSimpleName().compareTo(o2.getSimpleName());
        }
    });
    for (Class clazz : sortedClasses) {
        output.println();
        final List<Task> tasksByType = classListMap.get(clazz);
        final LinePrefixingStyledTextOutput pathOutput = createIndentedOutput(output, INDENT);
        pathOutput.println(tasksByType.size() > 1 ? "Paths" : "Path");
        for (Task task : tasksByType) {
            pathOutput.withStyle(UserInput).println(task.getPath());
        }
        output.println();
        final LinePrefixingStyledTextOutput typeOutput = createIndentedOutput(output, INDENT);
        typeOutput.println("Type");
        typeOutput.withStyle(UserInput).text(clazz.getSimpleName());
        typeOutput.println(String.format(" (%s)", clazz.getName()));

        printlnCommandlineOptions(output, tasksByType);

        output.println();
        printTaskDescription(output, tasksByType);
        output.println();
        if (multipleClasses) {
            output.println("----------------------");
        }
    }
}
 
Example 13
Source File: AmberApplication.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
private ListMultimap<Chromosome, TumorBAF> tumorBAF(@NotNull final SamReaderFactory readerFactory,
        @NotNull final ListMultimap<Chromosome, BaseDepth> normalHetSites) throws ExecutionException, InterruptedException {
    final int partitionSize = Math.max(config.minPartition(), normalHetSites.values().size() / config.threadCount());

    LOGGER.info("Processing {} heterozygous sites in tumor bam {}", normalHetSites.values().size(), config.tumorBamPath());
    final AmberTaskCompletion completion = new AmberTaskCompletion();

    final List<Future<TumorBAFEvidence>> futures = Lists.newArrayList();
    for (final Chromosome chromosome : normalHetSites.keySet()) {
        for (final List<BaseDepth> chromosomeBafPoints : Lists.partition(normalHetSites.get(chromosome), partitionSize)) {
            if (!chromosomeBafPoints.isEmpty()) {
                final String contig = chromosomeBafPoints.get(0).chromosome();
                final TumorBAFEvidence evidence = new TumorBAFEvidence(config.typicalReadDepth(),
                        config.minMappingQuality(),
                        config.minBaseQuality(),
                        contig,
                        config.tumorBamPath(),
                        readerFactory,
                        chromosomeBafPoints);
                futures.add(executorService.submit(completion.task(evidence)));
            }
        }
    }

    final ListMultimap<Chromosome, TumorBAF> result = ArrayListMultimap.create();
    getFuture(futures).forEach(x -> result.putAll(HumanChromosome.fromString(x.contig()), x.evidence()));

    return result;
}
 
Example 14
Source File: AmberApplication.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
private ListMultimap<Chromosome, BaseDepth> normalDepth(final SamReaderFactory readerFactory, final String bamPath,
        final ListMultimap<Chromosome, AmberSite> bedRegionsSortedSet) throws InterruptedException, ExecutionException {

    final int partitionSize = Math.max(config.minPartition(), bedRegionsSortedSet.size() / config.threadCount());

    LOGGER.info("Processing {} potential sites in reference bam {}", bedRegionsSortedSet.values().size(), bamPath);
    final AmberTaskCompletion completion = new AmberTaskCompletion();

    final List<Future<BaseDepthEvidence>> futures = Lists.newArrayList();
    for (final Chromosome contig : bedRegionsSortedSet.keySet()) {
        for (final List<AmberSite> inner : Lists.partition(Lists.newArrayList(bedRegionsSortedSet.get(contig)), partitionSize)) {
            final BaseDepthEvidence evidence = new BaseDepthEvidence(config.typicalReadDepth(),
                    config.minMappingQuality(),
                    config.minBaseQuality(),
                    inner.get(0).chromosome(),
                    bamPath,
                    readerFactory,
                    inner);
            futures.add(executorService.submit(completion.task(evidence)));
        }
    }

    final ListMultimap<Chromosome, BaseDepth> normalEvidence = ArrayListMultimap.create();
    getFuture(futures).forEach(x -> normalEvidence.putAll(HumanChromosome.fromString(x.contig()), x.evidence()));
    return normalEvidence;
}
 
Example 15
Source File: TaskDetailPrinter.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void print(StyledTextOutput output) {
    final List<Task> tasks = sort(selection.getTasks());

    output.text("Detailed task information for ").withStyle(UserInput).println(taskPath);
    final ListMultimap<Class, Task> classListMap = groupTasksByType(tasks);

    final Set<Class> classes = classListMap.keySet();
    boolean multipleClasses = classes.size() > 1;
    final List<Class> sortedClasses = sort(classes, new Comparator<Class>() {
        public int compare(Class o1, Class o2) {
            return o1.getSimpleName().compareTo(o2.getSimpleName());
        }
    });
    for (Class clazz : sortedClasses) {
        output.println();
        final List<Task> tasksByType = classListMap.get(clazz);
        final LinePrefixingStyledTextOutput pathOutput = createIndentedOutput(output, INDENT);
        pathOutput.println(tasksByType.size() > 1 ? "Paths" : "Path");
        for (Task task : tasksByType) {
            pathOutput.withStyle(UserInput).println(task.getPath());
        }
        output.println();
        final LinePrefixingStyledTextOutput typeOutput = createIndentedOutput(output, INDENT);
        typeOutput.println("Type");
        typeOutput.withStyle(UserInput).text(clazz.getSimpleName());
        typeOutput.println(String.format(" (%s)", clazz.getName()));

        printlnCommandlineOptions(output, tasksByType);

        output.println();
        printTaskDescription(output, tasksByType);
        if (multipleClasses) {
            output.println();
            output.println("----------------------");
        }
    }
}
 
Example 16
Source File: PluginDependenciesService.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public List<PluginRequest> getRequests() {
    List<PluginRequest> pluginRequests = collect(specs, new Transformer<PluginRequest, DependencySpecImpl>() {
        public PluginRequest transform(DependencySpecImpl original) {
            return new DefaultPluginRequest(original.id, original.version, original.lineNumber, scriptSource);
        }
    });

    ListMultimap<PluginId, PluginRequest> groupedById = CollectionUtils.groupBy(pluginRequests, new Transformer<PluginId, PluginRequest>() {
        public PluginId transform(PluginRequest pluginRequest) {
            return pluginRequest.getId();
        }
    });

    // Check for duplicates
    for (PluginId key : groupedById.keySet()) {
        List<PluginRequest> pluginRequestsForId = groupedById.get(key);
        if (pluginRequestsForId.size() > 1) {
            PluginRequest first = pluginRequests.get(0);
            PluginRequest second = pluginRequests.get(1);

            InvalidPluginRequestException exception = new InvalidPluginRequestException(second, "Plugin with id '" + key + "' was already requested at line " + first.getLineNumber());
            throw new LocationAwareException(exception, second.getScriptSource(), second.getLineNumber());
        }
    }

    return pluginRequests;
}
 
Example 17
Source File: ActionListCustomizationMediatorImpl.java    From rice with Educational Community License v2.0 4 votes vote down vote up
/**
 * <p>partitions ActionItems by application id, and calls the appropriate
 * {@link ActionListCustomizationHandlerService} for each parition, merging the results.</p>
 *
 * <dl><dt><b>inherited docs:</b></dt><dd>{@inheritDoc}</dd></dl>
 */
@Override
public Map<String, ActionItemCustomization> getActionListCustomizations(String principalId,
        List<ActionItem> actionItems) throws RiceIllegalArgumentException {
    if (StringUtils.isBlank(principalId)) {
        throw new RiceIllegalArgumentException("invalid principalId: " + principalId);
    }
    if (actionItems == null) {
        actionItems = Collections.emptyList();
    }

    // map from action item ID to ActionItemCustomization
    Map<String, ActionItemCustomization> results = new HashMap<String, ActionItemCustomization>();

    // group each action item by application id that needs to be called for action list customizations (note that
    // the application id comes from the extension/rule attribute record, most action lists will have doc types
    // with no custom action list attribute, though the default still needs to be run in this case)

    ListMultimap<String, ActionItem> itemsByApplicationId = ArrayListMultimap.create();

    for (ActionItem actionItem : actionItems) {
        //DocumentType docType = KewApiServiceLocator.getDocumentTypeService().getDocumentTypeByName(actionItem.getDocName());
        DocumentType docType = getDocumentTypeService().findByName(actionItem.getDocName());
        if (docType == null) {
            LOG.error(String.format("Action item %s has an invalid document type name of %s",
                    actionItem.getId(), actionItem.getDocName()));
            // OK to have a null key, this represents the default app id
            itemsByApplicationId.put(null, actionItem);
        } else {
            // OK to have a null key, this represents the default app id
            itemsByApplicationId.put(getActionListCustomizationApplicationId(docType), actionItem);
        }
    }

    // For each application id, pass all action items which might need to be customized (because they have a
    // document type, which declares an action list attribute, which has an application id declared) to the
    // appropriate ActionListCustomizationHandlerService endpoint

    for (String applicationId : itemsByApplicationId.keySet()) {
        ActionListCustomizationHandlerService actionListCustomizationHandler =
                getActionListCustomizationHandlerServiceChooser().getByApplicationId(applicationId);

        if (actionListCustomizationHandler == null) {
            // get the local ActionListCustomizationHandlerService as a fallback
            actionListCustomizationHandler =
                    getActionListCustomizationHandlerServiceChooser().getByApplicationId(null);
        }

        List<ActionItemCustomization> customizations =
                actionListCustomizationHandler.customizeActionList(principalId, itemsByApplicationId.get(
                        applicationId));


        // Get back the customized results and reassemble with customized results from all different application
        // customizations (as well as default customizations)
        if (customizations != null) for (ActionItemCustomization customization : customizations) {
            results.put(customization.getActionItemId(), customization);
        }
    }

    return results;
}
 
Example 18
Source File: ClusterManager.java    From artemis with Apache License 2.0 4 votes vote down vote up
private void updateNodesCache() {
    ListMultimap<Zone, ServiceNode> clusterNodes = _serviceCluster.clusterNodes();
    List<ServiceNode> localZoneNodes = new ArrayList<>();
    List<ServiceNode> otherZoneNodes = new ArrayList<>();
    List<ServiceNode> otherNodes = new ArrayList<>();
    List<ServiceNode> localZoneOtherNodes = new ArrayList<>();
    List<ServiceNode> allNodes = new ArrayList<>();
    for (Zone zone : clusterNodes.keySet()) {
        List<ServiceNode> nodes = clusterNodes.get(zone);
        if (zone.equals(_localZone)) {
            localZoneNodes.addAll(nodes);
            for (ServiceNode node : nodes) {
                if (isLocalNode(node)) {
                    _localNode.setUrl(node.getUrl());
                    continue;
                }

                localZoneOtherNodes.add(node);
            }

            continue;
        }

        otherZoneNodes.addAll(nodes);
    }

    otherNodes.addAll(localZoneOtherNodes);
    otherNodes.addAll(otherZoneNodes);

    if (localZoneNodes.size() > 0)
        _localZoneNodes = localZoneNodes;

    if (localZoneOtherNodes.size() > 0)
        _localZoneOtherNodes = localZoneOtherNodes;

    if (otherZoneNodes.size() > 0)
        _otherZoneNodes = otherZoneNodes;

    if (otherNodes.size() > 0)
        _otherNodes = otherNodes;

    allNodes.addAll(_localZoneNodes);
    allNodes.addAll(_otherZoneNodes);
    _allNodes = allNodes;
}
 
Example 19
Source File: StructBuild.java    From swift-t with Apache License 2.0 4 votes vote down vote up
private void structBuildRec(Logger logger, Block block) {
  // Track all assigned struct paths
  ListMultimap<Var, List<String>> assignedPaths = ArrayListMultimap.create();

  // Find all struct assign statements in block
  for (Statement stmt: block.getStatements()) {
    if (stmt.type() == StatementType.INSTRUCTION) {
      Instruction inst = stmt.instruction();
      if (inst.op == Opcode.STRUCT_STORE_SUB) {
        Var struct = inst.getOutput(0);
        List<Arg> inputs = inst.getInputs();
        List<Arg> fields = inputs.subList(1, inputs.size());
        assignedPaths.put(struct, Arg.extractStrings(fields));
      }
    }
  }

  // Check if all fields were assigned
  for (Var candidate: assignedPaths.keySet()) {
    StructType candidateType = (StructType)candidate.type().getImplType();
    Set<List<String>> expectedPaths = allAssignablePaths(candidateType);
    List<List<String>> assigned = assignedPaths.get(candidate);

    logger.trace("Check candidate " + candidate.name() + "\n" +
                 "expected: " + expectedPaths + "\n" +
                 "assigned: " + assigned);

    for (List<String> path: assigned) {
      Type fieldType;
      try {
        fieldType = candidateType.fieldTypeByPath(path);
      } catch (TypeMismatchException e) {
        throw new STCRuntimeError(e.getMessage());
      }

      Set<List<String>> assignedSubPaths;
      if (Types.isStruct(fieldType)) {
        // Handle case where we assign a substruct
        StructType structFieldType = (StructType)fieldType.getImplType();
        assignedSubPaths = allAssignablePaths(structFieldType, path);
      } else {
        assignedSubPaths = Collections.singleton(path);
      }

      for (List<String> assignedPath: assignedSubPaths) {
        boolean found = expectedPaths.remove(assignedPath);
        if (!found) {
          logger.warn("Invalid or double-assigned struct field: " +
                       candidate.name() + "." + assignedPath);
        }
      }
    }
    if (expectedPaths.isEmpty()) {
      doStructBuildTransform(logger, block, candidate, assigned.size());
    } else if (logger.isTraceEnabled()) {
      logger.trace("Fields not assigned: " + expectedPaths);
    }
  }

  for (Continuation cont: block.allComplexStatements()) {
    for (Block cb: cont.getBlocks()) {
      structBuildRec(logger, cb);
    }
  }
}