Java Code Examples for org.jgrapht.graph.DefaultEdge

The following are top voted examples for showing how to use org.jgrapht.graph.DefaultEdge. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: BART   File: FindFormulaWithAdornments.java   View source code 7 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 2
Project: AptSpring   File: DefinitionContentInspector.java   View source code 6 votes vote down vote up
private boolean testAllMissingEntitiesAreExpected(final DefinitionModel definition, final Consumer<ErrorModel> errorListner,
    final Map<String, ExpectedModel> missing, final DirectedGraph<BaseInstanceModel, DefaultEdge> entityGraph) {
  //check computed expected are actually expected
  boolean errored = false;
  List<String> expectedMissing = definition.getExpectedDefinitions().stream().map(em -> em.getIdentity())
      .collect(Collectors.toList());
  for (ExpectedModel expected : missing.values()) {
    if (!expectedMissing.contains(expected.getIdentity())) {
      List<AbstractModel> dependsOnMissing = Stream.concat(
          Stream.of(definition), 
          entityGraph.incomingEdgesOf(expected).stream().map(edge -> entityGraph.getEdgeSource(edge))
            .filter(m -> m.getSourceElement().isPresent()))
          .collect(Collectors.toList());
      errored = true;
      errorListner.accept(new ErrorModel(ErrorType.MISSING_BEAN_DEFINITIONS, Arrays.asList(expected), dependsOnMissing));
    } else {
      definition.addComputedExpected(expected);
    }
  }
  return errored;
}
 
Example 3
Project: custom-bytecode-analyzer   File: InvocationGraphImpl.java   View source code 6 votes vote down vote up
@Override
public Collection<Call> pathsToParents(MethodGraph element) {
  Collection<Call> paths = new HashSet<>();
    logger.debug("Finding path to parents for: {} ", element);
  if (!directedGraph.containsVertex(element)) {
    logger.warn("Graph does not contain vertex: {} . Returning empty collection.", element);
    return paths;
  }
  Set<DefaultEdge> incomingEdges = directedGraph.incomingEdgesOf(element);
  if (incomingEdges.isEmpty()) {
    Call lonelyCall = new Call(element, null);
    paths.add(lonelyCall);
    return paths;
  }
  for (DefaultEdge incomingEdge : incomingEdges) {
    MethodGraph father = directedGraph.getEdgeSource(incomingEdge);
    logger.debug("Finding path to parents, element={}, father={} . About to find paths from father", element, father);
    Call call = new Call(father, element);
    paths.add(call);
    paths.addAll(pathsToParents(father));
  }
  return paths;
}
 
Example 4
Project: sats-core   File: MRVMWorldSetup.java   View source code 6 votes vote down vote up
/**
 * Creates a naive, random, not necessarily planar graph
 */
@Deprecated
public static UndirectedGraph<RegionSetup, DefaultEdge> nonPlanarRandomGraphStructure(
        final double populationPerRegionMean,
        final double populationStandardDeviation,
        UniformDistributionRNG rng,
        IntegerInterval numberOfRegionsInterval,
        IntegerInterval averageAdjacenciesPerRegionInterval
) {
    int numberOfRegions = rng.nextInt(numberOfRegionsInterval);
    int numberOfAdjacencies = rng.nextInt(averageAdjacenciesPerRegionInterval) * numberOfRegions;
    RandomGraphGenerator<RegionSetup, DefaultEdge> randomGraphGenerator = new RandomGraphGenerator<>(
            numberOfRegions, numberOfAdjacencies, rng.nextLong());
    SimpleGraph<RegionSetup, DefaultEdge> targetGraph = new SimpleGraph<>(DefaultEdge.class);
    VertexFactory<RegionSetup> vertexFactory = () -> new RegionSetup(populationPerRegionMean, populationStandardDeviation, "randomly created");
    randomGraphGenerator.generateGraph(targetGraph, vertexFactory, null);
    return targetGraph;
}
 
Example 5
Project: sats-core   File: UndirectedGraphAdapter.java   View source code 6 votes vote down vote up
@Override
public UnmodifiableUndirectedGraph<MRVMRegionsMap.Region, DefaultEdge> deserialize(JsonElement json, Type typeOfT,
                                                                                   JsonDeserializationContext context) throws JsonParseException {

    JsonArray jsonArray = json.getAsJsonArray();
    Set<SerializedRegion> serializedRegions = new HashSet<>();
    Map<Integer, MRVMRegionsMap.Region> regionsById = new HashMap<>();
    SimpleGraph<MRVMRegionsMap.Region, DefaultEdge> graph = new SimpleGraph<>(DefaultEdge.class);
    for (int i = 0; i < jsonArray.size(); i++) {
        JsonElement regionElement = jsonArray.get(i);
        SerializedRegion r = context.deserialize(regionElement, SerializedRegion.class);
        serializedRegions.add(r);
        regionsById.put(r.getNode().getId(), r.getNode());
        graph.addVertex(r.getNode());

    }
    for (SerializedRegion serializedRegion : serializedRegions) {
        Set<Integer> neighbors = serializedRegion.getNeighbors();
        for (Integer neighborId : neighbors) {
            graph.addEdge(serializedRegion.getNode(), regionsById.get(neighborId));
        }
    }

    return new UnmodifiableUndirectedGraph<>(graph);
}
 
