org.jgrapht.UndirectedGraph Java Examples

The following examples show how to use org.jgrapht.UndirectedGraph. 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: SubstationIdMapping.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
private UndirectedGraph<String, Object> graphSubstationsTransformers() {
    UndirectedGraph<String, Object> graph = new Pseudograph<>(Object.class);
    for (PropertyBag s : context.cgmes().substations()) {
        String id = s.getId(CgmesNames.SUBSTATION);
        String iid = context.namingStrategy().getId(CgmesNames.SUBSTATION, id);
        graph.addVertex(iid);
    }
    for (PropertyBags tends : context.cgmes().groupedTransformerEnds().values()) {
        List<String> substationsIds = substationsIds(tends);
        if (substationsIds.size() > 1) {
            for (int i = 1; i < substationsIds.size(); i++) {
                graph.addEdge(substationsIds.get(0), substationsIds.get(i));
            }
        }
    }
    return graph;
}
 
Example #2
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 #3
Source File: FindConnectedTables.java    From BART with MIT License 6 votes vote down vote up
private UndirectedGraph<TableAlias, LabeledEdge> initJoinGraph(List<RelationalAtom> atoms, List<EqualityGroup> equalityGroups) {
    UndirectedGraph<TableAlias, LabeledEdge> joinGraph = new SimpleGraph<TableAlias, LabeledEdge>(LabeledEdge.class);
    if (logger.isDebugEnabled()) logger.debug("Build join graph for equality groups " + equalityGroups);
    Set<TableAlias> tableAliases = extracTableAliases(atoms);
    for (TableAlias tableAlias : tableAliases) {
        joinGraph.addVertex(tableAlias);
    }
    for (EqualityGroup equalityGroup : equalityGroups) {
        TableAlias leftTable = equalityGroup.getLeftTable();
        TableAlias rightTable = equalityGroup.getRightTable();
        if(leftTable.equals(rightTable)){
            continue;
        }
        joinGraph.addEdge(leftTable, rightTable, new LabeledEdge(leftTable.toString(), rightTable.toString(), equalityGroup.toString()));
    }
    return joinGraph;
}
 
Example #4
Source File: FindFormulaWithAdornments.java    From BART with MIT License 6 votes vote down vote up
private UndirectedGraph<FormulaGraphVertex, DefaultEdge> initJoinGraph(IFormula formula) {
    Map<FormulaVariable, FormulaGraphVertex> vertexMap = new HashMap<FormulaVariable, FormulaGraphVertex>();
    UndirectedGraph<FormulaGraphVertex, DefaultEdge> graph = new SimpleGraph<FormulaGraphVertex, DefaultEdge>(DefaultEdge.class);
    for (FormulaVariable formulaVariable : formula.getLocalVariables()) {
        FormulaGraphVertex vertex = new FormulaGraphVertex(formulaVariable);
        graph.addVertex(vertex);
        vertexMap.put(formulaVariable, vertex);
    }
    for (IFormulaAtom atom : formula.getAtoms()) {
        if (atom.isRelational()) {
            addVerticesForRelationalAtom(atom, graph, vertexMap);
        }
        if (atom.isComparison()) {
            addVerticesForComparisonAtom(atom, graph, vertexMap);
        }
    }
    return graph;
}
 
Example #5
Source File: FindFormulaWithAdornments.java    From BART with MIT License 6 votes vote down vote up
private void addVerticesForRelationalAtom(IFormulaAtom atom, UndirectedGraph<FormulaGraphVertex, DefaultEdge> graph, Map<FormulaVariable, FormulaGraphVertex> vertexMap) {
    RelationalAtom relationalAtom = (RelationalAtom) atom;
    FormulaGraphVertex atomVertex = new FormulaGraphVertex(relationalAtom);
    graph.addVertex(atomVertex);
    for (FormulaAttribute formulaAttribute : relationalAtom.getAttributes()) {
        if (formulaAttribute.getValue().isVariable()) {
            String variableId = ((FormulaVariableOccurrence) formulaAttribute.getValue()).getVariableId();
            FormulaVariable variable = AlgebraUtility.findVariable(variableId, new ArrayList<FormulaVariable>(vertexMap.keySet()));
            FormulaGraphVertex variableVertex = vertexMap.get(variable);
            assert (variableVertex != null) : "Unable to find vertex for variable " + variableId;
            graph.addEdge(atomVertex, variableVertex);
        } else if (formulaAttribute.getValue().isConstant() || formulaAttribute.getValue().isNull()) {
            createConstantVertex(formulaAttribute.getValue().toString(), atomVertex, graph);
        } else if (formulaAttribute.getValue().isExpression()) {
            throw new UnsupportedOperationException("Unable to check symmetry with expression");
        }
    }
}
 
