Пример #1
0
  private Graph condense(Graph mimStructure, Graph mimbuildStructure) {
    //        System.out.println("Uncondensed: " + mimbuildStructure);

    Map<Node, Node> substitutions = new HashMap<Node, Node>();

    for (Node node : mimbuildStructure.getNodes()) {
      for (Node _node : mimStructure.getNodes()) {
        if (node.getName().startsWith(_node.getName())) {
          substitutions.put(node, _node);
          break;
        }

        substitutions.put(node, node);
      }
    }

    HashSet<Node> nodes = new HashSet<Node>(substitutions.values());
    Graph graph = new EdgeListGraph(new ArrayList<Node>(nodes));

    for (Edge edge : mimbuildStructure.getEdges()) {
      Node node1 = substitutions.get(edge.getNode1());
      Node node2 = substitutions.get(edge.getNode2());

      if (node1 == node2) continue;

      if (graph.isAdjacentTo(node1, node2)) continue;

      graph.addEdge(new Edge(node1, node2, edge.getEndpoint1(), edge.getEndpoint2()));
    }

    //        System.out.println("Condensed: " + graph);

    return graph;
  }
Пример #2
0
  private void checkGetPathsArgs(Graph<E> graph, E source, E destination) {
    if (graph == null) {
      throw new NullPointerException("graph is null");
    }

    if (source == null) {
      throw new NullPointerException("source is null");
    }

    if (destination == null) {
      throw new NullPointerException("destination is null");
    }

    if (source.equals(destination)) {
      throw new IllegalArgumentException("source is equal to destination");
    }

    if (!graph.getNodes().contains(source)) {
      throw new IllegalArgumentException("source not found");
    }

    if (!graph.getNodes().contains(destination)) {
      throw new IllegalArgumentException("destination not found");
    }
  }
Пример #3
0
  /**
   * Execute Dijkstra's algorithm on the given graph to find the shortest path from {@code
   * sourceNode} to {@code destinationNode}. The length of the path is defined as the sum of the
   * edge weights, which are provided in the edge file. Every time the algorithm pulls a node into
   * the cloud, call {@link Logger#movedCharacter(String, String)} with the name {@link
   * #PATH_CHARACTER} and the location equal to the new cloud node. Every time the algorithm uses an
   * edge to relax the known distances to a node <b>which is not yet in the cloud</b>, call {@link
   * Logger#traversedEdge(String, String, String)} with the tag {@link #DIJKSTRA_TAG}, the node just
   * pulled into the cloud as the second argument, and the node whose known distance may be relaxed
   * as the third argument. Do this even if the known distance to the node doesn't decrease. For
   * testing purposes run the algorithm until all nodes are in the cloud and be sure to relax the
   * edges using alphabetical ordering of the nodes.
   *
   * @return the sequence of node GUIDs of the shortest path found, or null if there is no such path
   */
  public List<Graph.Node> dijkstra(Graph.Node sourceNode, Graph.Node destinationNode) {
    HashMap<Graph.Node, Double> dist = new HashMap<Graph.Node, Double>();
    HashMap<Graph.Node, Graph.Node> previous = new HashMap<Graph.Node, Graph.Node>();

    for (Graph.Node node : g.getNodes()) {
      dist.put(node, Double.POSITIVE_INFINITY);
      previous.put(node, null);
    }
    dist.put(sourceNode, 0.0);
    Set<Graph.Node> nodes = g.getNodes();
    while (!nodes.isEmpty()) {
      Graph.Node current = closest(nodes, dist);
      if (dist.get(current) == Double.POSITIVE_INFINITY) break;
      nodes.remove(current);
      if (current == destinationNode) {
        List<Graph.Node> sequence = new ArrayList<Graph.Node>();
        while (previous.get(current) != null) {
          sequence.add(current);
          current = previous.get(current);
        }
        sequence.add(sourceNode);
        Collections.reverse(sequence);
        return sequence;
      }
      for (Graph.Node neighbor : current.getNeighbors().keySet()) {
        double alt = dist.get(current) + current.getNeighbors().get(neighbor);
        if (alt < dist.get(neighbor)) {
          dist.put(neighbor, alt);
          previous.put(neighbor, current);
        }
      }
    }
    return new ArrayList<Graph.Node>();
  }
