Example #1
1
  public PathResult bruteSearch(Map map, Node curNode) {
    PathResult p = new PathResult();
    if (curNode.getName().equals("END")) {
      p.setPath("END");
      return p;
    }
    PathResult[] depends = new PathResult[curNode.getNumDepend()];
    for (int i = 0; i < curNode.getNumDepend(); i++) {
      Path path = map.getPath(curNode.getName(), curNode.getDepend(i).getName());
      depends[i] =
          (new PathResult(path.getA().getName() + ",", path.getWeight()))
              .append(bruteSearch(map, curNode.getDepend(i)));
      // System.out.println(i + " " + depends[i]);
    }

    int minIndex = 0;
    for (int i = 1; i < depends.length; i++) {
      if (depends[i].getWeight() < depends[minIndex].getWeight()) minIndex = i;
    }
    return depends[minIndex];
  }
Example #2
0
  private void calculateArrowsForward(Node x, Node y, Graph graph) {
    clearArrow(x, y);

    if (!knowledgeEmpty()) {
      if (getKnowledge().isForbidden(x.getName(), y.getName())) {
        return;
      }
    }

    List<Node> naYX = getNaYX(x, y, graph);
    List<Node> t = getTNeighbors(x, y, graph);

    DepthChoiceGenerator gen = new DepthChoiceGenerator(t.size(), t.size());
    int[] choice;

    while ((choice = gen.next()) != null) {
      List<Node> s = GraphUtils.asList(choice, t);

      if (!knowledgeEmpty()) {
        if (!validSetByKnowledge(y, s)) {
          continue;
        }
      }

      double bump = insertEval(x, y, s, naYX, graph);

      if (bump > 0.0) {
        Arrow arrow = new Arrow(bump, x, y, s, naYX);
        sortedArrows.add(arrow);
        addLookupArrow(x, y, arrow);
      }
    }
  }
  public void outputContext(PrintWriter printStream, String indentString) {
    AppearanceNode appearance = getAppearanceNodes();
    if (appearance != null) {
      if (appearance.isInstanceNode() == false) {
        String nodeName = appearance.getName();
        if (nodeName != null && 0 < nodeName.length())
          printStream.println(
              indentString + "\t" + "appearance DEF " + appearance.getName() + " Appearance {");
        else printStream.println(indentString + "\t" + "appearance Appearance {");
        appearance.outputContext(printStream, indentString + "\t");
        printStream.println(indentString + "\t" + "}");
      } else printStream.println(indentString + "\t" + "appearance USE " + appearance.getName());
    }

    Node geonode = getGeometry3DNode();
    if (geonode != null) {
      if (geonode.isInstanceNode() == false) {
        String nodeName = geonode.getName();
        if (nodeName != null && 0 < nodeName.length())
          printStream.println(
              indentString
                  + "\t"
                  + "geometry DEF "
                  + geonode.getName()
                  + " "
                  + geonode.getTypeString()
                  + " {");
        else
          printStream.println(indentString + "\t" + "geometry " + geonode.getTypeString() + " {");
        geonode.outputContext(printStream, indentString + "\t");
        printStream.println(indentString + "\t" + "}");
      } else printStream.println(indentString + "\t" + "geometry USE " + geonode.getName());
    }
  }
Example #4
0
 public boolean hasNode(String nodeName) {
   if (start.getName().equals(nodeName) || end.getName().equals(nodeName)) {
     return true;
   } else {
     return false;
   }
 }
Example #5
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;
  }
Example #6
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;
  }
Example #7
0
  /**
   * <<<<<<< HEAD ���ߵ�valueֵ���й��� ======= 按边的value值进行过滤 >>>>>>> seuvislogwws/master
   *
   * @param filter
   * @return
   */
  public SankeyGraph FilterByEdgeValue(double filter) {
    Set<Integer> nodeset = new HashSet<Integer>();
    Iterator<? extends Edge> iterator_links = this.links.iterator();
    while (iterator_links.hasNext()) {
      Edge edge = iterator_links.next();
      double value = ((StreamEdge) edge).getValue();
      if (value < filter) iterator_links.remove(); // �Ƴ��
      else {
        nodeset.add(edge.getSource());
        nodeset.add(edge.getTarget());
      }
    }
    Iterator<? extends Node> iterator_nodes = this.nodes.iterator();
    while (iterator_nodes.hasNext()) {
      Node node = iterator_nodes.next();

      if (!nodeset.contains(node.getName())) { // ����nodes��
        iterator_nodes.remove();
      }
    }
    // System.out.println( "���˺�nodes�Ĵ�С�� "+this.nodes.size());
    // �����˹���json����ٴΰ�node��name��0��ʼ�ź�
    int index = 0;
    for (Node n : this.nodes) {
      int old_name = n.getName();
      int new_name = index++;
      n.setName(new_name);

      for (Edge e : this.links) {
        if (e.getSource() == old_name) e.setSource(new_name);
        if (e.getTarget() == old_name) e.setTarget(new_name);
      }
    }
    return this;
  }