Example #6
Source File: FindFormulaWithAdornments.java    From BART with MIT License 6 votes vote down vote up
private void addVerticesForComparisonAtom(IFormulaAtom atom, UndirectedGraph<FormulaGraphVertex, DefaultEdge> graph, Map<FormulaVariable, FormulaGraphVertex> vertexMap) {
    ComparisonAtom comparisonAtom = (ComparisonAtom) atom;
    FormulaGraphVertex comparisonVertex = new FormulaGraphVertex(comparisonAtom);
    graph.addVertex(comparisonVertex);
    for (FormulaVariable variable : comparisonAtom.getVariables()) {
        FormulaGraphVertex variableVertex = vertexMap.get(variable);
        graph.addEdge(comparisonVertex, variableVertex);
    }
    if (comparisonAtom.getLeftConstant() != null) {
        createConstantVertex(comparisonAtom.getLeftConstant(), comparisonVertex, graph);
        addEdgesForEquivalenceClass(comparisonAtom.getLeftConstant(), comparisonAtom.getRightVariable(), comparisonAtom.getOperator(), atom.getFormula(), graph, vertexMap);
    }
    if (comparisonAtom.getRightConstant() != null) {
        createConstantVertex(comparisonAtom.getRightConstant(), comparisonVertex, graph);
        addEdgesForEquivalenceClass(comparisonAtom.getRightConstant(), comparisonAtom.getLeftVariable(), comparisonAtom.getOperator(), atom.getFormula(), graph, vertexMap);
    }
}
 
Example #7
Source File: FindFormulaWithAdornments.java    From BART with MIT License 6 votes vote down vote up
private void addEdgesForEquivalenceClass(String constant, FormulaVariable variable, String operator,
        IFormula formula, UndirectedGraph<FormulaGraphVertex, DefaultEdge> graph, Map<FormulaVariable, FormulaGraphVertex> vertexMap) {
    VariableEquivalenceClass equivalenceClass = DependencyUtility.findEquivalenceClassForVariable(variable, formula.getLocalVariableEquivalenceClasses());
    if (logger.isDebugEnabled()) logger.debug("Adding edges for equivalence class " + equivalenceClass);
    for (FormulaVariable otherVariable : equivalenceClass.getVariables()) {
        if (otherVariable.equals(variable)) {
            continue;
        }
        if (existComparison(otherVariable, constant, formula)) {
            continue;
        }
        Expression expression = new Expression(otherVariable.getId() + operator + constant);
        ComparisonAtom virtualComparisonAtom = new ComparisonAtom(formula, expression, otherVariable.getId(), null, null, constant, operator);
        virtualComparisonAtom.addVariable(otherVariable);
        FormulaGraphVertex virtualComparisonVertex = new FormulaGraphVertex(virtualComparisonAtom);
        virtualComparisonVertex.setVirtual(true);
        graph.addVertex(virtualComparisonVertex);
        FormulaGraphVertex variableVertex = vertexMap.get(otherVariable);
        graph.addEdge(virtualComparisonVertex, variableVertex);
        createConstantVertex(constant, virtualComparisonVertex, graph);
    }
}
 
