Example #1
0
  /**
   * Recursive DFS algorthm
   *
   * @param matrix Map of lists representing adj matrix
   * @param info Map of nodes representing node info
   * @param v Node source
   * @param n int number of nodes in graph
   * @param: print boolean if to print node during traversal
   * @return List of nodes in order visited
   */
  public ArrayList<String> dfs_rec(
      Map<Integer, List<Integer>> matrix,
      Map<Integer, GraphNode> info,
      GraphNode v,
      Integer n,
      boolean print,
      ArrayList<String> ops) {
    v.setVisited(true);
    if (print) System.out.println(v);
    ops.add(v.toString());

    //        if(checkStoppingCondition(v, getN())) {
    //            return;
    //        }

    List<Integer> edgeTarget = matrix.get(v.getID());

    for (int i = 0; i < edgeTarget.size(); ++i) {
      if (edgeTarget.get(i) == 1) {
        GraphNode node = info.get(i + 1);
        if (!node.getVisited()) {
          return dfs_rec(matrix, info, node, n, print, ops);
        }
      }
    }
    return ops;
  }
Example #2
0
  public static void saveGraph(Graph g, File f) throws FileNotFoundException, SecurityException {
    ArrayList<GraphEdge> edgemarks = new ArrayList<GraphEdge>();

    PrintStream p = new PrintStream(new FileOutputStream(f));
    try {
      Iterator<GraphNode> n = g.getNodeIterator();
      int count = 1;
      while (n.hasNext()) {
        GraphNode node = n.next();
        ListIterator<GraphEdge> e = node.getEdgeIterator();
        while (e.hasNext()) {
          GraphEdge edge = e.next();
          if (g.getNodeById(edge.getTarget().getId()) == null) {
            e.remove();
            continue;
          }
          if (!edgemarks.contains(edge))
            p.println(
                ""
                    + (node.getId() + 1)
                    + " "
                    + (edge.getTarget().getId() + 1)
                    + " "
                    + edge.getWeight());
          edgemarks.add(edge.getTarget().getEdgeByTargetId(node.getId()));
          edgemarks.add(edge);
        }
        if (count % 100 == 0) System.out.println("Saving. . ." + count++);
      }
    } finally {
      p.close();
    }
  }
  /**
   * 利用广度优先搜索进行路径判断 p -> q 是否有路径
   *
   * @return
   */
  private static boolean pathOrderCheckBFS(GraphNode<Integer> p, GraphNode<Integer> q) {
    IQueue<GraphNode<Integer>> queue = new Queue<GraphNode<Integer>>();

    if (!p.visited && p.equals(q)) {
      return true;
    }

    p.visited = true;
    queue.enqueue(p);

    while (!queue.isEmpty()) {
      List<GraphNode<Integer>> neighbors = queue.dequeue().neighborList;
      for (int i = 0; i < neighbors.size(); i++) {
        GraphNode<Integer> neighbor = neighbors.get(i);

        if (!neighbor.visited && neighbor.equals(q)) {
          return true;
        }
        neighbor.visited = true;
        queue.enqueue(neighbor);
      }
    }

    return false;
  }
Example #4
0
 /**
  * Returns the nodes of a particular stroke that are found in the cycle
  *
  * @param s stroke
  * @return nodes that belong to that stroke
  */
 public List<GraphNode> getNodesOfStroke(Stroke s) {
   List<GraphNode> nodes = new ArrayList<GraphNode>();
   for (GraphNode n : this) {
     if (n.getStroke().equals(s)) nodes.add(n);
   }
   return nodes;
 }
Example #5
0
 private void computeDependencies(List<GraphNode<T>> nodes) {
   List<GraphNode<T>> nextNodesToDisplay = null;
   for (GraphNode<T> node : nodes) {
     if (!isAlreadyEvaluated(node)) {
       List<GraphNode<T>> comingInNodes = node.getComingInNodes();
       if (areAlreadyEvaluated(comingInNodes)) {
         listener.evaluating(node.value);
         evaluatedNodes.add(node);
         List<GraphNode<T>> goingOutNodes = node.getGoingOutNodes();
         if (goingOutNodes != null) {
           if (nextNodesToDisplay == null) nextNodesToDisplay = new ArrayList<GraphNode<T>>();
           // add these too, so they get a chance to be displayed
           // as well
           nextNodesToDisplay.addAll(goingOutNodes);
         }
       } else {
         if (nextNodesToDisplay == null) nextNodesToDisplay = new ArrayList<GraphNode<T>>();
         // the checked node should be carried
         nextNodesToDisplay.add(node);
       }
     }
   }
   if (nextNodesToDisplay != null) {
     computeDependencies(nextNodesToDisplay);
   }
   // here the recursive call ends
 }