Пример #4
0
  public Graph orient() {
    Graph skeleton = GraphUtils.undirectedGraph(getPattern());
    Graph graph = new EdgeListGraph(skeleton.getNodes());

    List<Node> nodes = skeleton.getNodes();
    //        Collections.shuffle(nodes);

    if (isR1Done()) {
      ruleR1(skeleton, graph, nodes);
    }

    for (Edge edge : skeleton.getEdges()) {
      if (!graph.isAdjacentTo(edge.getNode1(), edge.getNode2())) {
        graph.addUndirectedEdge(edge.getNode1(), edge.getNode2());
      }
    }

    if (isR2Done()) {
      ruleR2(skeleton, graph);
    }

    if (isMeekDone()) {
      new MeekRules().orientImplied(graph);
    }

    return graph;
  }
Пример #5
0
  // Cannot be done if the graph changes.
  public void setInitialGraph(Graph initialGraph) {
    initialGraph = GraphUtils.replaceNodes(initialGraph, variables);

    out.println("Initial graph variables: " + initialGraph.getNodes());
    out.println("Data set variables: " + variables);

    if (!new HashSet<Node>(initialGraph.getNodes()).equals(new HashSet<Node>(variables))) {
      throw new IllegalArgumentException("Variables aren't the same.");
    }

    this.initialGraph = initialGraph;
  }
Пример #6
0
  static boolean hasRoute(Graph g, Node a, Node b) {
    LinkedList<Node> q = new LinkedList<Node>();
    for (Node u : g.getNodes()) { // set all nodes unvisited
      u.state = State.unvisited;
    }

    a.state = State.visiting; // set the start node a visiting
    q.add(a); // add a to list q
    Node u;
    while (!q.isEmpty()) {
      u = q.removeFirst();
      if (u != null) {
        for (Node v : u.getAdjacent()) {
          if (v.state == State.unvisited) {
            if (v == b) return true;
            else {
              v.state = State.visiting;
              q.add(v);
            }
          }
        }
        u.state = State.visiting;
      }
    }
    return false;
  }
Пример #7
0
  /**
   * @param type
   * @return a map whose keys are the values corresponding to nodes of type 'type' and the values
   *     are the number of them
   */
  private Map<String, Integer> extractNodes(NodeType type) {
    Map<String, Integer> resultNodes = new HashMap<String, Integer>();

    List<ISANode> node = graph.getNodes(type);

    for (ISANode nodeOfInterest : node) {
      // extract the values!
      for (int rowIndex = 1; rowIndex < assayTable.length; rowIndex++) {
        if (nodeOfInterest.getIndex() < assayTable[rowIndex].length) {

          String[] row =
              Arrays.copyOf(assayTable[rowIndex], assayTable[rowIndex].length, String[].class);
          String value = row[nodeOfInterest.getIndex()];
          if (value != null && !value.equals("")) {
            if (!resultNodes.containsKey(value)) {
              resultNodes.put(value, 1);
            } else {
              int newCount = resultNodes.get(value) + 1;
              resultNodes.put(value, newCount);
            }
          }
        }
      }
    }

    return resultNodes;
  }
