org.jgrapht.alg.ConnectivityInspector Java Examples

The following examples show how to use org.jgrapht.alg.ConnectivityInspector. 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: ContainersMapping.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
private static <N, B> void createVoltageLevelMapping(List<N> buses, List<B> branches, ToIntFunction<N> busToNum,
                                                     ToIntFunction<B> branchToNum1, ToIntFunction<B> branchToNum2,
                                                     ToDoubleFunction<B> branchToResistance, ToDoubleFunction<B> branchToReactance,
                                                     Function<Set<Integer>, String> busesToVoltageLevelId, ContainersMapping containersMapping) {
    UndirectedGraph<Integer, Object> vlGraph = new Pseudograph<>(Object.class);
    for (N bus : buses) {
        vlGraph.addVertex(busToNum.applyAsInt(bus));
    }
    for (B branch : branches) {
        if (branchToResistance.applyAsDouble(branch) == 0 && branchToReactance.applyAsDouble(branch) == 0) {
            vlGraph.addEdge(branchToNum1.applyAsInt(branch), branchToNum2.applyAsInt(branch));
        }
    }
    for (Set<Integer> busNums : new ConnectivityInspector<>(vlGraph).connectedSets()) {
        String voltageLevelId = busesToVoltageLevelId.apply(busNums);
        containersMapping.voltageLevelIdToBusNums.put(voltageLevelId, busNums);
        for (int busNum : busNums) {
            containersMapping.busNumToVoltageLevelId.put(busNum, voltageLevelId);
        }
    }
}
 
Example #2
Source File: NormalizeConclusionsInTGDs.java    From Llunatic with GNU General Public License v3.0 6 votes vote down vote up
public List<Dependency> normalizeTGD(Dependency tgd) {
    if (logger.isDebugEnabled()) logger.debug("Analyzing tgd: " + tgd);
    List<Dependency> normalizedTgds = new ArrayList<Dependency>();
    if (tgd.getConclusion().getAtoms().size() == 1) {
        if (logger.isDebugEnabled()) logger.debug("Tgd has single target variable, adding...");
        normalizedTgds.add(tgd);
        return normalizedTgds;
    }
    UndirectedGraph<RelationalAtom, DefaultEdge> graph = dualGaifmanGraphGenerator.getDualGaifmanGraph(tgd);
    ConnectivityInspector<RelationalAtom, DefaultEdge> inspector = new ConnectivityInspector<RelationalAtom, DefaultEdge>(graph);
    List<Set<RelationalAtom>> connectedComponents = inspector.connectedSets();
    if (connectedComponents.size() == 1) {
        if (logger.isDebugEnabled()) logger.debug("Tgd is normalized...");
        normalizedTgds.add(tgd);
        return normalizedTgds;
    }
    if (logger.isDebugEnabled()) logger.debug("Tgd is not normalized...");
    for (int i = 0; i < connectedComponents.size(); i++) {
        Set<RelationalAtom> connectedComponent = connectedComponents.get(i);
        String suffixId = "_norm_" + (i + 1);
        normalizedTgds.add(separateComponent(tgd, connectedComponent, suffixId));
    }
    if (logger.isDebugEnabled()) logger.debug("Resulting set of normalized tgds: " + normalizedTgds);
    return normalizedTgds;
}
 