Example #6
0
 /**
  * Returns a string like 'source -> destination'
  *
  * @return String
  */
 public String toString() {
   StringBuffer buffer = new StringBuffer("GraphModelConnection: ");
   buffer.append(sourceNode != null ? sourceNode.getText() : "null");
   buffer.append(isDirected() ? " --> " : " --- ");
   buffer.append(destinationNode != null ? destinationNode.getText() : "null");
   buffer.append("  (weight=").append(getWeightInLayout()).append(")");
   return buffer.toString();
 }
Example #7
0
  /**
   * Get the strokes found in the cycle
   *
   * @return list of strokes found
   */
  public List<Stroke> getStrokes() {
    List<Stroke> list = new ArrayList<Stroke>();
    for (GraphNode n : this) {
      if (!list.contains(n.getStroke())) list.add(n.getStroke());
    }

    return orderStrokes(list);
  }
Example #8
0
  private static void relax(GraphEdge e) {
    GraphNode v = e.from, w = e.to;

    if (w.minimumDistance < v.minimumDistance + 1) {
      w.minimumDistance = v.minimumDistance + 1;
      w.previous = v;
    }
  }
Example #9
0
  protected void nodeStmt(StreamTokenizer tk, final int nindex) throws Exception {
    tk.nextToken();

    GraphNode temp = m_nodes.get(nindex);

    if (tk.ttype == ']' || tk.ttype == StreamTokenizer.TT_EOF) {
      return;
    } else if (tk.ttype == StreamTokenizer.TT_WORD) {

      if (tk.sval.equalsIgnoreCase("label")) {

        tk.nextToken();
        if (tk.ttype == '=') {
          tk.nextToken();
          if (tk.ttype == StreamTokenizer.TT_WORD || tk.ttype == '"') {
            temp.lbl = tk.sval;
          } else {
            System.err.println("couldn't find label at line " + tk.lineno());
            tk.pushBack();
          }
        } else {
          System.err.println("couldn't find label at line " + tk.lineno());
          tk.pushBack();
        }
      } else if (tk.sval.equalsIgnoreCase("color")) {

        tk.nextToken();
        if (tk.ttype == '=') {
          tk.nextToken();
          if (tk.ttype == StreamTokenizer.TT_WORD || tk.ttype == '"') {;
          } else {
            System.err.println("couldn't find color at line " + tk.lineno());
            tk.pushBack();
          }
        } else {
          System.err.println("couldn't find color at line " + tk.lineno());
          tk.pushBack();
        }
      } else if (tk.sval.equalsIgnoreCase("style")) {

        tk.nextToken();
        if (tk.ttype == '=') {
          tk.nextToken();
          if (tk.ttype == StreamTokenizer.TT_WORD || tk.ttype == '"') {;
          } else {
            System.err.println("couldn't find style at line " + tk.lineno());
            tk.pushBack();
          }
        } else {
          System.err.println("couldn't find style at line " + tk.lineno());
          tk.pushBack();
        }
      }
    }
    nodeStmt(tk, nindex);
  }
  private double getPMulticluster(List<List<Integer>> clusters, int numRestarts) {
    if (false) {
      Graph g = new EdgeListGraph();
      List<Node> latents = new ArrayList<Node>();
      for (int i = 0; i < clusters.size(); i++) {
        GraphNode latent = new GraphNode("L" + i);
        latent.setNodeType(NodeType.LATENT);
        latents.add(latent);
        g.addNode(latent);

        List<Node> cluster = variablesForIndices(clusters.get(i));

        for (int j = 0; j < cluster.size(); j++) {
          g.addNode(cluster.get(j));
          g.addDirectedEdge(latent, cluster.get(j));
        }
      }
      SemPm pm = new SemPm(g);

      //            pm.fixOneLoadingPerLatent();

      SemOptimizerPowell semOptimizer = new SemOptimizerPowell();
      semOptimizer.setNumRestarts(numRestarts);

      SemEstimator est = new SemEstimator(cov, pm, semOptimizer);
      est.setScoreType(SemIm.ScoreType.Fgls);
      est.estimate();
      return est.getEstimatedSem().getPValue();
    } else {
      double max = Double.NEGATIVE_INFINITY;

      for (int i = 0; i < numRestarts; i++) {
        Mimbuild2 mimbuild = new Mimbuild2();

        List<List<Node>> _clusters = new ArrayList<List<Node>>();

        for (List<Integer> _cluster : clusters) {
          _clusters.add(variablesForIndices(_cluster));
        }

        List<String> names = new ArrayList<String>();

        for (int j = 0; j < clusters.size(); j++) {
          names.add("L" + j);
        }

        mimbuild.search(_clusters, names, cov);

        double c = mimbuild.getpValue();
        if (c > max) max = c;
      }

      return max;
    }
  }
  /**
   * 利用广度优先搜索进行路径判断 p - q 之间是否有路径
   *
   * @param p
   * @param q
   * @return
   */
  public static boolean pathCheckBFS(GraphNode<Integer> p, GraphNode<Integer> q) {
    boolean isFound = false;

    p.restoreVisited();
    isFound |= pathOrderCheckBFS(p, q);

    q.restoreVisited();
    isFound |= pathOrderCheckBFS(q, p);

    return isFound;
  }
 /** 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();
   }
 }
 /**
  * Tests constructor CutFreeTextAction(freeTextGraphNode, clipboard) if freeTextGraphNode contains
  * a semanticModel attribute, but not SimpleSemanticModelElement object. IllegalArgumentException
  * is expected.
  */
 public void testCtorIfFreeTextNodeContainInvalidSemanticModelAttribute() {
   try {
     freeTextGraphNode.addContained(new TextElement());
     freeTextGraphNode.setSemanticModel(new Uml1SemanticModelBridge());
     new CutFreeTextAction(freeTextGraphNode, null);
     fail(
         "IllegalArgumentException is expected because freeTextGraphNode contains invalid semanticModel"
             + "attribute (non-SimpleSemanticModelElement object).");
   } catch (IllegalArgumentException e) {
     // success
   }
 }
