Class GraphUtils
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classRepresents a comparison between two graphs.static enumThe GraphType enum represents the types of graphs that can be used in the application.static classTwo-cycle errors. -
Method Summary
Modifier and TypeMethodDescriptionstatic voidaddEdgeSpecializationMarkup(Graph graph) Adds markups for edge specializations for the edges in the given graph.static voidaddForbiddenReverseEdgesForDirectedEdges(Graph graph, Knowledge knowledge) Adds forbidden reverse edges for directed edges in the given graph based on the knowledge.anteriority(Graph G, Node... x) Computes the anteriority of the given nodes in a graph.static booleanapplyForbiddenCircleResolution(Graph pag, Knowledge knowledge) Resolves forbidden circles in the given partially oriented graph (PAG) based on the provided knowledge.asList(int[] choice) Creates a new list containing the elements of the given array.Constructs a list of nodes from the givennodeslist at the given indices in that list.Converts an array of indices into a set of corresponding nodes from a given list of nodes.Converts the given array of nodes into a Set of nodes.static booleanbidirectedExistsLatentCommonCause(Edge edge, Graph trueGraph) Determines whether a bidirected edge exists due to a latent common cause in the given graph.static booleanbidirectedExistsLatentCommonCauseUncovered(Edge edge, Graph trueGraph, Graph estGraph) Determines whether the given bidirected edge has a latent common cause in the true graph via a trek x <~~ L ~~> y whose source L is latent, but where at least one consecutive pair of nodes (w, r) along the trek is NOT adjacent in the estimated graph.static booleanbidirectedExistsLatentConfounder(Edge edge, Graph trueGraph) Determines if the given bidirected edge has a latent confounder in the true graph--that is, whether for X <-> Y there is a latent node Z such that X <- (Z) -> Y.static GraphbidirectedToUndirected(Graph graph) Converts a bidirected graph to an undirected graph.static booleanDetermines if the collider is allowed.static booleancompatible(Edge edge1, Edge edge2) Determines if two edges are compatible.static GraphcompleteGraph(Graph graph) completeGraph.Identifies all connected components in a given graph.static booleancontainsBidirectedEdge(Graph graph) Checks if a given graph contains a bidirected edge.static GraphConverts a string spec of a graph--for example, "X1-->X2, X1---X3, X2o->X4, X3<->X4" to a Graph.static NodeReturns a copy of the given node that is equal to it (same name, type, and, for a discrete variable, the same categories, so that it indexes the same column of a data set) and has the same position, but is a distinct object, so that a position later set on either is not seen through the other.static intcountAdjErrors(Graph graph1, Graph graph2) Counts the adjacencies that are in graph1 but not in graph2.static intCalculates the maximum degree of a graph.static GraphdetachNodes(Graph graph) Returns a copy of the graph whose nodes are fresh objects (seecopyNode(Node)), equal to the originals and in the same positions, with the same edges (including their properties, edge type probabilities, and display attributes), underlines, ambiguous triples, and graph attributes.static booleanDetermines whether threeNodeobjects are distinct.Calculates the district of a given node in a graph.Returns D-SEP(x, y) for a MAG G.Returns D-SEP(x, y) for a MAG G (or inducing path graph G, as in Causation, Prediction and Search).Returns D-SEP(x, y) for a MAG G.dsepReachability(Node x, Node y, Graph G) Returns D-SEP(x, y) for a MAG G.static int[][]edgeMisclassificationCounts(Graph leftGraph, Graph topGraph, boolean print) Computes the misclassification counts for each edge in the given graphs.static StringedgeMisclassifications(double[][] counts, NumberFormat nf) Generates a textual representation of the edge misclassifications based on the provided counts and number format.static StringedgeMisclassifications(int[][] counts) Calculates the misclassifications of edges based on the given counts.static GraphemptyGraph(int numNodes) Creates an empty graph with the specified number of nodes.static @NotNull GraphfixDirections(Graph graph) Processes the given graph by fixing the directions of edges to ensure consistency, flipping edges where necessary, and optionally preserving ancillary graph information.static GraphgetAdjacencySubgraphWithTargetNode(Graph graph, Node target) Calculates the subgraph over the adjacency of a target node for a DAG, CPDAG, MAG, or PAG.getAmbiguousTriplesFromGraph(Node node, Graph graph) Retrieves the list of ambiguous triples from the given graph for a given node.static NodegetAssociatedNode(Node errorNode, Graph graph) Returns the associated node for the given error node in the specified graph.static GraphgetComparisonGraph(Graph graph, Parameters params) Returns a comparison graph based on the specified parameters.static intReturns the maximum degree of a graph.getDottedUnderlinedTriplesFromGraph(Node node, Graph graph) Retrieves the list of dotted and underlined triples from the given graph, with the specified node as the middle node.static GraphgetGraphWithoutXToY(Graph G, Node x, Node y, GraphUtils.GraphType graphType) Returns a graph that is obtained by removing the edge from node x to node y from the input graph.static intgetIndegree(Graph graph) Calculates the maximum indegree in a given graph.static StringgetIntersectionComparisonString(List<Graph> graphs) Generates a comparison string for the intersection of multiple graphs.static GraphgetMarkovBlanketSubgraphWithTargetNode(Graph graph, Node target) Calculates the subgraph over the Markov blanket of a target node for a DAG, CPDAG, MAG, or PAG.static intgetNumCoveringAdjacenciesInPag(Graph trueGraph, Graph estGraph) Returns the number of covering edges in the given estimated partial ancestral graph (PAG) with respect to the given true PAG.static intgetNumInducedAdjacenciesInPag(Graph trueGraph, Graph estGraph) Calculates the number of induced adjacencies in the given estiamted Partial Ancestral (PAG) with respect to the given true PAG.static GraphgetParentsSubgraphWithTargetNode(Graph graph, Node target) Calculates the subgraph over the parents of a target node for a DAG, CPDAG, MAG, or PAG.static @NotNull GraphgetReplicatingGraph(Graph graph) Creates a replicating graph based on the provided graph.static NodegetTrekSource(Graph graph, List<Node> trek) This method returns the source node of a given trek in a graph.static GraphUtils.TwoCycleErrorsgetTwoCycleErrors(Graph trueGraph, Graph estGraph) Returns the TwoCycleErrors object that represents errors for direct feedback loops.getUnderlinedTriplesFromGraph(Node node, Graph graph) Retrieves the underlined triples from the given graph that involve the specified node.static StringgraphAttributesToText(Graph graph, String title) Converts the attributes of a given graph into a text format.static StringgraphEdgesToText(Graph graph, String title) Converts the edges of a graph to text representation.static StringgraphNodeAttributesToText(Graph graph, String title, char delimiter) Converts the attributes of nodes in a graph to text format.static StringgraphNodesToText(Graph graph, String title, char delimiter) Converts the nodes of a graph to a formatted text representation.static GraphguaranteePag(Graph pag, FciOrient fciOrient, Knowledge knowledge, Set<Triple> knownColliders, boolean verbose, Set<Node> selection, boolean excludeSelectionBias, int recursiveDepth) Guarantees the correctness of a Partial Ancestral Graph (PAG) by repairing faulty structures such as cycles, violations of maximality, and incorrectly oriented edges, using FCI orientation rules and knowledge constraints.static booleanisClique(Collection<Node> set, Graph graph) Checks if the given set of nodes forms a clique in the specified graph.static booleanChecks if the given trek in a graph is a confounding trek.static booleanisCoveringAdjacency(Graph trueGraph, Graph estGraph, Node x, Node y) Determines whether an edge between two nodes in the estimated graph is covering a collider or noncollider in the true graph.static booleanDetermines if the given graph is a directed acyclic graph (DAG).static LinkedList<Triple> listColliderTriples(Graph graph) Generates a list of triples where a node acts as a collider in a given graph.static doublelocalMarkovInitializePValues(Graph dag, boolean preserveMarkov, IndependenceTest test, Map<org.apache.commons.lang3.tuple.Pair<Node, Node>, Set<Double>> pValues) Initializes and evaluates p-values for local Markov properties in a given graph.markovBlanket(Node x, Graph G) Computes the Markov blanket for a given node in a graph.static GraphmarkovBlanketSubgraph(Node target, Graph graph) Calculates the subgraph over the Markov blanket of a target node in a given DAG, CPDAG, MAG, or PAG.maximalCliques(Graph graph, List<Node> nodes) Finds all maximal cliques in a given graph.static GraphnondirectedGraph(Graph graph) undirectedGraph.static voidorientCollider(Graph g, Node x, Node z, Node y) Orients the edges of the given graph by setting both specified nodes as arrow endpoints directed towards the specified target node.static StringpathString(Graph graph, Node... x) Generates a string representation of a path in a given graph, starting from the specified nodes.static StringpathString(Graph graph, List<Node> path, boolean showBlocked) Constructs a string representation of a path in a graph.static StringReturns a string representation of the given path in the graph, considering the conditioning variables.static StringpathString(Graph graph, List<Node> path, Set<Node> conditioningVars, boolean showBlocked, boolean excludeSelectionBias) Returns a string representation of the given path in the graph, with additional information about conditioning variables.static doubleCalculates the p-value using the Anderson-Darling test for a given set of p-values from an independence test.static voidrecallInitialColliders(Graph pag, Set<Triple> initialColliders, Knowledge knowledge) Recall unshielded triples in a given graph.static GraphremoveBidirectedOrientations(Graph estCpdag) removeBidirectedOrientations.static voidremoveNonSkeletonEdges(Graph graph, Knowledge knowledge) Removes non-skeleton edges from the given graph based on the provided knowledge.static voidreorientWithCircles(Graph pag, boolean verbose) Reorients all edges in a Graph as o-o.static booleanrepairMaximality(Graph pag, boolean verbose, Set<Node> selection, FciOrient fciOrient, Knowledge knowledge, Set<Triple> knownColliders) Repairs the maximality of a PAG (Partial Ancestral Graph) by ensuring that any inducing path between two nodes not currently adjacent in the graph results in an added non-directed edge.static GraphreplaceNodes(Graph originalGraph, List<Node> newVariables) Converts the given graph,originalGraph, to use the new variables (with the same names as the old).replaceNodes(List<Node> originalNodes, Graph graph) Converts the given list of nodes,originalNodes, to use the replacement nodes for them by the same name in the givengraph.replaceNodes(List<Node> originalNodes, List<Node> newNodes) Converts the given list of nodes,originalNodes, to use the new variables (with the same names as the old).static GraphrestrictToMeasured(Graph graph) Removes all latent nodes from the graph and returns the modified graph.Compute strongly connected components (SCCs) of a directed graph.static NodetraversePotentiallyDirected(Node node, Edge edge) Traverses a potentially directed edge to identify the next node in the traversal.static booleantrekIsUncovered(Graph trueGraph, Graph estGraph, List<Node> trek) Checks whether the given trek is "uncovered" relative to the estimated graph in the following sense: every consecutive pair along the trek is adjacent in the true graph, and among the consecutive pairs whose BOTH endpoints are measured, at least one is non-adjacent in the estimated graph.static booleanChecks if the souce L of the given trek in a graph (not equal to x or y) is a latent.static GraphTrims the given graph based on the specified trimming style.static booleanChecks if three nodes are connected in a graph.static StringtriplesToText(Set<Triple> triples, String title) Converts a set of triples into a formatted string.static GraphundirectedGraph(Graph graph) undirectedGraph.static GraphundirectedToBidirected(Graph graph) Converts an undirected graph to a bidirected graph.visibleEdgeAdjustments1(Graph G, Node x, Node y, int numSmallestSizes, GraphUtils.GraphType graphType) Calculates visual-edge adjustments given graph G between two nodes x and y that are subsets of MB(X).visibleEdgeAdjustments3(Graph G, Node x, Node y, int numSmallestSizes, GraphUtils.GraphType graphType) This method calculates visible-edge adjustments for a given graph, two nodes, a number of smallest sizes, and a graph type.
-
Method Details
-
getAssociatedNode
Returns the associated node for the given error node in the specified graph.- Parameters:
errorNode- The error node for which the associated node needs to be retrieved.graph- The graph in which to search for the associated node.- Returns:
- The associated node of the error node.
- Throws:
IllegalArgumentException- If the error node is not of type ERROR or if it does not have exactly one child.
-
isClique
Checks if the given set of nodes forms a clique in the specified graph.- Parameters:
set- the collection of nodes to be checkedgraph- the graph in which the nodes are located- Returns:
- true if the given set forms a clique, false otherwise
-
markovBlanketSubgraph
Calculates the subgraph over the Markov blanket of a target node in a given DAG, CPDAG, MAG, or PAG. Target Node is not included in the result graph's nodes list. Edges including the target node is included in the result graph's edges list.- Parameters:
target- a node in the given graph.graph- a DAG, CPDAG, MAG, or PAG.- Returns:
- a
Graphobject
-
getMarkovBlanketSubgraphWithTargetNode
Calculates the subgraph over the Markov blanket of a target node for a DAG, CPDAG, MAG, or PAG. This is not necessarily minimal (i.e. not necessarily a Markov Boundary). Target Node is included in the result graph's nodes list. Edges including the target node is included in the result graph's edges list.- Parameters:
graph- a DAG, CPDAG, MAG, or PAG.target- a node in the given graph.- Returns:
- a
Graphobject
-
getParentsSubgraphWithTargetNode
Calculates the subgraph over the parents of a target node for a DAG, CPDAG, MAG, or PAG. This is not necessarily minimal (i.e. not necessarily a Markov Boundary). Target Node is included in the result graph's nodes list. Edges including the target node is included in the result graph's edges list.- Parameters:
graph- a DAG, CPDAG, MAG, or PAG.target- a node in the given graph.- Returns:
- a
Graphobject
-
getAdjacencySubgraphWithTargetNode
Calculates the subgraph over the adjacency of a target node for a DAG, CPDAG, MAG, or PAG. This is not necessarily minimal (i.e. not necessarily a Markov Boundary). Target Node is included in the result graph's nodes list. Edges including the target node is included in the result graph's edges list.- Parameters:
graph- a DAG, CPDAG, MAG, or PAG.target- a node in the given graph.- Returns:
- a
Graphobject
-
removeBidirectedOrientations
-
undirectedGraph
-
nondirectedGraph
-
completeGraph
-
bidirectedToUndirected
-
undirectedToBidirected
-
pathString
Constructs a string representation of a path in a graph.- Parameters:
graph- the graph in which the path existspath- the list of nodes representing the pathshowBlocked- determines whether blocked nodes should be included in the string representation- Returns:
- the string representation of the path
-
pathString
-
pathString
Returns a string representation of the given path in the graph, considering the conditioning variables.- Parameters:
graph- the graph to find the path inpath- the list of nodes representing the pathconditioningVars- the set of conditioning variables to consider- Returns:
- a string representation of the path
-
pathString
public static String pathString(Graph graph, List<Node> path, Set<Node> conditioningVars, boolean showBlocked, boolean excludeSelectionBias) Returns a string representation of the given path in the graph, with additional information about conditioning variables.- Parameters:
graph- the graph containing the pathpath- the list of nodes representing the pathconditioningVars- the list of nodes representing the conditioning variablesshowBlocked- whether to show information about blocked pathsexcludeSelectionBias- whether to exclude selection bias- Returns:
- a string representation of the path with conditioning information
-
replaceNodes
Converts the given graph,originalGraph, to use the new variables (with the same names as the old).- Parameters:
originalGraph- The graph to be converted.newVariables- The new variables to use, with the same names as the old ones.- Returns:
- A new, converted, graph.
-
copyNode
Returns a copy of the given node that is equal to it (same name, type, and, for a discrete variable, the same categories, so that it indexes the same column of a data set) and has the same position, but is a distinct object, so that a position later set on either is not seen through the other. Node-level attributes are copied.Positions (the center used by the workbench) live on node objects, not in graphs. Two graphs that share node objects therefore share a layout: a data set's variable objects are shared by every graph built from that data set, and a graph handed from one session box to another is shared by both. See
detachNodes(Graph)andEdgeListGraph(Graph, boolean).- Parameters:
node- the node to copy- Returns:
- the copy
-
detachNodes
Returns a copy of the graph whose nodes are fresh objects (seecopyNode(Node)), equal to the originals and in the same positions, with the same edges (including their properties, edge type probabilities, and display attributes), underlines, ambiguous triples, and graph attributes. UnlikereplaceNodes(Graph, List), latent nodes are copied too.Use this on a graph that is about to become the graph of a session box and whose nodes are shared with something else: a search result, whose nodes are usually the data set's variable objects, or the graph of another box. Once detached, the box starts with the layout the graph came with, but the layout the workbench writes to it afterwards stays with it, and it no longer follows positions set on the shared objects by some other box. Where a fresh layout is wanted instead, lay the copy out afterwards.
- Parameters:
graph- the graph- Returns:
- the copy
-
restrictToMeasured
-
replaceNodes
Converts the given list of nodes,originalNodes, to use the new variables (with the same names as the old).- Parameters:
originalNodes- The list of nodes to be converted.newNodes- A list of new nodes, containing as a subset nodes with the same names as those inoriginalNodes. the old ones.- Returns:
- The converted list of nodes.
-
countAdjErrors
Counts the adjacencies that are in graph1 but not in graph2.- Parameters:
graph1- aGraphobjectgraph2- aGraphobject- Returns:
- a int
- Throws:
IllegalArgumentException- if graph1 and graph2 are not namewise isomorphic.
-
replaceNodes
Converts the given list of nodes,originalNodes, to use the replacement nodes for them by the same name in the givengraph.- Parameters:
originalNodes- The list of nodes to be converted.graph- A graph to be used as a source of new nodes.- Returns:
- A new, converted, graph.
-
emptyGraph
Creates an empty graph with the specified number of nodes.- Parameters:
numNodes- the number of nodes to create in the graph- Returns:
- a new empty graph with the specified number of nodes
-
getAmbiguousTriplesFromGraph
Retrieves the list of ambiguous triples from the given graph for a given node. These are triple (X, Y, Z) for which Sepset(X, Z) contains Y for some sepsets but not others.- Parameters:
node- the node for which to find ambiguous triplesgraph- the graph from which to retrieve the ambiguous triples- Returns:
- the list of ambiguous triples found in the graph for the given node
-
getUnderlinedTriplesFromGraph
Retrieves the underlined triples from the given graph that involve the specified node. These are triples that represent definite noncolliders in the given graph.- Parameters:
node- the node for which to retrieve the underlined triplesgraph- the graph from which to retrieve the underlined triples- Returns:
- a list of underlined triples involving the node
-
getDottedUnderlinedTriplesFromGraph
Retrieves the list of dotted and underlined triples from the given graph, with the specified node as the middle node.- Parameters:
node- The middle node to use for finding the triples.graph- The graph to search for the triples.- Returns:
- The list of dotted and underlined triples containing the specified node as the middle node.
-
containsBidirectedEdge
Checks if a given graph contains a bidirected edge.- Parameters:
graph- the graph to check for bidirected edges- Returns:
- true if the graph contains a bidirected edge, false otherwise
-
listColliderTriples
Generates a list of triples where a node acts as a collider in a given graph.- Parameters:
graph- the graph to search for collider triples in- Returns:
- a LinkedList of Triples where a node acts as a collider
-
asList
Constructs a list of nodes from the givennodeslist at the given indices in that list.- Parameters:
indices- The indices of the desired nodes innodes.nodes- The list of nodes from which we select a sublist.- Returns:
- The sublist selected.
-
asSet
Converts an array of indices into a set of corresponding nodes from a given list of nodes.- Parameters:
indices- an array of indices representing the positions of nodes in the listnodes- the list of nodes- Returns:
- a Set containing the nodes at the specified indices
-
asSet
-
degree
Calculates the maximum degree of a graph.- Parameters:
graph- The graph to calculate the degree.- Returns:
- The maximum degree of the graph. Returns 0 if the graph is empty.
-
getIntersectionComparisonString
-
edgeMisclassifications
Generates a textual representation of the edge misclassifications based on the provided counts and number format.- Parameters:
counts- The 2D array representing the counts of edge misclassifications.nf- The number format used to format the counts.- Returns:
- A string containing the textual representation of the edge misclassifications.
-
edgeMisclassifications
Calculates the misclassifications of edges based on the given counts.- Parameters:
counts- a 2D array containing the counts for different edge classifications- Returns:
- a string representing the misclassifications of edges
-
addEdgeSpecializationMarkup
Adds markups for edge specializations for the edges in the given graph. This used to be called PAG coloring.- Parameters:
graph- The graph to which PAG edge specialization markups will be added.
-
edgeMisclassificationCounts
Computes the misclassification counts for each edge in the given graphs.- Parameters:
leftGraph- The left graph.topGraph- The top graph.print- Whether to print debug information.- Returns:
- A 2-dimensional array containing the counts for each misclassification type. The array has dimensions [m][n], where m is the number of misclassification types in the left graph and n is the number of misclassification types in the top graph.
-
maximalCliques
-
graphNodeAttributesToText
Converts the attributes of nodes in a graph to text format.- Parameters:
graph- the graph containing nodestitle- the title to be displayed before the attributes, can be null or emptydelimiter- the delimiter character used for separating node attributes- Returns:
- a string representation of the graph node attributes, or null if there are no attributes
-
graphAttributesToText
Converts the attributes of a given graph into a text format.- Parameters:
graph- the graph whose attributes are to be convertedtitle- the title to be included at the beginning of the converted text- Returns:
- the converted attributes in text format, or null if the graph has no attributes
-
graphNodesToText
Converts the nodes of a graph to a formatted text representation.- Parameters:
graph- the graph containing the nodestitle- the title to be displayed at the beginning of the text (optional, can be null)delimiter- the character used to separate the nodes in the text- Returns:
- a string representing the nodes of the graph
-
graphEdgesToText
Converts the edges of a graph to text representation.- Parameters:
graph- The graph whose edges will be converted.title- The title to be included in the text representation. Can be null or empty.- Returns:
- The text representation of the graph edges.
-
triplesToText
-
getTwoCycleErrors
Returns the TwoCycleErrors object that represents errors for direct feedback loops.- Parameters:
trueGraph- The true Graph object.estGraph- The estimated Graph object.- Returns:
- The TwoCycleErrors object that represents the adjacency errors.
-
getDegree
Returns the maximum degree of a graph.- Parameters:
graph- the graph to calculate the degree for- Returns:
- the maximum degree of the graph
-
getIndegree
Calculates the maximum indegree in a given graph.- Parameters:
graph- The graph to calculate the maximum indegree for.- Returns:
- The maximum indegree in the graph.
-
traversePotentiallyDirected
Traverses a potentially directed edge to identify the next node in the traversal.- Parameters:
node- The starting node of the edge.edge- The potentially directed edge to be traversed.- Returns:
- The next node in the traversal, or null if no such node exists.
-
getComparisonGraph
Returns a comparison graph based on the specified parameters.- Parameters:
graph- the original graph to compareparams- the parameters for comparison- Returns:
- the comparison graph based on the specified parameters
-
addForbiddenReverseEdgesForDirectedEdges
Adds forbidden reverse edges for directed edges in the given graph based on the knowledge.- Parameters:
graph- The graph to add forbidden reverse edges to.knowledge- The knowledge used to determine the forbidden reverse edges.
-
removeNonSkeletonEdges
Removes non-skeleton edges from the given graph based on the provided knowledge. A non-skeleton edge is determined by the name of the nodes. If either node's name starts with "E_", the edge is considered a skeleton edge and will not be removed.- Parameters:
graph- the graph from which to remove non-skeleton edgesknowledge- the knowledge base to check for forbidden edges
-
compatible
-
markovBlanket
Computes the Markov blanket for a given node in a graph. The Markov blanket of a node x is the set of nodes that include the parents of x, the children of x, and all other parents of x's children (i.e., colliders involving x).- Parameters:
x- the target node for which the Markov blanket is computedG- the graph containing the nodes and edges- Returns:
- a set of nodes representing the Markov blanket of x
-
district
-
visibleEdgeAdjustments1
public static Set<Set<Node>> visibleEdgeAdjustments1(Graph G, Node x, Node y, int numSmallestSizes, GraphUtils.GraphType graphType) Calculates visual-edge adjustments given graph G between two nodes x and y that are subsets of MB(X).- Parameters:
G- the input graphx- the source nodey- the target nodenumSmallestSizes- the number of smallest adjustment sets to returngraphType- the type of the graph- Returns:
- the adjustment sets as a set of sets of nodes
- Throws:
IllegalArgumentException- if the input graph is not a legal PDAG
-
visibleEdgeAdjustments3
public static Set<Set<Node>> visibleEdgeAdjustments3(Graph G, Node x, Node y, int numSmallestSizes, GraphUtils.GraphType graphType) This method calculates visible-edge adjustments for a given graph, two nodes, a number of smallest sizes, and a graph type.- Parameters:
G- the input graphx- the first nodey- the second nodenumSmallestSizes- the number of smallest sizes to considergraphType- the type of the graph- Returns:
- a set of subsets of nodes representing visible-edge adjustments
-
getGraphWithoutXToY
Returns a graph that is obtained by removing the edge from node x to node y from the input graph. The type of the output graph is determined by the provided graph type.- Parameters:
G- the input graphx- the starting node of the edge to be removedy- the ending node of the edge to be removedgraphType- the type of the output graph (CPDAG, PAG, or MAG)- Returns:
- the resulting graph after removing the edge from node x to node y
- Throws:
IllegalArgumentException- if the input graph type is not legal (must be CPDAG, PAG, or MAG)
-
anteriority
Computes the anteriority of the given nodes in a graph. An anterior node is a node that has a directed path to any of the given nodes. This method returns a set of anterior nodes.- Parameters:
G- the graph to compute anteriority onx- the nodes to compute anteriority for- Returns:
- a set of anterior nodes
-
isDag
Determines if the given graph is a directed acyclic graph (DAG).- Parameters:
graph- the graph to be checked- Returns:
- true if the graph is a DAG, false otherwise
-
convert
Converts a string spec of a graph--for example, "X1-->X2, X1---X3, X2o->X4, X3<->X4" to a Graph. The spec consists of a comma separated list of edge specs of the forms just used in the previous sentence. Unconnected nodes may be listed separately--example: "X,Y->Z". To specify a node as latent, use "Latent()." Example: "Latent(L1),Y->L1." -
trimGraph
Trims the given graph based on the specified trimming style.- Parameters:
targets- the list of target nodes to be trimmedgraph- the graph to be trimmedtrimmingStyle- the style indicating how the graph should be trimmed - 1: No trimming - 2: Trim nodes adjacent to target nodes - 3: Trim nodes in the Markov blanket of target nodes - 4: Trim potentially directed arcs adjacent to target nodes- Returns:
- the trimmed graph
- Throws:
IllegalArgumentException- if an unknown trimming style is given
-
isConfoundingTrek
Checks if the given trek in a graph is a confounding trek. This is a trek from measured node x to measured node y that has only latent nodes in between.- Parameters:
trueGraph- the true graph representing the causal relationships between nodestrek- the trek to be checkedx- the first node in the treky- the last node in the trek- Returns:
- true if the trek is a confounding trek, false otherwise
-
trekSourceLatent
Checks if the souce L of the given trek in a graph (not equal to x or y) is a latent. This is a trek from measured node x to measured node y with a latent source. Other nodes on the path may be measured or latent.- Parameters:
trueGraph- the true graph representing the causal relationships between nodestrek- the trek to be checkedx- the first node in the treky- the last node in the trek- Returns:
- true if the source of the trek (not equal to x or y) is latent, false otherwise.
-
bidirectedExistsLatentCommonCauseUncovered
public static boolean bidirectedExistsLatentCommonCauseUncovered(Edge edge, Graph trueGraph, Graph estGraph) Determines whether the given bidirected edge has a latent common cause in the true graph via a trek x <~~ L ~~> y whose source L is latent, but where at least one consecutive pair of nodes (w, r) along the trek is NOT adjacent in the estimated graph. Other nodes on the trek may be measured or latent; only the source L is required to be latent.This is a variation of
bidirectedExistsLatentCommonCause(Edge, Graph)that additionally requires the trek to contain an edge (w, r) for which!estGraph.isAdjacentTo(w, r)-- i.e., the trek is not fully "covered" by adjacencies in the estimated graph.- Parameters:
edge- The edge to check.trueGraph- The true graph (DAG, CPDAG, PAG_of_the_true_DAG).estGraph- The estimated graph against which consecutive-pair adjacency is checked.- Returns:
- true if such a trek exists, false otherwise.
- Throws:
IllegalArgumentException- if the edge is not bidirected.
-
trekIsUncovered
Checks whether the given trek is "uncovered" relative to the estimated graph in the following sense: every consecutive pair along the trek is adjacent in the true graph, and among the consecutive pairs whose BOTH endpoints are measured, at least one is non-adjacent in the estimated graph. If the trek has no measured-to-measured consecutive pair, the condition is vacuously satisfied.Nodes are matched into the estimated graph by name, so the trek (from the true graph) and the estimated graph need not share node objects.
- Parameters:
trueGraph- the true graph, used to confirm consecutive-pair adjacency along the trekestGraph- the estimated graph in which measured-to-measured adjacency is checkedtrek- the trek whose consecutive pairs are examined- Returns:
- true if the trek is uncovered as defined above, false otherwise
-
getTrekSource
-
bidirectedExistsLatentConfounder
Determines if the given bidirected edge has a latent confounder in the true graph--that is, whether for X <-> Y there is a latent node Z such that X <- (Z) -> Y.- Parameters:
edge- The edge to check.trueGraph- The true graph (DAG, CPDAG, PAG_of_the_true_DAG).- Returns:
- true if the given bidirected has a latent confounder in the true graph, false otherwise.
- Throws:
IllegalArgumentException- if the edge is not bidirected.
-
bidirectedExistsLatentCommonCause
Determines whether a bidirected edge exists due to a latent common cause in the given graph. A latent common cause refers to an unobserved variable responsible for the relationship between the two nodes connected by the bidirected edge.- Parameters:
edge- the bidirected edge to be checked. Must be bidirected, otherwise an IllegalArgumentException will be thrown.trueGraph- the graph in which the check for a latent common cause is performed. This graph is assumed to contain the necessary structure and properties for validating the existence of a latent common cause.- Returns:
trueif the bidirected edge exists due to a latent common cause in the provided graph;falseotherwise.- Throws:
IllegalArgumentException- if the input edge is not a bidirected edge.
-
guaranteePag
public static Graph guaranteePag(Graph pag, FciOrient fciOrient, Knowledge knowledge, Set<Triple> knownColliders, boolean verbose, Set<Node> selection, boolean excludeSelectionBias, int recursiveDepth) Guarantees the correctness of a Partial Ancestral Graph (PAG) by repairing faulty structures such as cycles, violations of maximality, and incorrectly oriented edges, using FCI orientation rules and knowledge constraints.The method works down a ladder of increasingly aggressive fallbacks, returning at the first rung that yields a legal PAG (as judged by
PagLegalityCheck.isLegalPagQuiet(Graph, Set, int), uniformly, with the given selection set):- the repair loop (monotone edge additions to a fixpoint);
- a MAG round-trip of the repaired graph;
- a second repair pass and round-trip applied to the round-trip output, if it made progress;
- the pre-round-trip repaired state itself;
- a DAG orientation of the repaired skeleton (cannot fail: every DAG is a legal MAG). This rung preserves the estimated adjacencies but discards orientation information, and respects background knowledge only up to tier ordering.
NOTE:
pagis modified in place, andknownCollidersis destructively consumed as colliders are sacrificed to shielding repairs. Callers that need either object afterward should pass copies.- Parameters:
pag- the initial PAG to be repaired (modified in place)fciOrient- the FCI (Fast Causal Inference) orientation utility for edge orientationknowledge- the background knowledge to enforce during the repair processknownColliders- a set of triples representing unshielded colliders to be enforced; consumedverbose- whether to provide detailed logging of the repair processselection- a set of nodes to be considered during the maximality repairexcludeSelectionBias- whether to exclude the selection bias during the repair processrecursiveDepth- the maximum current depth of recursion in the repair process- Returns:
- a legal PAG
-
repairMaximality
public static boolean repairMaximality(Graph pag, boolean verbose, Set<Node> selection, FciOrient fciOrient, Knowledge knowledge, Set<Triple> knownColliders) Repairs the maximality of a PAG (Partial Ancestral Graph) by ensuring that any inducing path between two nodes not currently adjacent in the graph results in an added non-directed edge. The method modifies the graph in-place. (fciOrient, knowledge, and knownColliders are retained in the signature for API compatibility but are not used; reorientation happens once per pass in the repair loop.)- Parameters:
pag- the Partial Ancestral Graph to be repaired for maximalityverbose- if true, logs the actions performed during the repair processselection- a set of nodes to be considered during the inducing path checkfciOrient- The Fci orientation procedure.knowledge- The knowledge.knownColliders- Known colliders.- Returns:
- true if the graph was modified during the repair process; false otherwise
-
getNumInducedAdjacenciesInPag
Calculates the number of induced adjacencies in the given estiamted Partial Ancestral (PAG) with respect to the given true PAG. An induced adjacency in a PAG is an edge that is adjacent in the estimated graph, but not in the true graph, and is not covering a collider or noncollider in the true graph.- Parameters:
trueGraph- the true PAG.estGraph- the estimated PAG.- Returns:
- the number of induced adjacencies in the PAG.
- See Also:
-
getNumCoveringAdjacenciesInPag
Returns the number of covering edges in the given estimated partial ancestral graph (PAG) with respect to the given true PAG. A covering edge in a PAG connects two nodes such that the edges in the true graph represent the edges in the estimated graph.- Parameters:
trueGraph- The true ancestral graphestGraph- The estimated ancestral graph- Returns:
- The count of covering edges in the PAG
- See Also:
-
isCoveringAdjacency
Determines whether an edge between two nodes in the estimated graph is covering a collider or noncollider in the true graph. This is the case if the edge is adjacent in the estimated graph, but not in the true graph, and there is a common adjacent node in the estimated graph that is also a common adjacent node in the true graph. If the path through the common adjacent node is a collider in the true graph if and only if it is a noncollider in the estimated graph, then the edge is covering a collider or noncollider.- Parameters:
trueGraph- the true graphestGraph- the estimated graphx- the first nodey- the second node- Returns:
- true if the edge is covering a collider or noncollider, false otherwise
-
asList
-
dsep0
Returns D-SEP(x, y) for a MAG G (or inducing path graph G, as in Causation, Prediction and Search). This method implements a reachability style.We trust the user to make sure the given graph is a MAG or IPG; we don't check this.
- Parameters:
x- The one endpoint.y- The other endpoint.G- The MAG.- Returns:
- D-SEP(x, y) for MAG G.
-
dsep
Returns D-SEP(x, y) for a MAG G. This method implements a non-reachability style.We trust the user to make sure the given graph is a MAG or IPG; we don't check this.
- Parameters:
x- The one endpoint.y- The other endpoint.G- The MAG.- Returns:
- D-SEP(x, y) for MAG G.
-
dsep2
Returns D-SEP(x, y) for a MAG G. Somewhat optimized version.We trust the user to make sure the given graph is a MAG or IPG; we don't check this.
- Parameters:
x- The one endpoint.y- The other endpoint.G- The MAG.- Returns:
- D-SEP(x, y) for MAG G.
-
dsepReachability
Returns D-SEP(x, y) for a MAG G. This method implements a reachability style.We trust the user to make sure the given graph is a MAG or IPG; we don't check this.
- Parameters:
x- The one endpoint.y- The other endpoint.G- The MAG.- Returns:
- D-SEP(x, y) for MAG G.
-
reorientWithCircles
Reorients all edges in a Graph as o-o. This method is used to apply the o-o orientation to all edges in the given Graph following the PAG (Partially Ancestral Graph) structure.- Parameters:
pag- The Graph to be reoriented.verbose- A boolean value indicating whether verbose output should be printed.
-
recallInitialColliders
public static void recallInitialColliders(Graph pag, Set<Triple> initialColliders, Knowledge knowledge) Recall unshielded triples in a given graph.- Parameters:
pag- The graph to recall unshielded triples from.initialColliders- The set of unshielded colliders that need to be recalled from the CPDAG.knowledge- the knowledge object.
-
triple
-
colliderAllowed
Determines if the collider is allowed.- Parameters:
pag- The Graph representing the PAG.x- The Node object representing the first node.b- The Node object representing the second node.y- The Node object representing the third node.knowledge- The Knowledge object.- Returns:
- true if the collider is allowed, false otherwise.
-
distinct
-
localMarkovInitializePValues
public static double localMarkovInitializePValues(Graph dag, boolean preserveMarkov, IndependenceTest test, Map<org.apache.commons.lang3.tuple.Pair<Node, Node>, Set<Double>> pValues) throws InterruptedExceptionInitializes and evaluates p-values for local Markov properties in a given graph.- Parameters:
dag- The input graph, a DAG (Directed Acyclic Graph).preserveMarkov- Flag indicating that the method should proceed only if set to true.test- The statistical test instance used to check for conditional independence.pValues- A map to store the p-values, indexed by pairs of nodes.- Returns:
- The percentage of p-values that are less than the significance level (alpha) used in the test. Returns 0.0 if the number of p-values is less than 5 or if preserveMarkov is false or test instance is invalid.
- Throws:
IllegalArgumentException- if preserveMarkov is false.InterruptedException- if any
-
pValuesAdP
public static double pValuesAdP(Map<org.apache.commons.lang3.tuple.Pair<Node, Node>, Set<Double>> _pValues) Calculates the p-value using the Anderson-Darling test for a given set of p-values from an independence test.- Parameters:
_pValues- A map where each key is a pair of nodes, and each value is a set of p-values associated with that node pair.- Returns:
- The p-value calculated from the Anderson-Darling test.
-
fixDirections
Processes the given graph by fixing the directions of edges to ensure consistency, flipping edges where necessary, and optionally preserving ancillary graph information.- Parameters:
graph- the input graph whose edge directions are to be fixed- Returns:
- a new graph with corrected edge directions, preserving ancillary graph information if present
-
orientCollider
Orients the edges of the given graph by setting both specified nodes as arrow endpoints directed towards the specified target node.- Parameters:
g- The graph in which the edges will be oriented.x- The first node to be set as an arrow endpoint directed towards the target node z.z- The target node towards which both nodes x and y will be oriented.y- The second node to be set as an arrow endpoint directed towards the target node z.
-
connectedComponents
Identifies all connected components in a given graph. A connected component is a subset of the graph's nodes such that each pair of nodes is connected by a path, and which is not connected to any additional nodes in the graph.- Parameters:
g- The graph for which to find connected components. It is assumed to be an undirected graph and implemented as a data structure providing access to its nodes and the adjacency list for each node.- Returns:
- A list of sets, where each set contains the nodes that belong to a single connected component of the graph.
-
stronglyConnectedComponents
-
getReplicatingGraph
Creates a replicating graph based on the provided graph. The method generates a new graph where edges are replicated only for child nodes that are lag-0 (i.e., nodes without a colon in their name). Lag-0 nodes and their parent relationships are preserved and replicated automatically to all other lag-slices.- Parameters:
graph- the source graph from which the replicating graph is generated. The input graph contains nodes and edges that determine the structure of the resulting replicating graph.- Returns:
- a new
Graphinstance representing the replicating graph. This graph includes all the replicated relationships as described.
-
applyForbiddenCircleResolution
Resolves forbidden circles in the given partially oriented graph (PAG) based on the provided knowledge. Updates edge endpoints to arrowheads where forbidden relationships are detected. Temp method to try to fix a putative knowledge issue in FCI.- Parameters:
pag- the partially oriented graph to be processedknowledge- the knowledge object containing forbidden relationships between nodes- Returns:
trueif any changes were made to the graph;falseotherwise
-