org.jgrapht.graph.SimpleGraph Java Examples

The following examples show how to use org.jgrapht.graph.SimpleGraph. 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: BzHTileModifier.java    From Rails with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void modifyMapGraph(NetworkGraph mapGraph) {
    SimpleGraph<NetworkVertex, NetworkEdge> graph = mapGraph.getGraph();

    // 1. check Phase
    // this is a violation of the assumption that the track network only dependents on the map configuration
    // but not on other things (like phases)
    int phaseIndex = root.getPhaseManager().getCurrentPhase().getIndex();
    if (phaseIndex >= 3 ) {
        log.debug("Boznia-Herzegovina active, index of phase = {}", phaseIndex);
        return;
    }

    // 2. retrieve BzH vertices ...
    String[] bzhHexes = {"L16","L18","L20","L22","M17","M19","M21","N18","N20"};
    for(String bzhHex:bzhHexes){
        bzhMapHexes.add(root.getMapManager().getHex(bzhHex));
    }
    Set<NetworkVertex> bzhVertices = NetworkVertex.getVerticesByHexes(graph.vertexSet(), bzhMapHexes);

    // 3 ... and remove them from the graph
    graph.removeAllVertices(bzhVertices);
    log.debug("Bosnia Herzegovina inactive, index of phase = {}", phaseIndex);

}
 
Example #2
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 #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: 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 #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: NetworkVertex.java    From Rails with GNU General Public License v2.0 6 votes vote down vote up
/**
 * replaces one vertex by another for a network graph
 * copies all edges
 */
public static boolean replaceVertex(SimpleGraph<NetworkVertex, NetworkEdge> graph,
        NetworkVertex oldVertex, NetworkVertex newVertex) {
    // add new vertex
    graph.addVertex(newVertex);
    // replace old edges
    Set<NetworkEdge> oldEdges = graph.edgesOf(oldVertex);
    for (NetworkEdge oldEdge:oldEdges) {
        NetworkEdge newEdge = NetworkEdge.replaceVertex(oldEdge, oldVertex, newVertex);
        if (newEdge.getSource() == newVertex) {
            graph.addEdge(newVertex, newEdge.getTarget(), newEdge);
        } else {
            graph.addEdge(newEdge.getSource(), newVertex, newEdge);
        }
    }
    // remove old vertex
    return graph.removeVertex(oldVertex);
}
 
Example #7
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 #8
Source File: ElsasModifier.java    From Rails with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void modifyMapGraph(NetworkGraph mapGraph) {
    SimpleGraph<NetworkVertex, NetworkEdge> graph = mapGraph.getGraph();

    // Check if (one of the  elsasHex has zero value ...
    MapHex hex = root.getMapManager().getHex("M5");
    if (hex.getCurrentValueForPhase(root.getPhaseManager().getCurrentPhase()) == 0) {
        // .. then remove both
        Set<NetworkVertex> vertices = NetworkVertex.getVerticesByHex(graph.vertexSet(), hex);
        graph.removeAllVertices(vertices);
        hex = root.getMapManager().getHex("N4");
        vertices = NetworkVertex.getVerticesByHex(graph.vertexSet(), hex);
        graph.removeAllVertices(vertices);
        log.debug("Elsas is inactive");
    }
}
 
Example #9
Source File: BirminghamTileModifier.java    From Rails with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void modifyMapGraph(NetworkGraph mapGraph) {

    // TODO (Rails 2.0): Add root reference to modifiers
    SimpleGraph<NetworkVertex, NetworkEdge> graph = mapGraph.getGraph();

    // 1. check Phase
    // this is a violation of the assumption that the track network only dependents on the map configuration
    // but not on other things (like phases)
    int phaseIndex = root.getPhaseManager().getCurrentPhase().getIndex();
    if (phaseIndex >= 2 ) {
        log.debug("Birmingham active, index of phase = {}", phaseIndex);
        return;
    }

    // 2. retrieve Birmingham vertices ...
    MapHex birmingHex = root.getMapManager().getHex("J12");
    Set<NetworkVertex> birmingVertices = NetworkVertex.getVerticesByHex(graph.vertexSet(), birmingHex);

    // 3 ... and remove them from the graph
    graph.removeAllVertices(birmingVertices);
    log.debug("Birmingham inactive, index of phase = {}", phaseIndex);
}
 
