Ejemplo n.º 1
0
  private boolean existsUnblockedSemiDirectedPath(Node from, Node to, List<Node> cond, Graph G) {
    Queue<Node> Q = new LinkedList<Node>();
    Set<Node> V = new HashSet<Node>();
    Q.offer(from);
    V.add(from);

    while (!Q.isEmpty()) {
      Node t = Q.remove();
      if (t == to) return true;

      for (Node u : G.getAdjacentNodes(t)) {
        Edge edge = G.getEdge(t, u);
        Node c = Edges.traverseSemiDirected(t, edge);
        if (c == null) continue;
        if (cond.contains(c)) continue;
        if (c == to) return true;

        if (!V.contains(c)) {
          V.add(c);
          Q.offer(c);
        }
      }
    }

    return false;
  }
Ejemplo n.º 2
0
  void storeLatestWorkbenchGraph() {
    Graph latestWorkbenchGraph = workbench.getGraph();

    if (latestWorkbenchGraph.getNumNodes() == 0) {
      return;
    }

    SearchParams searchParams = algorithmRunner.getParams();

    try {
      Graph graph = new MarshalledObject<Graph>(latestWorkbenchGraph).get();

      if (graph == null) {
        throw new NullPointerException("Null graph");
      }

      if (searchParams != null) {
        searchParams.setSourceGraph(graph);
      }
    } catch (IOException e) {
      e.printStackTrace();

      if (searchParams != null) {
        searchParams.setSourceGraph(null);
      }
    } catch (ClassNotFoundException e) {
      if (searchParams != null) {
        searchParams.setSourceGraph(null);
      }

      e.printStackTrace();
    }
  }
Ejemplo n.º 3
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;
  }
Ejemplo n.º 4
0
  /** Initializes the lists of parents and parent dimension for the given variable. */
  private void initializeNode(int nodeIndex) {
    Node node = nodes[nodeIndex];

    // Set up parents array.  Should store the parents of
    // each node as ints in a particular order.
    Graph graph = getBayesPm().getDag();
    List<Node> parentList = new ArrayList<Node>(graph.getParents(node));
    int[] parentArray = new int[parentList.size()];

    for (int i = 0; i < parentList.size(); i++) {
      parentArray[i] = getNodeIndex(parentList.get(i));
    }

    // Sort parent array.
    Arrays.sort(parentArray);

    parents[nodeIndex] = parentArray;

    // Setup dimensions array for parents.
    int[] dims = new int[parentArray.length];

    for (int i = 0; i < dims.length; i++) {
      Node parNode = nodes[parentArray[i]];
      dims[i] = getBayesPm().getNumCategories(parNode);
    }

    parentDims[nodeIndex] = dims;
  }
Ejemplo n.º 5
0
  public static Graph erdosRenyiGraph(int n, int e) {
    List<Node> nodes = new ArrayList<Node>();
    for (int i = 0; i < n; i++) nodes.add(new GraphNode("X" + i));

    Graph graph = new EdgeListGraph(nodes);

    for (int e0 = 0; e0 < e; e0++) {
      int i1 = RandomUtil.getInstance().nextInt(n);
      int i2 = RandomUtil.getInstance().nextInt(n);

      if (i1 == i2) {
        e0--;
        continue;
      }

      Edge edge = Edges.undirectedEdge(nodes.get(i1), nodes.get(i2));

      if (graph.containsEdge(edge)) {
        e0--;
        continue;
      }

      graph.addEdge(edge);
    }

    return graph;
  }
Ejemplo n.º 6
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);
  }
  /** Get a graph and direct only the unshielded colliders. */
  public static void basicPattern(Graph graph) {
    Set<Edge> undirectedEdges = new HashSet<Edge>();

    NEXT_EDGE:
    for (Edge edge : graph.getEdges()) {
      Node head = null, tail = null;

      if (edge.getEndpoint1() == Endpoint.ARROW && edge.getEndpoint2() == Endpoint.TAIL) {
        head = edge.getNode1();
        tail = edge.getNode2();
      } else if (edge.getEndpoint2() == Endpoint.ARROW && edge.getEndpoint1() == Endpoint.TAIL) {
        head = edge.getNode2();
        tail = edge.getNode1();
      }

      if (head != null) {
        for (Node node : graph.getParents(head)) {
          if (node != tail && !graph.isAdjacentTo(tail, node)) {
            continue NEXT_EDGE;
          }
        }

        undirectedEdges.add(edge);
      }
    }

    for (Edge nextUndirected : undirectedEdges) {
      Node node1 = nextUndirected.getNode1(), node2 = nextUndirected.getNode2();

      graph.removeEdge(nextUndirected);
      graph.addUndirectedEdge(node1, node2);
    }
  }