Example #8
Source File: FindFormulaWithAdornments.java    From BART with MIT License 6 votes vote down vote up
private List<VariablePair> findVariablePairs(UndirectedGraph<FormulaGraphVertex, DefaultEdge> formulaGraph) {
    List<VariablePair> result = new ArrayList<VariablePair>();
    for (FormulaGraphVertex vertex : formulaGraph.vertexSet()) {
        if (!vertex.isAtom() || (vertex.isAtom() && !(vertex.getAtom().isComparison()))) {
            continue;
        }
        ComparisonAtom comparisonAtom = (ComparisonAtom) vertex.getAtom();
        if (comparisonAtom.isNumericalComparison() || !comparisonAtom.isVariableComparison()) {
            continue;
        }
        FormulaVariable leftVariable = comparisonAtom.getLeftVariable();
        FormulaVariable rightVariable = comparisonAtom.getRightVariable();
        if (logger.isDebugEnabled()) logger.debug("Left variable: " + leftVariable);
        if (logger.isDebugEnabled()) logger.debug("Right variable: " + rightVariable);
        if (!haveOccurrencesInSameAttributes(leftVariable, rightVariable)) {
            continue;
        }
        VariablePair variablePair = new VariablePair(leftVariable, rightVariable, vertex);
        result.add(variablePair);
    }
    return result;
}
 
Example #9
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 #10
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 #11
Source File: DualGaifmanGraph.java    From Llunatic with GNU General Public License v3.0 6 votes vote down vote up
private void addEdges(UndirectedGraph<RelationalAtom, DefaultEdge> graph, Dependency dependency) {
    Map<FormulaVariable, List<RelationalAtom>> occurrencesGroup = new HashMap<FormulaVariable, List<RelationalAtom>>();
    for (FormulaVariable formulaVariable : dependency.getConclusion().getLocalVariables()) {
        if (!formulaVariable.getPremiseRelationalOccurrences().isEmpty()) {
            //Universal variable
            continue;
        }
        for (FormulaVariableOccurrence formulaVariableOccurrence : formulaVariable.getConclusionRelationalOccurrences()) {
            RelationalAtom relationalAtom = getRelationalAtom(dependency, formulaVariableOccurrence.getTableAlias());
            addOccurrence(formulaVariable, relationalAtom, occurrencesGroup);
        }
    }
    if (logger.isDebugEnabled()) logger.debug("Variable occurrences " + LunaticUtility.printMap(occurrencesGroup));
    for (List<RelationalAtom> joinAtoms : occurrencesGroup.values()) {
        for (int i = 0; i < joinAtoms.size() - 1; i++) {
            for (int j = i + 1; j < joinAtoms.size(); j++) {
                RelationalAtom atomi = joinAtoms.get(i);
                RelationalAtom atomj = joinAtoms.get(j);
                graph.addEdge(atomi, atomj);
            }
        }
    }
}
 
Example #12
Source File: FindConnectedTables.java    From Llunatic with GNU General Public License v3.0 6 votes vote down vote up
private UndirectedGraph<TableAlias, LabeledEdge> initJoinGraph(List<RelationalAtom> atoms, List<EqualityGroup> equalityGroups) {
    UndirectedGraph<TableAlias, LabeledEdge> joinGraph = new SimpleGraph<TableAlias, LabeledEdge>(LabeledEdge.class);
    if (logger.isDebugEnabled()) logger.debug("Build join graph for equality groups " + equalityGroups);
    Set<TableAlias> tableAliases = extracTableAliases(atoms);
    for (TableAlias tableAlias : tableAliases) {
        joinGraph.addVertex(tableAlias);
    }
    for (EqualityGroup equalityGroup : equalityGroups) {
        TableAlias leftTable = equalityGroup.getLeftTable();
        TableAlias rightTable = equalityGroup.getRightTable();
        if(leftTable.equals(rightTable)){
            continue;
        }
        joinGraph.addEdge(leftTable, rightTable, new LabeledEdge(leftTable.toString(), rightTable.toString(), equalityGroup.toString()));
    }
    return joinGraph;
}
 