Example #10
Source File: SymmetryTools.java    From biojava with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Converts a self alignment into a directed jGraphT of aligned residues,
 * where each vertex is a residue and each edge means the equivalence
 * between the two residues in the self-alignment.
 *
 * @param selfAlignment
 *            AFPChain
 *
 * @return alignment Graph
 */
public static Graph<Integer, DefaultEdge> buildSymmetryGraph(
		AFPChain selfAlignment) {

	Graph<Integer, DefaultEdge> graph = new SimpleGraph<Integer, DefaultEdge>(
			DefaultEdge.class);

	for (int i = 0; i < selfAlignment.getOptAln().length; i++) {
		for (int j = 0; j < selfAlignment.getOptAln()[i][0].length; j++) {
			Integer res1 = selfAlignment.getOptAln()[i][0][j];
			Integer res2 = selfAlignment.getOptAln()[i][1][j];
			graph.addVertex(res1);
			graph.addVertex(res2);
			graph.addEdge(res1, res2);
		}
	}
	return graph;
}
 
Example #11
Source File: ItalyTileModifier.java    From Rails with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void modifyMapGraph(NetworkGraph mapGraph) {

    SimpleGraph<NetworkVertex, NetworkEdge> graph = mapGraph.getGraph();
    List<MapHex> italyMapHexes = new ArrayList<MapHex> ();
    // 1. check Phase
    // this is a violation of the assumption that the track network only dependents on the map configuration
    // but not on other things (like phases)
    int phaseIndex = root.getPhaseManager().getCurrentPhase().getIndex();
    if (phaseIndex < 4 ) {
        log.debug("Italy active, index of phase = {}", phaseIndex);
        return;
    }

    // 2. retrieve Italy vertices ...
    String [] italyHexes = {"K1","K3","K7","K9","L2","L4","L6","L8","M3","M5","M7"};
     for (String italyHex:italyHexes){
         italyMapHexes.add(root.getMapManager().getHex(italyHex));
     }
    Set<NetworkVertex> italyVertices = NetworkVertex.getVerticesByHexes(graph.vertexSet(), italyMapHexes);

    // 3 ... and remove them from the graph
    graph.removeAllVertices(italyVertices);
    log.debug("Italy inactive, index of phase = {}", phaseIndex);

}
 
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: SubtourSeparatorTest.java    From jorlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Test 2 - Undirected, incomplete graph without a subtour.
 */
public void testUndirectedGraphWithoutSubtour(){
	//Define a new Undirected Graph. For simplicity we'll use a simple, unweighted graph, but in reality this class is mainly used
	//in combination with weighted graphs for TSP problems.
	Graph<Integer, DefaultEdge> undirectedGraph=new SimpleGraph<Integer, DefaultEdge>(DefaultEdge.class);
	Graphs.addAllVertices(undirectedGraph, Arrays.asList(1,2,3,4,5,6));
	undirectedGraph.addEdge(1, 2);
	undirectedGraph.addEdge(2, 3);
	undirectedGraph.addEdge(3, 4);
	undirectedGraph.addEdge(4, 1);
	undirectedGraph.addEdge(1, 5);
	undirectedGraph.addEdge(4, 5);
	undirectedGraph.addEdge(5, 6);
	undirectedGraph.addEdge(2, 6);
	undirectedGraph.addEdge(3, 6);
	
	//Define the x_e values for every edge e\in E
	Map<DefaultEdge, Double> edgeValueMap=new HashMap<DefaultEdge, Double>();
	edgeValueMap.put(undirectedGraph.getEdge(1,2), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(2,3), 0.0);
	edgeValueMap.put(undirectedGraph.getEdge(3,4), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(4,1), 0.0);
	edgeValueMap.put(undirectedGraph.getEdge(1,5), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(4,5), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(5,6), 0.0);
	edgeValueMap.put(undirectedGraph.getEdge(2,6), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(3,6), 1.0);
	
	//Invoke the separator
	SubtourSeparator<Integer, DefaultEdge> separator=new SubtourSeparator<Integer, DefaultEdge>(undirectedGraph);
	separator.separateSubtour(edgeValueMap);
	
	assertFalse(separator.hasSubtour());
	assertEquals(2, separator.getCutValue(), PRECISION);
}
 
Example #14
Source File: SubtourSeparatorTest.java    From jorlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Test 1 - Undirected, incomplete graph with a subtour.
 */
