Java Code Examples for org.jgrapht.UndirectedGraph#addVertex()

The following examples show how to use org.jgrapht.UndirectedGraph#addVertex() . 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: 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 3
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 4
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 5
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 6
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 7
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 8
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 9
Source File: ComputeInstanceSimilarityBlock.java    From BART with MIT License 5 votes vote down vote up
private void addInstance(List<TupleWithTable> tuples, UndirectedGraph<TupleWithTable, DefaultEdge> instancesGraph) {
    Map<IValue, Set<TupleWithTable>> placeholdersInverseMap = new HashMap<>();
    for (TupleWithTable tuple : tuples) {
        instancesGraph.addVertex(tuple);
        addPlaceholders(tuple, placeholdersInverseMap);
    }
    for (IValue placeholder : placeholdersInverseMap.keySet()) {
        Set<TupleWithTable> tuplesWithPlaceholder = placeholdersInverseMap.get(placeholder);
        addEdgesBtwTuples(tuplesWithPlaceholder, instancesGraph);
    }
}
 
Example 10
Source File: UcteNetworkExt.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
private UndirectedGraph<UcteNodeCode, Object> createSubstationGraph(UcteNetwork network) {
    UndirectedGraph<UcteNodeCode, Object> graph = new Pseudograph<>(Object.class);
    for (UcteNode node : network.getNodes()) {
        graph.addVertex(node.getCode());
    }

    // in the same substation...
    addEdgeBetweenSameGeographicalSpotNodes(network, graph);
    addEdgeBetweenTransformers(network, graph);
    addEdgeForCouplerOrLowImpedanceLine(network, graph);

    return graph;
}
 
Example 11
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 12
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 13
Source File: FindFormulaWithAdornments.java    From BART with MIT License 4 votes vote down vote up
private void createConstantVertex(String value, FormulaGraphVertex vertexToConnect, UndirectedGraph<FormulaGraphVertex, DefaultEdge> graph) {
    FormulaGraphVertex constantVertex = new FormulaGraphVertex(value);
    graph.addVertex(constantVertex);
    graph.addEdge(vertexToConnect, constantVertex);
}
 
Example 14
Source File: ScanningAlgorithm.java    From CFGScanDroid with GNU General Public License v2.0 4 votes vote down vote up
public static boolean bipartiteMatchingVector(DoubleMatrix2D candidateList, DoubleMatrix2D signatureNodeVector, DoubleMatrix2D functionNodeVector, int[] signatureDepths, int[] functionDepths) {
	UndirectedGraph<String, DefaultEdge> g = new SimpleGraph<String, DefaultEdge>(DefaultEdge.class);

	IntArrayList signatureNonZeros = new IntArrayList();
	IntArrayList functionNonZeros = new IntArrayList();
	IntArrayList unusedInt = new IntArrayList();
	DoubleArrayList unusedDouble = new DoubleArrayList();

	// get set column indices for signature vector and function vector
	signatureNodeVector.getNonZeros(unusedInt, signatureNonZeros, unusedDouble);
	functionNodeVector.getNonZeros(unusedInt, functionNonZeros, unusedDouble);
	
	List<String> signatureIdcs = new ArrayList<String>();
	List<String> functionIdcs = new ArrayList<String>();
	int signatureNodeCount = 0;
	// add signature nodes graph
	for(int i=0; i<signatureNonZeros.size(); ++i) {
		int signatureIdx = signatureNonZeros.get(i);
		if(signatureDepths[signatureIdx] != -1) {
			signatureIdcs.add("s"+signatureIdx);
			g.addVertex("s"+signatureIdx);
			signatureNodeCount++;
		}
	}

	// add function nodes graph
	for(int j=0; j<functionNonZeros.size(); ++j) {
		int functionIdx = functionNonZeros.get(j);
		if(functionDepths[functionIdx] != -1) {
			functionIdcs.add("f"+functionNonZeros.get(j));
			g.addVertex("f"+functionNonZeros.get(j));
		}
	}

	// add edges
	for(int i=0; i<signatureNonZeros.size(); ++i) {
		for(int j=0; j<functionNonZeros.size(); ++j) {
			if(candidateList.get(signatureNonZeros.get(i), functionNonZeros.get(j)) != 0) {
				g.addEdge("s"+signatureNonZeros.get(i), "f"+functionNonZeros.get(j));
			}
		}
	}

	// define sets
	Set<String> p1 = new HashSet<String>(signatureIdcs);
       Set<String> p2 = new HashSet<String>(functionIdcs);

       // bipartite matching!
	HopcroftKarpBipartiteMatching<String, DefaultEdge> alg = 
		new HopcroftKarpBipartiteMatching<String, DefaultEdge>(g, p1, p2);

	Set<DefaultEdge> match = alg.getMatching();
	// sat || unsat
	if(match.size() == signatureNodeCount) {
		return true;
	} else { 
		return false;
	}

}
 