Example 6
Project: pgcodekeeper   File: DepcyGraphView.java   View source code 6 votes vote down vote up
@Override
public Object[] getConnectedTo(Object entity) {
    if (entity instanceof PgStatement){
        DirectedGraph<PgStatement, DefaultEdge> currentGraph = depRes.getOldGraph();
        if (currentGraph != null){
            List<PgStatement> connected = new ArrayList<>();
            for (DefaultEdge e : currentGraph.outgoingEdgesOf((PgStatement)entity)){
                PgStatement connectedVertex = currentGraph.getEdgeTarget(e);
                if (!(connectedVertex instanceof PgColumn)) {
                    connected.add(connectedVertex);
                }
            }
            return connected.toArray();
        }
    }
    return null;
}
 
Example 7
Project: obevo   File: StaticDataChangeTypeCommandCalculator.java   View source code 6 votes vote down vote up
private MutableList<ExecuteChangeCommand> handleChanges(MutableCollection<Change> fromSourceList) {
    final MutableList<ExecuteChangeCommand> commands = Lists.mutable.empty();

    DirectedGraph<Change, DefaultEdge> graph = enricher.createDependencyGraph(fromSourceList, false);

    if (graph != null) {
        ConnectivityInspector<Change, DefaultEdge> connectivityInspector
                = new ConnectivityInspector<Change, DefaultEdge>(graph);
        for (Set<Change> connectedSet : connectivityInspector.connectedSets()) {
            // once we have a connectedSet, sort within those changes to ensure that we still sort them in the
            // right order (i.e. via topological sort)
            ImmutableList<Change> fullChanges = sorter.sortChanges(graph, SetAdapter.adapt(connectedSet), SortableDependency.GRAPH_SORTER_COMPARATOR);
            commands.add(changeCommandFactory.createDeployCommand(new GroupChange(fullChanges)));
        }
    }

    return commands;
}
 
Example 8
Project: obevo   File: GraphSorter.java   View source code 6 votes vote down vote up
/**
 * Sorts the graph to provide a consistent topological ordering.
 *
 * @param graph          The input graph
 * @param subsetVertices The subset vertices of the graph we want to sort
 * @param comparator     The comparator on which to order the vertices to guarantee a consistent topological ordering
 */
public <T> ImmutableList<T> sortChanges(DirectedGraph<T, DefaultEdge> graph, RichIterable<T> subsetVertices, Comparator<? super T> comparator) {
    if (subsetVertices.toSet().size() != subsetVertices.size()) {
        throw new IllegalStateException("Unexpected state - have some dupe elements here: " + subsetVertices);
    }

    DirectedGraph<T, DefaultEdge> subsetGraph = new DirectedSubgraph<T, DefaultEdge>(
            graph, subsetVertices.toSet(), null);

    // At one point, we _thought_ that the DirectedSubGraph was dropping vertices that don't have edges, so we
    // manually add them back to the graph to ensure that we can still order them.
    // However, that no longer seems to be the case. We add a check here just in case this comes up again.
    if (subsetVertices.size() != subsetGraph.vertexSet().size()) {
        throw new IllegalArgumentException("This case should never happen! [subsetVertices: " + subsetVertices + ", subsetGraphVertices: " + subsetGraph.vertexSet());
    }

    return sortChanges(subsetGraph, comparator);
}
 
Example 9
Project: obevo   File: GraphEnricherImplTest.java   View source code 6 votes vote down vote up
/**
 * The test data in this class is all written w/ case-sensitivy as the default.
 * If we pass caseInsensitive == true, then we enable that mode in the graph enricher and tweak the object names
 * a bit so that we can verify that the resolution works either way.
 */