Example #3
Source File: FindFormulaWithAdornments.java    From BART with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private FormulaWithAdornments findFormulaWithAdornments(UndirectedGraph<FormulaGraphVertex, DefaultEdge> formulaGraph,
        List<VariablePair> variablePairs, List<FormulaVariable> anonymousVariables, IFormula formula) {
    Set<FormulaGraphVertex> vertices = new HashSet<FormulaGraphVertex>(formulaGraph.vertexSet());
    for (VariablePair variablePair : variablePairs) {
        vertices.remove(variablePair.getVertex());
    }
    UndirectedSubgraph<FormulaGraphVertex, DefaultEdge> subgraph = new UndirectedSubgraph<FormulaGraphVertex, DefaultEdge>(formulaGraph, vertices, formulaGraph.edgeSet());
    ConnectivityInspector<FormulaGraphVertex, DefaultEdge> inspector = new ConnectivityInspector<FormulaGraphVertex, DefaultEdge>(subgraph);
    List<Set<FormulaGraphVertex>> connectedVertices = inspector.connectedSets();
    if (connectedVertices.size() != 2) {
        return null;
    }
    UndirectedSubgraph<FormulaGraphVertex, DefaultEdge> connectedSubgraphOne = new UndirectedSubgraph<FormulaGraphVertex, DefaultEdge>(formulaGraph, connectedVertices.get(0), formulaGraph.edgeSet());
    UndirectedSubgraph<FormulaGraphVertex, DefaultEdge> connectedSubgraphTwo = new UndirectedSubgraph<FormulaGraphVertex, DefaultEdge>(formulaGraph, connectedVertices.get(1), formulaGraph.edgeSet());
    VertexEquivalenceComparator vertexComparator = new VertexEquivalenceComparator(variablePairs, anonymousVariables);
    UniformEquivalenceComparator<DefaultEdge, Graph<FormulaGraphVertex, DefaultEdge>> edgeComparator = new UniformEquivalenceComparator<DefaultEdge, Graph<FormulaGraphVertex, DefaultEdge>>();
    GraphIsomorphismInspector<Graph<FormulaGraphVertex, DefaultEdge>> isomorphismInspector = AdaptiveIsomorphismInspectorFactory.createIsomorphismInspector(connectedSubgraphOne, connectedSubgraphTwo, vertexComparator, edgeComparator);
    boolean areIsomorphic = isomorphismInspector.isIsomorphic();
    if (logger.isDebugEnabled()) logger.debug("Graph One: \n" + connectedSubgraphOne + "\nGraph Two: \n" + connectedSubgraphTwo + "\nAre isomorphic: " + areIsomorphic);
    if (!areIsomorphic) {
        return null;
    }
    return formulaWithAdornmentsGenerator.generate(formula, connectedSubgraphOne, connectedSubgraphTwo, variablePairs);
}
 
Example #4
Source File: CavMerger.java    From bioasq with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void modify(JCas jcas) throws AnalysisEngineProcessException {
  Collection<CandidateAnswerVariant> cavs = TypeUtil.getCandidateAnswerVariants(jcas);
  UndirectedGraph<Object, DefaultEdge> graph = new SimpleGraph<>(DefaultEdge.class);
  cavs.forEach(cav -> {
    graph.addVertex(cav);
    for (String name : TypeUtil.getCandidateAnswerVariantNames(cav)) {
      graph.addVertex(name);
      graph.addEdge(cav, name);
    }
  } );
  ConnectivityInspector<Object, DefaultEdge> ci = new ConnectivityInspector<>(graph);
  ci.connectedSets().stream().map(subgraph -> {
    List<CandidateAnswerVariant> subCavs = subgraph.stream()
            .filter(CandidateAnswerVariant.class::isInstance)
            .map(CandidateAnswerVariant.class::cast).collect(toList());
    return TypeFactory.createAnswer(jcas, TypeConstants.SCORE_UNKNOWN, subCavs);
  } ).forEach(Answer::addToIndexes);
}
 
Example #5
Source File: SubstationIdMapping.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
public void build() {
    // CGMES standard:
    // "a PowerTransformer is contained in one Substation but it can connect a Terminal to
    // another Substation"
    // Ends of transformers need to be in the same substation in the IIDM model.
    // We will map some CGMES substations to a single IIDM substation
    // when they are connected by transformers,
    // that is, when there are at least one power transformer that has terminals on both
    // substations

    UndirectedGraph<String, Object> g = graphSubstationsTransformers();
    new ConnectivityInspector<>(g).connectedSets().stream()
            .filter(substationIds -> substationIds.size() > 1)
            .forEach(substationIds -> {
                String selectedSubstationId = representativeSubstationId(substationIds);
                for (String substationId : substationIds) {
                    if (!substationId.equals(selectedSubstationId)) {
                        mapping.put(substationId, selectedSubstationId);
                    }
                }
            });
    if (!mapping.isEmpty()) {
        LOG.warn("Substation id mapping needed for {} substations: {}",
                mapping.size(), mapping);
    }
}
 
Example #6
Source File: FindConnectedTables.java    From BART with MIT License 5 votes vote down vote up
List<ConnectedTables> findConnectedEqualityGroups(List<RelationalAtom> atoms, List<EqualityGroup> equalityGroups) {
    List<ConnectedTables> result = new ArrayList<ConnectedTables>();
    UndirectedGraph<TableAlias, LabeledEdge> joinGraph = initJoinGraph(atoms, equalityGroups);
    ConnectivityInspector<TableAlias, LabeledEdge> inspector = new ConnectivityInspector<TableAlias, LabeledEdge>(joinGraph);
    List<Set<TableAlias>> connectedVertices = inspector.connectedSets();
    for (Set<TableAlias> connectedComponent : connectedVertices) {
        ConnectedTables connectedTables = new ConnectedTables(connectedComponent);
        result.add(connectedTables);
    }
    return result;
}
 