Example #13
Source File: QueryGraphBuilder.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
public Graph<IModelEntity, Relationship> buildGraphFromPaths(Collection<GraphPath<IModelEntity, Relationship>> paths){
	logger.debug("IN");
	Assert.assertNotNull(paths, "The list of paths is null. Impossbile to create a graph");
	logger.debug("The number of paths is "+paths.size());

	UndirectedGraph<IModelEntity, Relationship> graph = new Multigraph<IModelEntity, Relationship>(Relationship.class);
	
	if(paths!=null){
		Iterator<GraphPath<IModelEntity, Relationship>> pathIter = paths.iterator();
		while(pathIter.hasNext()){
			GraphPath<IModelEntity, Relationship> path = pathIter.next();
			addPathToGraph(graph, path);
		}
	}

	logger.debug("OUT");
	return graph;
}
 
Example #14
Source File: AssociationManager.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Craete a toy graph based on String objects.
 *
 * @return a graph based on String objects.
 */
private static UndirectedGraph<String, DefaultEdge> createStringGraph() {

	UndirectedGraph<String, DefaultEdge> g = new SimpleGraph<String, DefaultEdge>(DefaultEdge.class);

	String v1 = "v1";
	String v2 = "v2";
	String v3 = "v3";
	String v4 = "v4";
	String v5 = "v5";

	// add the vertices
	g.addVertex(v1);
	g.addVertex(v2);
	g.addVertex(v3);
	g.addVertex(v4);
	g.addVertex(v5);

	// add edges to create a circuit
	g.addEdge(v1, v2);
	// g.addEdge(v2, v3);
	g.addEdge(v3, v4);
	// g.addEdge(v4, v1);

	return g;
}
 
Example #15
Source File: UcteNetworkExt.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
private void addEdgeForCouplerOrLowImpedanceLine(UcteNetwork network, UndirectedGraph<UcteNodeCode, Object> graph) {
    // ...nodes connected by a coupler or by a low impedance line
    for (UcteLine l : network.getLines()) {
        UcteNodeCode nodeCode1 = l.getId().getNodeCode1();
        UcteNodeCode nodeCode2 = l.getId().getNodeCode2();
        if (l.getStatus() == UcteElementStatus.BUSBAR_COUPLER_IN_OPERATION
                || l.getStatus() == UcteElementStatus.BUSBAR_COUPLER_OUT_OF_OPERATION) {
            graph.addEdge(nodeCode1, nodeCode2);
        } else {
            double z = Math.hypot(l.getResistance(), l.getReactance());
            if (z < lineMinZ) {
                graph.addEdge(nodeCode1, nodeCode2);
            }
        }
    }
}
 
Example #16
Source File: FindSymmetricAtoms.java    From Llunatic with GNU General Public License v3.0 6 votes vote down vote up
private SymmetricAtoms analyzeAtoms(SelfJoin selfJoin, UndirectedGraph<TableAlias, LabeledEdge> joinGraph) {
    Set<TableAlias> symmetricAtoms = new HashSet<TableAlias>();
    if (logger.isDebugEnabled()) logger.debug("Analyzing self join " + selfJoin);
    for (int i = 0; i < selfJoin.getAtoms().size() - 1; i++) {
        TableAlias aliasi = selfJoin.getAtoms().get(i);
        for (int j = i + 1; j < selfJoin.getAtoms().size(); j++) {
            TableAlias aliasj = selfJoin.getAtoms().get(j);
            UndirectedGraph<TableAlias, LabeledEdge> joinGraphForTableAliasi = buildSubGraph(aliasi, aliasj, joinGraph);
            UndirectedGraph<TableAlias, LabeledEdge> joinGraphForTableAliasj = buildSubGraph(aliasj, aliasi, joinGraph);
            Set<LabeledEdge> edgesi = joinGraphForTableAliasi.edgeSet();
            Set<LabeledEdge> edgesj = joinGraphForTableAliasj.edgeSet();
            if (containsAll(edgesi, edgesj) && containsAll(edgesj, edgesi)) {
                symmetricAtoms.addAll(joinGraphForTableAliasi.vertexSet());
            }
        }
    }
    return new SymmetricAtoms(symmetricAtoms, selfJoin);
}
 