public void testSchemaObjectDependencies(boolean caseInsensitive) {
    this.enricher = new GraphEnricherImpl(caseInsensitive ? StringFunctions.toUpperCase() : Functions.getStringPassThru());

    SortableDependencyGroup sch1Obj1 = newChange(schema1, type1, "obj1", Sets.immutable.with("obj3", schema2 + ".obj2"));
    SortableDependencyGroup sch1Obj2 = newChange(schema1, type2, "obj2", Sets.immutable.<String>with());
    // change the case of the object name to ensure others can still point to it
    SortableDependencyGroup sch1Obj3 = newChange(schema1, type1, caseInsensitive ? "obj3".toUpperCase() : "obj3", Sets.immutable.with("obj2"));
    // change the case of the dependency name to ensure that it can point to others
    SortableDependencyGroup sch2Obj1 = newChange(schema2, type1, "obj1", Sets.immutable.with(caseInsensitive ? "obj2".toUpperCase() : "obj2"));
    SortableDependencyGroup sch2Obj2 = newChange(schema2, type2, "obj2", Sets.immutable.with(schema1 + ".obj3"));

    DirectedGraph<SortableDependencyGroup, DefaultEdge> sortGraph = enricher.createDependencyGraph(Lists.mutable.with(
            sch1Obj1, sch1Obj2, sch1Obj3, sch2Obj1, sch2Obj2), false);

    validateChange(sortGraph, sch1Obj1, Sets.immutable.with(sch1Obj3, sch2Obj2), Sets.immutable.<SortableDependencyGroup>with());
    validateChange(sortGraph, sch1Obj2, Sets.immutable.<SortableDependencyGroup>with(), Sets.immutable.with(sch1Obj3));
    validateChange(sortGraph, sch1Obj3, Sets.immutable.with(sch1Obj2), Sets.immutable.with(sch1Obj1, sch2Obj2));
    validateChange(sortGraph, sch2Obj1, Sets.immutable.with(sch2Obj2), Sets.immutable.<SortableDependencyGroup>with());
    validateChange(sortGraph, sch2Obj2, Sets.immutable.with(sch1Obj3), Sets.immutable.with(sch1Obj1, sch2Obj1));
}
 
Example 10
Project: obevo   File: GraphEnricherImplTest.java   View source code 6 votes vote down vote up
@Test
public void testGetChangesCaseInsensitive() {
    this.enricher = new GraphEnricherImpl(StringFunctions.toUpperCase());
    String schema1 = "schema1";
    String schema2 = "schema2";
    String type1 = "type1";

    SortableDependencyGroup sp1 = newChange(schema1, type1, "SP1", "n/a", 0, Sets.immutable.with("sp2"));
    SortableDependencyGroup sp2 = newChange(schema1, type1, "SP2", Sets.immutable.<String>with());
    SortableDependencyGroup sp3 = newChange(schema1, type1, "SP3", Sets.immutable.with("sp1", "sp2"));
    SortableDependencyGroup spA = newChange(schema1, type1, "SPA", Sets.immutable.with("sp3"));
    SortableDependencyGroup sp1Schema2 = newChange(schema2, type1, "sp1", "n/a", 0, Sets.immutable.with("sp2", schema1 + ".sp3"));
    SortableDependencyGroup sp2Schema2 = newChange(schema2, type1, "sP2", "n/a", 0, Sets.immutable.<String>with());

    DirectedGraph<SortableDependencyGroup, DefaultEdge> sortGraph = enricher.createDependencyGraph(Lists.mutable.with(
            sp1, sp2, sp3, spA, sp1Schema2, sp2Schema2), false);

    validateChange(sortGraph, sp1, Sets.immutable.with(sp2), Sets.immutable.with(sp3));
    validateChange(sortGraph, sp2, Sets.immutable.<SortableDependencyGroup>with(), Sets.immutable.with(sp1, sp3));
    validateChange(sortGraph, sp3, Sets.immutable.with(sp1, sp2), Sets.immutable.with(spA, sp1Schema2));
    validateChange(sortGraph, spA, Sets.immutable.with(sp3), Sets.immutable.<SortableDependencyGroup>with());
    validateChange(sortGraph, sp1Schema2, Sets.immutable.with(sp2Schema2, sp3), Sets.immutable.<SortableDependencyGroup>with());
    validateChange(sortGraph, sp2Schema2, Sets.immutable.<SortableDependencyGroup>with(), Sets.immutable.with(sp1Schema2));
}
 
Example 11
Project: taboola-cronyx   File: StdNameAndGroupGraphValidator.java   View source code 6 votes vote down vote up
private void assertHasSingleCronRoot(DirectedAcyclicGraph<NameAndGroup, DefaultEdge> graph) {
    Iterator<NameAndGroup> itr = graph.iterator();
    NameAndGroup root = null;
    while (itr.hasNext()) {
        NameAndGroup cur = itr.next();
        if(!isRoot(graph, cur)) {
            continue;
        }

        if(root != null) {
            throw new CronyxException(String.format("Graph has at least 2 roots: %s, %s", root, cur));
        }

        if(!isCron(cur)) {
            throw new CronyxException("Found a root that is not a cron trigger: " + cur);
        }

        root = cur;
    }

    if(root == null) {
        throw new CronyxException("Didn't find a root in the graph!");
    }
}
 