Example #8
0
 /**
  * Use background knowledge to decide if an insert or delete operation does not orient edges in a
  * forbidden direction according to prior knowledge. If some orientation is forbidden in the
  * subset, the whole subset is forbidden.
  */
 private boolean validSetByKnowledge(Node y, List<Node> subset) {
   for (Node node : subset) {
     if (getKnowledge().isForbidden(node.getName(), y.getName())) {
       return false;
     }
   }
   return true;
 }
  /**
   * 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);
  }
Example #10
0
  private double pValue(Node node, List<Node> parents) {
    List<Double> _residuals = new ArrayList<Double>();

    Node _target = node;
    List<Node> _regressors = parents;
    Node target = getVariable(variables, _target.getName());
    List<Node> regressors = new ArrayList<Node>();

    for (Node _regressor : _regressors) {
      Node variable = getVariable(variables, _regressor.getName());
      regressors.add(variable);
    }

    DATASET:
    for (int m = 0; m < dataSets.size(); m++) {
      RegressionResult result = regressions.get(m).regress(target, regressors);
      TetradVector residualsSingleDataset = result.getResiduals();

      for (int h = 0; h < residualsSingleDataset.size(); h++) {
        if (Double.isNaN(residualsSingleDataset.get(h))) {
          continue DATASET;
        }
      }

      DoubleArrayList _residualsSingleDataset =
          new DoubleArrayList(residualsSingleDataset.toArray());

      double mean = Descriptive.mean(_residualsSingleDataset);
      double std =
          Descriptive.standardDeviation(
              Descriptive.variance(
                  _residualsSingleDataset.size(),
                  Descriptive.sum(_residualsSingleDataset),
                  Descriptive.sumOfSquares(_residualsSingleDataset)));

      for (int i2 = 0; i2 < _residualsSingleDataset.size(); i2++) {
        //                _residualsSingleDataset.set(i2, (_residualsSingleDataset.get(i2) - mean) /
        // std);
        if (isMeanCenterResiduals()) {
          _residualsSingleDataset.set(i2, (_residualsSingleDataset.get(i2) - mean));
        }
        //                _residualsSingleDataset.set(i2, (_residualsSingleDataset.get(i2)));
      }

      for (int k = 0; k < _residualsSingleDataset.size(); k++) {
        _residuals.add(_residualsSingleDataset.get(k));
      }
    }

    double[] _f = new double[_residuals.size()];

    for (int k = 0; k < _residuals.size(); k++) {
      _f[k] = _residuals.get(k);
    }

    return new AndersonDarlingTest(_f).getP();
  }
Example #11
0
 public Node getOppositeEnd(String nodeName) {
   assert start.getName().equals(nodeName) || end.getName().equals(nodeName)
       : "Node must belong to link";
   if (start.getName().equals(nodeName)) {
     return end;
   } else {
     return start;
   }
 }
Example #12
0
  public String getGraphCommands() {
    String commands = "";

    for (Node aNode : nodeList) {
      commands += ("node " + aNode.getName() + "\n");
    }

    for (DirectedArc dirArc : dirArcList) {
      commands +=
          ("dir-arc "
              + dirArc.getParent().getName()
              + " "
              + dirArc.getChild().getName()
              + " "
              + dirArc.getRelation()
              + "\n");
    }

    for (UndirectedArc undirArc : undirArcList) {
      Node[] nodes = undirArc.getNodes();
      commands +=
          ("undir-arc "
              + nodes[0].getName()
              + " "
              + nodes[1].getName()
              + " "
              + undirArc.getRelation()
              + "\n");
    }

    return commands;
  }
  /** Recursively outputs the contents of the given node. */
  private static void dump(Node node) throws RepositoryException {
    // First output the node path
    System.out.println(node.getPath());
    // Skip the virtual (and large!) jcr:system subtree
    if (node.getName().equals("jcr:system")) {
      return;
    }

    // Then output the properties
    PropertyIterator properties = node.getProperties();
    while (properties.hasNext()) {
      Property property = properties.nextProperty();
      if (property.getDefinition().isMultiple()) {
        // A multi-valued property, print all values
        Value[] values = property.getValues();
        for (int i = 0; i < values.length; i++) {
          System.out.println(property.getPath() + " = " + values[i].getString());
        }
      } else {
        // A single-valued property
        System.out.println(property.getPath() + " = " + property.getString());
      }
    }

    // Finally output all the child nodes recursively
    NodeIterator nodes = node.getNodes();
    while (nodes.hasNext()) {
      dump(nodes.nextNode());
    }
  }
