-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathdagitty.R
2221 lines (2129 loc) · 71.2 KB
/
dagitty.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#' @import V8 jsonlite
#' @importFrom boot boot
#' @importFrom MASS ginv
#' @importFrom grDevices dev.size
#' @importFrom methods is
#' @importFrom utils tail combn capture.output
#' @importFrom stats as.formula coef confint cov cov2cor cor lm pnorm pchisq qnorm quantile runif loess sd weighted.mean complete.cases rbinom cancor cor.test
#' @importFrom graphics abline arrows axis lines par plot plot.new segments strheight strwidth text xspline
NULL
#' Get Graph Type
#'
#' @param x the input graph.
#' @examples
#' graphType( "mag{ x<-> y }" ) == "mag"
#' @export
#'
graphType <- function( x ){
x <- as.dagitty( x )
xv <- .getJSVar()
r <- NULL
tryCatch({
.jsassigngraph( xv, x )
.jsassign( xv, .jsp("global.",
xv,".getType()") )
r <- .jsget( xv )
},
error=function(e) stop(e),
finally={.deleteJSVar(xv)})
r
}
'graphType<-' <- function( x, value=c("dag","mag","pdag","pag") ){
value <- match.arg(value)
x <- as.dagitty( x )
xv <- .getJSVar()
r <- NULL
tryCatch({
.jsassigngraph( xv, x )
.jseval( paste0("global.",xv,".setType('",value,"')") )
r <- .jsgetgraph( xv )
},
error=function(e) stop(e),
finally={.deleteJSVar(xv)})
r
}
#' Get Bundled Examples
#'
#' Provides access to the builtin examples of the dagitty website.
#'
#' @param x name of the example, or part thereof. Supported values are:
#' \describe{
#' \item{"M-bias"}{ the M-bias graph.}
#' \item{"confounding"}{ an extended confounding triangle.}
#' \item{"mediator"}{ a small model with a mediator.}
#' \item{"paths"}{ a graph with many variables but few paths}
#' \item{"Sebastiani"}{ a small part of a genetics study (Sebastiani et al., 2005)}
#' \item{"Polzer"}{ DAG from a dentistry study (Polzer et al., 2012)}
#' \item{"Schipf"}{ DAG from a study on diabetes (Schipf et al., 2010)}
#' \item{"Shrier"}{ DAG from a classic sports medicine example (Shrier & Platt, 2008)}
#' \item{"Thoemmes"}{ DAG with unobserved variables
#' (communicated by Felix Thoemmes, 2013)}.
#' \item{"Kampen"}{ DAG from a psychiatry study (van Kampen, 2014)}
#' }
#' @references
#' Sabine Schipf, Robin Haring, Nele Friedrich, Matthias Nauck, Katharina Lau,
#' Dietrich Alte, Andreas Stang, Henry Voelzke, and Henri Wallaschofski (2011),
#' Low total testosterone is associated with increased risk of incident
#' type 2 diabetes mellitus in men: Results from the study of health in
#' pomerania (SHIP). \emph{The Aging Male} \bold{14}(3):168--75.
#'
#' Paola Sebastiani, Marco F. Ramoni, Vikki Nolan, Clinton T. Baldwin, and
#' Martin H. Steinberg (2005), Genetic dissection and prognostic modeling of overt
#' stroke in sickle cell anemia. \emph{Nature Genetics}, \bold{37}:435--440.
#'
#' Ian Shrier and Robert W. Platt (2008),
#' Reducing bias through directed acyclic graphs.
#' \emph{BMC Medical Research Methodology}, \bold{8}(70).
#'
#' Ines Polzer, Christian Schwahn, Henry Voelzke, Torsten Mundt, and Reiner
#' Biffar (2012), The association of tooth loss with all-cause and circulatory
#' mortality. Is there a benefit of replaced teeth? A systematic review and
#' meta-analysis. \emph{Clinical Oral Investigations}, \bold{16}(2):333--351.
#'
#' Dirk van Kampen (2014),
#' The SSQ model of schizophrenic prodromal unfolding revised: An
#' analysis of its causal chains based on the language of directed graphs.
#' \emph{European Psychiatry}, \bold{29}(7):437--48.
#'
#' @examples
#' g <- getExample("Shrier")
#' plot(g)
#'
#' @export
getExample <- function( x ){
ct <- .getJSContext()
xv <- .getJSVar()
tryCatch({
.jsassign( xv, x )
r <- ct$eval( paste0("DagittyR.findExample(global.",xv,")") )
}, finally={.deleteJSVar(xv)})
if( r != "undefined" ){
structure(r,class="dagitty")
} else {
stop("Example ",x," could not be found!")
}
}
#' Implied Covariance Matrix of a Gaussian Graphical Model
#'
#' @inheritParams simulateSEM
#'
#' @export
impliedCovarianceMatrix <- function( x, b.default=NULL, b.lower=-.6, b.upper=.6, eps=1, standardized=TRUE ){
if( !requireNamespace( "MASS", quietly=TRUE ) ){
stop("This function requires the 'MASS' package!")
}
.supportsTypes( x, "dag" )
x <- as.dagitty( x )
e <- .edgeAttributes( x, "beta" )
e$a <- as.double(as.character(e$a))
b.not.set <- is.na(e$a)
if( is.null( b.default ) ){
e$a[b.not.set] <- runif(sum(b.not.set),b.lower,b.upper)
} else {
e$a[b.not.set] <- b.default
}
ovars <- names(x)
nV <- length(ovars)
nL <- sum(e$e=="<->")
if( nrow(e) > 0 ){
vars <- paste0("v",ovars)
if( nL > 0 ){
lats <- paste0("l",seq_len(nL))
} else {
lats <- c()
}
Beta <- matrix( 0, nrow=nV+nL, ncol=nV+nL )
rownames(Beta) <- colnames(Beta) <- c(vars,lats)
cL <- 1
for( i in seq_len( nrow(e) ) ){
b <- e$a[i]
if( e$e[i] == "<->" ){
lV <- paste0("l",cL)
lb <- sqrt(abs(b))
Beta[lV,paste0("v",e$v[i])] <- lb
if( b < 0 ){
Beta[lV,paste0("v",e$w[i])] <- -lb
} else {
Beta[lV,paste0("v",e$w[i])] <- lb
}
cL <- cL + 1
} else if( e$e[i] == "->" ){
Beta[paste0("v",e$v[i]),paste0("v",e$w[i])] <- b
}
}
L <- (diag( 1, nV+nL ) - Beta)
Li <- MASS::ginv( L )
if( standardized == TRUE ){
Phi <- MASS::ginv( t(Li)^2 ) %*% rep(eps,nrow(Beta))
Phi <- diag( c(Phi), nV+nL )
} else {
Phi <- diag( eps, nV+nL )
}
Sigma <- t(Li) %*% Phi %*% Li
} else {
Sigma <- diag(1,nV+nL)
}
Sigma <- Sigma[1:nV,1:nV]
colnames( Sigma ) <- rownames( Sigma ) <- ovars
Sigma[setdiff(ovars,latents(x)),setdiff(ovars,latents(x))]
}
#' Ancestral Relations
#'
#' Retrieve the names of all variables in a given graph that are in the specified
#' ancestral relationship to the input variable \code{v}.
#'
#' @param x the input graph, of any type.
#' @param v name(s) of variable(s).
#' @param proper logical. By default (\code{proper=FALSE}), the \code{descendants} or \code{ancestors}
#' of a variable include the variable itself. For (\code{proper=TRUE}), the variable itself
#' is not included.
#'
#' \code{descendants(x,v)} retrieves variables that are are reachable from \code{v} via
#' a directed path.
#'
#' \code{ancestors(x,v)} retrieves variables from which \code{v} is reachable via a
#' directed path.
#'
#' \code{children(x,v)} finds all variables \code{w} connected to \code{v}
#' by an edge \eqn{v} -> \eqn{w}.
#'
#' \code{parents(x,v)} finds all variables \code{w} connected to \code{v}
#' by an edge \eqn{w} -> \eqn{v}.
#'
#' \code{markovBlanket(x,v}) returns \code{x}'s parents, its children, and all other
#' parents of its children. The Markov blanket always renders \code{x} independent
#' of all other nodes in the graph.
#'
#' By convention, \code{descendants(x,v)} and \code{ancestors(x,v)} include
#' \code{v} but \code{children(x,v)} and \code{parents(x,v)} do not.
#'
#' @name AncestralRelations
#'
#' @examples
#' g <- dagitty("graph{ a <-> x -> b ; c -- x <- d }")
#' # Includes "x"
#' descendants(g,"x")
#' # Does not include "x"
#' descendants(g,"x",TRUE)
#' parents(g,"x")
#' spouses(g,"x")
#'
NULL
#' @rdname AncestralRelations
#' @export
descendants <- function( x, v, proper=FALSE ){
r <- .kins( x, v, "descendants" )
if( proper ){
setdiff( r, v )
} else {
r
}
}
#' @rdname AncestralRelations
#' @export
ancestors <- function( x, v, proper=FALSE ){
r <- .kins( x, v, "ancestors" )
if( proper ){
setdiff( r, v )
} else {
r
}
}
#' @rdname AncestralRelations
#' @export
children <- function( x, v ){
.kins( x, v, "children" )
}
#' @rdname AncestralRelations
#' @export
parents <- function( x, v ){
.kins( x, v, "parents" )
}
#' @rdname AncestralRelations
#' @export
neighbours <- function( x, v ){
.kins( x, v, "neighbours" )
}
#' @rdname AncestralRelations
#' @export
spouses <- function( x, v ){
.kins( x, v, "spouses" )
}
#' @rdname AncestralRelations
#' @export
adjacentNodes <- function( x, v ){
.kins( x, v, "adjacentNodes" )
}
#' @rdname AncestralRelations
#' @export
markovBlanket <- function( x, v ){
setdiff( union( union( parents( x, v ), children( x, v ) ),
parents( x, children( x, v ) ) ), v )
}
#' Orient Edges in PDAG.
#'
#' Orients as many edges as possible in a partially directed acyclic graph (PDAG)
#' by converting induced subgraphs
#' X -> Y -- Z to X -> Y -> Z.
#'
#' @param x the input graph, a PDAG.
#'
#' @examples
#' orientPDAG( "pdag { x -> y -- z }" )
#' @export
#'
orientPDAG <- function( x ){
.supportsTypes( x, "pdag" )
.graphTransformer( x, "cgToRcg" )
}
#' Convert DAG to MAG.
#'
#' Given a DAG, possibly with latent variables, construct a MAG that represents its
#' marginal independence model.
#'
#' @param x the input graph, a DAG
#'
#' @examples
#' toMAG( "dag { ParentalSmoking->Smoking
#' { Profession [latent] } -> {Income->Smoking}
#' Genotype -> {Smoking->LungCancer} }")
#' @export
#'
toMAG <- function( x ){
.supportsTypes( x, "dag" )
.graphTransformer( x, "dagToMag" )
}
#' Generating Equivalent Models
#'
#' \code{equivalenceClass(x)} generates a complete partially directed acyclic graph
#' (CPDAG) from an input DAG \code{x}. The CPDAG represents all graphs that are Markov
#' equivalent to \code{x}: undirected
#' edges in the CPDAG can be oriented either way, as long as this does not create a cycle
#' or a new v-structure (a sugraph a -> m <- b, where a and b are not adjacent).
#'
#' \code{equivalentDAGs(x,n)} enumerates at most \code{n} DAGs that are Markov equivalent
#' to the input DAG or CPDAG \code{x}.
#'
#' @param x the input graph, a DAG (or CPDAG for \code{equivalentDAGs}).
#' @param n maximal number of returned graphs.
#' @name EquivalentModels
#' @examples
#' # How many equivalent DAGs are there for the sports DAG example?
#' g <- getExample("Shrier")
#' length(equivalentDAGs(g))
#' # Plot all equivalent DAGs
#' par( mfrow=c(2,3) )
#' lapply( equivalentDAGs(g), plot )
#' # How many edges can be reversed without changing the equivalence class?
#' sum(edges(equivalenceClass(g))$e == "--")
NULL
#' @rdname EquivalentModels
#' @export
equivalenceClass <- function( x ){
x <- as.dagitty( x )
.supportsTypes( x, "dag" )
.graphTransformer( x, "dagToCpdag" )
}
#' @rdname EquivalentModels
#' @export
equivalentDAGs <- function( x, n=100 ){
x <- as.dagitty(x)
.supportsTypes( x, c("dag","pdag") )
xv <- .getJSVar()
r <- NULL
tryCatch({
.jsassigngraph( xv, x )
.jsassign( xv, .jsp("DAGitty.GraphTransformer.markovEquivalentDags(global.",
xv,",",n,").map(function(x){return x.toString()})") )
r <- .jsget( xv )
},
error=function(e) stop(e),
finally={.deleteJSVar(xv)})
lapply( r, dagitty )
}
#' Moral Graph
#'
#' Graph obtained from \code{x} by (1) \dQuote{marrying} (inserting an undirected
#' ede between) all nodes that have common children, and then replacing all edges
#' by undirected edges. If \code{x} contains bidirected edges, then all sets of
#' nodes connected by a path containing only bidirected edges are treated like a
#' single node (see Examples).
#'
#' @param x the input graph, a DAG, MAG, or PDAG.
#'
#' @examples
#' # returns a complete graph
#' moralize( "dag{ x->m<-y }" )
#' # also returns a complete graph
#' moralize( "dag{ x -> m1 <-> m2 <-> m3 <-> m4 <- y }" )
#'
#' @export
moralize <- function( x ){
x <- as.dagitty( x )
.supportsTypes( x, c("dag","mag","pdag") )
.graphTransformer( x, "moralGraph" )
}
#' Extract Structural Part from Structural Equation Model
#'
#' Removes all observed variables from the input graph.
#'
#' @param x the input graph, a DAG.
#'
#' @details Assumes that x is a graph where there are edges between
#' the latent variables, between the observed variables, and
#' from latent to observed variables, but no edge between
#' a latent L and an observed X may have an arrowhead at L.
#
#' @export
structuralPart <- function( x ){
x <- as.dagitty( x )
.supportsTypes( x, c("dag","digraph") )
.graphTransformer( x, "structuralPart" )
}
#' Extract Measurement Part from Structural Equation Model
#'
#' Removes all edges between latent variables, then removes any
#' latent variables without adjacent edges, then returns the graph.
#'
#' @param x the input graph, a DAG.
#'
#' @details Assumes that x is a graph where there are edges between
#' the latent variables, between the observed variables, and
#' from latent to observed variables, but no edge between
#' a latent L and an observed X may have an arrowhead at L.
#'
#' @export
measurementPart <- function( x ){
x <- as.dagitty( x )
.supportsTypes( x, c("dag","digraph") )
.graphTransformer( x, "measurementPart" )
}
#' Back-Door Graph
#'
#' Removes every first edge on a proper causal path from \code{x}.
#' If \code{x} is a MAG or PAG, then only \dQuote{visible} directed
#' edges are removed (Zhang, 2008).
#'
#' @param x the input graph, a DAG, MAG, PDAG, or PAG.
#'
#' @references
#' J. Zhang (2008), Causal Reasoning with Ancestral Graphs.
#' \emph{Journal of Machine Learning Research} 9: 1437-1474.
#'
#' @examples
#' g <- dagitty( "dag { x <-> m <-> y <- x }" )
#' backDoorGraph( g ) # x->y edge is removed
#'
#' g <- dagitty( "mag { x <-> m <-> y <- x }" )
#' backDoorGraph( g ) # x->y edge is not removed
#'
#' g <- dagitty( "mag { x <-> m <-> y <- x <- i }" )
#' backDoorGraph( g ) # x->y edge is removed
#'
#' @export
backDoorGraph <- function( x ){
x <- as.dagitty(x)
.supportsTypes( x, c("dag","mag","pdag","pag") )
.graphTransformer( x, "backDoorGraph" )
}
#' Ancestor Graph
#'
#' Creates the induced subgraph containing only the vertices
#' in \code{v}, their ancestors, and the edges between them. All
#' other vertices and edges are discarded.
#'
#' @param x the input graph, a DAG, MAG, or PDAG.
#' @param v variable names.
#'
#' @details If the input graph is a MAG or PDAG, then all *possible* ancestors
#' will be returned (see Examples).
#'
#' @examples
#' g <- dagitty("dag{ z <- x -> y }")
#' ancestorGraph( g, "z" )
#'
#' g <- dagitty("pdag{ z -- x -> y }")
#' ancestorGraph( g, "y" ) # includes z
#'
#' @export
ancestorGraph <- function( x, v=NULL ){
x <- as.dagitty(x)
.supportsTypes( x, c("dag","mag","pdag") )
if( is.null(v) ){
v <- c(exposures(x),outcomes(x),adjustedNodes(x))
} else {
.checkAllNames( x, v )
v <- as.list(v)
}
xv <- .getJSVar()
xv2 <- .getJSVar()
r <- NULL
tryCatch({
.jsassigngraph( xv, x )
.jsassign( xv2, v )
.jsassign( xv2, .jsp("DagittyR.getVertices(global.",xv,",global.",xv2,")") )
.jsassign( xv, .jsp("DAGitty.GraphTransformer.ancestorGraph(global.",xv,",global.",xv2,")") )
r <- .jsgetgraph( xv )
},
error=function(e) stop(e),
finally={.deleteJSVar(xv);.deleteJSVar(xv2)})
r
}
#' Variable Statuses
#'
#' Get or set variables with a given status in a graph. Variables in dagitty graphs can
#' have one of several statuses. Variables with status \emph{exposure} and
#' \emph{outcome} are important when determining causal effects via the functions
#' \code{\link{adjustmentSets}} and \code{\link{instrumentalVariables}}. Variables
#' with status \emph{latent} are assumed
#' to be unobserved variables or latent constructs, which is respected when deriving
#' testable implications of a graph via the functions
#' \code{\link{impliedConditionalIndependencies}} or \code{\link{vanishingTetrads}}.
#'
#' \code{setVariableStatus} first removes the given status from all variables in the graph
#' that had it, and then sets it on the given variables.
#' For instance, if \code{status="exposure"} and \code{value="X"} are given, then
#' \code{X} will be the only exposure in the resulting graph.
#'
#' @param x the input graph, of any type.
#' @param value character vector; names of variables to receive the given status.
#' @param status character, one of "exposure", "outcome" or "latent".
#'
#' @name VariableStatus
#'
#' @examples
#' g <- dagitty("dag{ x<->m<->y<-x }") # m-bias graph
#' exposures(g) <- "x"
#' outcomes(g) <- "y"
#' adjustmentSets(g)
#'
NULL
#' @rdname VariableStatus
#' @export
exposures <- function( x ){
.nodesWithProperty( x, "source" )
}
#' @rdname VariableStatus
#' @export
'exposures<-' <- function( x, value ){
setVariableStatus(x, "exposure", value )
}
#' @rdname VariableStatus
#' @export
outcomes <- function( x ){
.nodesWithProperty( x, "target" )
}
#' @rdname VariableStatus
#' @export
'outcomes<-' <- function( x, value ){
setVariableStatus(x, "outcome", value )
}
#' @rdname VariableStatus
#' @export
latents <- function( x ){
.nodesWithProperty( x, "latentNode" )
}
#' @rdname VariableStatus
#' @export
'latents<-' <- function( x, value ){
setVariableStatus(x, "latent", value )
}
#' @rdname VariableStatus
#' @export
adjustedNodes <- function( x ){
.nodesWithProperty( x, "adjustedNode" )
}
#' @rdname VariableStatus
#' @export
'adjustedNodes<-' <- function( x, value ){
setVariableStatus(x, "adjustedNode", value )
}
#' @rdname VariableStatus
#' @export
setVariableStatus <- function( x, status, value ) {
allowed.statuses <- c("exposure","outcome","latent","adjustedNode")
if( !(status %in% allowed.statuses) ){
stop( "Status must be one of: ", paste(allowed.statuses,collapse=", ") )
}
.checkAllNames( x, value )
xv <- .getJSVar()
vv <- .getJSVar()
tryCatch({
.jsassign( xv, as.character(x) )
.jsassign( xv, .jsp("DAGitty.GraphParser.parseGuess(global.",xv,")") )
if( status == "exposure" ){
jsstatname <- "Source"
} else if (status == "outcome" ){
jsstatname <- "Target"
} else if (status == "latent" ){
jsstatname <- "LatentNode"
} else if (status == "adjustedNode" ){
jsstatname <- "AdjustedNode"
}
.jseval( paste0( "global.",xv,".removeAll",jsstatname,"s()" ) )
for( n in value ){
.jsassign( vv, n )
.jseval( paste0( "global.",xv,".add",jsstatname,"(global.",vv,")" ) )
}
r <- .jsget( paste0( xv,".toString()" ) )
},finally={
.deleteJSVar(vv)
.deleteJSVar(xv)
})
structure(r,class="dagitty")
}
#' Names of Variables in Graph
#'
#' Extracts the variable names from an input graph. Useful for iterating
#' over all variables.
#'
#' @param x the input graph, of any type.
#' @export
#' @examples
#' ## A "DAG" with Romanian and Swedish variable names. These can be
#' ## input using quotes to overcome the limitations on unquoted identifiers.
#' g <- dagitty( 'digraph {
#' "coração" [pos="0.297,0.502"]
#' "hjärta" [pos="0.482,0.387"]
#' "coração" -> "hjärta"
#' }' )
#' names( g )
names.dagitty <- function( x ){
ct <- .getJSContext()
xv <- .getJSVar()
tryCatch({
.jsassigngraph( xv, x )
.jsassign( xv, .jsp("global.",xv,".vertices.keys()") )
r <- .jsget(xv)},
finally={.deleteJSVar(xv)})
r
}
#' Retrieve Exogenous Variables
#'
#' Returns the names of all variables that have no directed arrow pointing to them.
#' Note that this does not preclude variables connected to bidirected arrows.
#'
#' @param x the input graph, of any type.
#' @export
exogenousVariables <- function( x ){
x <- as.dagitty( x )
e <- edges( x )
setdiff( names(x), as.character( e$w[e$e=="->"] ) )
}
#' Plot Coordinates of Variables in Graph
#'
#' The DAGitty syntax allows specification of plot coordinates for each variable in a
#' graph. This function extracts these plot coordinates from the graph description in a
#' \code{dagitty} object. Note that the coordinate system is undefined, typically one
#' needs to compute the bounding box before plotting the graph.
#'
#' @param x the input graph, of any type.
#' @param value a list with components \code{x} and \code{y},
#' giving relative coordinates for each variable. This format is suitable
#' for \code{\link{xy.coords}}.
#'
#' @examples
#' ## Plot localization of each node in the Shrier example
#' plot( coordinates( getExample("Shrier") ) )
#'
#' ## Define a graph and set coordinates afterwards
#' x <- dagitty('dag{
#' G <-> H <-> I <-> G
#' D <- B -> C -> I <- F <- B <- A
#' H <- E <- C -> G <- D
#' }')
#' coordinates( x ) <-
#' list( x=c(A=1, B=2, D=3, C=3, F=3, E=4, G=5, H=5, I=5),
#' y=c(A=0, B=0, D=1, C=0, F=-1, E=0, G=1, H=0, I=-1) )
#' plot( x )
#'
#' @seealso
#' Function \link{graphLayout} for automtically generating layout coordinates, and function
#' \link{plot.dagitty} for plotting graphs.
#'
#' @export
coordinates <- function( x ){
ct <- .getJSContext()
xv <- .getJSVar()
yv <- .getJSVar()
tryCatch({
.jsassigngraph( xv, x )
.jsassign( xv, .jsp("global.",xv,".getVertices()") )
.jsassign( yv, .jsp("DagittyR.pluck(global.",xv,",'id')") )
labels <- .jsget(yv)
.jsassign( yv, .jsp("DagittyR.pluck(global.",xv,",'layout_pos_x')") )
rx <- .jsget(yv)
.jsassign( yv, .jsp("DagittyR.pluck(global.",xv,",'layout_pos_y')") )
ry <- .jsget(yv)},
finally={
.deleteJSVar(xv)
.deleteJSVar(yv)
})
names(rx) <- labels
names(ry) <- labels
list( x=rx, y=ry )
}
#' @rdname coordinates
#' @export
'coordinates<-' <- function( x, value ){
xv <- .getJSVar()
xv2 <- .getJSVar()
tryCatch({
.jsassigngraph( xv, x )
if( is.null( value ) ){
for( n in names(x) ){
.jsassign( xv2, as.character(n) )
.jseval(.jsp("delete global.",xv,".vertices.get(",xv2,
")['layout_pos_x']"))
.jseval(.jsp("delete global.",xv,".vertices.get(",xv2,
")['layout_pos_y']"))
}
} else {
for( n in intersect( names(value$x), names(x) ) ){
.jsassign( xv2, as.character(n) )
.jseval(.jsp("global.",xv,".vertices.get(",xv2,
").layout_pos_x=",
as.numeric(value$x[n])))
.jseval(.jsp("global.",xv,".vertices.get(",xv2,
").layout_pos_y=",
as.numeric(value$y[n])))
}
}
.jsassign( xv, .jsp("global.",xv,".toString()") )
r <- .jsget( xv )
},
error=function(e) stop(e),
finally={.deleteJSVar(xv);.deleteJSVar(xv2)})
structure(r,class="dagitty")
}
#' Canonicalize an Ancestral Graph
#'
#' Takes an input ancestral graph (a graph with directed, bidirected and undirected
#' edges) and converts it to a DAG by replacing every bidirected edge x <-> y with a
#' substructure x <- L -> y, where L is a latent variable, and every undirected edge
#' x -- y with a substructure x -> S <- y, where S is a selection variable. This function
#' does not check whether the input is actually an ancestral graph.
#'
#' @param x the input graph, a DAG or MAG.
#' @return A list containing the following components:
#' \describe{
#' \item{g}{The resulting graph.}
#' \item{L}{Names of newly inserted latent variables.}
#' \item{S}{Names of newly inserted selection variables.}
#' }
#'
#' @examples
#' canonicalize("mag{x<->y--z}") # introduces two new variables
#' @export
canonicalize <- function( x ){
x <- as.dagitty(x)
.supportsTypes(x,c("dag","mag"))
xv <- .getJSVar()
xv2 <- .getJSVar()
r <- NULL
tryCatch({
.jsassigngraph( xv, x )
.jsassign( xv, .jsp("DAGitty.GraphTransformer.canonicalDag(global.",xv,")") )
.jsassign( xv2, .jsp("global.",xv,".g.toString()") )
g <- .jsget( xv2 )
.jsassign( xv2, .jsp("DagittyR.pluck(",xv,".L,'id')") )
L <- .jsget( xv2 )
.jsassign( xv2, .jsp("DagittyR.pluck(",xv,".S,'id')") )
S <- .jsget( xv2 )
r <- list( g=structure(g,class="dagitty"), L=L, S=S )
},
error=function(e) stop(e),
finally={.deleteJSVar(xv);.deleteJSVar(xv2)})
r
}
#' Graph Edges
#'
#' Extracts edge information from the input graph.
#'
#' @param x the input graph, of any type.
#' @return a data frame with the following variables:
#' \describe{
#' \item{v}{ name of the start node.}
#' \item{w}{ name of the end node. For symmetric edges (bidirected and undirected), the
#' order of start and end node is arbitrary.}
#' \item{e}{ type of edge. Can be one of \code{"->"}, \code{"<->"} and \code{"--"}.}
#' \item{x}{ X coordinate for a control point. If this is not \code{NA}, then the edge
#' is drawn as an \code{\link{xspline}} through the start point, this control point,
#' and the end point. This is especially important for cases where there is more than
#' one edge between two variables (for instance, both a directed and a bidirected edge).}
#' \item{y}{ Y coordinate for a control point.}
#' }
#'
#' @examples
#' ## Which kinds of edges are used in the Shrier example?
#' levels( edges( getExample("Shrier") )$e )
#' @export
edges <- function( x ) UseMethod("edges")
#' @export
edges.character <- function( x ){
edges( dagitty( x ) )
}
#' @export
edges.dagitty <- function( x ){
xv <- .getJSVar()
tryCatch({
.jsassigngraph( xv, x )
.jsassign( xv, .jsp("DagittyR.edge2r(global.",xv,")") )
r <- .jsget(xv)
}, finally={.deleteJSVar(xv)})
as.data.frame(r)
}
#' Test for Graph Class
#'
#' A function to check whether an object has class \code{dagitty}.
#'
#' @param x object to be tested.
#'
#' @export
is.dagitty <- function(x) inherits(x,"dagitty")
#' Generate Graph Layout
#'
#' This function generates plot coordinates for each variable in a graph that does not
#' have them already. To this end, the well-known \dQuote{Spring} layout algorithm is
#' used. Note that this is a stochastic algorithm, so the generated layout will be
#' different every time (which also means that you can try several times until you find
#' a decent layout).
#'
#' @param x the input graph, of any type.
#' @param method the layout method; currently, only \code{"spring"} is supported.
#' @return the same graph as \code{x} but with layout coordinates added.
#'
#' @examples
#' ## Generate a layout for the M-bias graph and plot it
#' plot( graphLayout( dagitty( "dag { X <- U1 -> M <- U2 -> Y } " ) ) )
#' ## Plot larger graph and abbreviate its variable names.
#' plot( getExample("Shrier"), abbreviate.names=TRUE )
#'
#' @export
graphLayout <- function( x, method="spring" ){
x <- as.dagitty( x )
if( !(method %in% c("spring")) ){
stop("Layout method ",method," not supported!")
}
xv <- .getJSVar()
tryCatch({
.jsassigngraph( xv, x )
.jseval( paste0("(new DAGitty.GraphLayouter.Spring(global.",xv,")).layout()") )
.jsassign( xv, .jsp("global.",xv,".toString()") )
r <- .jsget(xv)
}, finally={.deleteJSVar(xv)})
structure( r, class="dagitty" )
}
#' Plot Graph
#'
#' A simple plot method to quickly visualize a graph. This is intended mainly for
#' simple visualization purposes and not as a full-fledged graph drawing
#' function.
#'
#' @param x the input graph, a DAG, MAG, or PDAG.
#' @param abbreviate.names logical. Whether to abbreviate variable names.
#' @param show.coefficients logical. Whether to plot coefficients defined in the graph syntax
#' on the edges.
#' @param adjust.coefficients numerical. Adjustment for coefficient labels; the distance between
#' the edge labels and the midpoint of the edge can be controlled using this paramer.
#' Can also be a vector of 2 numbers for separate horizontal and vertical adjustment. NA means
#' no adjustment (default).
#' @param node.names If not NULL, a named vector or expression list
#' to rename the nodes.
#' @param ... not used.
#'
#' @details If \code{node.names} is not \code{NULL}, it should be a
#' named vector of characters or expressions to use to rename (some of)
#' the nodes, e.g. node \code{"X"} could be renamed using \code{expression(X = alpha^2)}.
#'
#' @examples
#'
#' # Showing usage of "node.names"
#' plot(dagitty('{x[pos="0,0"]}->{y[pos="1,0"]}'), node.names=expression(x = alpha^2, y=gamma^2))
#'
#'
#' @export
plot.dagitty <- function( x,
abbreviate.names=FALSE,
show.coefficients=FALSE,
adjust.coefficients=NA,
node.names=NULL,
... ){
parms <- list(...)
x <- as.dagitty( x )
.supportsTypes(x,c("dag","mag","pdag"))
coords <- coordinates( x )
if( any( !is.finite( coords$x ) | !is.finite( coords$y ) ) ){
message("Plot coordinates for graph not supplied! Generating coordinates, see ?coordinates for how to set your own.")
x <- graphLayout(x)
coords <- coordinates(x)
}
if( abbreviate.names ){
labels <- abbreviate(names(coords$x))
} else {
labels <- names(coords$x)
}
if(!is.null(node.names)){
names(labels) <- names(coords$x)
if(is.null(names(node.names)))
stop("'node.names' must be named")
if(!all(names(node.names) %in% names(labels)))
stop("node(s) not found: ",
paste0("'", setdiff(names(node.names), names(labels)), "'",
collapse = ","))
labels[names(node.names)] <- node.names
names(labels) <- names(coords$x) # If coerced to expression, names are lost
}
omar <- par("mar")
par(mar=rep(0,4))
plot.new()
par(new=TRUE)
wx <- sapply( labels,
function(s) strwidth(s,units="inches") ) + strwidth("mm",units="inches")
wy <- sapply( labels,
function(s) strheight(s,units="inches") ) + strheight("\n")
ppi.x <- dev.size("in")[1] / (max(coords$x)-min(coords$x))
ppi.y <- dev.size("in")[2] / (max(coords$y)-min(coords$y))
wx <- wx/ppi.x
wy <- wy/ppi.y
if( 'xlim' %in% names(parms) ){
xlim <- parms$xlim
} else {
xlim <- c(min(coords$x-wx/2),max(coords$x+wx/2))
}
if( 'ylim' %in% names(parms) ){
ylim <- parms$ylim
} else {
ylim <- c(-max(coords$y+wy/2),-min(coords$y-wy/2))
}
plot( NA, xlim=xlim, ylim=ylim, xlab="", ylab="", bty="n",
xaxt="n", yaxt="n" )
wx <- sapply( labels, strwidth ) + strwidth("xx")
wy <- sapply( labels, strheight ) + strheight("\n")
asp <- par("pin")[1]/diff(par("usr")[1:2]) /
(par("pin")[2]/diff(par("usr")[3:4]))
ex <- edges(x)
if( show.coefficients ){
ea <- .edgeAttributes(x,"beta")
ex <- merge( ex, ea )
}
ax1 <- rep(0,nrow(ex))
ax2 <- rep(0,nrow(ex))
ay1 <- rep(0,nrow(ex))
ay2 <- rep(0,nrow(ex))
axc <- rep(0,nrow(ex))
ayc <- rep(0,nrow(ex))
acode <- rep(2,nrow(ex))
has.control.point <- rep(FALSE,nrow(ex))
for( i in seq_len(nrow(ex)) ){
if( ex[i,3] == "<->" ){
acode[i] <- 3
has.control.point[i] <- TRUE
}
if( ex[i,3] == "--" ){
acode[i] <- 0
}
l1 <- as.character(ex[i,1]); l2 <- as.character(ex[i,2])
x1 <- coords$x[l1]; y1 <- coords$y[l1]
x2 <- coords$x[l2]; y2 <- coords$y[l2]
if( is.na( ex[i,4] ) || is.na( ex[i,5] ) ){
cp <- .autoControlPoint( x1, y1, x2, y2, asp,
.2*as.integer( acode[i]==3 ) )
} else {
cp <- list(x=ex[i,4],y=ex[i,5])
has.control.point[i] <- TRUE
}
bi1 <- .lineSegBoxIntersect( x1-wx[l1]/2,y1-wy[l1]/2,
x1+wx[l1]/2,y1+wy[l1]/2, x1, y1, cp$x, cp$y )
bi2 <- .lineSegBoxIntersect( x2-wx[l2]/2,y2-wy[l2]/2,
x2+wx[l2]/2,y2+wy[l2]/2, cp$x, cp$y, x2, y2 )
if( length(bi1) == 2 ){
x1 <- bi1$x; y1 <- bi1$y
}
if( length(bi2) == 2 ){
x2 <- bi2$x; y2 <- bi2$y
}
ax1[i] <- x1; ax2[i] <- x2
ay1[i] <- y1; ay2[i] <- y2
axc[i] <- cp$x; ayc[i] <- cp$y
}
directed <- acode==2 & !has.control.point
undirected <- acode==0 & !has.control.point
arrows( ax1[directed], -ay1[directed],
ax2[directed], -ay2[directed], length=0.1, col="gray" )
segments( ax1[undirected], -ay1[undirected],
ax2[undirected], -ay2[undirected], col="black", lwd=2 )