Example #7
Source File: GraphComponentOrderDetector.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public int calculateOrder(AFPChain selfAlignment, Atom[] ca)
		throws RefinerFailedException {

	// Construct the alignment graph with jgrapht
	Graph<Integer, DefaultEdge> graph = SymmetryTools
			.buildSymmetryGraph(selfAlignment);

	// Find the maximally connected components of the graph
	ConnectivityInspector<Integer, DefaultEdge> inspector =
			new ConnectivityInspector<Integer, DefaultEdge>(graph);
	List<Set<Integer>> components = inspector.connectedSets();

	// The order maximizes the residues aligned
	Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
	for (Set<Integer> c : components) {
		if (counts.containsKey(c.size()))
			counts.put(c.size(), counts.get(c.size()) + c.size());
		else
			counts.put(c.size(), c.size());
	}
	int maxCounts = 0;
	int order = 1;
	for (Integer ord : counts.keySet()) {
		if (counts.get(ord) > maxCounts) {
			order = ord;
			maxCounts = counts.get(ord);
		}
	}
	return order;
}
 
Example #8
Source File: FindSymmetricAtoms.java    From Llunatic with GNU General Public License v3.0 5 votes vote down vote up
private UndirectedGraph<TableAlias, LabeledEdge> buildSubGraph(TableAlias alias, TableAlias otherAlias, UndirectedGraph<TableAlias, LabeledEdge> graph) {
    Set<TableAlias> vertices = new HashSet<TableAlias>(graph.vertexSet());
    vertices.remove(otherAlias);
    UndirectedSubgraph<TableAlias, LabeledEdge> subgraph = new UndirectedSubgraph<TableAlias, LabeledEdge>(graph, vertices, graph.edgeSet());
    ConnectivityInspector<TableAlias, LabeledEdge> inspector = new ConnectivityInspector<TableAlias, LabeledEdge>(subgraph);
    Set<TableAlias> connectedVertices = inspector.connectedSetOf(alias);
    UndirectedSubgraph<TableAlias, LabeledEdge> connectedSubgraph = new UndirectedSubgraph<TableAlias, LabeledEdge>(graph, connectedVertices, graph.edgeSet());
    return connectedSubgraph;
}
 
Example #9
Source File: BuildExtendedDependencies.java    From Llunatic with GNU General Public License v3.0 5 votes vote down vote up
private void findAffectedAttributes(List<ExtendedEGD> dependencies) {
    // affected attributes must take into account also clustering of values, not only local affected attributes
    // eg: e1 -> AB, e2: -> A
    Map<AttributeRef, List<ExtendedEGD>> attributeMap = initAttributeMap(dependencies);
    UndirectedGraph<ExtendedEGD, DefaultEdge> dependencyGraph = initDependencyGraph(dependencies, attributeMap);
    ConnectivityInspector<ExtendedEGD, DefaultEdge> inspector = new ConnectivityInspector<ExtendedEGD, DefaultEdge>(dependencyGraph);
    List<Set<ExtendedEGD>> connectedComponents = inspector.connectedSets();
    for (Set<ExtendedEGD> connectedComponent : connectedComponents) {
        List<AttributeRef> affectedAttributesForComponent = extractAttributesForComponent(connectedComponent);
        for (ExtendedEGD dependency : connectedComponent) {
            if (logger.isDebugEnabled()) logger.debug("Dependency " + dependency + "\nAffected: " + affectedAttributesForComponent);
            dependency.setAffectedAttributes(affectedAttributesForComponent);
        }
    }
}
 
Example #10
Source File: FindConnectedTables.java    From Llunatic with GNU General Public License v3.0 5 votes vote down vote up
List<ConnectedTables> findConnectedEqualityGroups(List<RelationalAtom> atoms, List<EqualityGroup> equalityGroups) {
    List<ConnectedTables> result = new ArrayList<ConnectedTables>();
    UndirectedGraph<TableAlias, LabeledEdge> joinGraph = initJoinGraph(atoms, equalityGroups);
    ConnectivityInspector<TableAlias, LabeledEdge> inspector = new ConnectivityInspector<TableAlias, LabeledEdge>(joinGraph);
    List<Set<TableAlias>> connectedVertices = inspector.connectedSets();
    for (Set<TableAlias> connectedComponent : connectedVertices) {
        ConnectedTables connectedTables = new ConnectedTables(connectedComponent);
        result.add(connectedTables);
    }
    return result;
}
 
Example #11
Source File: AssociationManager.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) {
	UndirectedGraph<String, DefaultEdge> g = createStringGraph();
	ConnectivityInspector ci = new ConnectivityInspector(g);
	List connectedSet = ci.connectedSets();
	for (Object o : connectedSet) {
		Set vertexes = (Set) o;
		for (Object vertex : vertexes) {
			logger.debug(vertex.toString());
		}
		logger.debug("-----------------------------");
	}
	logger.debug(connectedSet.size());
}
 