Ejemplo n.º 8
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;
  }
Ejemplo n.º 9
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;
  }
Ejemplo n.º 10
0
 public Set<Edge> getNonadjacencies() {
   Graph complete = GraphUtils.completeGraph(graph);
   Set<Edge> nonAdjacencies = complete.getEdges();
   Graph undirected = GraphUtils.undirectedGraph(graph);
   nonAdjacencies.removeAll(undirected.getEdges());
   return new HashSet<Edge>(nonAdjacencies);
 }
Ejemplo n.º 11
0
  /**
   * Constructs a new on-the-fly BayesIM that will calculate conditional probabilities on the fly
   * from the given discrete data set, for the given Bayes PM.
   *
   * @param bayesPm the given Bayes PM, which specifies a directed acyclic graph for a Bayes net and
   *     parametrization for the Bayes net, but not actual values for the parameters.
   * @param dataSet the discrete data set from which conditional probabilities should be estimated
   *     on the fly.
   */
  public OnTheFlyMarginalCalculator(BayesPm bayesPm, DataSet dataSet)
      throws IllegalArgumentException {
    if (bayesPm == null) {
      throw new NullPointerException();
    }

    if (dataSet == null) {
      throw new NullPointerException();
    }

    // Make sure all of the variables in the PM are in the data set;
    // otherwise, estimation is impossible.
    BayesUtils.ensureVarsInData(bayesPm.getVariables(), dataSet);
    //        DataUtils.ensureVariablesExist(bayesPm, dataSet);

    this.bayesPm = new BayesPm(bayesPm);

    // Get the nodes from the BayesPm. This fixes the order of the nodes
    // in the BayesIm, independently of any change to the BayesPm.
    // (This order must be maintained.)
    Graph graph = bayesPm.getDag();
    this.nodes = graph.getNodes().toArray(new Node[0]);

    // Initialize.
    initialize();

    // Create a subset of the data set with the variables of the IM, in
    // the order of the IM.
    List<Node> variables = getVariables();
    this.dataSet = dataSet.subsetColumns(variables);

    // Create a tautologous proposition for evidence.
    this.evidence = new Evidence(Proposition.tautology(this));
  }
Ejemplo n.º 12
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;
  }
Ejemplo n.º 13
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;
  }
Ejemplo n.º 14
0
  private boolean isUndirected(Graph graph, Node x, Node y) {
    List<Edge> edges = graph.getEdges(x, y);
    if (edges.size() == 1) {
      Edge edge = graph.getEdge(x, y);
      return Edges.isUndirectedEdge(edge);
    }

    return false;
  }
  /**
   * 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.");
  }
Ejemplo n.º 16
0
 private boolean localMarkovIndep(Node x, Node y, Graph pattern, IndependenceTest test) {
   List<Node> future = pattern.getDescendants(Collections.singletonList(x));
   List<Node> boundary = pattern.getAdjacentNodes(x);
   boundary.removeAll(future);
   List<Node> closure = new ArrayList<>(boundary);
   closure.add(x);
   closure.remove(y);
   if (future.contains(y) || boundary.contains(y)) return false;
   return test.isIndependent(x, y, boundary);
 }
  /**
   * Provides methods for estimating a Bayes IM from an existing BayesIM and a discrete dataset
   * using EM (Expectation Maximization). The data columns in the given data must be equal to a
   * variable in the given Bayes IM but the latter may contain variables which don't occur in the
   * dataset (latent variables). The first argument of the constructoris the BayesPm whose graph
   * contains latent and observed variables. The second is the dataset of observed variables;
   * missing value codes may be present.
   */
  public EmBayesEstimator(BayesPm bayesPm, DataSet dataSet) {

    if (bayesPm == null) {
      throw new NullPointerException();
    }

    if (dataSet == null) {
      throw new NullPointerException();
    }

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

    this.bayesPm = bayesPm;
    this.dataSet = dataSet;

    // this.variables = Collections.unmodifiableList(vars);
    graph = bayesPm.getDag();
    this.nodes = new Node[graph.getNumNodes()];

    Iterator<Node> it = graph.getNodes().iterator();

    for (int i = 0; i < this.nodes.length; i++) {
      this.nodes[i] = it.next();
      // System.out.println("node " + i + " " + nodes[i]);
    }

    for (int i = 0; i < this.nodes.length; i++) {
      if (nodes[i].getNodeType() == NodeType.MEASURED) {
        observedVars.add(bayesPm.getVariable(nodes[i]));
      }
    }

    // Make sure variables in dataset are measured variables in the BayesPM
    //        for (Node dataSetVariable : this.dataSet.getVariables()) {
    //            if (!observedVars.contains(dataSetVariable)) {
    //                throw new IllegalArgumentException(
    //                        "Some var in the dataset is not a " +
    //                                "measured variable in the Bayes net");
    //            }
    //        }

    // Make sure all measured variables in the BayesPm are in the discrete dataset
    for (Node observedVar : observedVars) {
      try {
        this.dataSet.getVariable(observedVar.getName());
      } catch (Exception e) {
        throw new IllegalArgumentException(
            "Some observed var in the Bayes net " + "is not in the dataset: " + observedVar);
      }
    }

    findBayesNetObserved(); // Sets bayesPmObs

    initialize();
  }