Example #17
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 #18
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 #19
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 #20
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 #21
Source File: DualGaifmanGraph.java    From Llunatic with GNU General Public License v3.0 5 votes vote down vote up
private void addVertices(UndirectedGraph<RelationalAtom, DefaultEdge> graph, Dependency dependency) {
    for (IFormulaAtom atom : dependency.getConclusion().getAtoms()) {
        if (!(atom instanceof RelationalAtom)) {
            throw new IllegalArgumentException("Unable to normalize TGD " + dependency + ". Only relational atoms in conclusion are allowed");
        }
        graph.addVertex((RelationalAtom) atom);
    }
}
 
Example #22
Source File: FindSymmetricAtoms.java    From Llunatic with GNU General Public License v3.0 5 votes vote down vote up
private void findSymmetricAtoms(Dependency dependency) {
    if (logger.isDebugEnabled()) logger.debug("Finding symmetric atoms for dependency: " + dependency);
    if (hasInequalitiesOrBuiltIns(dependency) || hasNegation(dependency)) {
        return;
    }
    List<VariableEquivalenceClass> joinVariables = ChaseUtility.findJoinVariablesInTarget(dependency);
    if (logger.isDebugEnabled()) logger.debug("Join variables: " + joinVariables);
    UndirectedGraph<TableAlias, LabeledEdge> joinGraph = initJoinGraph(dependency, joinVariables);
    if (joinGraph == null) {
        return;
    }
    if (logger.isDebugEnabled()) logger.debug("Join graph: " + joinGraph.toString());
    List<SelfJoin> selfJoins = findSelfJoins(joinVariables);
    if (logger.isDebugEnabled()) logger.debug("Self joins: " + selfJoins);
    if (selfJoins.size() != 1) {
        return;
    }
    SelfJoin selfJoin = selfJoins.get(0);
    if (selfJoin.getAtoms().size() > 2) {
        return;
    }
    SymmetricAtoms symmetricAtoms = analyzeAtoms(selfJoin, joinGraph);
    if (logger.isDebugEnabled()) logger.debug("Symmetric atoms: " + symmetricAtoms);
    if (checkIfConclusionVariablesAreSymmetric(dependency, symmetricAtoms)) {
        dependency.setSymmetricAtoms(symmetricAtoms);
    }
}
 
Example #23
Source File: FindSymmetricAtoms.java    From Llunatic with GNU General Public License v3.0 5 votes vote down vote up
private UndirectedGraph<TableAlias, LabeledEdge> initJoinGraph(Dependency dependency, List<VariableEquivalenceClass> joinVariableClasses) {
    UndirectedGraph<TableAlias, LabeledEdge> joinGraph = new SimpleGraph<TableAlias, LabeledEdge>(LabeledEdge.class);
    if (logger.isDebugEnabled()) logger.debug("Find symmetric atoms for dependency " + dependency);
    if (logger.isDebugEnabled()) logger.debug("Join variables: " + joinVariableClasses);
    for (IFormulaAtom atom : dependency.getPremise().getAtoms()) {
        if (!(atom instanceof RelationalAtom)) {
            continue;
        }
        RelationalAtom relationalAtom = (RelationalAtom) atom;
        joinGraph.addVertex(relationalAtom.getTableAlias());
    }
    if (logger.isDebugEnabled()) logger.debug("Vertices: " + joinGraph.vertexSet());
    for (VariableEquivalenceClass joinVariableClass : joinVariableClasses) {
        List<FormulaVariableOccurrence> occurrences = joinVariableClass.getPremiseRelationalOccurrences();
        for (int i = 0; i < occurrences.size() - 1; i++) {
            FormulaVariableOccurrence occurrencei = occurrences.get(i);
            TableAlias aliasi = occurrencei.getAttributeRef().getTableAlias();
            for (int j = i + 1; j < occurrences.size(); j++) {
                FormulaVariableOccurrence occurrencej = occurrences.get(j);
                TableAlias aliasj = occurrencej.getAttributeRef().getTableAlias();
                String edgeLabel = buildEdgeLabel(occurrencei, occurrencej);
                try {
                    joinGraph.addEdge(aliasi, aliasj, new LabeledEdge(aliasi.toString(), aliasj.toString(), edgeLabel));
                } catch (IllegalArgumentException ex) {
                    // graph is cyclic
                    dependency.setJoinGraphIsCyclic(true);
                    return null;
                }
            }
        }
    }
    return joinGraph;
}
 