Пример #8
0
  public TimeLagGraphWrapper(GraphWrapper graphWrapper) {
    if (graphWrapper == null) {
      throw new NullPointerException("No graph wrapper.");
    }

    TimeLagGraph graph = new TimeLagGraph();

    Graph _graph = graphWrapper.getGraph();

    for (Node node : _graph.getNodes()) {
      Node _node = node.like(node.getName() + ":0");
      _node.setNodeType(node.getNodeType());
      graph.addNode(_node);
    }

    for (Edge edge : _graph.getEdges()) {
      if (!Edges.isDirectedEdge(edge)) {
        throw new IllegalArgumentException();
      }

      Node from = edge.getNode1();
      Node to = edge.getNode2();

      Node _from = graph.getNode(from.getName(), 1);
      Node _to = graph.getNode(to.getName(), 0);

      graph.addDirectedEdge(_from, _to);
    }

    this.graph = graph;
  }
Пример #9
0
  /** Method coolectPatternNodesToBeKeptInfo */
  private void collectPatternNodesToBeKeptInfo() {
    patternNodeIsToBeKept = new int[n_graph_actions][max_n_pattern_nodes];

    // init the arrays with -1
    for (int i = 0; i < n_graph_actions; i++)
      for (int j = 0; j < max_n_pattern_nodes; j++) patternNodeIsToBeKept[i][j] = -1;

    // for all nodes to be kept set the corresponding array entry to the
    // appropriate replacement node number
    for (Rule action : actionRuleMap.keySet()) {
      int act_id = actionRuleMap.get(action).intValue();

      // compute the set of pattern nodes to be kept for this action
      Collection<Node> pattern_nodes_to_keep = new HashSet<Node>();
      pattern_nodes_to_keep.addAll(action.getPattern().getNodes());
      if (action.getRight() != null) {
        Graph replacement = action.getRight();
        pattern_nodes_to_keep.retainAll(replacement.getNodes());
        // iterate over the pattern nodes to be kept and store their
        // corresponding replacement node number
        for (Node node : pattern_nodes_to_keep) {
          int node_num = pattern_node_num.get(act_id).get(node).intValue();
          patternNodeIsToBeKept[act_id][node_num] =
              replacement_node_num.get(act_id).get(node).intValue();
        }
      }
    }
  }
Пример #10
0
  // ===========================SCORING METHODS===================//
  public double scoreDag(Graph graph) {
    Graph dag = new EdgeListGraphSingleConnections(graph);
    buildIndexing(graph);

    double score = 0.0;

    for (Node y : dag.getNodes()) {
      Set<Node> parents = new HashSet<Node>(dag.getParents(y));
      int nextIndex = -1;
      for (int i = 0; i < getVariables().size(); i++) {
        nextIndex = hashIndices.get(variables.get(i));
      }
      int parentIndices[] = new int[parents.size()];
      Iterator<Node> pi = parents.iterator();
      int count = 0;
      while (pi.hasNext()) {
        Node nextParent = pi.next();
        parentIndices[count++] = hashIndices.get(nextParent);
      }

      if (this.isDiscrete()) {
        score += localDiscreteScore(nextIndex, parentIndices);
      } else {
        score += localSemScore(nextIndex, parentIndices);
      }
    }
    return score;
  }
Пример #11
0
  ////////////////////////////////////////////////
  // collect in rTupleList all unshielded tuples
  ////////////////////////////////////////////////
  private List<Node[]> getRTuples() {
    List<Node[]> rTuples = new ArrayList<Node[]>();
    List<Node> nodes = graph.getNodes();

    for (Node j : nodes) {
      List<Node> adjacentNodes = graph.getAdjacentNodes(j);

      if (adjacentNodes.size() < 2) {
        continue;
      }

      ChoiceGenerator cg = new ChoiceGenerator(adjacentNodes.size(), 2);
      int[] combination;

      while ((combination = cg.next()) != null) {
        Node i = adjacentNodes.get(combination[0]);
        Node k = adjacentNodes.get(combination[1]);

        // Skip triples that are shielded.
        if (!graph.isAdjacentTo(i, k)) {
          Node[] newTuple = {i, j, k};
          rTuples.add(newTuple);
        }
      }
    }

    return (rTuples);
  }