Example #14
0
 private ImmutableMap<String, Node<?>> buildNodeMap(List<Node<?>> nodes) {
   ImmutableMap.Builder<String, Node<?>> builder = ImmutableMap.builder();
   for (Node<?> node : nodes) {
     builder.put(node.getName(), node);
   }
   return builder.build();
 }
 public void deliverMessages() {
   while (!getSequencer().getSequenceNbsOfMachine().isEmpty()) {
     Node node = new Node(getLastMinimumSequenceNumber(getSequencer().getSequenceNbsOfMachine()));
     node.buildListDependencies(node.getName(), this);
     node.resolveDependencies(this);
   }
 }
Example #16
0
 private List<String> getNames(List<Node> nodes) {
   List<String> names = new ArrayList<String>();
   for (Node node : nodes) {
     names.add(node.getName());
   }
   return names;
 }
Example #17
0
  public boolean isViolatedBy(Graph graph) {
    for (Edge edge : graph.getEdges()) {
      if (!edge.isDirected()) {
        continue;
      }

      Node from = Edges.getDirectedEdgeTail(edge);
      Node to = Edges.getDirectedEdgeHead(edge);

      if (isForbidden(from.getName(), to.getName())) {
        return true;
      }
    }

    return false;
  }
Example #18
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;
  }
Example #19
0
  public NodeId getNodeId(Node node) {
    String _name = node.getName();
    String[] tokens = _name.split(":");
    if (tokens.length > 2)
      throw new IllegalArgumentException("Name may contain only one colon: " + _name);
    if (tokens[0].length() == 0)
      throw new IllegalArgumentException(
          "Part to the left of the colon may "
              + "not be empty; that's the name of the variable: "
              + _name);
    String name = tokens[0];
    int lag;

    if (tokens.length == 1) {
      lag = 0;
    } else {
      lag = Integer.parseInt(tokens[1]);
      if (lag == 0) throw new IllegalArgumentException("Lag 0 edges don't have :0 descriptors");
    }

    if (lag < 0) throw new IllegalArgumentException("Lag is less than 0: " + lag);
    if (lag > getMaxLag())
      throw new IllegalArgumentException("Lag is greater than the maximum lag: " + lag);

    return new NodeId(name, lag);
  }
Example #20
0
  /**
   * Gets a node with the specified name
   *
   * @param name name of graph node which is to be retrieved
   * @throws Exception node is not found
   * @return graph Node
   */
  public Node getNode(String name) throws Exception {
    for (Node aNode : nodeList) {
      if (aNode.getName().equals(name)) {
        return aNode;
      }
    }

    throw new Exception(String.format("Node %s not found", name));
  }
  /** Returns the string in nodelist which matches string in BK. */
  public static Node translate(String a, List<Node> nodes) {
    for (Node node : nodes) {
      if ((node.getName()).equals(a)) {
        return node;
      }
    }

    return null;
  }
Example #22
0
  private Node getVariable(List<Node> variables, String name) {
    for (Node node : variables) {
      if (name.equals(node.getName())) {
        return node;
      }
    }

    return null;
  }
Example #23
0
  /**
   * Helper method. Appears to check if an arrowpoint is permitted by background knowledge.
   *
   * @param x The possible other node.
   * @param y The possible point node.
   * @return Whether the arrowpoint is allowed.
   */
  private boolean isArrowpointAllowed(Node x, Node y) {
    if (graph.getEndpoint(x, y) == Endpoint.ARROW) {
      return true;
    }

    if (graph.getEndpoint(x, y) == Endpoint.TAIL) {
      return false;
    }

    if (graph.getEndpoint(y, x) == Endpoint.ARROW) {
      if (!knowledge.isForbidden(x.getName(), y.getName())) return true;
    }

    if (graph.getEndpoint(y, x) == Endpoint.TAIL) {
      if (!knowledge.isForbidden(x.getName(), y.getName())) return true;
    }

    return graph.getEndpoint(y, x) == Endpoint.CIRCLE;
  }