Example 12
Project: bioasq   File: CavMerger.java   View source code 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 13
Project: cf-converger   File: HardcodedOrderedHandlerBuilder.java   View source code 6 votes vote down vote up
private void addVertexAndEdge(Intent<? extends Resolution> fromIntent,
		Intent<? extends Resolution> toIntent,
		DirectedAcyclicGraph<Handler<? extends Intent<? extends Resolution>>, DefaultEdge> dag)
{
	Handler<? extends Intent<? extends Resolution>> toHandler = handlerFactory.build(toIntent);
	dag.addVertex(toHandler);

	try
	{
		dag.addDagEdge(handlerFactory.build(fromIntent), toHandler);
	}
	catch (CycleFoundException e)
	{
		throw new RuntimeException("Cycle found building allegedly acyclical graph", e);
	}
}
 
Example 14
Project: SemanticSCo   File: ServiceComposer.java   View source code 6 votes vote down vote up
public List<String> findParentNodes(String nodeID){
	
List<String> parentNodes = new LinkedList<>();

       //Get incoming edges of given service
       Set<DefaultEdge> incomingEdges = graphComposition.incomingEdgesOf(nodeID);
	
//Put the source nodes of the incomingEdges in the list of parentNodes
Iterator it = incomingEdges.iterator();
while (it.hasNext()) {
           String sourceNode = graphComposition.getEdgeSource((DefaultEdge) it.next());
           parentNodes.add(sourceNode);
}
	
return parentNodes;
   }
 
Example 15
Project: minibrass   File: ConfigurationProvider.java   View source code 6 votes vote down vote up
private List<Field> getParameterOrdering(DirectedGraph<Field, DefaultEdge> dependencyGraph) {
	CycleDetector<Field, DefaultEdge> cycleDetector = new CycleDetector<Field, DefaultEdge>(dependencyGraph);
	if (cycleDetector.detectCycles()) {
		throw new RuntimeException("Cyclic dependency detected!");
	} else {
		TopologicalOrderIterator<Field, DefaultEdge> orderIterator;
		Field f;
		orderIterator = new TopologicalOrderIterator<Field, DefaultEdge>(dependencyGraph);
	
		List<Field> output = new ArrayList<>(dependencyGraph.vertexSet().size());

		while (orderIterator.hasNext()) {
			f = orderIterator.next();
			output.add(f);
		}

		return output;
	}
}
 
Example 16
Project: minibrass   File: DirectedGraph.java   View source code 6 votes vote down vote up
public void transcribe(org.jgrapht.DirectedGraph<Integer, DefaultEdge> jgraph) throws MiniBrassParseException {
	for (int v = 1; v <= adjacencyMatrix.length; ++v) {
		jgraph.addVertex(v);
	}

	for (int i = 0; i < adjacencyMatrix.length; ++i) {
		for (int j = 0; j < adjacencyMatrix.length; ++j) {

			try {
				if (adjacencyMatrix[i][j]) {
					jgraph.addEdge(i + 1, j + 1);
				}
			} catch (IllegalArgumentException ce) {
				throw new MiniBrassParseException(
						"Detected cyclic edge when adding edge : " + (i + 1) + " -> " + (j + 1));
			}
		}
	}

}
 
Example 17
Project: Articleate   File: TextRank.java   View source code 6 votes vote down vote up
/**
 * Method for calculating token score
 * Note the difference between this and the method for calculating
 * SentenceVertex scores. The SentenceVertex graph has edge weights,
 * which changes the algorithm significantly.
 * @param vi The vertex whose score will be computed
 * @return The calculated score
 */
private double calculateTokenScore(TokenVertex vi){
    double scorei = (1.0 - PROBABILITY);
    double sum = 0;
    //Iterate over edges of vi
    for(DefaultEdge eij: tokenGraph.edgesOf(vi)){
        double numerator = 1.0;
        //Get other vertex
        TokenVertex vj = tokenGraph.getEdgeSource(eij);
        if(vi == vj){
            vj = tokenGraph.getEdgeTarget(eij);
        }
        //Find the denominator
        double denominator = tokenGraph.edgesOf(vj).size();
        double scorej = vj.getScore();
        sum += (numerator/denominator)*scorej;
    }
    scorei += PROBABILITY *sum;
    return scorei;
}
 
Example 18
Project: DramaNLP   File: NetworkExtractor.java   View source code 6 votes vote down vote up
protected DirectedGraph<Figure, DefaultEdge> extractMentionNetwork(JCas jcas) {
	DirectedGraph<Figure, DefaultEdge> graph = new DirectedPseudograph<Figure, DefaultEdge>(DefaultEdge.class);

	for (Utterance utterance : JCasUtil.select(jcas, Utterance.class)) {
		Speaker speaker = DramaUtil.getFirstSpeaker(utterance);
		if (speaker != null)
			for (FigureMention mention : JCasUtil.selectCovered(jcas, FigureMention.class, utterance)) {
				if (speaker.getFigure() != null && mention.getFigure() != null) {
					if (!graph.containsVertex(speaker.getFigure()))
						graph.addVertex(speaker.getFigure());
					if (!graph.containsVertex(mention.getFigure()))
						graph.addVertex(mention.getFigure());
					graph.addEdge(speaker.getFigure(), mention.getFigure());
				}
			}
	}
	return graph;
}
 