Пример #12
0
  private Graph changeLatentNames(Graph full, Clusters measurements, List<String> latentVarList) {
    Graph g2 = null;

    try {
      g2 = (Graph) new MarshalledObject(full).get();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }

    for (int i = 0; i < measurements.getNumClusters(); i++) {
      List<String> d = measurements.getCluster(i);
      String latentName = latentVarList.get(i);

      for (Node node : full.getNodes()) {
        if (!(node.getNodeType() == NodeType.LATENT)) {
          continue;
        }

        List<Node> _children = full.getChildren(node);

        _children.removeAll(ReidentifyVariables.getLatents(full));

        List<String> childNames = getNames(_children);

        if (new HashSet<String>(childNames).equals(new HashSet<String>(d))) {
          g2.getNode(node.getName()).setName(latentName);
        }
      }
    }

    return g2;
  }
Пример #13
0
  public List<Triple> getUnshieldedCollidersFromGraph(Graph graph) {
    List<Triple> colliders = new ArrayList<>();

    List<Node> nodes = graph.getNodes();

    for (Node b : nodes) {
      List<Node> adjacentNodes = graph.getAdjacentNodes(b);

      if (adjacentNodes.size() < 2) {
        continue;
      }

      ChoiceGenerator cg = new ChoiceGenerator(adjacentNodes.size(), 2);
      int[] combination;

      while ((combination = cg.next()) != null) {
        Node a = adjacentNodes.get(combination[0]);
        Node c = adjacentNodes.get(combination[1]);

        // Skip triples that are shielded.
        if (graph.isAdjacentTo(a, c)) {
          continue;
        }

        if (graph.isDefCollider(a, b, c)) {
          colliders.add(new Triple(a, b, c));
        }
      }
    }

    return colliders;
  }
  /**
   * Double checks a sepset map against a pattern to make sure that X is adjacent to Y in the
   * pattern iff {X, Y} is not in the domain of the sepset map.
   *
   * @param sepset a sepset map, over variables V.
   * @param pattern a pattern over variables W, V subset of W.
   * @return true if the sepset map is consistent with the pattern.
   */
  public static boolean verifySepsetIntegrity(SepsetMap sepset, Graph pattern) {
    for (Node x : pattern.getNodes()) {
      for (Node y : pattern.getNodes()) {
        if (x == y) {
          continue;
        }

        if ((pattern.isAdjacentTo(y, x)) != (sepset.get(x, y) == null)) {
          System.out.println("Sepset not consistent with graph for {" + x + ", " + y + "}");
          return false;
        }
      }
    }

    return true;
  }
Пример #15
0
 public static void main(String a[]) {
   Graph g = createNewGraph();
   Node[] n = g.getNodes();
   Node start = n[3];
   Node end = n[5];
   System.out.println(n[3].data);
   System.out.println(hasRoute(g, start, end));
 }
  /**
   * Transforms a maximally directed pattern (PDAG) represented in graph <code>g</code> into an
   * arbitrary DAG by modifying <code>g</code> itself. Based on the algorithm described in
   * Chickering (2002) "Optimal structure identification with greedy search" Journal of Machine
   * Learning Research. R. Silva, June 2004
   */
  public static void pdagToDag(Graph g) {
    Graph p = new EdgeListGraph(g);
    List<Edge> undirectedEdges = new ArrayList<Edge>();

    for (Edge edge : g.getEdges()) {
      if (edge.getEndpoint1() == Endpoint.TAIL
          && edge.getEndpoint2() == Endpoint.TAIL
          && !undirectedEdges.contains(edge)) {
        undirectedEdges.add(edge);
      }
    }
    g.removeEdges(undirectedEdges);
    List<Node> pNodes = p.getNodes();

    do {
      Node x = null;

      for (Node pNode : pNodes) {
        x = pNode;

        if (p.getChildren(x).size() > 0) {
          continue;
        }

        Set<Node> neighbors = new HashSet<Node>();

        for (Edge edge : p.getEdges()) {
          if (edge.getNode1() == x || edge.getNode2() == x) {
            if (edge.getEndpoint1() == Endpoint.TAIL && edge.getEndpoint2() == Endpoint.TAIL) {
              if (edge.getNode1() == x) {
                neighbors.add(edge.getNode2());
              } else {
                neighbors.add(edge.getNode1());
              }
            }
          }
        }
        if (neighbors.size() > 0) {
          Collection<Node> parents = p.getParents(x);
          Set<Node> all = new HashSet<Node>(neighbors);
          all.addAll(parents);
          if (!GraphUtils.isClique(all, p)) {
            continue;
          }
        }

        for (Node neighbor : neighbors) {
          Node node1 = g.getNode(neighbor.getName());
          Node node2 = g.getNode(x.getName());

          g.addDirectedEdge(node1, node2);
        }
        p.removeNode(x);
        break;
      }
      pNodes.remove(x);
    } while (pNodes.size() > 0);
  }
