Java Code Examples for org.jgrapht.alg.ConnectivityInspector#connectedSets()

The following examples show how to use org.jgrapht.alg.ConnectivityInspector#connectedSets() . 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: 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 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: 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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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;
}