public void testUndirectedGraphWithSubtour(){
	//Define a new Undirected Graph. For simplicity we'll use a simple, unweighted graph, but in reality this class is mainly used
	//in combination with weighted graphs for TSP problems.
	Graph<Integer, DefaultEdge> undirectedGraph=new SimpleGraph<Integer, DefaultEdge>(DefaultEdge.class);
	Graphs.addAllVertices(undirectedGraph, Arrays.asList(1,2,3,4,5,6));
	undirectedGraph.addEdge(1, 2);
	undirectedGraph.addEdge(2, 3);
	undirectedGraph.addEdge(3, 4);
	undirectedGraph.addEdge(4, 1);
	undirectedGraph.addEdge(1, 5);
	undirectedGraph.addEdge(4, 5);
	undirectedGraph.addEdge(5, 6);
	undirectedGraph.addEdge(2, 6);
	undirectedGraph.addEdge(3, 6);
	
	//Define the x_e values for every edge e\in E
	Map<DefaultEdge, Double> edgeValueMap=new HashMap<DefaultEdge, Double>();
	edgeValueMap.put(undirectedGraph.getEdge(1,2), 0.0);
	edgeValueMap.put(undirectedGraph.getEdge(2,3), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(3,4), 0.0);
	edgeValueMap.put(undirectedGraph.getEdge(4,1), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(1,5), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(4,5), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(5,6), 0.0);
	edgeValueMap.put(undirectedGraph.getEdge(2,6), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(3,6), 1.0);
	
	//Invoke the separator
	SubtourSeparator<Integer, DefaultEdge> separator=new SubtourSeparator<Integer, DefaultEdge>(undirectedGraph);
	separator.separateSubtour(edgeValueMap);
	
	assertTrue(separator.hasSubtour());
	assertEquals(0, separator.getCutValue(), PRECISION);
	assertEquals(new HashSet<Integer>(Arrays.asList(2,3,6)), separator.getCutSet());
}
 
Example #15
Source File: SubtourSeparatorDemo.java    From jorlib with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Example on undirected graph
 */
public static void example1(){
	//Define a new Undirected Graph. For simplicity we'll use a simple, unweighted graph, but in reality this class is mainly used
	//in combination with weighted graphs for TSP problems.
	Graph<Integer, DefaultEdge> undirectedGraph=new SimpleGraph<Integer, DefaultEdge>(DefaultEdge.class);
	Graphs.addAllVertices(undirectedGraph, Arrays.asList(1,2,3,4,5,6));
	undirectedGraph.addEdge(1, 2);
	undirectedGraph.addEdge(2, 3);
	undirectedGraph.addEdge(3, 4);
	undirectedGraph.addEdge(4, 1);
	undirectedGraph.addEdge(1, 5);
	undirectedGraph.addEdge(4, 5);
	undirectedGraph.addEdge(5, 6);
	undirectedGraph.addEdge(2, 6);
	undirectedGraph.addEdge(3, 6);
	
	//Define the x_e values for every edge e\in E
	Map<DefaultEdge, Double> edgeValueMap=new HashMap<DefaultEdge, Double>();
	edgeValueMap.put(undirectedGraph.getEdge(1,2), 0.0);
	edgeValueMap.put(undirectedGraph.getEdge(2,3), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(3,4), 0.0);
	edgeValueMap.put(undirectedGraph.getEdge(4,1), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(1,5), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(4,5), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(5,6), 0.0);
	edgeValueMap.put(undirectedGraph.getEdge(2,6), 1.0);
	edgeValueMap.put(undirectedGraph.getEdge(3,6), 1.0);
	
	//Invoke the separator
	SubtourSeparator<Integer, DefaultEdge> separator=new SubtourSeparator<Integer, DefaultEdge>(undirectedGraph);
	separator.separateSubtour(edgeValueMap);
	
	System.out.println("Has found a violated subtour: "+separator.hasSubtour());
	System.out.println("Cut value: "+separator.getCutValue());
	System.out.println("Cut set: "+separator.getCutSet());
	//The returned cut set is: {2,3,6}. This leads to the cut: \sum_{e\in \delta{2,3,6}} x_e >=2
}
 