Пример #17
0
  /**
   * Step C of PC; orients colliders using specified sepset. That is, orients x *-* y *-* z as x *->
   * y <-* z just in case y is in Sepset({x, z}).
   */
  public Map<Triple, Double> findCollidersUsingSepsets(
      SepsetProducer sepsetProducer, Graph graph, boolean verbose, IKnowledge knowledge) {
    TetradLogger.getInstance().log("details", "Starting Collider Orientation:");
    Map<Triple, Double> colliders = new HashMap<>();

    System.out.println("Looking for colliders");

    List<Node> nodes = graph.getNodes();

    for (Node b : nodes) {
      List<Node> adjacentNodes = graph.getAdjacentNodes(b);

      if (adjacentNodes.size() < 2) {
        continue;
      }

      ChoiceGenerator cg = new ChoiceGenerator(adjacentNodes.size(), 2);
      int[] combination;

      while ((combination = cg.next()) != null) {
        Node a = adjacentNodes.get(combination[0]);
        Node c = adjacentNodes.get(combination[1]);

        // Skip triples that are shielded.
        if (graph.isAdjacentTo(a, c)) {
          continue;
        }

        List<Node> sepset = sepsetProducer.getSepset(a, c);

        if (sepset == null) continue;

        //                if (sepsetProducer.getPValue() < 0.5) continue;

        if (!sepset.contains(b)) {
          if (verbose) {
            //                        boolean dsep = this.dsep.isIndependent(a, c);
            //                        System.out.println("QQQ p = " + independenceTest.getPValue() +
            // " " + dsep);

            System.out.println(
                "\nCollider orientation <" + a + ", " + b + ", " + c + "> sepset = " + sepset);
          }

          colliders.put(new Triple(a, b, c), sepsetProducer.getPValue());

          TetradLogger.getInstance()
              .log("colliderOrientations", SearchLogUtils.colliderOrientedMsg(a, b, c, sepset));
        }
      }
    }

    TetradLogger.getInstance().log("details", "Finishing Collider Orientation.");

    System.out.println("Done finding colliders");

    return colliders;
  }
  public static boolean meekR1Locally2(
      Graph graph, Knowledge knowledge, IndependenceTest test, int depth) {
    List<Node> nodes = graph.getNodes();
    boolean changed = true;

    while (changed) {
      changed = false;

      for (Node a : nodes) {
        List<Node> adjacentNodes = graph.getAdjacentNodes(a);

        if (adjacentNodes.size() < 2) {
          continue;
        }

        ChoiceGenerator cg = new ChoiceGenerator(adjacentNodes.size(), 2);
        int[] combination;

        while ((combination = cg.next()) != null) {
          Node b = adjacentNodes.get(combination[0]);
          Node c = adjacentNodes.get(combination[1]);

          // Skip triples that are shielded.
          if (graph.isAdjacentTo(b, c)) {
            continue;
          }

          if (graph.getEndpoint(b, a) == Endpoint.ARROW && graph.isUndirectedFromTo(a, c)) {
            if (existsLocalSepsetWithoutDet(b, a, c, test, graph, depth)) {
              continue;
            }

            if (isArrowpointAllowed(a, c, knowledge)) {
              graph.setEndpoint(a, c, Endpoint.ARROW);
              TetradLogger.getInstance()
                  .edgeOriented(SearchLogUtils.edgeOrientedMsg("Meek R1", graph.getEdge(a, c)));
              changed = true;
            }
          } else if (graph.getEndpoint(c, a) == Endpoint.ARROW && graph.isUndirectedFromTo(a, b)) {
            if (existsLocalSepsetWithoutDet(b, a, c, test, graph, depth)) {
              continue;
            }

            if (isArrowpointAllowed(a, b, knowledge)) {
              graph.setEndpoint(a, b, Endpoint.ARROW);
              TetradLogger.getInstance()
                  .edgeOriented(SearchLogUtils.edgeOrientedMsg("Meek R1", graph.getEdge(a, b)));
              changed = true;
            }
          }
        }
      }
    }

    return changed;
  }
  /**
   * Performs step C of the algorithm, as indicated on page xxx of CPS, with the modification that
   * X--W--Y is oriented as X-->W<--Y if W is *determined by* the sepset of (X, Y), rather than W
   * just being *in* the sepset of (X, Y).
   */
  public static void pcdOrientC(
      SepsetMap set, IndependenceTest test, Knowledge knowledge, Graph graph) {
    TetradLogger.getInstance().log("info", "Staring Collider Orientation:");

    List<Node> nodes = graph.getNodes();

    for (Node y : nodes) {
      List<Node> adjacentNodes = graph.getAdjacentNodes(y);

      if (adjacentNodes.size() < 2) {
        continue;
      }

      ChoiceGenerator cg = new ChoiceGenerator(adjacentNodes.size(), 2);
      int[] combination;

      while ((combination = cg.next()) != null) {
        Node x = adjacentNodes.get(combination[0]);
        Node z = adjacentNodes.get(combination[1]);

        // Skip triples that are shielded.
        if (graph.isAdjacentTo(x, z)) {
          continue;
        }

        List<Node> sepset = set.get(x, z);

        if (sepset == null) {
          continue;
        }

        List<Node> augmentedSet = new LinkedList<Node>(sepset);
        augmentedSet.add(y);

        if (test.determines(sepset, y)) {
          continue;
        }
        //
        if (!test.splitDetermines(sepset, x, z) && test.splitDetermines(augmentedSet, x, z)) {
          continue;
        }

        if (!isArrowpointAllowed(x, y, knowledge) || !isArrowpointAllowed(z, y, knowledge)) {
          continue;
        }

        graph.setEndpoint(x, y, Endpoint.ARROW);
        graph.setEndpoint(z, y, Endpoint.ARROW);

        TetradLogger.getInstance()
            .log("colliderOriented", SearchLogUtils.colliderOrientedMsg(x, y, z));
      }
    }

    TetradLogger.getInstance().log("info", "Finishing Collider Orientation.");
  }
 public static int getIdOf(Graph g, double latitude) {
   int s = g.getNodes();
   NodeAccess na = g.getNodeAccess();
   for (int i = 0; i < s; i++) {
     if (Math.abs(na.getLatitude(i) - latitude) < 1e-4) {
       return i;
     }
   }
   return -1;
 }