Example 19
Project: jReto   File: MinimumSteinerTreeApproximation.java   View source code 6 votes vote down vote up
/**
   * Computes an approximation of a directed minimum steiner tree.
   * @param graph The graph of which the minimum steiner tree should be computed
   * @param startVertex The vertex at which the directed minimum steiner tree should be rooted.
   * @param vertices A set of vertices that should be included in the minimum steiner tree.
   * @return A tree representation of the computed tree.
   */
public static <V, E> Tree<V> approximateSteinerTree(DirectedWeightedPseudograph<V, E> graph, V startVertex, Set<V> vertices) {
	// 1. Construct the metric closure for the given set of vertices.
	DirectedWeightedPseudograph<V, MetricClosureEdge<V>> metricClosure = createMetricClosure(graph, vertices);
	
	// 2. Compute the edges that compose an aborescence of the metric closure (aka. directed minimum spanning tree).
	Set<MetricClosureEdge<V>> arborescenceEdges = minimumArborescenceEdges(metricClosure, startVertex);

	// 3. Reduce the metric closure by removing all edges not computed before.
	metricClosure.removeAllEdges(inverseEdgeSet(metricClosure, arborescenceEdges));

	// 4. Reconstruct a graph containing all vertices of the original graph.
	DirectedMultigraph<V, DefaultEdge> steinerTreeGraphApproximation = reconstructGraphFromMetricClosure(metricClosure);
	
	// 5. Construct a tree representation.
	Tree<V> steinerTree = constructSteinerTreeApproximation(startVertex, steinerTreeGraphApproximation);
	
	return steinerTree;
}
 
Example 20
Project: age3-nanorobots   File: RingTopologyProcessor.java   View source code 6 votes vote down vote up
@Override public @NonNull DirectedGraph<String, DefaultEdge> createGraphFrom(
		final @NonNull Set<? extends NodeDescriptor> identities) {
	requireNonNull(identities);

	final DefaultDirectedGraph<String, DefaultEdge> graph = new DefaultDirectedGraph<>(DefaultEdge.class);
	identities.forEach(identity -> graph.addVertex(identity.id()));

	final List<String> sortedIds = identities.stream()
	                                         .map(NodeDescriptor::id)
	                                         .sorted()
	                                         .collect(Collectors.toList());
	sortedIds.stream().reduce(getLast(sortedIds), (nodeIdentity1, nodeIdentity2) -> {
		graph.addEdge(nodeIdentity1, nodeIdentity2);
		return nodeIdentity2;
	});
	return new UnmodifiableDirectedGraph<>(graph);
}
 
Example 21
Project: LifeTiles   File: JGraphTGraphFactory.java   View source code 6 votes vote down vote up
/**
 * @param base
 *            the graph to create a subgraph from.
 * @param vertexSubSet
 *            the vertices to include in the subgraph
 * @return a subgraph based on the base graph
 * @throws NotAJGraphTAdapterException
 *             if the base graph is not a JGraphT library
 */
@Override
public Graph<V> getSubGraph(final Graph<V> base, final Set<V> vertexSubSet)
        throws NotAJGraphTAdapterException {

    if (base instanceof JGraphTGraphAdapter) {
        JGraphTGraphAdapter<V> baseGraph = (JGraphTGraphAdapter<V>) base;

        return new JGraphTGraphAdapter<V>(
                new DirectedSubgraph<V, DefaultEdge>(
                        baseGraph.getInternalGraph(), vertexSubSet, null),
                edgeFact, baseGraph.getVertexIdentifiers());

    } else {
        throw new NotAJGraphTAdapterException();
    }

}
 
Example 22
Project: age3-nanorobots   File: RingTopologyProcessorTest.java   View source code 6 votes vote down vote up
@Test public void testTwoNodes() {
	final String node1Id = "1";
	final String node2Id = "2";
	final NodeDescriptor node1Identity = new NodeDescriptor(node1Id, NodeType.UNKNOWN, Collections.emptySet());
	final NodeDescriptor node2Identity = new NodeDescriptor(node2Id, NodeType.UNKNOWN, Collections.emptySet());
	final ImmutableSet<NodeDescriptor> identities = ImmutableSet.of(node1Identity, node2Identity);

	final DirectedGraph<String, DefaultEdge> graph = processor.createGraphFrom(identities);

	assertThat(graph.containsVertex(node1Id)).isTrue();
	assertThat(graph.inDegreeOf(node1Id)).isEqualTo(1);
	assertThat(graph.outDegreeOf(node1Id)).isEqualTo(1);

	assertThat(graph.containsVertex(node2Id)).isTrue();
	assertThat(graph.inDegreeOf(node2Id)).isEqualTo(1);
	assertThat(graph.outDegreeOf(node2Id)).isEqualTo(1);

	assertThat(graph.getEdge(node1Id, node1Id)).isNull();
	assertThat(graph.getEdge(node1Id, node2Id)).isNotNull();
	assertThat(graph.getEdge(node2Id, node1Id)).isNotNull();
	assertThat(graph.getEdge(node2Id, node2Id)).isNull();
}
 