Ejemplo n.º 18
0
  private void calcStats() {
    //        Graph resultGraph = getAlgorithmRunner().getResultGraph();
    IGesRunner runner = (IGesRunner) getAlgorithmRunner();

    if (runner.getTopGraphs().isEmpty()) {
      throw new IllegalArgumentException(
          "No patterns were recorded. Please adjust the number of " + "patterns to store.");
    }

    Graph resultGraph = runner.getTopGraphs().get(runner.getIndex()).getGraph();

    if (getAlgorithmRunner().getDataModel() instanceof DataSet) {

      // resultGraph may be the output of a PC search.
      // Such graphs sometimes contain doubly directed edges.

      // /We converte such edges to directed edges here.
      // For the time being an orientation is arbitrarily selected.
      Set<Edge> allEdges = resultGraph.getEdges();

      for (Edge edge : allEdges) {
        if (edge.getEndpoint1() == Endpoint.ARROW && edge.getEndpoint2() == Endpoint.ARROW) {
          // Option 1 orient it from node1 to node2
          resultGraph.setEndpoint(edge.getNode1(), edge.getNode2(), Endpoint.ARROW);

          // Option 2 remove such edges:
          resultGraph.removeEdge(edge);
        }
      }

      Pattern pattern = new Pattern(resultGraph);
      PatternToDag ptd = new PatternToDag(pattern);
      Graph dag = ptd.patternToDagMeekRules();

      DataSet dataSet = (DataSet) getAlgorithmRunner().getDataModel();
      String report;

      if (dataSet.isContinuous()) {
        report = reportIfContinuous(dag, dataSet);
      } else if (dataSet.isDiscrete()) {
        report = reportIfDiscrete(dag, dataSet);
      } else {
        throw new IllegalArgumentException("");
      }

      JScrollPane dagWorkbenchScroll = dagWorkbenchScroll(dag);
      modelStatsText.setLineWrap(true);
      modelStatsText.setWrapStyleWord(true);
      modelStatsText.setText(report);

      removeStatsTabs();
      tabbedPane.addTab("DAG in pattern", dagWorkbenchScroll);
      tabbedPane.addTab("DAG Model Statistics", modelStatsText);
    }
  }
  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;
    }
  }
  /** 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;
  }
Ejemplo n.º 21
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);
  }
Ejemplo n.º 22
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;
  }
Ejemplo n.º 23
0
  public List<Node> findMb(String targetName) {
    Node target = getVariableForName(targetName);

    Pc search = new Pc(test);
    search.setDepth(depth);
    Graph graph = search.search();
    MbUtils.trimToMbNodes(graph, target, false);
    List<Node> mbVariables = graph.getNodes();
    mbVariables.remove(target);

    return mbVariables;
  }
Ejemplo n.º 24
0
 private boolean missingColliders(Graph graph) {
   List<Triple> colliders = getUnshieldedCollidersFromGraph(graph);
   Graph copy = new EdgeListGraphSingleConnections(graph);
   new MeekRules().orientImplied(copy);
   if (copy.existsDirectedCycle()) return true;
   List<Triple> newColliders = getUnshieldedCollidersFromGraph(copy);
   newColliders.removeAll(colliders);
   if (!newColliders.isEmpty()) {
     return true;
   }
   return false;
 }
  public static Graph bestGuessCycleOrientation(Graph graph, IndependenceTest test) {
    while (true) {
      List<Node> cycle = GraphUtils.directedCycle(graph);

      if (cycle == null) {
        break;
      }

      LinkedList<Node> _cycle = new LinkedList<Node>(cycle);

      Node first = _cycle.getFirst();
      Node last = _cycle.getLast();

      _cycle.addFirst(last);
      _cycle.addLast(first);

      int _j = -1;
      double minP = Double.POSITIVE_INFINITY;

      for (int j = 1; j < _cycle.size() - 1; j++) {
        int i = j - 1;
        int k = j + 1;

        Node x = test.getVariable(_cycle.get(i).getName());
        Node y = test.getVariable(_cycle.get(j).getName());
        Node z = test.getVariable(_cycle.get(k).getName());

        test.isIndependent(x, z, Collections.singletonList(y));

        System.out.println("Testing " + x + " _||_ " + z + " | " + y);

        double p = test.getPValue();

        System.out.println("p = " + p);

        if (p < minP) {
          _j = j;
          minP = p;
        }
      }

      Node x = _cycle.get(_j - 1);
      Node y = _cycle.get(_j);
      Node z = _cycle.get(_j + 1);

      graph.removeEdge(x, y);
      graph.removeEdge(z, y);
      graph.addDirectedEdge(x, y);
      graph.addDirectedEdge(z, y);
    }

    return graph;
  }
Ejemplo n.º 26
0
  private boolean dConnected(Graph graph, String x, String y, String... z) {
    Node _x = graph.getNode(x);
    Node _y = graph.getNode(y);

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

    for (String name : z) {
      _z.add(graph.getNode(name));
    }

    return graph.isDConnectedTo(_x, _y, _z);
  }
Ejemplo n.º 27
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;
  }
Ejemplo n.º 28
0
  private void addColliders(
      Graph graph, final SepsetProducer sepsetProducer, IKnowledge knowledge) {
    final Map<Triple, Double> collidersPs =
        findCollidersUsingSepsets(sepsetProducer, graph, verbose, knowledge);

    List<Triple> colliders = new ArrayList<>(collidersPs.keySet());

    Collections.shuffle(colliders);

    Collections.sort(
        colliders,
        new Comparator<Triple>() {
          public int compare(Triple o1, Triple o2) {
            return -Double.compare(collidersPs.get(o1), collidersPs.get(o2));
          }
        });

    if (trueDag != null) {
      for (Triple collider : colliders) {
        Node a = collider.getX();
        Node b = collider.getY();
        Node c = collider.getZ();

        List<Node> sep = trueDag.getSepset(a, c);

        System.out.println(
            "JJJ "
                + collider
                + " collider = "
                + (sep != null && !sep.contains(b))
                + " p = "
                + collidersPs.get(collider));
      }
    }

    for (Triple collider : colliders) {
      Node a = collider.getX();
      Node b = collider.getY();
      Node c = collider.getZ();

      if (!(isArrowpointAllowed(a, b, knowledge) && isArrowpointAllowed(c, b, knowledge))) {
        continue;
      }

      if (!graph.getEdge(a, b).pointsTowards(a) && !graph.getEdge(b, c).pointsTowards(c)) {
        graph.setEndpoint(a, b, Endpoint.ARROW);
        graph.setEndpoint(c, b, Endpoint.ARROW);
      }
    }
  }
  /** Orients according to background knowledge. */
  public static void pcOrientbk(Knowledge bk, Graph graph, List<Node> nodes) {
    TetradLogger.getInstance().log("info", "Staring BK Orientation.");
    for (Iterator<KnowledgeEdge> it = bk.forbiddenEdgesIterator(); it.hasNext(); ) {
      KnowledgeEdge edge = it.next();

      // match strings to variables in the graph.
      Node from = translate(edge.getFrom(), nodes);
      Node to = translate(edge.getTo(), nodes);

      if (from == null || to == null) {
        continue;
      }

      if (graph.getEdge(from, to) == null) {
        continue;
      }

      // Orient to-->from
      graph.removeEdge(from, to);
      graph.addDirectedEdge(from, to);
      graph.setEndpoint(from, to, Endpoint.TAIL);
      graph.setEndpoint(to, from, Endpoint.ARROW);

      TetradLogger.getInstance()
          .edgeOriented(SearchLogUtils.edgeOrientedMsg("Knowledge", graph.getEdge(to, from)));
    }

    for (Iterator<KnowledgeEdge> it = bk.requiredEdgesIterator(); it.hasNext(); ) {
      KnowledgeEdge edge = it.next();

      // match strings to variables in this graph
      Node from = translate(edge.getFrom(), nodes);
      Node to = translate(edge.getTo(), nodes);

      if (from == null || to == null) {
        continue;
      }

      if (graph.getEdge(from, to) == null) {
        continue;
      }

      // Orient from-->to
      graph.setEndpoint(to, from, Endpoint.TAIL);
      graph.setEndpoint(from, to, Endpoint.ARROW);
      TetradLogger.getInstance()
          .edgeOriented(SearchLogUtils.edgeOrientedMsg("Knowledge", graph.getEdge(from, to)));
    }
    TetradLogger.getInstance().log("info", "Finishing BK Orientation.");
  }
  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);
        }
      }
    }
  }