Пример #21
0
  public static GraphOrder forwardGraph(Graph graph) {
    GraphOrder result = new GraphOrder();

    NodeBitMap visited = graph.createNodeBitMap();

    for (ControlSinkNode node : graph.getNodes(ControlSinkNode.class)) {
      result.visitForward(visited, node);
    }
    return result;
  }
  /** Meek's rule R3. If a--b, a--c, a--d, c-->b, c-->b, then orient a-->b. */
  public static boolean meekR3(Graph graph, Knowledge knowledge) {

    List<Node> nodes = graph.getNodes();
    boolean changed = false;

    for (Node a : nodes) {
      List<Node> adjacentNodes = graph.getAdjacentNodes(a);

      if (adjacentNodes.size() < 3) {
        continue;
      }

      for (Node b : adjacentNodes) {
        List<Node> otherAdjacents = new LinkedList<Node>(adjacentNodes);
        otherAdjacents.remove(b);

        if (!graph.isUndirectedFromTo(a, b)) {
          continue;
        }

        ChoiceGenerator cg = new ChoiceGenerator(otherAdjacents.size(), 2);
        int[] combination;

        while ((combination = cg.next()) != null) {
          Node c = otherAdjacents.get(combination[0]);
          Node d = otherAdjacents.get(combination[1]);

          if (graph.isAdjacentTo(c, d)) {
            continue;
          }

          if (!graph.isUndirectedFromTo(a, c)) {
            continue;
          }

          if (!graph.isUndirectedFromTo(a, d)) {
            continue;
          }

          if (graph.isDirectedFromTo(c, b) && graph.isDirectedFromTo(d, b)) {
            if (isArrowpointAllowed(a, b, knowledge)) {
              graph.setEndpoint(a, b, Endpoint.ARROW);
              TetradLogger.getInstance()
                  .edgeOriented(SearchLogUtils.edgeOrientedMsg("Meek R3", graph.getEdge(a, b)));
              changed = true;
              break;
            }
          }
        }
      }
    }

    return changed;
  }
