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; }
public GraphIndex(Graph graph) { LOG.info("Indexing graph..."); for (String feedId : graph.getFeedIds()) { for (Agency agency : graph.getAgencies(feedId)) { Map<String, Agency> agencyForId = agenciesForFeedId.getOrDefault(feedId, new HashMap<>()); agencyForId.put(agency.getId(), agency); this.agenciesForFeedId.put(feedId, agencyForId); } } Collection<Edge> edges = graph.getEdges(); /* We will keep a separate set of all vertices in case some have the same label. * Maybe we should just guarantee unique labels. */ Set<Vertex> vertices = Sets.newHashSet(); for (Edge edge : edges) { vertices.add(edge.getFromVertex()); vertices.add(edge.getToVertex()); if (edge instanceof TablePatternEdge) { TablePatternEdge patternEdge = (TablePatternEdge) edge; TripPattern pattern = patternEdge.getPattern(); patternForId.put(pattern.code, pattern); } } for (Vertex vertex : vertices) { vertexForId.put(vertex.getLabel(), vertex); if (vertex instanceof TransitStop) { TransitStop transitStop = (TransitStop) vertex; Stop stop = transitStop.getStop(); stopForId.put(stop.getId(), stop); stopVertexForStop.put(stop, transitStop); stopsForParentStation.put(stop.getParentStation(), stop); } } for (TransitStop stopVertex : stopVertexForStop.values()) { Envelope envelope = new Envelope(stopVertex.getCoordinate()); stopSpatialIndex.insert(envelope, stopVertex); } for (TripPattern pattern : patternForId.values()) { patternsForFeedId.put(pattern.getFeedId(), pattern); patternsForRoute.put(pattern.route, pattern); for (Trip trip : pattern.getTrips()) { patternForTrip.put(trip, pattern); tripForId.put(trip.getId(), trip); } for (Stop stop : pattern.getStops()) { patternsForStop.put(stop, pattern); } } for (Route route : patternsForRoute.asMap().keySet()) { routeForId.put(route.getId(), route); } // Copy these two service indexes from the graph until we have better ones. calendarService = graph.getCalendarService(); serviceCodes = graph.serviceCodes; this.graph = graph; LOG.info("Done indexing graph."); }
protected Graph<String, DefaultWeightedEdge> createWithBias(boolean negate) { Graph<String, DefaultWeightedEdge> g; double bias = 1; if (negate) { // negative-weight edges are being tested, so only a directed graph // makes sense g = new SimpleDirectedWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class); bias = -1; } else { // by default, use an undirected graph g = new SimpleWeightedGraph<String, DefaultWeightedEdge>(DefaultWeightedEdge.class); } g.addVertex(V1); g.addVertex(V2); g.addVertex(V3); g.addVertex(V4); g.addVertex(V5); e12 = Graphs.addEdge(g, V1, V2, bias * 2); e13 = Graphs.addEdge(g, V1, V3, bias * 3); e24 = Graphs.addEdge(g, V2, V4, bias * 5); e34 = Graphs.addEdge(g, V3, V4, bias * 20); e45 = Graphs.addEdge(g, V4, V5, bias * 5); e15 = Graphs.addEdge(g, V1, V5, bias * 100); return g; }
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; }
/** * Generates AdjacencyListGraph based on the values in the input file. * * @requires twitterStream is properly initialized * @param twitterStream initialized input stream for reading twitter file * @return generated graph based on input file */ private static Graph readTwitterFile(FileInputStream twitterStream) { final int U1_INDEX = 0; final int U2_INDEX = 1; try { Graph g = new AdjacencyListGraph(); BufferedReader twitterReader = new BufferedReader(new InputStreamReader(twitterStream)); String line; while ((line = twitterReader.readLine()) != null) { // eliminate any unnecessary whitespace String[] columns = line.trim().replaceAll("\\s+", "").split("->"); // first column is user 1 // second column is user 2 Vertex u1 = new Vertex(columns[U1_INDEX]); Vertex u2 = new Vertex(columns[U2_INDEX]); // System.out.println(columns[0]+","+columns[1]); g.addVertex(u1); g.addVertex(u2); g.addEdge(u1, u2); // System.out.println(line); } twitterReader.close(); return g; } catch (Exception e) { // if something somehow goes wrong throw new RuntimeException(e); } }
Graph create(Collection<? extends Deployer> deployers) { // S ← Set of all nodes with no incoming edges List<Deployer> s = new ArrayList<Deployer>(); Map<String, Collection<Deployer>> inputCache = new HashMap<String, Collection<Deployer>>(); // Map<Deployer, Set<Edge>> edgeCache = new IdentityHashMap<Deployer, Set<Edge>>(); Map edgeCache = new IdentityHashMap<Deployer, Set<?>>(); Set<String> outputs = new HashSet<String>(); Map<String, Collection<Deployer>> outputCache = new HashMap<String, Collection<Deployer>>(); for (Deployer deployer : deployers) { process(deployer, s, inputCache, edgeCache, outputs, outputCache); } processTransientDeployers(s, inputCache, outputCache, edgeCache); Graph graph = new Graph(); for (Deployer d : deployers) { graph.addNode(d.toString()); } for (Map.Entry entry : (Set<Map.Entry>) edgeCache.entrySet()) { System.out.println(entry); Set<Object> edges = (Set<Object>) entry.getValue(); for (Object edge : edges) { String fromNode = fromNode(edge); String edgeLabel = edgeLabel(edge); String toNode = toNode(edge); graph.addEdge(fromNode, toNode, edgeLabel); } } System.out.println(graph.edges.size()); return graph; }
/** 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); } }
/** * Creates a new iterator for the specified graph. Iteration will start at the specified start * vertex. If the specified start vertex is <code> * null</code>, Iteration will start at an arbitrary graph vertex. * * @param g the graph to be iterated. * @param startVertex the vertex iteration to be started. * @throws IllegalArgumentException if <code>g==null</code> or does not contain <code>startVertex * </code> */ public CrossComponentIterator(Graph<V, E> g, V startVertex) { super(); if (g == null) { throw new IllegalArgumentException("graph must not be null"); } graph = g; specifics = createGraphSpecifics(g); vertexIterator = g.vertexSet().iterator(); setCrossComponentTraversal(startVertex == null); reusableEdgeEvent = new FlyweightEdgeEvent<V, E>(this, null); reusableVertexEvent = new FlyweightVertexEvent<V>(this, null); if (startVertex == null) { // pick a start vertex if graph not empty if (vertexIterator.hasNext()) { this.startVertex = vertexIterator.next(); } else { this.startVertex = null; } } else if (g.containsVertex(startVertex)) { this.startVertex = startVertex; } else { throw new IllegalArgumentException("graph must contain the start vertex"); } }
private void init(Graph<V, E> g, Set<V> vertexSet, Set<E> edgeSet) { // create a map between vertex value to its order(1st,2nd,etc) // "CAT"=1 "DOG"=2 "RHINO"=3 this.mapVertexToOrder = new HashMap<V, Integer>(vertexSet.size()); int counter = 0; for (V vertex : vertexSet) { mapVertexToOrder.put(vertex, new Integer(counter)); counter++; } // create a friendlier representation of an edge // by order, like 2nd->3rd instead of B->A // use the map to convert vertex to order // on directed graph, edge A->B must be (A,B) // on undirected graph, edge A-B can be (A,B) or (B,A) this.labelsEdgesSet = new HashSet<LabelsEdge>(edgeSet.size()); for (E edge : edgeSet) { V sourceVertex = g.getEdgeSource(edge); Integer sourceOrder = mapVertexToOrder.get(sourceVertex); int sourceLabel = sourceOrder.intValue(); int targetLabel = (mapVertexToOrder.get(g.getEdgeTarget(edge))).intValue(); LabelsEdge lablesEdge = new LabelsEdge(sourceLabel, targetLabel); this.labelsEdgesSet.add(lablesEdge); if (g instanceof UndirectedGraph<?, ?>) { LabelsEdge oppositeEdge = new LabelsEdge(targetLabel, sourceLabel); this.labelsEdgesSet.add(oppositeEdge); } } }
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; }
/** * @param vertexNumber the number which identifies the vertex v in this order. * @return the identifying numbers of all vertices which are connected to v by an edge incoming to * v. */ public int[] getInEdges(int vertexNumber) { if (cacheEdges && (incomingEdges[vertexNumber] != null)) { return incomingEdges[vertexNumber]; } V v = getVertex(vertexNumber); Set<E> edgeSet; if (graph instanceof DirectedGraph<?, ?>) { edgeSet = ((DirectedGraph<V, E>) graph).incomingEdgesOf(v); } else { edgeSet = graph.edgesOf(v); } int[] vertexArray = new int[edgeSet.size()]; int i = 0; for (E edge : edgeSet) { V source = graph.getEdgeSource(edge), target = graph.getEdgeTarget(edge); vertexArray[i++] = mapVertexToOrder.get(source.equals(v) ? target : source); } if (cacheEdges) { incomingEdges[vertexNumber] = vertexArray; } return vertexArray; }
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; }
//////////////////////////////////////////////// // 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); }
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); }
public Graph copy() { WeightedArcSet list = new WeightedArcSet(); Constructor[] cons = WeightedArc.class.getDeclaredConstructors(); for (int i = 0; i < cons.length; i++) cons[i].setAccessible(true); ArcLabelledNodeIterator it = graph.nodeIterator(); while (it.hasNext()) { Integer aux1 = it.nextInt(); Integer aux2 = null; ArcLabelledNodeIterator.LabelledArcIterator suc = it.successors(); while ((aux2 = suc.nextInt()) != null && aux2 >= 0 && (aux2 < graph.numNodes())) try { if (commit++ % COMMIT_SIZE == 0) { list.commit(); } WeightedArc arc = (WeightedArc) cons[0].newInstance(aux2, aux1, suc.label().getFloat()); list.add(arc); } catch (Exception ex) { throw new Error(ex); } } Graph result = new Graph(list.toArray(new WeightedArc[0])); result.nodes.clear(); result.nodesReverse.clear(); for (Integer n : this.nodes.keySet()) { if (commit++ % COMMIT_SIZE == 0) { result.commit(); } result.nodesReverse.put(this.nodes.get(n), n); result.nodes.put(n, this.nodes.get(n)); } return result; }
/** * Random graph. Generates randomly k directed edges out of each node. The neighbors (edge * targets) are chosen randomly without replacement from the nodes of the graph other than the * source node (i.e. no loop edge is added). If k is larger than N-1 (where N is the number of * nodes) then k is set to be N-1 and a complete graph is returned. * * @param g the graph to be wired * @param k samples to be drawn for each node * @param r source of randomness * @return returns g for convenience */ public static Graph wireKOut(Graph g, int k, Random r) { final int n = g.size(); if (n < 2) { return g; } if (n <= k) { k = n - 1; } int[] nodes = new int[n]; for (int i = 0; i < nodes.length; ++i) { nodes[i] = i; } for (int i = 0; i < n; ++i) { int j = 0; while (j < k) { int newedge = j + r.nextInt(n - j); int tmp = nodes[j]; nodes[j] = nodes[newedge]; nodes[newedge] = tmp; if (nodes[j] != i) { g.setEdge(i, nodes[j]); j++; } } } return g; }
// ===========================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; }
/** @return dfs wenn gefunden, ansonsten NULL */ @Override public Graph<Integer> dfs(Node<Integer> start, Node<Integer> goal) { this.unvisitAllNodes(); Graph<Integer> dfs = new ImplGraph(); dfs.setNode(start.value()); boolean found = this.dfs(start, goal, dfs); return found ? dfs : null; }
private void populateLists(List<Vertex> verticies, List<Edge> edges) { for (Vertex v : graph.getVertices()) { verticies.add(v); } for (Edge e : graph.getEdges()) { edges.add(e); } }
private Set<String> getDownstream(String mut) { Set<String> tfs = new HashSet<String>(); tfs.add(mut); if (depth > 1) tfs.addAll(travSt.getDownstream(tfs, depth - 1)); return travExp.getDownstream(tfs); }
/** * A sink star. Wires a sink star topology adding a link to 0 from all other nodes. * * @param g the graph to be wired * @return returns g for convenience */ public static Graph wireStar(Graph g) { final int n = g.size(); for (int i = 1; i < n; ++i) { g.setEdge(i, 0); } return g; }
public static void main(String[] args) { Graph g = new Graph(); g.addEdge(0, 1); g.addEdge(1, 2); System.out.println(g.edges); g.removeNode(1); System.out.println(g.edges); }
/** * 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; }
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; }
public int[] getEdgeNumbers(E e) { V v1 = graph.getEdgeSource(e), v2 = graph.getEdgeTarget(e); int[] edge = new int[2]; edge[0] = mapVertexToOrder.get(v1); edge[1] = mapVertexToOrder.get(v2); return edge; }
/** * 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."); }
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); }
public Graph transpose() { Graph g = copy(); try { g.graph = Transform.transposeOffline(g.graph, 1000); g.reverse = Transform.transposeOffline(g.reverse, 1000); } catch (IOException ex) { throw new Error(ex); } return g; }
public static GraphOrder forwardGraph(Graph graph) { GraphOrder result = new GraphOrder(); NodeBitMap visited = graph.createNodeBitMap(); for (ControlSinkNode node : graph.getNodes(ControlSinkNode.class)) { result.visitForward(visited, node); } return result; }
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; } }