Beispiel #1
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;
  }
Beispiel #2
0
  /**
   * @return Returns the error covariance matrix of the model. i.e. [a][b] is the covariance of E_a
   *     and E_b, with [a][a] of course being the variance of E_a. THESE ARE NOT PARAMETERS OF THE
   *     MODEL; THEY ARE CALCULATED. Note that elements of this matrix may be Double.NaN; this
   *     indicates that these elements cannot be calculated.
   */
  private TetradMatrix errCovar(Map<Node, Double> errorVariances) {
    List<Node> variableNodes = getVariableNodes();
    List<Node> errorNodes = new ArrayList<Node>();

    for (Node node : variableNodes) {
      errorNodes.add(semGraph.getExogenous(node));
    }

    TetradMatrix errorCovar = new TetradMatrix(errorVariances.size(), errorVariances.size());

    for (int index = 0; index < errorNodes.size(); index++) {
      Node error = errorNodes.get(index);
      double variance = getErrorVariance(error);
      errorCovar.set(index, index, variance);
    }

    for (int index1 = 0; index1 < errorNodes.size(); index1++) {
      for (int index2 = 0; index2 < errorNodes.size(); index2++) {
        Node error1 = errorNodes.get(index1);
        Node error2 = errorNodes.get(index2);
        Edge edge = semGraph.getEdge(error1, error2);

        if (edge != null && Edges.isBidirectedEdge(edge)) {
          double covariance = getErrorCovariance(error1, error2);
          errorCovar.set(index1, index2, covariance);
        }
      }
    }

    return errorCovar;
  }
  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;
    }
  }
Beispiel #4
0
  /** Returns true iif the given set forms a clique in the given graph. */
  private static boolean isClique(List<Node> nodes, Graph graph) {
    for (int i = 0; i < nodes.size() - 1; i++) {
      for (int j = i + 1; j < nodes.size(); j++) {
        if (!graph.isAdjacentTo(nodes.get(i), nodes.get(j))) {
          return false;
        }
      }
    }

    return true;
  }
Beispiel #5
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;
  }
Beispiel #6
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;
  }
Beispiel #7
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;
  }
Beispiel #8
0
 private static int weight(List<Node> nodes, Graph graph, int total, int b) {
   double p = 1;
   int degree = graph.getNumEdges(nodes.get(b));
   int t = degree + 1;
   total += pow((double) t, p);
   return total;
 }
Beispiel #9
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;
  }
Beispiel #10
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);
  }
  private boolean clique(Set<Integer> cluster, Map<Node, Set<Node>> adjacencies) {
    List<Integer> _cluster = new ArrayList<Integer>(cluster);

    for (int i = 0; i < cluster.size(); i++) {
      for (int j = i + 1; j < cluster.size(); j++) {
        Node nodei = variables.get(_cluster.get(i));
        Node nodej = variables.get(_cluster.get(j));

        if (!adjacencies.get(nodei).contains(nodej)) {
          return false;
        }
      }
    }

    return true;
  }
Beispiel #12
0
  /** Removes the knowledge group at the given index. */
  public void removeKnowledgeGroup(int index) {
    OrderedPair<Set<MyNode>> old = knowledgeGroupRules.get(knowledgeGroups.get(index));

    forbiddenRulesSpecs.remove(old);
    requiredRulesSpecs.remove(old);

    this.knowledgeGroups.remove(index);
  }
Beispiel #13
0
  public static Graph weightedRandomGraph(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 = weightedRandom(nodes, graph);
      //            int i2 = RandomUtil.getInstance().nextInt(n);
      int i2 = weightedRandom(nodes, graph);

      if (!(shortestPath(nodes.get(i1), nodes.get(i2), graph) < 9)) {
        e0--;
        continue;
      }

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

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

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

      graph.addEdge(edge);
    }

    for (Edge edge : graph.getEdges()) {
      Node n1 = edge.getNode1();
      Node n2 = edge.getNode2();

      if (!graph.isAncestorOf(n2, n1)) {
        graph.removeEdge(edge);
        graph.addDirectedEdge(n1, n2);
      } else {
        graph.removeEdge(edge);
        graph.addDirectedEdge(n2, n1);
      }
    }

    return graph;
  }
Beispiel #14
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;
  }