Example #16
Source File: ComputeInstanceSimilarityBlock.java    From BART with MIT License 5 votes vote down vote up
@Override
    public InstanceMatchTask compare(IDatabase leftDb, IDatabase rightDb) {
        if (!ComparisonConfiguration.isInjective() || !ComparisonConfiguration.isFunctional()) {
            throw new IllegalArgumentException("Only fully-injective mappings are supported");
        }
        long start = System.currentTimeMillis();
        InstanceMatchTask instanceMatch = new InstanceMatchTask(this.getClass().getSimpleName(), leftDb, rightDb);
        List<TupleWithTable> sourceTuples = SpeedyUtility.extractAllTuplesFromDatabase(leftDb);
        List<TupleWithTable> destinationTuples = SpeedyUtility.extractAllTuplesFromDatabase(rightDb);
        ComparisonStats.getInstance().addStat(ComparisonStats.PROCESS_INSTANCE_TIME, System.currentTimeMillis() - start);
        UndirectedGraph<TupleWithTable, DefaultEdge> instancesGraph = new SimpleGraph<TupleWithTable, DefaultEdge>(DefaultEdge.class);
        start = System.currentTimeMillis();
        addInstance(sourceTuples, instancesGraph);
        addInstance(destinationTuples, instancesGraph);
        ComparisonStats.getInstance().addStat(ComparisonStats.BUILD_INSTANCES_GRAPH, System.currentTimeMillis() - start);
        CompatibilityMap compatibilityMap = compatibleTupleFinder.find(sourceTuples, destinationTuples);
        TupleMatches tupleMatches = ComparisonUtility.findTupleMatches(destinationTuples, compatibilityMap);
        start = System.currentTimeMillis();
        addTupleMatches(tupleMatches, instancesGraph);
        ComparisonStats.getInstance().addStat(ComparisonStats.BUILD_INSTANCES_GRAPH, System.currentTimeMillis() - start);
        findCompatibileTuples(sourceTuples, destinationTuples, instancesGraph);
        findCompatibileTuples(destinationTuples, sourceTuples, instancesGraph);
        saveGraph(instancesGraph);
//        TupleMatches tupleMatches = findTupleMatches(sourceTuples, destinationTuples);
//        ComparisonUtility.sortTupleMatches(tupleMatches);
//        if (logger.isTraceEnabled()) logger.trace(tupleMatches.toString());
//        TupleMapping bestTupleMapping = bestTupleMappingFinder.findBestTupleMapping(sourceTuples, destinationTuples, tupleMatches);
//        nonMatchingTuplesFinder.find(sourceTuples, destinationTuples, bestTupleMapping);
//        instanceMatch.setTupleMapping(bestTupleMapping);
        return instanceMatch;
    }
 
Example #17
Source File: AbstractGtReader.java    From JedAIToolkit with Apache License 2.0 5 votes vote down vote up
public AbstractGtReader (String filePath) {
    super(filePath);
    idDuplicates = new HashSet<>();
    duplicatesGraph = new SimpleGraph(DefaultEdge.class);
    urlToEntityId1 = new TObjectIntHashMap();
    urlToEntityId2 = new TObjectIntHashMap();
}
 
Example #18
Source File: QuatSymmetryDetector.java    From biojava with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static  Graph<Integer, DefaultEdge> initContactGraph(List<SubunitCluster> clusters){

		Graph<Integer, DefaultEdge> graph = new SimpleGraph<>(DefaultEdge.class);

		// extract Ca coords from every subunit of every cluster.
		// all subunit coords are used for contact evaluation,
		// not only the aligned equivalent residues
		List <Point3d[]> clusterSubunitCoords =
				clusters.stream().
					flatMap(c -> c.getSubunits().stream()).
						map(r -> Calc.atomsToPoints(r.getRepresentativeAtoms())).
						collect(Collectors.toList());

		for (int i = 0; i < clusterSubunitCoords.size(); i++) {
			graph.addVertex(i);
		}

		// pre-compute bounding boxes
		List<BoundingBox> boundingBoxes = new ArrayList<>();
		clusterSubunitCoords.forEach(c -> boundingBoxes.add(new BoundingBox(c)));

		for (int i = 0; i < clusterSubunitCoords.size() - 1; i++) {
			Point3d[] coords1 = clusterSubunitCoords.get(i);
			BoundingBox bb1 = boundingBoxes.get(i);

			for (int j = i + 1; j < clusterSubunitCoords.size(); j++) {
				Point3d[] coords2 = clusterSubunitCoords.get(j);
				BoundingBox bb2 = boundingBoxes.get(j);
				Grid grid = new Grid(CONTACT_GRAPH_DISTANCE_CUTOFF);
				grid.addCoords(coords1, bb1, coords2, bb2);

				if (grid.getIndicesContacts().size() >= CONTACT_GRAPH_MIN_CONTACTS) {
					graph.addEdge(i, j);
				}
			}
		}
		return graph;
	}
 