Example #24
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 #25
Source File: FindFormulaWithAdornments.java    From BART with MIT License 5 votes vote down vote up
public void findFormulaWithAdornments(IFormula formula, EGTask task) {
    if (!task.getConfiguration().isUseSymmetricOptimization()) {
        return;
    }
    if (DependencyUtility.hasNumericComparison(formula) || formula.hasNegations()) {
        return;
    }
    if (DependencyUtility.hasBuiltIns(formula)) {
        throw new UnsupportedOperationException("Unable to check symmetry with built-ins");
    }
    if (logger.isDebugEnabled()) logger.debug("Finding symmetric atoms in formula \n\t" + formula);
    if (logger.isDebugEnabled()) logger.debug("EquivalenceClasses: \n\t" + formula.getLocalVariableEquivalenceClasses());
    UndirectedGraph<FormulaGraphVertex, DefaultEdge> formulaGraph = initJoinGraph(formula);
    if (logger.isDebugEnabled()) logger.debug("Formula graph: \n\t" + formulaGraph.toString());
    List<VariablePair> variablePairs = findVariablePairs(formulaGraph);
    if (logger.isDebugEnabled()) logger.debug("Variable pairs:\n" + BartUtility.printCollection(variablePairs, "\t"));
    if (variablePairs.isEmpty()) {
        return;
    }
    List<FormulaVariable> anonymousVariables = findAnonymousVariables(formula, variablePairs);
    FormulaWithAdornments formulaWithAdornments = findFormulaWithAdornments(formulaGraph, variablePairs, anonymousVariables, formula);
    if (logger.isDebugEnabled()) logger.debug("Formula with adornments: \n\t" + formulaWithAdornments);
    if (formulaWithAdornments == null) {
        return;
    }
    formula.setFormulaWithAdornments(formulaWithAdornments);
}
 
Example #26
Source File: ComputeInstanceSimilarityBlock.java    From BART with MIT License 5 votes vote down vote up
private void saveGraph(UndirectedGraph<TupleWithTable, DefaultEdge> instancesGraph) {
        JGraphXAdapter<TupleWithTable, DefaultEdge> jgxAdapterContext = new JGraphXAdapter<TupleWithTable, DefaultEdge>(instancesGraph);
        jgxAdapterContext.getStylesheet().getDefaultEdgeStyle().put(mxConstants.STYLE_NOLABEL, "1");
        jgxAdapterContext.getStylesheet().getDefaultEdgeStyle().put(mxConstants.STYLE_ENDARROW, "0");
        jgxAdapterContext.setCellsEditable(false);
        jgxAdapterContext.setCellsMovable(false);
        jgxAdapterContext.setEdgeLabelsMovable(false);
        jgxAdapterContext.setCellsDeletable(false);
        jgxAdapterContext.setCellsDisconnectable(false);
        jgxAdapterContext.setCellsResizable(false);
        jgxAdapterContext.setCellsBendable(false);
        JFrame frame = new JFrame();
        mxGraphComponent mxGraphComponent = new mxGraphComponent(jgxAdapterContext);
        frame.getContentPane().add(mxGraphComponent, BorderLayout.CENTER);
        mxHierarchicalLayout layout = new mxHierarchicalLayout(jgxAdapterContext);
        layout.execute(jgxAdapterContext.getDefaultParent());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("Graph");
        frame.pack();
        frame.setLocationRelativeTo(null);
//        frame.setVisible(true);
//        try {
//            while (true) {
//                Thread.sleep(500);
//            }
//        } catch (InterruptedException ex) {
//            java.util.logging.Logger.getLogger(ComputeInstanceSimilarityBlock.class.getName()).log(Level.SEVERE, null, ex);
//        }
        try {
            BufferedImage image = mxCellRenderer.createBufferedImage(jgxAdapterContext, null, 1, Color.WHITE, true, null);
            File file = new File("/Users/Shared/Temp/bart/similarity/instances-graph.png");
            file.getParentFile().mkdirs();
            ImageIO.write(image, "PNG", file);
        } catch (IOException ex) {
            logger.error("Unable to save graph image: " + ex.getLocalizedMessage());
        }
    }
 