Beispiel #15
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();
  }
  /**
   * Constructs a list of nodes from the given <code>nodes</code> list at the given indices in that
   * list.
   *
   * @param indices The indices of the desired nodes in <code>nodes</code>.
   * @param nodes The list of nodes from which we select a sublist.
   * @return the The sublist selected.
   */
  public static List<Node> asList(int[] indices, List<Node> nodes) {
    List<Node> list = new LinkedList<Node>();

    for (int i : indices) {
      list.add(nodes.get(i));
    }

    return list;
  }
  /**
   * 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 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;
  }
 private boolean testVanishing(int x, int y, int z, int w) {
   if (testType == TestType.TETRAD_DELTA) {
     Tetrad t1 =
         new Tetrad(variables.get(x), variables.get(y), variables.get(z), variables.get(w));
     Tetrad t2 =
         new Tetrad(variables.get(x), variables.get(y), variables.get(w), variables.get(z));
     double p = deltaTest.getPValue(t1, t2);
     return p > alpha;
   } else {
     return test.tetradHolds(x, y, z, w) && test.tetradHolds(x, y, w, z);
   }
 }
Beispiel #20
0
  /** Tests to see if d separation facts are symmetric. */
  public void testDSeparation2() {
    EdgeListGraphSingleConnections graph =
        new EdgeListGraphSingleConnections(
            new Dag(GraphUtils.randomGraph(7, 0, 14, 30, 15, 15, true)));

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

    int depth = -1;

    for (int i = 0; i < nodes.size(); i++) {
      for (int j = i; j < nodes.size(); j++) {
        Node x = nodes.get(i);
        Node y = nodes.get(j);

        List<Node> theRest = new ArrayList<Node>(nodes);
        //                theRest.remove(x);
        //                theRest.remove(y);

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

        while ((choice = gen.next()) != null) {
          List<Node> z = new LinkedList<Node>();

          for (int k = 0; k < choice.length; k++) {
            z.add(theRest.get(choice[k]));
          }

          boolean dConnectedTo = graph.isDConnectedTo(x, y, z);
          boolean dConnectedTo1 = graph.isDConnectedTo(y, x, z);

          if (dConnectedTo != dConnectedTo1) {
            System.out.println(x + " d connected to " + y + " given " + z);
            System.out.println(graph);
            System.out.println("dconnectedto = " + dConnectedTo);
            System.out.println("dconnecteto1 = " + dConnectedTo1);
            fail();
          }
        }
      }
    }
  }
  /** 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;
  }
  private List<Node> variablesForIndices(List<Integer> cluster) {
    List<Node> _cluster = new ArrayList<Node>();

    for (int c : cluster) {
      _cluster.add(variables.get(c));
    }

    Collections.sort(_cluster);

    return _cluster;
  }
Beispiel #23
0
  /** Tests to see if d separation facts are symmetric. */
  public void testDSeparation() {
    EdgeListGraphSingleConnections graph =
        new EdgeListGraphSingleConnections(
            new Dag(GraphUtils.randomGraph(7, 0, 7, 30, 15, 15, true)));
    System.out.println(graph);

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

    int depth = -1;

    for (int i = 0; i < nodes.size(); i++) {
      for (int j = i + 1; j < nodes.size(); j++) {
        Node x = nodes.get(i);
        Node y = nodes.get(j);

        List<Node> theRest = new ArrayList<Node>(nodes);
        theRest.remove(x);
        theRest.remove(y);

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

        while ((choice = gen.next()) != null) {
          List<Node> z = new LinkedList<Node>();

          for (int k = 0; k < choice.length; k++) {
            z.add(theRest.get(choice[k]));
          }

          if (graph.isDSeparatedFrom(x, y, z) != graph.isDSeparatedFrom(y, x, z)) {
            fail(
                SearchLogUtils.independenceFact(x, y, z)
                    + " should have same d-sep result as "
                    + SearchLogUtils.independenceFact(y, x, z));
          }
        }
      }
    }
  }
 public static List<Set<Node>> powerSet(List<Node> nodes) {
   List<Set<Node>> subsets = new ArrayList<Set<Node>>();
   int total = (int) Math.pow(2, nodes.size());
   for (int i = 0; i < total; i++) {
     Set<Node> newSet = new HashSet<Node>();
     String selection = Integer.toBinaryString(i);
     for (int j = selection.length() - 1; j >= 0; j--) {
       if (selection.charAt(j) == '1') {
         newSet.add(nodes.get(selection.length() - j - 1));
       }
     }
     subsets.add(newSet);
   }
   return subsets;
 }