Example 23
Project: hawkular-agent   File: ResourceManager.java   View source code 6 votes vote down vote up
/**
 * Remove the resources from {@link #resourcesGraph} matching the given {@code query} including all direct and
 * indirect descendants.
 *
 * @param query a location eventually containing wildcards
 * @param locationResolver the {@link LocationResolver} to perform the matching of graph nodes against the given
 *            {@code query}
 * @return an unmodifiable list of {@link Resources} that were removed by this method
 */
public List<Resource<L>> removeResources(L query, LocationResolver<L> locationResolver) {
    graphLockWrite.lock();
    try {
        List<Resource<L>> doomedResources = new ArrayList<Resource<L>>();
        GraphIterator<Resource<L>, DefaultEdge> it = new DepthFirstIterator<>(this.resourcesGraph);
        while (it.hasNext()) {
            Resource<L> resource = it.next();
            if (locationResolver.matches(query, resource.getLocation())) {
                getAllDescendants(resource, doomedResources);
                doomedResources.add(resource);
            }
        }

        // we couldn't do this while iterating (a ConcurrentModificationException would have resulted)
        // but now that we have the doomed resources, we can remove them from the graph now
        for (Resource<L> doomedResource : doomedResources) {
            this.resourcesGraph.removeVertex(doomedResource);
        }

        return Collections.unmodifiableList(doomedResources);
    } finally {
        graphLockWrite.unlock();
    }
}
 
Example 24
Project: hawkular-agent   File: ResourceTypeManager.java   View source code 6 votes vote down vote up
/**
 * Adds the given types to the manager, building a graph to represent the type hierarchy.
 *
 * @param resourceTypeSetMap a full set of types, must be immutable
 * @param setsToUse optional set of type names that the manager to care about - it will ignore others it finds. If
 *            null, then the full set is used (by "full set" it means the resourceTypeSetMap param).
 * @throws IllegalStateException if types are missing (e.g. a type needs a parent but the parent is missing)
 */
public ResourceTypeManager(Map<Name, TypeSet<ResourceType<L>>> resourceTypeSetMap, Collection<Name> setsToUse)
        throws IllegalStateException {
    // If setsToUse is null, that means we need to use all the ones in the incoming map.
    // If setsToUse is not null, just use those named sets and ignore the others.
    if (setsToUse == null) {
        this.typeSetMap = resourceTypeSetMap;
    } else {
        Map<Name, TypeSet<ResourceType<L>>> m = new HashMap<>();
        for (Name setToUse : setsToUse) {
            if (resourceTypeSetMap.containsKey(setToUse)) {
                m.put(setToUse, resourceTypeSetMap.get(setToUse));
            }
        }
        this.typeSetMap = Collections.unmodifiableMap(m);
    }

    this.resourceTypesGraph = new ListenableDirectedGraph<>(DefaultEdge.class);
    this.index = new DirectedNeighborIndex<>(this.resourceTypesGraph);
    this.resourceTypesGraph.addGraphListener(index);

    prepareGraph();
}
 
Example 25
Project: presto   File: SqlQueryQueueManager.java   View source code 6 votes vote down vote up
private static void checkIsDAG(List<QueryQueueRule> rules)
{
    DirectedPseudograph<String, DefaultEdge> graph = new DirectedPseudograph<>(DefaultEdge.class);
    for (QueryQueueRule rule : rules) {
        String lastQueueName = null;
        for (QueryQueueDefinition queue : rule.getQueues()) {
            String currentQueueName = queue.getTemplate();
            graph.addVertex(currentQueueName);
            if (lastQueueName != null) {
                graph.addEdge(lastQueueName, currentQueueName);
            }
            lastQueueName = currentQueueName;
        }
    }

    List<String> shortestCycle = shortestCycle(graph);

    if (shortestCycle != null) {
        String s = Joiner.on(", ").join(shortestCycle);
        throw new IllegalArgumentException(format("Queues must not contain a cycle. The shortest cycle found is [%s]", s));
    }
}
 