Example #12
Source File: CategoryGraph.java    From dkpro-jwpl with Apache License 2.0 5 votes vote down vote up
/**
 * @return Returns the largest connected component as a new graph. If the base graph already is connected, it simply returns the whole graph.
 */
public CategoryGraph getLargestConnectedComponent() throws WikiApiException {
    ConnectivityInspector connectInspect = new ConnectivityInspector<Integer, DefaultEdge>(graph);

    // if the graph is connected, simply return the whole graph
    if (connectInspect.isGraphConnected()) {
        return this;
    }

    // else, get the largest connected component
    List<Set<Integer>> connectedComponentList = connectInspect.connectedSets();

    logger.info(connectedComponentList.size() + " connected components.");

    int i = 0;
    int maxSize = 0;
    Set<Integer> largestComponent = new HashSet<Integer>();
    for (Set<Integer> connectedComponent : connectedComponentList) {
        i++;
        if (connectedComponent.size() > maxSize) {
            maxSize = connectedComponent.size();
            largestComponent = connectedComponent;
        }
    }

    double largestComponentRatio = largestComponent.size() * 100 / this.getNumberOfNodes();
    logger.info ("Largest component contains " + largestComponentRatio + "% (" + largestComponent.size() + "/" + this.getNumberOfNodes() + ") of the nodes in the graph.");

    return CategoryGraphManager.getCategoryGraph(wiki, largestComponent);
}
 
Example #13
Source File: AssociationManager.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public List<AssociationGroup> getAssociationGroups() {
	List<AssociationGroup> associationGroups = new ArrayList<AssociationGroup>();
	UndirectedGraph<String, DefaultEdge> g = buildGraph();
	ConnectivityInspector ci = new ConnectivityInspector(g);
	List<Set> connectedSet = ci.connectedSets();
	for (Set<String> datasets : connectedSet) {
		AssociationGroup associationGroup = new AssociationGroup();
		for (String dataset : datasets) {
			List<Association> associations = getAssociations(dataset);
			associationGroup.addAssociations(associations);
		}
		associationGroups.add(associationGroup);
	}
	return associationGroups;
}
 
Example #14
Source File: TopologyHistoryConnectedComponentsAnalyser.java    From ipst with Mozilla Public License 2.0 5 votes vote down vote up
public Set<String> analyse() {
    UndirectedGraph<Vertex, Object> graph = createGraph();

    // sort by ascending size
    return new ConnectivityInspector<>(graph).connectedSets().stream()
            .sorted(new Comparator<Set<Vertex>>() {
                @Override
                public int compare(Set<Vertex> o1, Set<Vertex> o2) {
                    return o2.size() - o1.size();
                }
            })
            .map(s -> s.stream().map(v -> v.equipmentId).collect(Collectors.<String>toSet()))
            .collect(Collectors.toList())
            .get(0);
}
 
Example #15
Source File: CompoundFactory.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Browse through the provided isolated sections and return a list of compound
 * instances, one for each set of connected sections.
 * <p>
 * This method does not use the sections neighboring links, it is thus rather slow but usable
 * when these links are not yet set.
 *
 * @param sections    the sections to browse
 * @param constructor specific compound constructor
 * @return the list of compound instances created
 */
public static List<SectionCompound> buildCompounds (Collection<Section> sections,
                                                    CompoundConstructor constructor)
{
    // Build a temporary graph of all sections with "touching" relations
    List<Section> list = new ArrayList<>(sections);

    ///Collections.sort(list, Section.byAbscissa);
    SimpleGraph<Section, Touching> graph = new SimpleGraph<>(Touching.class);

    // Populate graph with all sections as vertices
    for (Section section : list) {
        graph.addVertex(section);
    }

    // Populate graph with relations
    for (int i = 0; i < list.size(); i++) {
        Section one = list.get(i);

        for (Section two : list.subList(i + 1, list.size())) {
            if (one.touches(two)) {
                graph.addEdge(one, two, new Touching());
            }
        }
    }

    // Retrieve all the clusters of sections (sets of touching sections)
    ConnectivityInspector<Section, Touching> inspector = new ConnectivityInspector<>(graph);
    List<Set<Section>> sets = inspector.connectedSets();
    logger.debug("sets: {}", sets.size());

    List<SectionCompound> compounds = new ArrayList<>();

    for (Set<Section> set : sets) {
        compounds.add(buildCompound(set, constructor));
    }

    return compounds;
}
 