Beispiel #25
0
  /** Legacy, do not use. */
  public void setKnowledgeGroup(int index, KnowledgeGroup group) {
    OrderedPair<Set<MyNode>> o = getGroupRule(group);
    OrderedPair<Set<MyNode>> old = knowledgeGroupRules.get(knowledgeGroups.get(index));

    forbiddenRulesSpecs.remove(old);
    requiredRulesSpecs.remove(old);

    if (group.getType() == KnowledgeGroup.FORBIDDEN) {
      forbiddenRulesSpecs.add(o);
    } else if (group.getType() == KnowledgeGroup.REQUIRED) {
      requiredRulesSpecs.add(o);
    }

    knowledgeGroups.set(index, group);
  }
  private Graph convertToGraph(Set<Set<Integer>> allClusters) {
    Set<Set<Node>> _clustering = new HashSet<Set<Node>>();

    for (Set<Integer> cluster : allClusters) {
      Set<Node> nodes = new HashSet<Node>();

      for (int i : cluster) {
        nodes.add(variables.get(i));
      }

      _clustering.add(nodes);
    }

    return convertSearchGraphNodes(_clustering);
  }
Beispiel #27
0
  /**
   * @param node The variable node in question.
   * @return the error node for the given node.
   */
  public Node getErrorNode(Node node) {
    if (errorNodes.contains(node)) {
      return node;
    }

    int index = variableNodes.indexOf(node);

    if (index == -1) {
      throw new NullPointerException(
          node
              + " is not a node in this model. Perhaps "
              + "it's another node with the same name.");
    }

    return errorNodes.get(index);
  }
Beispiel #28
0
  public Lofs(Graph pattern, List<DataSet> dataSets) throws IllegalArgumentException {

    if (pattern == null) {
      throw new IllegalArgumentException("Pattern must be specified.");
    }

    if (dataSets == null) {
      throw new IllegalArgumentException("Data set must be specified.");
    }

    this.pattern = pattern;
    this.dataSets = dataSets;

    regressions = new ArrayList<Regression>();
    this.variables = dataSets.get(0).getVariables();

    for (DataSet dataSet : dataSets) {
      regressions.add(new RegressionDataset(dataSet));
    }
  }
  /**
   * 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 static void orientCollidersUsingSepsets(SepsetMap set, Knowledge knowledge, Graph graph) {
    TetradLogger.getInstance().log("info", "Starting Collider Orientation:");

    //        verifySepsetIntegrity(set, graph);

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

    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;
        }

        List<Node> sepset = set.get(b, c);
        if (sepset != null
            && !sepset.contains(a)
            && isArrowpointAllowed(b, a, knowledge)
            && isArrowpointAllowed(c, a, knowledge)) {
          graph.setEndpoint(b, a, Endpoint.ARROW);
          graph.setEndpoint(c, a, Endpoint.ARROW);
          TetradLogger.getInstance()
              .log("colliderOriented", SearchLogUtils.colliderOrientedMsg(b, a, c, sepset));
        }
      }
    }

    TetradLogger.getInstance().log("info", "Finishing Collider Orientation.");
  }
  /** If */
  public static boolean meekR2(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() < 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]);

        if (graph.isDirectedFromTo(b, a)
            && graph.isDirectedFromTo(a, c)
            && graph.isUndirectedFromTo(b, c)) {
          if (isArrowpointAllowed(b, c, knowledge)) {
            graph.setEndpoint(b, c, Endpoint.ARROW);
            TetradLogger.getInstance()
                .edgeOriented(SearchLogUtils.edgeOrientedMsg("Meek R2", graph.getEdge(b, c)));
          }
        } else if (graph.isDirectedFromTo(c, a)
            && graph.isDirectedFromTo(a, b)
            && graph.isUndirectedFromTo(c, b)) {
          if (isArrowpointAllowed(c, b, knowledge)) {
            graph.setEndpoint(c, b, Endpoint.ARROW);
            TetradLogger.getInstance()
                .edgeOriented(SearchLogUtils.edgeOrientedMsg("Meek R2", graph.getEdge(c, b)));
          }
        }
      }
    }

    return changed;
  }