Example #14
0
 public void computeDependencies() {
   List<GraphNode<T>> orphanNodes = getOrphanNodes();
   List<GraphNode<T>> nextNodesToDisplay = new ArrayList<GraphNode<T>>();
   if (orphanNodes != null) {
     for (GraphNode<T> node : orphanNodes) {
       listener.evaluating(node.value);
       evaluatedNodes.add(node);
       nextNodesToDisplay.addAll(node.getGoingOutNodes());
     }
     computeDependencies(nextNodesToDisplay);
   }
 }
Example #15
0
 /**
  * An edge for the dynamic graph
  *
  * @param info - the info contained in the edge
  * @param weight - the weight of the edge
  * @param fromNode - the origin node of the edge
  * @param toNode - the end node of the edge
  */
 public GraphEdge(
     EdgeType info,
     double weight,
     GraphNode<NodeType, EdgeType> fromNode,
     GraphNode<NodeType, EdgeType> toNode) {
   _fromNode = fromNode;
   _toNode = toNode;
   _info = info;
   _weight = weight;
   fromNode.addOutgoingEdge(this);
   toNode.addIncomingEdge(this);
 }
Example #16
0
 private List<GraphNode<T>> getOrphanNodes() {
   List<GraphNode<T>> orphanNodes = null;
   Set<T> keys = nodes.keySet();
   for (T key : keys) {
     GraphNode<T> node = nodes.get(key);
     if (node.getComingInNodes() == null) {
       if (orphanNodes == null) orphanNodes = new ArrayList<GraphNode<T>>();
       orphanNodes.add(node);
     }
   }
   return orphanNodes;
 }
 /**
  * Tests method copyToClipboard(node, clipboard) if node is null. IllegalArgumentException is
  * expected
  *
  * @throws Exception exception
  */
 public void testCopyToClipboardIfNodeNull() throws Exception {
   SimpleSemanticModelElement semanticModelBridge = new SimpleSemanticModelElement();
   semanticModelBridge.setTypeInfo("FreeText");
   freeTextGraphNode.setSemanticModel(semanticModelBridge);
   freeTextGraphNode.addContained(new TextElement());
   CutFreeTextActionExt cutFreeTextAction = new CutFreeTextActionExt(freeTextGraphNode, null);
   try {
     cutFreeTextAction.copyToClipboard(null, null);
     fail("IllegalArgumentException is expected because node cannot be null.");
   } catch (IllegalArgumentException e) {
     // success
   }
 }
Example #18
0
 public LinkedList<String> getTree(GraphNode graph, String tabname) {
   List<?> elementsTree = trees.get(tabname);
   LinkedList<String> tree = new LinkedList<String>();
   if (elementsTree == null) return tree;
   for (Object o : elementsTree) {
     if (o instanceof String) {
       String pathElem =
           jrds.Util.parseTemplate((String) o, graph.getProbe(), this, graph.getProbe().getHost());
       tree.add(pathElem);
     } else if (o instanceof PathElement) tree.add(((PathElement) o).resolve(graph));
   }
   return tree;
 }