Example #16
Source File: ClefBuilder.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Retrieve the map of best clefs, organized per kind.
 *
 * @param isFirstPass true for first pass only
 * @return the bestMap found
 */
private Map<ClefKind, ClefInter> getBestMap (boolean isFirstPass)
{
    List<Glyph> parts = getParts(isFirstPass);

    // Formalize parts relationships in a global graph
    SimpleGraph<Glyph, GlyphLink> graph = Glyphs.buildLinks(parts, params.maxPartGap);
    List<Set<Glyph>> sets = new ConnectivityInspector<>(graph).connectedSets();
    logger.debug("Staff#{} sets: {}", staff.getId(), sets.size());

    // Best inter per clef kind
    Map<ClefKind, ClefInter> bestMap = new EnumMap<>(ClefKind.class);

    for (Set<Glyph> set : sets) {
        // Use only the subgraph for this set
        SimpleGraph<Glyph, GlyphLink> subGraph = GlyphCluster.getSubGraph(set, graph, false);
        ClefAdapter adapter = new ClefAdapter(subGraph, bestMap);
        new GlyphCluster(adapter, null).decompose();

        int trials = adapter.trials;
        logger.debug("Staff#{} clef parts:{} trials:{}", staff.getId(), set.size(), trials);
    }

    // Discard poor candidates as much as possible
    if (bestMap.size() > 1) {
        purgeClefs(bestMap);
    }

    return bestMap;
}
 
Example #17
Source File: SymbolsBuilder.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Process all clusters of connected glyphs, based on the glyphs graph.
 *
 * @param systemGraph the graph of candidate glyphs, with their mutual distances
 */
private void processClusters (SimpleGraph<Glyph, GlyphLink> systemGraph)
{
    // Retrieve all the clusters of glyphs (sets of connected glyphs)
    final ConnectivityInspector<Glyph, GlyphLink> inspector = new ConnectivityInspector<>(
            systemGraph);
    final List<Set<Glyph>> sets = inspector.connectedSets();
    logger.debug("symbols sets: {}", sets.size());

    final int interline = sheet.getInterline();
    final int maxPartCount = constants.maxPartCount.getValue();

    for (Collection<Glyph> set : sets) {
        final int setSize = set.size();
        logger.debug("set size: {}", setSize);

        if (setSize > 1) {
            if (setSize > maxPartCount) {
                List<Glyph> list = new ArrayList<>(set);
                Collections.sort(list, Glyphs.byReverseWeight);
                set = list.subList(0, maxPartCount);
                logger.info("Symbol parts shrunk from {} to {}", setSize, maxPartCount);
            }

            // Use just the subgraph for this (sub)set
            final SimpleGraph<Glyph, GlyphLink> subGraph;
            subGraph = GlyphCluster.getSubGraph(set, systemGraph, true);
            new GlyphCluster(new SymbolAdapter(subGraph), GlyphGroup.SYMBOL).decompose();
        } else {
            // The set is just an isolated glyph, to be evaluated directly
            final Glyph glyph = set.iterator().next();

            if (classifier.isBigEnough(glyph, interline)) {
                evaluateGlyph(glyph);
            }
        }
    }
}
 
