org.jgrapht.Graph类的使用及代码示例

x33g5p2x  于2022-01-20 转载在 其他  
字(11.2k)|赞(0)|评价(0)|浏览(204)

本文整理了Java中org.jgrapht.Graph类的一些代码示例,展示了Graph类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Graph类的具体详情如下:
包路径:org.jgrapht.Graph
类名称:Graph

Graph介绍

[英]The root interface in the graph hierarchy. A mathematical graph-theory graph object G(V,E) contains a set V of vertices and a set E of edges. Each edge e=(v1,v2) in E connects vertex v1 to vertex v2. for more information about graphs and their related definitions see http://mathworld.wolfram.com/Graph.html.

This library generally follows the terminology found at: http://mathworld.wolfram.com/topics/GraphTheory.html. Implementation of this interface can provide simple-graphs, multigraphs, pseudographs etc. The package org.jgrapht.graph provides a gallery of abstract and concrete graph implementations.

This library works best when vertices represent arbitrary objects and edges represent the relationships between them. Vertex and edge instances may be shared by more than one graph.

Through generics, a graph can be typed to specific classes for vertices V and edges E<T>. Such a graph can contain vertices of type V and all sub-types and Edges of type E and all sub-types.

For guidelines on vertex and edge classes, see this wiki page.
[中]图形层次结构中的根接口。数学图论图形对象G(V,E)包含一组V顶点和一组E边。e中的每条边e=(v1,v2)将顶点v1连接到顶点v2。有关图及其相关定义的更多信息,请参见http://mathworld.wolfram.com/Graph.html
此库通常遵循以下术语:http://mathworld.wolfram.com/topics/GraphTheory.html。此接口的实现可以提供简单图、多重图、伪图等。包org.jgrapht.graph提供抽象和具体图实现的库。
当顶点表示任意对象且边表示它们之间的关系时,此库最为有效。顶点和边实例可以由多个图形共享。
通过泛型,可以将图形键入顶点V和边E<T>的特定类。此类图可以包含V类型的顶点以及E类型和所有子类型的所有子类型和边。
有关顶点和边类的指导原则,请参见this wiki page

代码示例

代码示例来源:origin: io.github.oliviercailloux.jmcda/utils

static public <V, E> void copyTo(Graph<V, E> source, Graph<V, E> target) {
  for (V vertex : source.vertexSet()) {
    target.addVertex(vertex);
  }
  for (E edge : source.edgeSet()) {
    final boolean added = target.addEdge(source.getEdgeSource(edge), source.getEdgeTarget(edge), edge);
    if (!added) {
      throw new IllegalArgumentException("Target graph does not support addition of (some) source edges.");
    }
  }
}

代码示例来源:origin: cwensel/cascading

@Override
public boolean addHeadVertex( FlowElement flowElement )
 {
 if( !graph.containsVertex( Extent.head ) )
  graph.addVertex( Extent.head );
 if( flowElement == Extent.head )
  return false;
 boolean result = true;
 if( !graph.containsVertex( flowElement ) )
  result = graph.addVertex( flowElement );
 return result && graph.addEdge( Extent.head, flowElement ) != null;
 }

代码示例来源:origin: org.jgrapht/jgrapht-core

@Override
protected void transformGraph(List<E> previousPath)
{
  V source, target;
  E reversedEdge;
  // replace previous path edges with reversed edges with negative weight
  for (E originalEdge : previousPath) {
    source = workingGraph.getEdgeSource(originalEdge);
    target = workingGraph.getEdgeTarget(originalEdge);
    double originalEdgeWeight = workingGraph.getEdgeWeight(originalEdge);
    workingGraph.removeEdge(originalEdge);
    workingGraph.addEdge(target, source);
    reversedEdge = workingGraph.getEdge(target, source);
    workingGraph.setEdgeWeight(reversedEdge, -originalEdgeWeight);
  }
}

代码示例来源:origin: mulesoft/mule

private void addType(ErrorTypeDefinition<?> errorType,
           Graph<ErrorTypeDefinition, Pair<ErrorTypeDefinition, ErrorTypeDefinition>> graph) {
 graph.addVertex(errorType);
 String type = errorType.getType();
 if (!ANY.name().equals(type) && !CRITICAL.name().equals(type)) {
  ErrorTypeDefinition parentErrorType = errorType.getParent().orElse((ANY));
  graph.addVertex(parentErrorType);
  graph.addEdge(errorType, parentErrorType);
 }
}

代码示例来源:origin: org.jgrapht/jgrapht-core

private V getEdgeSource(E e)
{
  return this.workingGraph.containsEdge(e) ? this.workingGraph.getEdgeSource(e)
    : this.originalGraph.getEdgeSource(e);
}

代码示例来源:origin: org.jgrapht/jgrapht-core

/**
 * Create a copy of a graph for internal use.
 *
 * @param graph the graph to copy.
 *
 * @return A copy of the graph projected to a SimpleGraph.
 */
