This repository has been archived by the owner on Mar 22, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
utils-sanitization.R
2321 lines (1619 loc) · 64.1 KB
/
utils-sanitization.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
# is x a real number?
is.real.number = function(x) {
is.numeric(x) &&
(length(x) == 1) &&
is.finite(x)
}#IS.REAL
# is x a positive number?
is.positive = function(x) {
is.numeric(x) &&
(length(x) == 1) &&
is.finite(x) &&
(x > 0)
}#IS.POSITIVE
# is x a non-negative number?
is.non.negative = function(x) {
is.numeric(x) &&
(length(x) == 1) &&
is.finite(x) &&
(x >= 0)
}#IS.NON.NEGATIVE
# is x a positive integer?
is.positive.integer = function(x) {
is.positive(x) && ((x %/% 1) == x)
}#IS.POSITIVE.INTEGER
# is x a vector of positive numbers?
is.positive.vector = function(x) {
is.numeric(x) &&
all(is.finite(x)) &&
all(x > 0)
}#IS.POSITIVE.VECTOR
# is x a vector of non-negative numbers?
is.nonnegative.vector = function(x) {
is.numeric(x) &&
all(is.finite(x)) &&
all(x >= 0)
}#IS.NONNEGATIVE.VECTOR
# is x a probability?
is.probability = function(x) {
is.numeric(x) &&
(length(x) == 1) &&
is.finite(x) &&
(x >= 0) &&
(x <= 1)
}#IS.PROBABILITY
# is x a vector of probabilities?
is.probability.vector = function(x) {
is.numeric(x) &&
all(is.finite(x)) &&
all(x >= 0) &&
all(x <= 1) &&
any(x > 0)
}#IS.PROBABILITY.VECTOR
# is x a single character string?
is.string = function(x) {
is.character(x) &&
(length(x) == 1) &&
!any(is.na(x)) &&
any(x != "")
}#IS.STRING
is.ndmatrix = function(x) {
is(x, c("table", "matrix", "array"))
}#IS.NDMATRIX
# is x a symmetric matrix?
is.symmetric = function(x) {
.Call("is_symmetric",
matrix = x)
}#IS.SYMMETRIC
is.cauchy.schwarz = function(x) {
.Call("is_cauchy_schwarz",
matrix = x)
}#Is.CAUCHY.SCHWARZ
# check the data set.
check.data = function(x, allow.mixed = FALSE) {
# check the data are there.
if (missing(x))
stop("the data are missing.")
# x must be a data frame.
if(!is.data.frame(x))
stop("the data must be in a data frame.")
# check the data for NULL/NaN/NA.
if (missing.data(x))
stop("the data set contains NULL/NaN/NA values.")
if (allow.mixed) {
# check whether the variables are all factors or numeric.
if (!is.data.mixed(x))
stop("variables must be either numeric or factors.")
}#THEN
else {
# check whether the variables are either all continuous or all discrete.
if (!is.data.discrete(x) && !is.data.continuous(x))
stop("variables must be either all real numbers or all factors.")
}
# check the number of levels of discrete variables, to guarantee that
# the degrees of freedom of the tests are positive.
if (is.data.discrete(x))
for (col in names(x))
if (nlevels(x[, col]) < 2)
stop("all factors must have at least two levels.")
}#CHECK.DATA
# check nodes (not necessarily from a bn object).
check.nodes = function(nodes, graph = NULL, min.nodes = 1, max.nodes = Inf) {
# a node is needed.
if (missing(nodes))
stop("no node specified.")
# nodes must be a vector of character strings.
if (!is(nodes, "character"))
stop("nodes must be a vector of character strings, the labels of the nodes.")
# no duplicates allowed.
if (any(duplicated(nodes)))
stop("node labels must be unique.")
# no empty strings.
if (any(is.na(nodes)) || any(nodes == ""))
stop("an empty string is not a valid node label.")
# maximum number of nodes requirement.
if (length(nodes) > max.nodes)
stop(paste("at most", max.nodes, "node(s) needed."))
# minimum number of nodes requirement (usually 1).
if (length(nodes) < min.nodes)
stop(paste("at least", min.nodes, "node(s) needed."))
# node must be a valid node label.
if (!is.null(graph)) {
if (is(graph, "bn")) {
if (!all(nodes %in% names(graph$nodes)))
stop(paste(c("node(s)", nodes[!(nodes %in% names(graph$nodes))],
"not present in the graph."), collapse = " "))
}#THEN
else if (is(graph, "bn.fit")) {
if (!all(nodes %in% names(graph)))
stop(paste(c("node(s)", nodes[!(nodes %in% names(graph))],
"not present in the graph."), collapse = " "))
}#THEN
else if (is.character(graph)) {
if (!all(nodes %in% graph))
stop(paste(c("node(s)", nodes[!(nodes %in% graph)],
"not present in the graph."), collapse = " "))
}#THEN
}#THEN
}#CHECK.NODES
# check an arc set.
check.arcs = function(arcs, nodes) {
# sanitize the set of arcs.
if (is(arcs, "matrix") || is(arcs, "data.frame")) {
if (dim(arcs)[2] != 2)
stop("arc sets must have two columns.")
if (is.data.frame(arcs))
arcs = as.matrix(cbind(as.character(arcs[, 1]),
as.character(arcs[, 2])))
# be sure to set the column names.
dimnames(arcs) = list(c(), c("from", "to"))
}#THEN
else if (is.character(arcs)) {
# if there is an even number of labels fit them into a 2-column matrix.
if ((length(arcs) %% 2) != 0)
stop("arc sets must have two columns.")
arcs = matrix(arcs, ncol = 2, byrow = TRUE,
dimnames = list(c(), c("from", "to")))
}#THEN
else {
stop("an arc set must be a matrix or data.frame with two columns.")
}#ELSE
# nodes must be valid node labels.
if (!all(arcs %in% nodes))
stop(paste(c("node(s)", unique(arcs[!(arcs %in% nodes)]),
"not present in the graph."), collapse = " "))
# remove duplicate arcs.
arcs = unique.arcs(arcs, nodes, warn = TRUE)
# check there are no loops among the arcs.
loop = (arcs[, "from"] == arcs[, "to"])
if (any(loop))
stop(paste(c("invalid arcs that are actually loops:\n",
paste(" ", arcs[loop, 1], "->", arcs[loop, 2], "\n"))))
return(arcs)
}#CHECK.ARCS
# build a valid whitelist.
build.whitelist = function(whitelist, nodes) {
if (is.null(whitelist)) {
# no whitelist, nothing to do.
return(NULL)
}#THEN
if (class(whitelist) %in% c("matrix", "data.frame")) {
if (dim(whitelist)[2] != 2)
stop("whitelist must have two columns.")
if (is.data.frame(whitelist))
whitelist = as.matrix(cbind(as.character(whitelist[, 1]),
as.character(whitelist[, 2])))
}#THEN
else if (is.character(whitelist)) {
if (length(whitelist) != 2)
stop("whitelist must have two columns.")
whitelist = matrix(whitelist, ncol = 2, byrow = TRUE)
}#THEN
else {
stop("whitelist must be a matrix or data.frame with two columns.")
}#ELSE
# drop duplicate rows.
whitelist = unique.arcs(whitelist, nodes, warn = TRUE)
# add column names for easy reference.
colnames(whitelist) = c("from", "to")
# check all the names in the whitelist against the column names of x.
if (any(!(unique(as.vector(whitelist)) %in% nodes)))
stop("unknown node label present in the whitelist.")
# if the whitelist itself contains cycles, no acyclic graph
# can be learned.
if (!is.acyclic(whitelist, nodes))
stop("this whitelist does not allow an acyclic graph.")
return(whitelist)
}#BUILD.WHITELIST
# build a valid blacklist.
build.blacklist = function(blacklist, whitelist, nodes) {
if (!is.null(blacklist)) {
if (class(blacklist) %in% c("matrix", "data.frame")) {
if (dim(blacklist)[2] != 2)
stop("blacklist must have two columns.")
if (is.data.frame(blacklist))
blacklist = as.matrix(cbind(as.character(blacklist[, 1]),
as.character(blacklist[, 2])))
}#THEN
else if (is.character(blacklist)) {
if (length(blacklist) != 2)
stop("blacklist must have two columns.")
blacklist = matrix(blacklist, ncol = 2, byrow = TRUE)
}#THEN
else {
stop("blacklist must be a matrix or data.frame with two columns.")
}#ELSE
# check all the names in the blacklist against the column names of x.
if (any(!(unique(as.vector(blacklist)) %in% nodes)))
stop("unknown node label present in the blacklist.")
# drop duplicate rows.
blacklist = unique.arcs(blacklist, nodes)
}#THEN
# update blacklist to agree with whitelist.
# NOTE: whitelist and blacklist relationship is the same as hosts.allow
# and hosts.deny.
if (!is.null(whitelist)) {
# if x -> y is whitelisted but y -> x is not, it is to be blacklisted.
apply(whitelist, 1,
function(x) {
if (!is.whitelisted(whitelist, x[c(2, 1)]))
assign("blacklist", rbind(blacklist, x[c(2, 1)]),
envir = sys.frame(-2))
})
# if x -> y is whitelisted, it is to be removed from the blacklist.
if (!is.null(blacklist)) {
blacklist = blacklist[!apply(blacklist, 1,
function(x){ is.whitelisted(whitelist, x) }),]
blacklist = matrix(blacklist, ncol = 2, byrow = FALSE,
dimnames = list(NULL, c("from", "to")))
# drop duplicate rows.
blacklist = unique.arcs(blacklist, nodes)
}#THEN
}#THEN
return(blacklist)
}#BUILD.BLACKLIST
# check the list of networks passed to custom.strength().
check.customlist = function(custom, nodes) {
# check
if (!is(custom, "list"))
stop("networks must be a list of objects of class 'bn' or of arc sets.")
if(!all(sapply(custom, function(x) { is(x, "bn") || is(x, "matrix") })))
stop("x must be a list of objects of class 'bn' or of arc sets.")
validate = function(custom, nodes) {
if (is(custom, "bn")) {
check.nodes(names(custom$nodes), graph = nodes, min.nodes = length(nodes),
max.nodes = length(nodes))
}
else if (is(custom, "matrix")) {
check.arcs(arcs = custom, nodes = nodes)
}#THEN
else {
stop("x must be a list of objects of class 'bn' or of arc sets.")
}
return(TRUE)
}#VALIDATE
if (!all(sapply(custom, validate, nodes = nodes)))
stop("x must be a list of objects of class 'bn' or of arc sets.")
}#CHECK.CUSTOMLIST
# check score labels.
check.score = function(score, data) {
if (!is.null(score)) {
# check it's a single character string.
check.string(score)
# check the score/test label.
if (!(score %in% available.scores))
stop(paste(c("valid scores are:\n",
sprintf(" %-15s %s\n", names(score.labels), score.labels)), sep = ""))
# check if it's the right score for the data (discrete, continuous).
if (!is.data.discrete(data) && (score %in% available.discrete.scores))
stop(paste("score '", score, "' may be used with discrete data only.", sep = ""))
if (!is.data.continuous(data) && (score %in% available.continuous.scores))
stop(paste("score '", score, "' may be used with continuous data only.", sep = ""))
return(score)
}#THEN
else {
# warn about ordinal data modelled as unordered categorical ones.
if (is.data.ordinal(data))
warning("no score is available for ordinal data, disregarding the ordering of the levels.")
if (is.data.discrete(data))
return("bic")
else
return("bic-g")
}#ELSE
}#CHECK.SCORE
# check whether a score is score equivalent.
is.score.equivalent = function(score, nodes, extra) {
# log-likelihood is always score equivalent.
if (score %in% c("loglik", "loglik-g"))
return(TRUE)
# same with AIC and BIC.
if (score %in% c("aic", "aic-g", "bic", "bic-g"))
return(TRUE)
# BDe and BGe are score equivalent if they have uniform priors (e.g. BDeu and BGeu).
else if ((score %in% c("bde", "bge")) && (extra$prior == "uniform"))
return(TRUE)
# a conservative default.
return(FALSE)
}#IS.SCORE.EQUIVALENT
# check whether a score is decomposable.
is.score.decomposable = function(score, nodes, extra) {
# Castelo & Siebes prior is not decomposable.
if ((score %in% c("bde", "bge")) && (extra$prior == "cs"))
return(FALSE)
# a sensible default.
return(TRUE)
}#IS.SCORE.DECOMPOSABLE
# check test labels.
check.test = function(test, data) {
if (!missing(test) && !is.null(test)) {
# check it's a single character string.
check.string(test)
# check the score/test label.
if (!(test %in% available.tests))
stop(paste(c("valid tests are:\n",
sprintf(" %-15s %s\n", names(test.labels), test.labels)), sep = ""))
# check if it's the right test for the data (discrete, continuous).
if (!is.data.ordinal(data) && (test %in% available.ordinal.tests))
stop(paste("test '", test, "' may be used with ordinal data only.", sep = ""))
if (!is.data.discrete(data) && (test %in% available.discrete.tests))
stop(paste("test '", test, "' may be used with discrete data only.", sep = ""))
if (!is.data.continuous(data) && (test %in% available.continuous.tests))
stop(paste("test '", test, "' may be used with continuous data only.", sep = ""))
return(test)
}#THEN
else {
if (is.data.ordinal(data))
return("jt")
else if (is.data.discrete(data))
return("mi")
else
return("cor")
}#ELSE
}#CHECK.TEST
check.criterion = function(criterion, data) {
# check it's a single character string.
check.string(criterion)
# check criterion's label.
if (criterion %in% available.tests)
criterion = check.test(criterion, data)
else if (criterion %in% available.scores)
criterion = check.score(criterion, data)
else
stop(paste(c("valid tests are:\n",
sprintf(" %-15s %s\n", names(test.labels), test.labels),
" valid scores are:\n",
sprintf(" %-15s %s\n", names(score.labels), score.labels)),
sep = ""))
return(criterion)
}#CHECK.CRITERION
# check loss functions' labels.
check.loss = function(loss, data) {
if (!is.null(loss)) {
# check it's a single character string.
check.string(loss)
# check the score/test label.
if (!(loss %in% loss.functions))
stop(paste(c("valid loss functions are:\n",
sprintf(" %-15s %s\n", names(loss.labels), loss.labels)), sep = ""))
if (!is.data.discrete(data) && (loss %in% discrete.loss.functions))
stop(paste("loss function '", loss, "' may be used with discrete data only.", sep = ""))
if (!is.data.continuous(data) && (loss %in% continuous.loss.functions))
stop(paste("loss function '", loss, "' may be used with continuous data only.", sep = ""))
return(loss)
}#THEN
else {
if (is.data.discrete(data))
return("logl")
else
return("logl-g")
}#ELSE
}#CHECK.LOSS
# check the method used to fit the parameters of the network.
check.fitting.method = function(method, data) {
if (!is.null(method)) {
# check it's a single character string.
check.string(method)
# check the score/test label.
if (!(method %in% available.fitting.methods))
stop(paste(c("valid fitting methods are:\n",
sprintf(" %-15s %s\n", names(fitting.labels), fitting.labels)), sep = ""))
# bayesian parameter estimation is implemented only for discrete data.
if (is.data.continuous(data) && (method == "bayes"))
stop("Bayesian parameter estimation for Gaussian Bayesian networks is not implemented.")
return(method)
}#THEN
else {
return("mle")
}#ELSE
}#CHECK.FITTING.METHOD
# check the method used to discretize the data.
check.discretization.method = function(method) {
if (!is.null(method)) {
# check it's a single character string.
check.string(method)
# check the score/test label.
if (!(method %in% available.discretization.methods))
stop(paste(c("valid discretization methods are:\n",
sprintf(" %-15s %s\n", names(discretization.labels), discretization.labels)), sep = ""))
return(method)
}#THEN
else {
return("quantile")
}#ELSE
}#CHECK.DISCRETIZATION.METHOD
# check the estimator for the mutual information.
check.mi.estimator = function(estimator, data) {
if (!is.null(estimator)) {
# check it's a single character string.
check.string(estimator)
# check the score/estimator label.
if (!(estimator %in% available.mi))
stop(paste(c("valid estimators are:\n",
sprintf(" %-15s %s\n", names(mi.estimator.labels), mi.estimator.labels)), sep = ""))
# check if it's the right estimator for the data (discrete, continuous).
if (!is.data.discrete(data) && (estimator %in% available.discrete.mi))
stop(paste("estimator '", estimator, "' may be used with discrete data only.", sep = ""))
if (!is.data.continuous(data) && (estimator %in% available.continuous.mi))
stop(paste("estimator '", estimator, "' may be used with continuous data only.", sep = ""))
return(estimator)
}#THEN
else {
if (is.data.discrete(data))
return("mi")
else
return("mi-g")
}#ELSE
}#CHECK.MI.ESTIMATOR
# is the fitted bayesian network of a prarticular type?
is.fitted.type = function(fitted, type) {
for (i in 1:length(fitted))
if (!is(fitted[[i]], type))
return(FALSE)
return(TRUE)
}#IS.FITTED.TYPE
# is the fitted bayesian network a discrete one?
is.fitted.discrete = function(fitted) is.fitted.type(fitted, "bn.fit.dnode") || is.fitted.type(fitted, "bn.fit.onode")
# is the fitted bayesian network an ordinal one?
is.fitted.ordinal = function(fitted) is.fitted.type(fitted, "bn.fit.onode")
# is the fitted bayesian network a continuous one?
is.fitted.continuous = function(fitted) is.fitted.type(fitted, "bn.fit.gnode")
# is the data of a particular type?
is.data.type = function(data, type) {
for (i in 1:ncol(data))
if (!is(data[, i], type))
return(FALSE)
return(TRUE)
}#IS.DATA.TYPE
# will the bayesian network be a discrete one?
is.data.discrete = function(data) is.data.type(data, "factor")
# will the bayesian network be an ordinal one?
is.data.ordinal = function(data) is.data.type(data, "ordered")
# will the bayesian network be a continuous one?
is.data.continuous = function(data) is.data.type(data, "double")
# does the data include coth discrete and continuous variables?
is.data.mixed = function(data) is.data.type(data, c("factor", "double"))
# there are missing data?
missing.data = function(data) {
!all(complete.cases(data))
}#MISSING.DATA
# check the imaginary sample size.
check.iss = function(iss, network, data) {
if (!is.null(iss)) {
# validate the imaginary sample size.
if (!is.positive(iss) || (iss < 1))
stop("the imaginary sample size must be a numeric value greater than 1.")
# if iss = 1 the bge is NaN, if iss = 2 and phi = "heckerman" the
# computation stops with the following error:
# Error in solve.default(phi[A, A]) :
# Lapack routine dgesv: system is exactly singular
if(is.data.continuous(data) && (iss < 3))
stop("the imaginary sample size must be a numeric value greater than 3.")
}#THEN
else {
# check whether there is an imaginary sample size stored in the bn object;
# otherwise use a the de facto standard value of 10.
if (!is.null(network$learning$args$iss))
iss = network$learning$args$iss
else
iss = 10
}#ELSE
# coerce iss to integer.
return(as.integer(iss))
}#CHECK.ISS
# check the phi defintion to be used in the bge score.
check.phi = function(phi, network, data) {
if (!is.null(phi)) {
if (!(phi %in% c("heckerman", "bottcher")))
stop("unknown phi definition, should be either 'heckerman' or 'bottcher'.")
}#THEN
else {
# check if there is an phi definition stored in the bn object;
# otherwise use the one by heckerman.
if (!is.null(network$learning$args$phi))
phi = network$learning$args$phi
else
phi = "heckerman"
}#ELSE
return(phi)
}#CHECK.PHI
# check the experimental data list.
check.experimental = function(exp, network, data) {
if (!is.null(exp)) {
if (!is.list(exp))
stop("experimental data must be specified via a list of indexes.")
if (!all(names(exp) %in% names(data)) || (length(names(exp)) == 0))
stop("unkown variables specified in the experimental data list.")
for (var in names(exp)) {
if (!is.positive.vector(exp[[var]]))
stop("indexes of experimental data must be positive integer numbers.")
if (any(duplicated(exp[[var]])))
stop("duplicated indexes for experimental data.")
if (any(exp[[var]] > length(data[, var])))
stop("out of bounds indexes for experimental data.")
# just kill empty elements.
if (length(exp[[var]]) == 0)
exp[[var]] = NULL
# also, convert evetything to integers to make things simpler at the
# C level.
exp[[var]] = as.integer(exp[[var]])
}#FOR
}#THEN
else {
# check whether there is a list stored in the bn object; if no experimental
# data is specified, return an empty list (which is the same as using the
# plain BDe score).
if (!is.null(network$learning$args$exp))
exp = network$learning$args$exp
else
exp = structure(vector(ncol(data), mode = "list"), names = names(data))
}#ELSE
return(exp)
}#CHECK.EXPERIMENTAL
# check the penalty used in AIC and BIC.
check.penalty = function(k, network, data, score) {
if (!is.null(k)) {
# validate the penalty weight.
if (!is.positive(k))
stop("the penalty weight must be a positive numeric value.")
}#THEN
else {
# check whether there is a penalization coefficient stored in the bn object,
# use the default for the score function otherwise.
if (!is.null(network$learning$args$k))
k = network$learning$args$k
else
k = ifelse((score %in% c("aic", "aic-g")), 1, log(nrow(data))/2)
}#ELSE
return(k)
}#CHECK.PENALTY
# sanitize prior distributions over the graph space.
check.graph.prior = function(prior, network) {
if (is.null(prior)) {
# check whether there is a graph prior stored in the bn object, use the
# uniform one otherwise.
if (!is.null(network$learning$args$prior))
prior = network$learning$args$prior
else
prior = "uniform"
}#THEN
else {
# check whether prior is a string.
check.string(prior)
# check whether the label matches a known prior.
if (!(prior %in% prior.distributions))
stop("valid prior distributions are: ",
paste(prior.distributions, collapse = " "), ".")
}#ELSE
return(prior)
}#CHECK.GRAPH.PRIOR
# check the sparsity parameter of the prior distribution over the graph space.
check.graph.sparsity = function(beta, prior, network, data) {
default.beta = list("uniform" = NULL, "vsp" = 1/ncol(data), cs = NULL)
if (is.null(beta)) {
# check whether there is a graph prior stored in the bn object, use the
# uniform one otherwise.
if (!is.null(network$learning$args$prior))
beta = network$learning$args$beta
else
beta = default.beta[[prior]]
}#THEN
else {
if (prior == "uniform") {
warning("unused argument beta.")
beta = NULL
}#THEN
else if (prior == "vsp") {
if (!is.probability(beta) || (beta >= 1))
stop("beta must be a probability smaller than 1.")
}#THEN
else if (prior == "cs") {
# arcs' prior probabilities should be provided in a data frame.
if (!is.data.frame(beta) || (ncol(beta) != 3) ||
!identical(colnames(beta), c("from", "to", "prob")))
stop("beta must be a data frame with three colums: 'from', 'to' and 'prob'.")
# the probs cloumns must contain only probabilities.
if (!is.probability.vector(beta$prob))
stop("arcs prior must contain only probabilities.")
# check that the first two columns contain only valid arcs.
check.arcs(beta[, c("from", "to")], nodes = names(data))
# complete the user-specified prior.
beta = cs.completed.prior(beta,names(data))
}#THEN
}#ELSE
return(beta)
}#CHECK.GRAPH.SPARSITY
check.maxp = function(maxp, data) {
if (is.null(maxp)) {
maxp = Inf
}#THEN
else if (!isTRUE(all.equal(maxp, Inf))) {
if (!is.positive.integer(maxp))
stop("maxp must be a positive number.")
if (maxp >= ncol(data))
warning("maximum number of parents should be lower than the number of nodes, the limit will be ignored.")
}#ELSE
return(as.numeric(maxp))
}#CHECK.MAXP
# sanitize the extra arguments passed to the network scores.
check.score.args = function(score, network, data, extra.args) {
# check the imaginary sample size.
if (score %in% c("bde", "bdes", "mbde", "bge"))
extra.args$iss = check.iss(iss = extra.args$iss,
network = network, data = data)
# check the graph prior distribution.
if (score %in% c("bde", "bge"))
extra.args$prior = check.graph.prior(prior = extra.args$prior,
network = network)
# check the sparsity parameter of the graph prior distribution.
if (score %in% c("bde", "bge"))
extra.args$beta = check.graph.sparsity(beta = extra.args$beta,
prior = extra.args$prior, network = network, data = data)
# check the list of the experimental observations in the data set.
if (score == "mbde")
extra.args$exp = check.experimental(exp = extra.args$exp,
network = network, data = data)
# check the likelihood penalty.
if (score %in% c("aic", "bic", "aic-g", "bic-g"))
extra.args$k = check.penalty(k = extra.args$k, network = network,
data = data, score = score)
# check phi estimator.
if (score == "bge")
extra.args$phi = check.phi(phi = extra.args$phi,
network = network, data = data)
check.unused.args(extra.args, score.extra.args[[score]])
return(extra.args)
}#CHECK.SCORE.ARGS
# sanitize the extra arguments passed to the random graph generation algorithms.
check.graph.generation.args = function(method, nodes, extra.args) {
if (method == "ordered") {
if (!is.null(extra.args$prob)) {
# prob must be numeric.
if (!is.probability(extra.args$prob))
stop("the branching probability must be a numeric value in [0,1].")
}#THEN
else {
# this default produces graphs with about the same number of
# arcs as there are nodes.
extra.args$prob = 2 / (length(nodes) - 1)
}#ELSE
}#THEN
else if (method %in% c("ic-dag", "melancon")) {
if (!is.null(extra.args$every)) {
if (!is.positive(extra.args$every))
stop("'every' must be a positive integer number.")
}#THEN
else {
extra.args$every = 1
}#ELSE
if (!is.null(extra.args$burn.in)) {
if (!is.positive(extra.args$burn.in))
stop("the burn in length must be a positive integer number.")
}#THEN
else {
extra.args$burn.in = 6 * length(nodes)^2
}#ELSE
if (!is.null(extra.args$max.in.degree)) {
if (!is.positive.integer(extra.args$max.in.degree))
stop("the maximum in-degree must be a positive integer number.")
if (extra.args$max.in.degree >= length(nodes)) {
warning("a node cannot have an in-degree greater or equal to the number of nodes in the graph.")
warning("the condition on the in-degree will be ignored.")