Example #18
Source File: ConceptMerger.java    From bioasq with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void process(JCas jcas) throws AnalysisEngineProcessException {
  // create views and get all concepts in the views
  List<JCas> views = new ArrayList<>();
  if (includeDefaultView) {
    views.add(jcas);
  }
  views.addAll(ViewType.listViews(jcas, viewNamePrefix));
  List<Concept> concepts = views.stream().map(TypeUtil::getConcepts).flatMap(Collection::stream)
          .collect(toList());
  // preserve concept fields
  Set<String> uuids = new HashSet<>();
  SetMultimap<String, String> uuid2ids = HashMultimap.create();
  SetMultimap<String, String> uuid2names = HashMultimap.create();
  SetMultimap<String, String> uuid2uris = HashMultimap.create();
  SetMultimap<String, ConceptMention> uuid2mentions = HashMultimap.create();
  SetMultimap<String, List<String>> uuid2types = HashMultimap.create();
  for (Concept concept : concepts) {
    String uuid = UUID_PREFIX + UUID.randomUUID().toString();
    uuids.add(uuid);
    uuid2ids.putAll(uuid, TypeUtil.getConceptIds(concept));
    uuid2names.putAll(uuid, TypeUtil.getConceptNames(concept));
    uuid2uris.putAll(uuid, TypeUtil.getConceptUris(concept));
    uuid2mentions.putAll(uuid, TypeUtil.getConceptMentions(concept));
    // also remove duplicated concept type entries
    TypeUtil.getConceptTypes(concept).forEach(type -> uuid2types.put(uuid, toTypeList(type)));
  }
  // connectivity detection for merging
  UndirectedGraph<String, DefaultEdge> graph = new SimpleGraph<>(DefaultEdge.class);
  uuids.forEach(graph::addVertex);
  uuid2ids.values().forEach(graph::addVertex);
  uuid2ids.entries().forEach(entry -> graph.addEdge(entry.getKey(), entry.getValue()));
  if (useName) {
    uuid2names.values().stream().map(ConceptMerger::nameKey).forEach(graph::addVertex);
    uuid2names.entries().forEach(entry -> graph.addEdge(entry.getKey(), nameKey(entry.getValue())));
  }
  views.forEach(view -> view.removeAllIncludingSubtypes(Concept.type));
  ConnectivityInspector<String, DefaultEdge> ci = new ConnectivityInspector<>(graph);
  Multiset<Integer> mergedSizes = HashMultiset.create();
  List<Concept> mergedConcepts = ci.connectedSets().stream().map(subgraph -> {
    Set<String> cuuids = subgraph.stream().filter(str -> str.startsWith(UUID_PREFIX))
            .collect(toSet());
    List<String> ids = cuuids.stream().map(uuid2ids::get).flatMap(Set::stream)
            .filter(Objects::nonNull).distinct().collect(toList());
    List<String> names = cuuids.stream().map(uuid2names::get).flatMap(Set::stream)
            .filter(Objects::nonNull).distinct().collect(toList());
    List<String> uris = cuuids.stream().map(uuid2uris::get).flatMap(Set::stream)
            .filter(Objects::nonNull).distinct().collect(toList());
    List<ConceptType> types = cuuids.stream().map(uuid2types::get).flatMap(Set::stream)
            .filter(Objects::nonNull).distinct().map(type -> parseTypeList(jcas, type))
            .collect(toList());
    List<ConceptMention> mentions = cuuids.stream().map(uuid2mentions::get).flatMap(Set::stream)
            .filter(Objects::nonNull).collect(toList());
    mergedSizes.add(cuuids.size());
    return TypeFactory.createConcept(jcas, names, uris, ImmutableList.copyOf(ids), mentions,
            types);
  }).collect(toList());
  mergedConcepts.forEach(Concept::addToIndexes);
  LOG.info("Merged concepts from {} concepts.", mergedSizes);
  if (LOG.isDebugEnabled()) {
    mergedConcepts.stream().map(TypeUtil::toString).forEachOrdered(c -> LOG.debug(" - {}", c));
  }
}
 
Example #19
Source File: UcteNetworkExt.java    From powsybl-core with Mozilla Public License 2.0 4 votes vote down vote up
private void updateSubstation() {
    if (substations == null) {
        LOGGER.trace("Update substations...");
        substations = new ArrayList<>();
        node2voltageLevel = new HashMap<>();
        UndirectedGraph<UcteNodeCode, Object> graph = createSubstationGraph(network);
        for (Set<UcteNodeCode> substationNodes : new ConnectivityInspector<>(graph).connectedSets()) {
            // the main node of the substation is not an xnode and the one with the highest voltage
            // level and the lowest busbar number.
            UcteNodeCode mainNode = substationNodes.stream()
                    .sorted((nodeCode1, nodeCode2) -> {
                        if (nodeCode1.getUcteCountryCode() == UcteCountryCode.XX &&
                                nodeCode2.getUcteCountryCode() != UcteCountryCode.XX) {
                            return 1;
                        } else if (nodeCode1.getUcteCountryCode() != UcteCountryCode.XX &&
                                nodeCode2.getUcteCountryCode() == UcteCountryCode.XX) {
                            return -1;
                        } else {
                            return compareVoltageLevelThenBusbar(nodeCode1, nodeCode2);
                        }
                    })
                    .findFirst()
                    .orElseThrow(AssertionError::new);

            Multimap<UcteVoltageLevelCode, UcteNodeCode> nodesByVoltageLevel
                    = Multimaps.index(substationNodes, UcteNodeCode::getVoltageLevelCode);

            String substationName = mainNode.getUcteCountryCode().getUcteCode() + mainNode.getGeographicalSpot();
            List<UcteVoltageLevel> voltageLevels = new ArrayList<>();
            UcteSubstation substation = new UcteSubstation(substationName, voltageLevels);
            substations.add(substation);

            LOGGER.trace("Define substation {}", substationName);

            for (Map.Entry<UcteVoltageLevelCode, Collection<UcteNodeCode>> entry : nodesByVoltageLevel.asMap().entrySet()) {
                UcteVoltageLevelCode vlc = entry.getKey();
                Collection<UcteNodeCode> voltageLevelNodes = entry.getValue();
                String voltageLevelName = mainNode.getUcteCountryCode().getUcteCode() + mainNode.getGeographicalSpot() + vlc.ordinal();
                UcteVoltageLevel voltageLevel = new UcteVoltageLevel(voltageLevelName, substation, voltageLevelNodes);
                voltageLevels.add(voltageLevel);
                voltageLevelNodes.forEach(voltageLevelNode -> node2voltageLevel.put(voltageLevelNode, voltageLevel));

                LOGGER.trace("Define voltage level {} as a group of {} nodes", voltageLevelName, voltageLevelNodes);
            }
        }
    }
}
 