private static <V, E> Graph<V, E> copyAsSimpleGraph(Graph<V, E> graph)
{
  Graph<V,
    E> copy = GraphTypeBuilder
      .<V, E> undirected().edgeSupplier(graph.getEdgeSupplier())
      .vertexSupplier(graph.getVertexSupplier()).allowingMultipleEdges(false)
      .allowingSelfLoops(false).buildGraph();
  if (graph.getType().isSimple()) {
    Graphs.addGraph(copy, graph);
  } else {
    // project graph to SimpleGraph
    Graphs.addAllVertices(copy, graph.vertexSet());
    for (E e : graph.edgeSet()) {
      V v1 = graph.getEdgeSource(e);
      V v2 = graph.getEdgeTarget(e);
      if (!v1.equals(v2) && !copy.containsEdge(e)) {
        copy.addEdge(v1, v2);
      }
    }
  }
  return copy;
}

代码示例来源:origin: org.jgrapht/jgrapht-core

/**
 * Adds all the vertices and all the edges of the specified source digraph to the specified
 * destination digraph, reversing all of the edges. If you want to do this as a linked view of
 * the source graph (rather than by copying to a destination graph), use
 * {@link EdgeReversedGraph} instead.
 *
 * <p>
 * The behavior of this operation is undefined if any of the specified graphs is modified while
 * operation is in progress.
 *
 * @param destination the graph to which vertices and edges are added
 * @param source the graph used as source for vertices and edges to add
 * @param <V> the graph vertex type
 * @param <E> the graph edge type
 *
 * @see EdgeReversedGraph
 */
public static <V,
  E> void addGraphReversed(Graph<? super V, ? super E> destination, Graph<V, E> source)
{
  if (!source.getType().isDirected() || !destination.getType().isDirected()) {
    throw new IllegalArgumentException("graph must be directed");
  }
  addAllVertices(destination, source.vertexSet());
  for (E edge : source.edgeSet()) {
    destination.addEdge(source.getEdgeTarget(edge), source.getEdgeSource(edge));
  }
}

代码示例来源:origin: org.jgrapht/jgrapht-core

public int[] getEdgeNumbers(E e)
{
  V v1 = graph.getEdgeSource(e), v2 = graph.getEdgeTarget(e);
  int[] edge = new int[2];
  edge[0] = mapVertexToOrder.get(v1);
  edge[1] = mapVertexToOrder.get(v2);
  return edge;
}

代码示例来源:origin: org.jgrapht/jgrapht-core

/**
 * Returns the set of edges which run from the source partition to the sink partition, in the
 * $s-t$ cut obtained after the last invocation of {@link #calculateMinCut(Set, boolean)}
 *
 * @return set of edges which have one endpoint in the source partition and one endpoint in the
 *         sink partition.
 */
public Set<E> getCutEdges()
{
  Predicate<E> predicate = e -> sourcePartitionMinimumCut.contains(network.getEdgeSource(e))
    ^ sourcePartitionMinimumCut.contains(network.getEdgeTarget(e));
  return network.edgeSet().stream().filter(predicate).collect(
    Collectors.toCollection(LinkedHashSet::new));
}

代码示例来源:origin: org.jgrapht/jgrapht-io

private void exportAsEdgeList(Graph<V, E> g, PrintWriter out)
{
  boolean exportEdgeWeights = parameters.contains(CSVFormat.Parameter.EDGE_WEIGHTS);
  for (E e : g.edgeSet()) {
    exportEscapedField(out, vertexIDProvider.getName(g.getEdgeSource(e)));
    out.print(delimiter);
    exportEscapedField(out, vertexIDProvider.getName(g.getEdgeTarget(e)));
    if (exportEdgeWeights) {
      out.print(delimiter);
      exportEscapedField(out, String.valueOf(g.getEdgeWeight(e)));
    }
    out.println();
  }
}

代码示例来源:origin: openimaj/openimaj

/**
 * Calculate the density of the graph as the
 * number of edges divided by the number of vertices
 * @param g the graph
 * @return the density
 */
public static double calculateDensity(Graph<?,?> g) {
  return (double)g.edgeSet().size() / (double)g.vertexSet().size();
}

代码示例来源:origin: org.jgrapht/jgrapht-core

/**
 * {@inheritDoc}
 */
@Override
protected Iterable<V> getVertexOrdering()
{
  List<V> order = new ArrayList<V>(graph.vertexSet());
  Collections.shuffle(order, rng);
  return order;
}

代码示例来源:origin: org.jgrapht/jgrapht-core

/**
   * Returns a set of vertices that are neighbors of the source of the specified edge or of the
   * target of specified edge. The endpoints of the specified edge aren't included in the result.
   *
   * @param g the graph to look for neighbors in
   * @param edge the edge to get the neighbors of
   * @return a set of vertices that are neighbors of at least one endpoint of the specified edge.
   *         The endpoints of the specified edge aren't included in the result
   */
  private Set<V> neighborhoodSetOf(Graph<V, E> g, E edge)
  {
    Set<V> neighborhood = new HashSet<>();

    V source = g.getEdgeSource(edge);
    V target = g.getEdgeTarget(edge);

    for (E e : g.edgesOf(source)) {
      neighborhood.add(Graphs.getOppositeVertex(g, e, source));
    }
    for (E e : g.edgesOf(target)) {
      neighborhood.add(Graphs.getOppositeVertex(g, e, target));
    }
    neighborhood.remove(source);
    neighborhood.remove(target);

    return neighborhood;
  }
}