Example #24
0
 public String toString() {
   StringBuffer buffer = new StringBuffer();
   buffer.append("DataNode: " + getName() + "\n");
   if (getComments() != null) {
     for (Node commentNode : getComments()) {
       buffer.append("\t comment: " + commentNode.getName() + "\n");
     }
   }
   return buffer.toString();
 }
Example #25
0
  private String reportIfDiscrete(Graph dag, DataSet dataSet) {
    List vars = dataSet.getVariables();
    Map<String, DiscreteVariable> nodesToVars = new HashMap<String, DiscreteVariable>();
    for (int i = 0; i < dataSet.getNumColumns(); i++) {
      DiscreteVariable var = (DiscreteVariable) vars.get(i);
      String name = var.getName();
      Node node = new GraphNode(name);
      nodesToVars.put(node.getName(), var);
    }

    BayesPm bayesPm = new BayesPm(new Dag(dag));
    List<Node> nodes = bayesPm.getDag().getNodes();

    for (Node node : nodes) {
      Node var = nodesToVars.get(node.getName());

      if (var instanceof DiscreteVariable) {
        DiscreteVariable var2 = nodesToVars.get(node.getName());
        int numCategories = var2.getNumCategories();
        List<String> categories = new ArrayList<String>();
        for (int j = 0; j < numCategories; j++) {
          categories.add(var2.getCategory(j));
        }
        bayesPm.setCategories(node, categories);
      }
    }

    BayesProperties properties = new BayesProperties(dataSet, dag);
    properties.setGraph(dag);

    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(4);

    StringBuilder buf = new StringBuilder();
    buf.append("\nP-value = ").append(properties.getLikelihoodRatioP());
    buf.append("\nDf = ").append(properties.getPValueDf());
    buf.append("\nChi square = ").append(nf.format(properties.getPValueChisq()));
    buf.append("\nBIC score = ").append(nf.format(properties.getBic()));
    buf.append("\n\nH0: Completely disconnected graph.");

    return buf.toString();
  }
Example #26
0
 // Thanks for Giordano Sassaroli <[email protected]> (09/08/03)
 private Property getProperty(Node varNode) {
   Property prop = new Property();
   if (varNode == null) return prop;
   // remove the event namespace
   String variableName = varNode.getName();
   int index = variableName.lastIndexOf(':');
   if (index != -1) variableName = variableName.substring(index + 1);
   prop.setName(variableName);
   prop.setValue(varNode.getValue());
   return prop;
 }
Example #27
0
  public Node getNode(String name) {
    if (name == null) return null;

    int nLists = size();
    for (int n = 0; n < nLists; n++) {
      Node node = getNode(n);
      String nodeName = node.getName();
      if (name.compareTo(nodeName) == 0) return node;
    }
    return null;
  }
 @Test
 public void testFullReplaceMissingProperty() throws Exception {
   try {
     Node target = (Node) createValue("name", "%{garbage}").getTarget();
     assertEquals("bar", target.getName());
     fail("Expected IllegalStateException");
   } catch (BeanCreationException e) {
     String message = e.getMessage();
     assertTrue("Wrong message: " + message, message.toLowerCase().contains("cannot bind"));
   }
 }
Example #29
0
 @Override
 public String toString() {
   return com.google.common.base.Objects.toStringHelper(this)
       .add("name", name)
       .add("nodeType", nodeType)
       .add("parent", (parent != null ? parent.getName() : null))
       .add("namespace", namespace)
       .add("comment", comment)
       .add("children", children)
       .toString();
 }
Example #30
0
  // Invalid if then nodes or graph changes.
  private void calculateArrowsBackward(Node x, Node y, Graph graph) {
    if (x == y) {
      return;
    }

    if (!graph.isAdjacentTo(x, y)) {
      return;
    }

    if (!knowledgeEmpty()) {
      if (!getKnowledge().noEdgeRequired(x.getName(), y.getName())) {
        return;
      }
    }

    List<Node> naYX = getNaYX(x, y, graph);

    clearArrow(x, y);

    List<Node> _naYX = new ArrayList<Node>(naYX);
    DepthChoiceGenerator gen = new DepthChoiceGenerator(_naYX.size(), _naYX.size());
    int[] choice;

    while ((choice = gen.next()) != null) {
      List<Node> H = GraphUtils.asList(choice, _naYX);

      if (!knowledgeEmpty()) {
        if (!validSetByKnowledge(y, H)) {
          continue;
        }
      }

      double bump = deleteEval(x, y, H, naYX, graph);

      if (bump > 0.0) {
        Arrow arrow = new Arrow(bump, x, y, H, naYX);
        sortedArrows.add(arrow);
        addLookupArrow(x, y, arrow);
      }
    }
  }