Example #20
Source File: KeyExtractor.java    From audiveris with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Retrieve all possible candidates (as connected components) with acceptable shape.
 *
 * @param range  working range
 * @param roi    key roi
 * @param peaks  relevant peaks
 * @param shapes acceptable shapes
 * @return the candidates found
 */
public List<Candidate> retrieveCandidates (StaffHeader.Range range,
                                           KeyRoi roi,
                                           List<KeyPeak> peaks,
                                           Set<Shape> shapes)
{
    logger.debug("retrieveCandidates for staff#{}", id);

    // Key-signature area pixels
    ByteProcessor keyBuf = roi.getAreaPixels(staffFreeSource, range);
    RunTable runTable = new RunTableFactory(VERTICAL).createTable(keyBuf);
    List<Glyph> parts = GlyphFactory.buildGlyphs(runTable, new Point(range.getStart(), roi.y));

    purgeParts(parts, range.getStop());
    system.registerGlyphs(parts, null);

    // Formalize parts relationships in a global graph
    SimpleGraph<Glyph, GlyphLink> graph = Glyphs.buildLinks(parts, params.maxPartGap);
    List<Set<Glyph>> sets = new ConnectivityInspector<>(graph).connectedSets();
    logger.debug("Staff#{} sets:{}", id, sets.size());

    List<Candidate> allCandidates = new ArrayList<>();

    for (Set<Glyph> set : sets) {
        // Use only the subgraph for this set
        SimpleGraph<Glyph, GlyphLink> subGraph = GlyphCluster.getSubGraph(set, graph, false);
        MultipleAdapter adapter = new MultipleAdapter(
                roi,
                peaks,
                subGraph,
                shapes,
                Grades.keyAlterMinGrade1);
        new GlyphCluster(adapter, null).decompose();
        logger.debug("Staff#{} set:{} trials:{}", id, set.size(), adapter.trials);
        allCandidates.addAll(adapter.candidates);
    }

    purgeCandidates(allCandidates);
    Collections.sort(allCandidates, Candidate.byReverseGrade);

    return allCandidates;
}
 
Example #21
Source File: TGraphs.java    From Llunatic with GNU General Public License v3.0 4 votes vote down vote up
public void testGraph() {
        UndirectedGraph<String, LabeledEdge> graph = new SimpleGraph<String, LabeledEdge>(LabeledEdge.class);
        Set<String> vertices = new HashSet<String>();
        vertices.add("R1");
        vertices.add("R2");
        vertices.add("T1");
        vertices.add("T2");
        vertices.add("S");
        vertices.add("V");
        graph.addVertex("R1");
        graph.addVertex("R2");
        graph.addVertex("T1");
        graph.addVertex("T2");
        graph.addVertex("S");
        graph.addVertex("V");
        graph.addEdge("R1", "S", new LabeledEdge("R1", "S", "R.A,S.A"));
        graph.addEdge("R2", "S", new LabeledEdge("R2", "S", "R.A,S.A"));
        graph.addEdge("R1", "T1", new LabeledEdge("R1", "T1", "R.B,T.B"));
        graph.addEdge("R2", "T2", new LabeledEdge("R2", "T2", "R.B,T.B"));
        graph.addEdge("R1", "R2", new LabeledEdge("R1", "R2", "R.A,R.A"));
//        graph.addEdge("T1", "V", new LabeledEdge("T1", "V", "T.C,V.C"));
        Set<String> vertices1 = new HashSet<String>(vertices);
        vertices1.remove("R2");
        UndirectedSubgraph<String, LabeledEdge> subgraph1 = new UndirectedSubgraph<String, LabeledEdge>(graph, vertices1, graph.edgeSet());
        ConnectivityInspector<String, LabeledEdge> inspector1 = new ConnectivityInspector<String, LabeledEdge>(subgraph1);
        Set<String> connectedVertices1 = inspector1.connectedSetOf("R1");
        UndirectedSubgraph<String, LabeledEdge> connectedSubgraph1 = new UndirectedSubgraph<String, LabeledEdge>(graph, connectedVertices1, graph.edgeSet());
        Set<String> vertices2 = new HashSet<String>(vertices);
        vertices2.remove("R1");
        UndirectedSubgraph<String, LabeledEdge> subgraph2 = new UndirectedSubgraph<String, LabeledEdge>(graph, vertices2, graph.edgeSet());
        ConnectivityInspector<String, LabeledEdge> inspector2 = new ConnectivityInspector<String, LabeledEdge>(subgraph2);
        Set<String> connectedVertices2 = inspector2.connectedSetOf("R2");
        UndirectedSubgraph<String, LabeledEdge> connectedSubgraph2 = new UndirectedSubgraph<String, LabeledEdge>(graph, connectedVertices2, graph.edgeSet());
        Set<LabeledEdge> edges1 = connectedSubgraph1.edgeSet();
        Set<LabeledEdge> edges2 = connectedSubgraph2.edgeSet();
        if (containsAll(edges1, edges2)) {
            logger.debug("R1 is contained in R2");
        }
        if (containsAll(edges2, edges1)) {
            logger.debug("R2 is contained in R1");
        }
    }
 