Example 26
Project: openimaj   File: SimilarityMatrix.java   View source code 6 votes vote down vote up
/**
 * Convert the similarity matrix to an unweighted, undirected
 * graph representation. A threshold is used to determine
 * if edges should be created. If the value at [r][c] is bigger
 * than the threshold, then an edge will be created between the
 * vertices represented by index[r] and index[c].
 * 
 * @param threshold the threshold
 * @return the graph
 */
public UndirectedGraph<String, DefaultEdge> toUndirectedUnweightedGraph(double threshold) {
	UndirectedGraph<String, DefaultEdge> graph = new SimpleGraph<String, DefaultEdge>(DefaultEdge.class);

	final int rows = this.getRowDimension();
	final int cols = this.getColumnDimension();
	final double[][] data = this.getArray(); 

	for (String s : index) {
		graph.addVertex(s);
	}

	for (int r=0; r<rows; r++) {
		for (int c=0; c<cols; c++) {
			if (r != c && data[r][c] > threshold)
				graph.addEdge(index[r], index[c]);
		}
	}

	return graph;
}
 
Example 27
Project: BART   File: GenerateFormulaWithAdornments.java   View source code 6 votes vote down vote up
public FormulaWithAdornments generate(IFormula formula, UndirectedSubgraph<FormulaGraphVertex, DefaultEdge> connectedSubgraphOne, 
        UndirectedSubgraph<FormulaGraphVertex, DefaultEdge> connectedSubgraphTwo, List<VariablePair> variablePairs) {
    UndirectedSubgraph<FormulaGraphVertex, DefaultEdge> connectedSubgraph = chooseSubgraphWithNoVirtualVertices(connectedSubgraphOne, connectedSubgraphTwo);
    if (connectedSubgraph == null) {
        throw new IllegalArgumentException("Please add explicit selection for variables to make the formula symmetric...");
    }

    FormulaWithAdornments formulaWithAdornment = new FormulaWithAdornments(formula.clone());
    List<IFormulaAtom> symmetricAtoms = extractFormulaAtoms(connectedSubgraph);
    if (logger.isDebugEnabled()) logger.debug("Symmetric atoms: " + symmetricAtoms);
    removeAtoms(formulaWithAdornment, symmetricAtoms);
    Set<FormulaVariable> variablesToKeep = findVariablesToKeep(formulaWithAdornment);
    if (logger.isDebugEnabled()) logger.debug("Variables to keep: " + variablesToKeep);
    removeUnneededVariables(formulaWithAdornment, variablesToKeep);
    removeUnneededVariableOccurrences(formulaWithAdornment, symmetricAtoms);
    equivalenceClassFinder.findVariableEquivalenceClasses(formulaWithAdornment.getFormula());
    addAdornments(formulaWithAdornment, variablePairs);
    if (logger.isDebugEnabled()) logger.debug("Result: " + formulaWithAdornment);
    return formulaWithAdornment;
}
 
Example 28
Project: BART   File: FindFormulaWithAdornments.java   View source code 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 29
Project: BART   File: FindFormulaWithAdornments.java   View source code 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 30
Project: BART   File: FindFormulaWithAdornments.java   View source code 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 31
Project: jorlib   File: ExactPricingProblemSolver.java   View source code 6 votes vote down vote up
/**
 * Build the MIP model. Essentially this model calculates maximum weight independent sets.
 */
private void buildModel(){
    try {
        cplex=new IloCplex();
        cplex.setParam(IloCplex.IntParam.AdvInd, 0);
        cplex.setParam(IloCplex.IntParam.Threads, 1);
        cplex.setOut(null);

        //Create the variables (a single variable per edge)
        vars=cplex.boolVarArray(dataModel.getNrVertices());

        //Create the objective function
        obj=cplex.addMaximize();

        //Create the constraints z_i+z_j <= 1 for all (i,j)\in E:
        for(DefaultEdge edge : dataModel.edgeSet())
            cplex.addLe(cplex.sum(vars[dataModel.getEdgeSource(edge)], vars[dataModel.getEdgeTarget(edge)]), 1);

        branchingConstraints=new HashMap<>();
    } catch (IloException e) {
        e.printStackTrace();
    }
}
 
Example 32
Project: wikit   File: Graphs.java   View source code 6 votes vote down vote up
/**
 * Converts a FactorGraph into a plain graph where each Variable is a vertex,
 * and two Variables are connected by an edge if they are arguments to the same factor. 
 *  (Essentially converts an fg into an MRF structure, minus the factors.)
 * @param fg
 * @return a Graph
 */
public static UndirectedGraph mdlToGraph (FactorGraph fg)
{
  UndirectedGraph g = new SimpleGraph(DefaultEdge.class);

  for (Iterator it = fg.variablesIterator (); it.hasNext ();) {
    Variable var = (Variable) it.next ();
    g.addVertex (var);
  }

  for (Iterator it = fg.factorsIterator (); it.hasNext ();) {
    Factor factor = (Factor) it.next ();
    VarSet varSet = factor.varSet ();
    int nv = varSet.size ();
    for (int i = 0; i < nv; i++) {
      for (int j = i + 1; j < nv; j++) {
        g.addEdge (varSet.get (i), varSet.get (j));
      }
    }
  }

  return g;
}
 