Example #19
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 #20
Source File: GlyphCluster.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Extract a subgraph limited to the provided collection of glyphs.
 *
 * @param collection the provided collection of glyphs
 * @param graph      the global graph to extract from
 * @param checkEdges true if glyph edges may point outside the provided set.
 * @return the graph limited to glyph set and related edges
 */
public static SimpleGraph<Glyph, GlyphLink> getSubGraph (Collection<Glyph> collection,
                                                         SimpleGraph<Glyph, GlyphLink> graph,
                                                         boolean checkEdges)
{
    // Which edges should be extracted for this set?
    Set<GlyphLink> setEdges = new LinkedHashSet<>();
    for (Glyph glyph : collection) {
        Set<GlyphLink> glyphEdges = graph.edgesOf(glyph);

        if (!checkEdges) {
            setEdges.addAll(glyphEdges); // Take all edges
        } else {
            // Keep only the edges that link within the set
            for (GlyphLink link : glyphEdges) {
                Glyph opposite = Graphs.getOppositeVertex(graph, link, glyph);

                if (collection.contains(opposite)) {
                    setEdges.add(link);
                }
            }
        }
    }
    SimpleGraph<Glyph, GlyphLink> subGraph = new SimpleGraph<>(GlyphLink.class);
    Graphs.addAllVertices(subGraph, collection);
    Graphs.addAllEdges(subGraph, graph, setEdges);
    return subGraph;
}
 
Example #21
Source File: KeyExtractor.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
MultipleAdapter (KeyRoi roi,
                 List<KeyPeak> peaks,
                 SimpleGraph<Glyph, GlyphLink> graph,
                 Set<Shape> targetShapes,
                 double minGrade)
{
    super(graph, peaks, targetShapes, minGrade);
    this.roi = roi;
}
 
Example #22
Source File: F21Modifier.java    From Rails with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void modifyMapGraph(NetworkGraph mapGraph) {
    SimpleGraph<NetworkVertex, NetworkEdge> graph = mapGraph.getGraph();

    // Check if F21 has zero value
    MapHex hex = root.getMapManager().getHex("F21");
    if (hex.getCurrentValueForPhase(root.getPhaseManager().getCurrentPhase()) == 0) {
        // ... then remove those vertices
        Set<NetworkVertex> vertices = NetworkVertex.getVerticesByHex(graph.vertexSet(), hex);
        graph.removeAllVertices(vertices);
    }
}
 
Example #23
Source File: SpecialRight.java    From Rails with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void modifyRouteGraph(NetworkGraph routeGraph, PublicCompany company) {
    // 1. check operating company if it has the right then it is excluded from the removal
    // TODO: Only use one right for all companies instead of one per company
    if (this.getOriginalCompany() != company || company.hasRight(this)) return;

    SimpleGraph<NetworkVertex, NetworkEdge> graph = routeGraph.getGraph();

    // 2. find vertices to hex and remove the station
    Set<NetworkVertex> verticesToRemove = NetworkVertex.getVerticesByHexes(graph.vertexSet(), locations);
    // 3 ... and remove them from the graph
    graph.removeAllVertices(verticesToRemove);
}
 
Example #24
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 #25
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 #26
Source File: SymbolsBuilder.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Find all possible interpretations of symbols composed from available system glyphs.
 * <p>
 * <b>Synopsis:</b>
 *
 * <pre>
 * - retrieveFineBoxes()                            // Retrieve areas around small chords
 * - getSymbolsGlyphs()                             // Retrieve all glyphs usable for symbols
 * - buildLinks()                                   // Build graph with distances
 * - processClusters():                             // Group connected glyphs into clusters
 *    + FOREACH cluster of connected glyphs:
 *       + cluster.decompose()                      // Decompose cluster into all subsets
 *       + FOREACH subset process(subset):
 *          - build compound glyph                  // Build one compound glyph per subset
 *          - evaluateGlyph(compound)               // Run shape classifier on compound
 *          - FOREACH acceptable evaluation
 *             + symbolFactory.create(eval, glyph)  // Create inter(s) related to evaluation
 * </pre>
 *
 * @param optionalsMap the optional (weak) glyphs per system
 */