Example #22
Source File: CeSymmIterative.java    From biojava with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * After all the analysis iterations have finished, the final Result object
 * is reconstructed using the cumulative alignment graph.
 *
 * @param atoms
 *            the original structure atoms
 * @return CeSymmResult reconstructed symmetry result
 * @throws StructureException
 */
private CeSymmResult reconstructSymmResult(Atom[] atoms)
		throws StructureException {

	// If one level, nothing to build or calculate
	if (levels.size() == 1)
		return levels.get(0);

	CeSymmResult result = new CeSymmResult();
	result.setSelfAlignment(levels.get(0).getSelfAlignment());
	result.setStructureId(levels.get(0).getStructureId());
	result.setAtoms(levels.get(0).getAtoms());
	result.setParams(levels.get(0).getParams());

	// Initialize a new multiple alignment
	MultipleAlignment msa = new MultipleAlignmentImpl();
	msa.getEnsemble().setAtomArrays(new ArrayList<Atom[]>());
	msa.getEnsemble().setStructureIdentifiers(
			new ArrayList<StructureIdentifier>());
	msa.getEnsemble().setAlgorithmName(CeSymm.algorithmName);
	msa.getEnsemble().setVersion(CeSymm.version);

	BlockSet bs = new BlockSetImpl(msa);
	Block b = new BlockImpl(bs);
	b.setAlignRes(new ArrayList<List<Integer>>());

	// Calculate the connected groups of the alignment graph
	ConnectivityInspector<Integer, DefaultEdge> inspector = new ConnectivityInspector<Integer, DefaultEdge>(
			alignGraph);
	List<Set<Integer>> comps = inspector.connectedSets();
	List<ResidueGroup> groups = new ArrayList<ResidueGroup>(comps.size());
	for (Set<Integer> comp : comps)
		groups.add(new ResidueGroup(comp));

	// Calculate the total number of repeats
	int order = 1;
	for (CeSymmResult sr : levels)
		order *= sr.getMultipleAlignment().size();
	for (int su = 0; su < order; su++)
		b.getAlignRes().add(new ArrayList<Integer>());

	// Construct the resulting MultipleAlignment from ResidueGroups
	for (ResidueGroup group : groups) {
		if (group.order() != order)
			continue;
		group.combineWith(b.getAlignRes());
	}

	// The reconstruction failed, so the top level is returned
	if (b.length() == 0)
		return levels.get(0);

	for (int su = 0; su < order; su++) {
		Collections.sort(b.getAlignRes().get(su));
		msa.getEnsemble().getAtomArrays().add(atoms);
		msa.getEnsemble().getStructureIdentifiers()
				.add(result.getStructureId());
	}

	result.setMultipleAlignment(msa);
	result.setRefined(true);
	result.setNumRepeats(order);

	SymmetryAxes axes = recoverAxes(result);
	result.setAxes(axes);

	// Set the transformations and scores of the final alignment
	SymmetryTools
			.updateSymmetryTransformation(result.getAxes(), msa);
	double tmScore = MultipleAlignmentScorer.getAvgTMScore(msa)
			* msa.size();
	double rmsd = MultipleAlignmentScorer.getRMSD(msa);
	msa.putScore(MultipleAlignmentScorer.AVGTM_SCORE, tmScore);
	msa.putScore(MultipleAlignmentScorer.RMSD, rmsd);

	return result;
}