Example 33
Project: evosuite   File: InheritanceTree.java   View source code 6 votes vote down vote up
public Set<String> getSuperclasses(String className) {
	String classNameWithDots = ResourceList.getClassNameFromResourcePath(className);
	if (!inheritanceGraph.containsVertex(classNameWithDots)) {
		LoggingUtils.logWarnAtMostOnce(logger, "Class not in inheritance graph: " + classNameWithDots);
		return new LinkedHashSet<>();
	}
	EdgeReversedGraph<String, DefaultEdge> reverseGraph = new EdgeReversedGraph<String, DefaultEdge>(
	        inheritanceGraph);

	// TreeSet so that classes are sorted by name and thus deterministic across platforms
	Set<String> result = new TreeSet<>();
	BreadthFirstIterator<String, DefaultEdge> bfi = new BreadthFirstIterator<String, DefaultEdge>(
	        reverseGraph, classNameWithDots);
	while (bfi.hasNext()) {
		result.add(bfi.next());
	}
	return result;
}
 
Example 34
Project: evosuite   File: InheritanceTree.java   View source code 6 votes vote down vote up
public List<String> getOrderedSuperclasses(String className) {
	String classNameWithDots = ResourceList.getClassNameFromResourcePath(className);
	if (!inheritanceGraph.containsVertex(classNameWithDots)) {
		LoggingUtils.logWarnAtMostOnce(logger, "Class not in inheritance graph: " + classNameWithDots);
		return new LinkedList<>();
	}
	EdgeReversedGraph<String, DefaultEdge> reverseGraph = new EdgeReversedGraph<String, DefaultEdge>(
	        inheritanceGraph);
	List<String> orderedList = new LinkedList<>();
	BreadthFirstIterator<String, DefaultEdge> bfi = new BreadthFirstIterator<String, DefaultEdge>(
	        reverseGraph, classNameWithDots);
	while (bfi.hasNext()) {
		orderedList.add(bfi.next());
	}
	return orderedList;
}
 
Example 35
Project: DoSeR   File: Sampling.java   View source code 6 votes vote down vote up
private String performRandomStep(String current) {
	if (current == null) {
		return null;
	}
	String jumpstep = null;
	Set<DefaultEdge> edges = graph.edgesOf(current);
	int max = edges.size();
	int ran = random.nextInt(max);
	int counter = 0;
	for (DefaultEdge e : edges) {
		if (ran == counter) {
			String source = graph.getEdgeSource(e);
			String target = graph.getEdgeTarget(e);
			if (source.equalsIgnoreCase(current)) {
				jumpstep = target;
			} else {
				jumpstep = source;
			}
			break;
		}
		counter++;
	}
	return jumpstep;
}
 
Example 36
Project: DSL   File: ProgramASTNode.java   View source code 5 votes vote down vote up
public Graph<ASTNode, DefaultEdge> getAST() {
    Graph<ASTNode, DefaultEdge> ast = new ListenableDirectedGraph<>(DefaultEdge.class);
    ast.addVertex(this);
    body.forEach(node -> {
        node.addDependency(ast);
        ast.addEdge(this, node);
    });
    
    return ast;
}
 
Example 37
Project: DSL   File: ProgramASTNode.java   View source code 5 votes vote down vote up
@Override
public void addDependency(Graph<ASTNode, DefaultEdge> graph) {
    graph.addVertex(this);
    
    body.forEach(node -> {
        node.addDependency(graph);
        graph.addEdge(this, node);
    });
}
 
Example 38
Project: DSL   File: BinaryASTNode.java   View source code 5 votes vote down vote up
@Override
public void addDependency(Graph<ASTNode, DefaultEdge> graph) {
    graph.addVertex(this);
    
    left.addDependency(graph);
    graph.addEdge(this, left);
    
    right.addDependency(graph);
    graph.addEdge(this, right);
}
 
Example 39
Project: DSL   File: StatementASTNode.java   View source code 5 votes vote down vote up
@Override
public void addDependency(Graph<ASTNode, DefaultEdge> graph) {
    graph.addVertex(this);
    
    body.forEach(node -> {
        node.addDependency(graph);
        graph.addEdge(this, node);
    });
}
 
Example 40
Project: DSL   File: PrintASTNode.java   View source code 5 votes vote down vote up
@Override
public void addDependency(Graph<ASTNode, DefaultEdge> graph) {
    graph.addVertex(this);
    
    expr.addDependency(graph);
    graph.addEdge(this, expr);
}