public void buildSymbols (Map<SystemInfo, List<Glyph>> optionalsMap)
{
    final StopWatch watch = new StopWatch("buildSymbols system #" + system.getId());
    logger.debug("System#{} buildSymbols", system.getId());

    // Identify areas for fine glyphs
    watch.start("retrieveFineBoxes");
    retrieveFineBoxes();

    // Retrieve all candidate glyphs
    watch.start("getSymbolsGlyphs");

    final List<Glyph> glyphs = getSymbolsGlyphs(optionalsMap);

    // Formalize glyphs relationships in a system-level graph
    watch.start("buildLinks");

    final SimpleGraph<Glyph, GlyphLink> systemGraph = Glyphs.buildLinks(glyphs, params.maxGap);

    // Process all sets of connected glyphs
    watch.start("processClusters");
    processClusters(systemGraph);

    if (constants.printWatch.isSet()) {
        watch.print();
    }
}
 
Example #27
Source File: KeyExtractor.java    From audiveris with GNU Affero General Public License v3.0 5 votes vote down vote up
AbstractKeyAdapter (SimpleGraph<Glyph, GlyphLink> graph,
                    List<KeyPeak> peaks,
                    Set<Shape> targetShapes,
                    double minGrade)
{
    super(graph);
    this.peaks = peaks;
    this.targetShapes.addAll(targetShapes);
    this.minGrade = minGrade;
}
 
Example #28
Source File: NetworkGraph.java    From Rails with GNU General Public License v2.0 4 votes vote down vote up
public SimpleGraph<NetworkVertex, NetworkEdge> getGraph() {
    return graph;
}
 
Example #29
Source File: Investor_1880.java    From Rails with GNU General Public License v2.0 4 votes vote down vote up
public boolean isConnectedToLinkedCompany() {
    Multimap<MapHex,Station> lStations;
    Multimap<MapHex,Station> iStations;
    NetworkGraph nwGraph = NetworkGraph.createMapGraph(getRoot());
    NetworkGraph companyGraph =
            NetworkGraph.createRouteGraph(nwGraph, this, true, false);
    SimpleGraph<NetworkVertex, NetworkEdge> graph =
            companyGraph.getGraph();
    Set<NetworkVertex> verticies = graph.vertexSet();



    PublicCompany_1880 linkedCompany =
            (PublicCompany_1880) ((Investor_1880) this).getLinkedCompany();

    if (linkedCompany != null) {
        NetworkGraph linkedCompanyGraph=NetworkGraph.createRouteGraph(nwGraph, linkedCompany, true, false);
        // Creating a list of stations blocked by tokens.
        // The connection between investor and Linked Company is NOT blocked by any token of any company.
        // A token that is counted as blocked can be reached by the company for which it blocks the route.
        // Based on that logic a blocking token is reachable by both actors.
        lStations = linkedCompanyGraph.getNonPassableStations();
        iStations = companyGraph.getNonPassableStations();
        //Case A) the token in Question from a linked Company is actually on the route of the Investor
        for (BaseToken token : linkedCompany.getLaidBaseTokens()) {
            Owner holder = token.getOwner();
            if (!(holder instanceof Stop)) continue;
            Stop stop = (Stop) holder;
            for (NetworkVertex vertex : verticies) {
                if (vertex.getType() == NetworkVertex.VertexType.STATION) {
                    if ((stop.getRelatedStation() == vertex.getStation())
                            && (stop.getParent() == vertex.getHex())) {
                        return true;
                    }
                }
            }
        }
        // Case B) the Blocking Token is not from the linked Company
        // so we need to check if the MapHex of a blocking station is showing up in the
        // List of non Passable Stations
         for (MapHex blockedHex:lStations.keys()) {
             if (iStations.containsKey(blockedHex)) {
                 //Make sure its not an Offboard Map Hex
                 if (blockedHex.getCurrentTile().getColour().toString() == "RED" ) continue;
                 if (blockedHex.getStopName().equals("Beijing")) continue;
                 return true;
                }
         }

    }
    return false;
}
 
Example #30
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");
        }
    }