Пример #23
0
  private Graph structure(Graph mim) {
    List<Node> latents = new ArrayList<Node>();

    for (Node node : mim.getNodes()) {
      if (node.getNodeType() == NodeType.LATENT) {
        latents.add(node);
      }
    }

    return mim.subgraph(latents);
  }
Пример #24
0
  private Graph restrictToEmpiricalLatents(Graph mimStructure, Graph mimbuildStructure) {
    Graph _mim = new EdgeListGraph(mimStructure);

    for (Node node : mimbuildStructure.getNodes()) {
      if (!mimbuildStructure.containsNode(node)) {
        _mim.removeNode(node);
      }
    }

    return _mim;
  }
 /** Validate that each node has been colored and connected nodes have different coloring. */
 private static <N, E> void validateColoring(Graph<N, E> graph) {
   for (GraphNode<N, E> node : graph.getNodes()) {
     assertNotNull(node.getAnnotation());
   }
   for (GraphEdge<N, E> edge : graph.getEdges()) {
     Color c1 = edge.getNodeA().getAnnotation();
     Color c2 = edge.getNodeB().getAnnotation();
     assertNotNull(c1);
     assertNotNull(c2);
     assertThat(c1.equals(c2)).isFalse();
   }
 }
Пример #26
0
  private void checkFindPathArgs(Graph<E> graph, E source) {
    if (graph == null) {
      throw new NullPointerException("graph is null");
    }

    if (source == null) {
      throw new NullPointerException("source is null");
    }

    if (!graph.getNodes().contains(source)) {
      throw new IllegalArgumentException("source not found");
    }
  }
  public static void arrangeByKnowledgeTiers(Graph graph, Knowledge knowledge) {
    if (knowledge.getNumTiers() == 0) {
      throw new IllegalArgumentException("There are no Tiers to arrange.");
    }

    List<Node> nodes = graph.getNodes();
    List<String> varNames = new ArrayList<String>();
    int ySpace = 500 / knowledge.getNumTiers();
    ySpace = ySpace < 50 ? 50 : ySpace;

    for (Node node1 : nodes) {
      varNames.add(node1.getName());
    }

    List<String> notInTier = knowledge.getVarsNotInTier(varNames);

    int x = 0;
    int y = 50 - ySpace;

    if (notInTier.size() > 0) {
      y += ySpace;

      for (String name : notInTier) {
        x += 90;
        Node node = graph.getNode(name);

        if (node != null) {
          node.setCenterX(x);
          node.setCenterY(y);
        }
      }
    }

    for (int i = 0; i < knowledge.getNumTiers(); i++) {
      List<String> tier = knowledge.getTier(i);
      y += ySpace;
      x = -25;

      for (String name : tier) {
        x += 90;
        Node node = graph.getNode(name);

        if (node != null) {
          node.setCenterX(x);
          node.setCenterY(y);
        }
      }
    }
  }