代码示例来源:origin: org.jgrapht/jgrapht-core

/**
   * {@inheritDoc}
   */
  @Override
  public void generateGraph(Graph<V, E> target, Map<String, V> resultMap)
  {
    for (int i = 0; i < size; ++i) {
      target.addVertex();
    }
  }
}

代码示例来源:origin: cwensel/cascading

private static <V, E> Graph<V, E> disconnectExtentsAndExclude( Graph<V, E> full, Set<E> withoutEdges )
 {
 IdentityMultiGraphGraph<V, E> copy = (IdentityMultiGraphGraph<V, E>) new IdentityMultiGraphGraph<>( Object.class );
 Graphs.addAllVertices( copy, full.vertexSet() );
 copy.removeVertex( (V) Extent.head );
 copy.removeVertex( (V) Extent.tail );
 Set<E> edges = full.edgeSet();
 if( !withoutEdges.isEmpty() )
  {
  edges = new HashSet<>( edges );
  edges.removeAll( withoutEdges );
  }
 Graphs.addAllEdges( copy, full, edges );
 return copy;
 }

代码示例来源:origin: org.jgrapht/jgrapht-core

@Override
public E getEdgeCorrespondence(E currEdge, boolean forward)
{
  Graph<V, E> sourceGraph, targetGraph;
  if (forward) {
    sourceGraph = this.graph1;
    targetGraph = this.graph2;
  } else {
    sourceGraph = this.graph2;
    targetGraph = this.graph1;
  }
  V mappedSourceVertex =
    getVertexCorrespondence(sourceGraph.getEdgeSource(currEdge), forward);
  V mappedTargetVertex =
    getVertexCorrespondence(sourceGraph.getEdgeTarget(currEdge), forward);
  if ((mappedSourceVertex == null) || (mappedTargetVertex == null)) {
    return null;
  } else {
    return targetGraph.getEdge(mappedSourceVertex, mappedTargetVertex);
  }
}

代码示例来源:origin: cwensel/cascading

public Scope addEdge( FlowElement sourceVertex, FlowElement targetVertex )
  {
//     prevent multiple edges from head or to tail
  if( !allowMultipleExtentEdges() && ( sourceVertex == Extent.head || targetVertex == Extent.tail ) && graph.containsEdge( sourceVertex, targetVertex ) )
   return graph.getEdge( sourceVertex, targetVertex );

  return graph.addEdge( sourceVertex, targetVertex );
  }

代码示例来源:origin: org.jgrapht/jgrapht-core

/**
 * Construct a new Brown backtracking algorithm.
 * 
 * @param graph the input graph
 */
public BrownBacktrackColoring(Graph<V, E> graph)
{
  Objects.requireNonNull(graph, "Graph cannot be null");
  final int numVertices = graph.vertexSet().size();
  vertexList = new ArrayList<>(numVertices);
  neighbors = new int[numVertices][];
  indexMap = new HashMap<>(numVertices);
  for (V vertex : graph.vertexSet()) {
    neighbors[vertexList.size()] = new int[graph.edgesOf(vertex).size()];
    indexMap.put(vertex, vertexList.size());
    vertexList.add(vertex);
  }
  for (int i = 0; i < numVertices; i++) {
    int nbIndex = 0;
    final V vertex = vertexList.get(i);
    for (E e : graph.edgesOf(vertex)) {
      neighbors[i][nbIndex++] = indexMap.get(Graphs.getOppositeVertex(graph, e, vertex));
    }
  }
}

代码示例来源:origin: org.jgrapht/jgrapht-io

private void exportAdjacencyMatrix(Graph<V, E> g, Writer writer)
{
  for (V from : g.vertexSet()) {
    // assign ids in vertex set iteration order
    vertexIDProvider.getName(from);
  }
  PrintWriter out = new PrintWriter(writer);
  if (g.getType().isDirected()) {
    for (V from : g.vertexSet()) {
      exportAdjacencyMatrixVertex(out, from, Graphs.successorListOf(g, from));
    }
  } else {
    for (V from : g.vertexSet()) {
      exportAdjacencyMatrixVertex(out, from, Graphs.neighborListOf(g, from));
    }
  }
  out.flush();
}

代码示例来源:origin: org.jgrapht/jgrapht-io

private void exportAsAdjacencyList(Graph<V, E> g, PrintWriter out)
{
  boolean exportEdgeWeights = parameters.contains(CSVFormat.Parameter.EDGE_WEIGHTS);
  for (V v : g.vertexSet()) {
    exportEscapedField(out, vertexIDProvider.getName(v));
    for (E e : g.outgoingEdgesOf(v)) {
      V w = Graphs.getOppositeVertex(g, e, v);
      out.print(delimiter);
      exportEscapedField(out, vertexIDProvider.getName(w));
      if (exportEdgeWeights) {
        out.print(delimiter);
        exportEscapedField(out, String.valueOf(g.getEdgeWeight(e)));
      }
    }
    out.println();
  }
}

相关文章