Example #19
0
 /*
  * (non-Javadoc)
  *
  * @see java.util.AbstractSet#equals(java.lang.Object)
  */
 @Override
 public boolean equals(Object o) {
   if (o instanceof GraphCycle) {
     GraphCycle gc = (GraphCycle) o;
     if (gc.size() != size()) return false;
     for (int i = 0; i < size(); i++) {
       GraphNode n1 = (GraphNode) toArray()[i];
       GraphNode n2 = (GraphNode) gc.toArray()[i];
       if (!n1.equals(n2)) return false;
     }
     return true;
   }
   return false;
 }
 /**
  * Tests constructor CutFreeTextAction(freeTextGraphNode, clipboard) if freeTextGraphNode contains
  * a semanticModel attribute (SimpleSemanticModelElement object), but its typeInfo attribute is
  * not equal to "FreeText". IllegalArgumentException is expected.
  */
 public void testCtorITypeInfoInvalid() {
   try {
     freeTextGraphNode.addContained(new TextElement());
     SimpleSemanticModelElement semanticModelBridge = new SimpleSemanticModelElement();
     semanticModelBridge.setTypeInfo("invalid_type_info");
     freeTextGraphNode.setSemanticModel(semanticModelBridge);
     new CutFreeTextAction(freeTextGraphNode, null);
     fail(
         "IllegalArgumentException is expected because semanticModel's typeInfo is not equal "
             + "to 'FreeText'.");
   } catch (IllegalArgumentException e) {
     // success
   }
 }
Example #21
0
 private void addNode(GraphNode graphNode) {
   if (graphNodeMap == null) {
     graphNodeMap = new HashMap<String, GraphNode<?>>();
   } else {
     final AttributeNode old = graphNodeMap.get(graphNode.getRegistrationName());
     if (old != null) {
       log.debugf(
           "Encountered request to add entity graph node [%s] using a name [%s] under which another "
               + "node is already registered [%s]",
           old.getClass().getName(),
           graphNode.getRegistrationName(),
           graphNode.getClass().getName());
     }
   }
   graphNodeMap.put(graphNode.getAttributeName(), graphNode);
 }
Example #22
0
 public String resolve(GraphNode graph) {
   StringBuffer retValue = new StringBuffer("empty");
   if (graph.getProbe() instanceof IndexedProbe) {
     retValue.setLength(0);
     IndexedProbe ip = (IndexedProbe) graph.getProbe();
     retValue.append(ip.getIndexName());
     // Check to see if a label is defined and needed to add
     String label = graph.getProbe().getLabel();
     if (label != null) {
       retValue.append(" (" + label + ")");
     }
   } else {
     logger.debug("Bad graph definition for " + graph);
   }
   return retValue.toString();
 }
  /**
   * Set up environment.
   *
   * @throws Exception exception
   */
  public void setUp() throws Exception {
    Helper.clearNamespace();
    Helper.initNamespace();

    freeTextGraphNode = new GraphNode();
    freeTextGraphNode.setContainer(new GraphElement() {});
  }
Example #24
0
 public String resolve(GraphNode graph) {
   String url = "";
   Probe<?, ?> probe = graph.getProbe();
   if (probe instanceof UrlProbe) {
     url = ((UrlProbe) probe).getUrlAsString();
   }
   return url;
 }
Example #25
0
  /**
   * BFS algorith
   *
   * @param: print boolean if to print node during traversal
   * @return List of nodes in order visited
   */
  public ArrayList<String> bfs(boolean print) {

    ArrayList<String> ops = new ArrayList<>();

    GraphNode v = source;
    ArrayList<GraphNode> Q = new ArrayList<>();
    Q.add(v);
    v.setVisited(true);
    while (Q.size() != 0) {
      v = Q.remove(0);
      if (print) System.out.println(v);
      ops.add(v.toString());
      //      if(checkStoppingCondition(v, getN())) {
      //        return;
      //      }
      List<Integer> edgeTarget = matrix.get(v.getID());
      for (int i = 0; i < edgeTarget.size(); ++i) {
        if (edgeTarget.get(i) == 1) {
          GraphNode w = info.get(i + 1);
          if (!w.getVisited()) {
            Q.add(w);
            w.setVisited(true);
          }
        }
      }
    }
    return ops;
  }
  public void bfs(GraphNode n) {

    Queue<GraphNode> q = new LinkedList<>();
    q.add(n);
    n.visited = true;
    while (!q.isEmpty()) {
      GraphNode nd = q.poll();
      System.out.print(nd + "   ");
      if (nd.neibhours != null) {
        for (GraphNode gn : nd.neibhours) {
          if (!gn.visited) {
            q.add(gn);
            gn.visited = true;
          }
        }
      }
    }
  }