Пример #28
0
  private static double characteristicPathLength(Graph g) {
    List<Node> nodes = g.getNodes();
    int total = 0;
    int count = 0;

    for (int i = 0; i < nodes.size(); i++) {
      for (int j = i; j < nodes.size(); j++) {
        int shortest = shortestPath(nodes.get(i), nodes.get(j), g);
        total += shortest;
        count++;
      }
    }

    return total / (double) count;
  }
Пример #29
0
  public HashMap<Graph.Node, Double> dijkstra2(Graph.Node sourceNode, Graph.Node destinationNode) {
    HashMap<Graph.Node, Double> dist = new HashMap<Graph.Node, Double>();
    HashMap<Graph.Node, Graph.Node> previous = new HashMap<Graph.Node, Graph.Node>();

    for (Graph.Node node : g.getNodes()) {
      dist.put(node, Double.POSITIVE_INFINITY);
      previous.put(node, null);
    }
    dist.put(sourceNode, 0.0);
    Set<Graph.Node> nodes = g.getNodes();
    while (!nodes.isEmpty()) {
      Graph.Node current = closest(nodes, dist);
      if (dist.get(current) == Double.POSITIVE_INFINITY) break;
      nodes.remove(current);
      for (Graph.Node neighbor : current.getNeighbors().keySet()) {
        double alt = dist.get(current) + current.getNeighbors().get(neighbor);
        if (alt < dist.get(current)) {
          dist.put(neighbor, alt);
          previous.put(neighbor, current);
        }
      }
    }
    return dist;
  }
Пример #30
0
  public void testAlternativeGraphs() {

    //        UniformGraphGenerator gen = new UniformGraphGenerator(UniformGraphGenerator.ANY_DAG);
    //        gen.setNumNodes(100);
    //        gen.setMaxEdges(200);
    //        gen.setMaxDegree(30);
    //        gen.setMaxInDegree(30);
    //        gen.setMaxOutDegree(30);
    ////        gen.setNumIterations(3000000);
    //        gen.setResamplingDegree(10);
    //
    //        gen.generate();
    //
    //        Graph graph = gen.getDag();

    Graph graph = weightedRandomGraph(250, 400);

    List<Integer> degreeCounts = new ArrayList<Integer>();
    Map<Integer, Integer> degreeCount = new HashMap<Integer, Integer>();

    for (Node node : graph.getNodes()) {
      int degree = graph.getNumEdges(node);
      degreeCounts.add(degree);

      if (degreeCount.get(degree) == null) {
        degreeCount.put(degree, 0);
      }

      degreeCount.put(degree, degreeCount.get(degree) + 1);
    }

    Collections.sort(degreeCounts);
    System.out.println(degreeCounts);
    List<Integer> _degrees = new ArrayList<Integer>(degreeCount.keySet());
    Collections.sort(_degrees);

    for (int i : _degrees) {
      int j = degreeCount.get(i);
      //            System.out.println(i + " " + j);
      System.out.println(log(i + 1) + " " + log(j));
    }

    System.out.println("\nCPL = " + characteristicPathLength(graph));

    Graph erGraph = erdosRenyiGraph(200, 200);
    System.out.println("\n ER CPL = " + characteristicPathLength(erGraph));
  }