Example #27
Source File: UcteNetworkExt.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
private void addEdgeBetweenSameGeographicalSpotNodes(UcteNetwork network, UndirectedGraph<UcteNodeCode, Object> graph) {
    // ...nodes with same geographical spot
    Multimap<String, UcteNode> nodesByGeographicalSpot = Multimaps.index(network.getNodes(), node -> node.getCode().getUcteCountryCode() + node.getCode().getGeographicalSpot());
    for (Map.Entry<String, Collection<UcteNode>> entry : nodesByGeographicalSpot.asMap().entrySet()) {
        for (UcteNode n1 : entry.getValue()) {
            for (UcteNode n2 : entry.getValue()) {
                if (n1 != n2) {
                    graph.addEdge(n1.getCode(), n2.getCode());
                }
            }
        }
    }
}
 
Example #28
Source File: GraphUtilities.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Get the map of the relation between the node vertex and the other nodes. This map is useful for the role analysis. If a node has more than one role with
 * the vertex node in the map the linked list has one relation for each role
 *
 * @param G
 * @param vertex
 * @return
 */
public static Map<IModelEntity, List<Relationship>> getEdgeMap(Graph G, IModelEntity vertex) {

	Map<IModelEntity, List<Relationship>> vertexRelationsMap = new HashMap<IModelEntity, List<Relationship>>();

	Set<Relationship> vertexConnection = G.edgesOf(vertex);
	if (vertexConnection != null) {
		Iterator<Relationship> vertexConnectionIter = vertexConnection.iterator();

		while (vertexConnectionIter.hasNext()) {
			Relationship relationship = vertexConnectionIter.next();

			IModelEntity otherEntity = relationship.getTargetEntity();// the entity not equal to vertex

			if (vertex.equals(otherEntity) && (G instanceof UndirectedGraph)) {
				otherEntity = relationship.getSourceEntity();
			}
			if (!vertex.equals(otherEntity)) {
				List<Relationship> relationsWithOther = vertexRelationsMap.get(otherEntity);

				if (relationsWithOther == null) {
					relationsWithOther = new ArrayList<Relationship>();
					vertexRelationsMap.put(otherEntity, relationsWithOther);
				}
				relationsWithOther.add(relationship);
			}

		}
	}
	return vertexRelationsMap;
}
 
Example #29
Source File: AssociationAnalyzerTest.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testProcessOneAssociation() {
	AssociationAnalyzer analyzer = new AssociationAnalyzer(oneAssociationMap.values());
	analyzer.process();
	Map<String, Map<String, String>> datasetToAssociationToColumnsMap = analyzer.getDatasetToAssociationToColumnMap();
	UndirectedGraph<String, LabeledEdge<String>> graph = analyzer.getGraph();

	assertTrue(datasetToAssociationToColumnsMap.containsKey(X));
	assertTrue(datasetToAssociationToColumnsMap.containsKey(Y));

	Map<String, String> associationToColumnsMap = null;

	associationToColumnsMap = datasetToAssociationToColumnsMap.get(X);
	assertTrue(associationToColumnsMap.containsKey(A1));
	assertEquals(buildColumnLabel(X, A1), associationToColumnsMap.get(A1));

	associationToColumnsMap = datasetToAssociationToColumnsMap.get(Y);
	assertTrue(associationToColumnsMap.containsKey(A1));
	assertEquals(buildColumnLabel(Y, A1), associationToColumnsMap.get(A1));

	assertEquals(2, graph.vertexSet().size());
	assertTrue(graph.containsVertex(X));
	assertTrue(graph.containsVertex(Y));

	assertEquals(1, graph.edgeSet().size());
	assertTrue(graph.containsEdge(new LabeledEdge<String>(Y, X, A1)));
}
 
Example #30
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);
}