Example #27
0
 public void add(T evalFirstValue, T evalAfterValue) {
   GraphNode<T> firstNode = null;
   GraphNode<T> afterNode = null;
   if (nodes.containsKey(evalFirstValue)) {
     firstNode = nodes.get(evalFirstValue);
   } else {
     firstNode = createNode(evalFirstValue);
     nodes.put(evalFirstValue, firstNode);
   }
   if (nodes.containsKey(evalAfterValue)) {
     afterNode = nodes.get(evalAfterValue);
   } else {
     afterNode = createNode(evalAfterValue);
     nodes.put(evalAfterValue, afterNode);
   }
   firstNode.addGoingOutNode(afterNode);
   afterNode.addComingInNode(firstNode);
 }
  void updateNodeLabel(InternalNodeLayout internalNode) {
    if (internalNode.isDisposed()) {
      return;
    }
    IFigure figure = internalNode.getNode().getFigure();
    GraphLabel label = (GraphLabel) nodeFigureToLabel.get(figure);
    IFigure fisheye = getFisheyeFigure(figure);
    if (fisheye != null) {
      figure = fisheye;
    }
    if (label == null) {
      label = new GraphLabel(false);
      label.setForegroundColor(ColorConstants.white);
      label.setBackgroundColor(ColorConstants.red);
      FontData fontData = Display.getDefault().getSystemFont().getFontData()[0];
      fontData.setHeight(6);
      label.setFont(new Font(Display.getCurrent(), fontData));
      figure.addFigureListener(nodeFigureListener);
      addLabelForFigure(figure, label);
      nodeFigureToLabel.put(figure, label);
    }

    GraphNode graphNode = internalNode.getNode();
    if (!graphNode.getGraphModel().canExpand(graphNode)
        || graphNode.getGraphModel().canCollapse(graphNode)
        || internalNode.isPruned()) {
      label.setVisible(false);
    } else {
      NodeLayout[] successors = internalNode.getSuccessingNodes();
      int numberOfHiddenSuccessors = 0;
      for (int i = 0; i < successors.length; i++) {
        if (successors[i].isPruned()) {
          numberOfHiddenSuccessors++;
        }
      }
      String labelText = numberOfHiddenSuccessors > 0 ? "" + numberOfHiddenSuccessors : "";
      if (!labelText.equals(label.getText())) {
        label.setText(labelText);
      }
      label.setVisible(true);
    }

    refreshLabelBounds(figure, label);
  }
 public void allPaths(GraphNode n1, GraphNode n2, int index) {
   if (n1 == null || n2 == null) return;
   aa[index] = n1;
   n1.visited = true;
   index++;
   if (n1 == n2) {
     for (int i = 0; i < index; i++) System.out.print(aa[i] + "  ");
     System.out.println();
     n1.visited = false;
     return;
   }
   if (n1.neibhours != null) {
     GraphNode[] nbr = n1.neibhours;
     for (int i = 0; i < nbr.length; i++) {
       if (!nbr[i].visited) allPaths(nbr[i], n2, index);
     }
   }
   n1.visited = false;
 }
Example #30
0
 private void generateShortestPathsFrom(GraphNode source) throws NegativeEdgeException {
   Iterator<GraphNode> l = g.getNodeIterator();
   ListIterator<GraphEdge> m;
   FibonacciHeap<GraphNode> h = new FibonacciHeap<GraphNode>();
   GraphNode t, v;
   GraphEdge e;
   h.insert(source, 0);
   data(source).setPrev(null);
   data(source).setIncidentEdge(null);
   this.source = source;
   while (l.hasNext()) {
     t = l.next();
     if (t == source) continue;
     data(t).setPrev(null);
     data(t).setIncidentEdge(null);
     h.insert(t, Integer.MAX_VALUE);
   }
   while (!h.isEmpty()) {
     t = h.extractMin();
     m = t.getEdgeIterator();
     while (m.hasNext()) {
       e = m.next();
       if (g.getNodeById(e.getTarget().getId()) == null) {
         m.remove();
         continue;
       }
       if (e.getWeight() < 0) {
         throw new NegativeEdgeException(
             "Dijkstra's algorithm won't work on graphs with negative edge weights!");
       }
       v = e.getTarget();
       if (h.getKey(v) > h.getKey(t) + e.getWeight()) {
         try {
           h.decreaseKey(v, h.getKey(t) + e.getWeight());
         } catch (KeyNotLessException x) {
           // can't happen!
         }
         data(v).setPrev(t);
         data(v).setIncidentEdge(e);
       }
     }
   }
 }