Example 15
Source File: ScanningAlgorithm.java    From CFGScanDroid with GNU General Public License v2.0 4 votes vote down vote up
public static boolean bipartiteMatchingFull(SparseDoubleMatrix2D candidateList, int[] signatureDepths, int[] functionDepths, int depth) {
	UndirectedGraph<String, DefaultEdge> g = new SimpleGraph<String, DefaultEdge>(DefaultEdge.class);
	
	List<String> signatureIdcs = new ArrayList<String>();
	for(int i=0; i<signatureDepths.length; ++i) {
		signatureIdcs.add("s"+i);
		g.addVertex("s"+i);
	}

	List<String> functionIdcs = new ArrayList<String>();
	for(int j=0; j<functionDepths.length; ++j) {
		functionIdcs.add("f"+j);
		g.addVertex("f"+j);
	}

	for(int i=0; i<signatureDepths.length; ++i) {
		DoubleMatrix1D row = candidateList.viewRow(i);

		for(int j=0; j<row.size(); ++j) {
			if(row.get(j) != 0) {
				g.addEdge("s"+i, "f"+j);
			}
		}
	}

	Set<String> p1 = new HashSet<String>(signatureIdcs);
       Set<String> p2 = new HashSet<String>(functionIdcs);

	HopcroftKarpBipartiteMatching<String, DefaultEdge> alg = 
		new HopcroftKarpBipartiteMatching<String, DefaultEdge>(g, p1, p2);

	Set<DefaultEdge> match = alg.getMatching();

	//System.out.println(g.toString());
	//System.out.println(match);
	if(match.size() == signatureDepths.length)
		return true;
	else
		return false;

}
 
Example 16
Source File: ScanningAlgorithm.java    From CFGScanDroid with GNU General Public License v2.0 4 votes vote down vote up
public static boolean bipartiteMatchingDepth(SparseDoubleMatrix2D candidateList, int[] signatureDepths, int[] functionDepths, int depth) {
	UndirectedGraph<String, DefaultEdge> g = new SimpleGraph<String, DefaultEdge>(DefaultEdge.class);
	List<String> signatureIdcs = new ArrayList<String>();
	int signatureNodesAtDepth = 0;
	for(int i=0; i<signatureDepths.length; ++i) {
		if(signatureDepths[i] == depth) {
			signatureIdcs.add("s"+i);
			g.addVertex("s"+i);
			//System.out.println("bpm:\ts"+i);
			signatureNodesAtDepth++;
		}
	}

	List<String> functionIdcs = new ArrayList<String>();
	for(int j=0; j<functionDepths.length; ++j) {
		if(functionDepths[j] == depth) {
			functionIdcs.add("f"+j);
			g.addVertex("f"+j);
			//System.out.println("bpm:\tf"+j);
		}
	}

	for(int i=0; i<signatureDepths.length; ++i) {
		if(signatureDepths[i] == depth) {
			DoubleMatrix1D row = candidateList.viewRow(i);

			for(int j=0; j<row.size(); ++j) {
				if(row.get(j) == 1.0 && functionDepths[j] == depth) {
					g.addEdge("s"+i, "f"+j);
				}
			}
		}
	}

	Set<String> p1 = new HashSet<String>(signatureIdcs);
       Set<String> p2 = new HashSet<String>(functionIdcs);

	HopcroftKarpBipartiteMatching<String, DefaultEdge> alg = 
		new HopcroftKarpBipartiteMatching<String, DefaultEdge>(g, p1, p2);

	Set<DefaultEdge> match = alg.getMatching();

	// System.out.println(g.toString());
	// System.out.println(match);
	if(match.size() == signatureNodesAtDepth)
		return true;
	else
		return false;

}
 
Example 17
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");
        }
    }