-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBNDataset-methods.R
745 lines (646 loc) · 23.8 KB
/
BNDataset-methods.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
#' initialize a \code{\link{BNDataset}} object.
#'
#' @name BNDataset
#' @rdname BNDataset-class
#' @docType method
#' @aliases initialize,BNDataset-method
#'
#' @param .Object an empty BNDataset.
#'
#' @return a BNDataset object.
setMethod("initialize",
"BNDataset", function(.Object)
{
validObject(.Object)
return(.Object)
})
#' @export
BNDataset <- function(data, discreteness, variables = NULL, node.sizes = NULL, ...)
{
dataset <- new("BNDataset")
# # this is here for 2 purposes:
# # 1. spare changes all over the package in order to remove name field
# # 2. keep a suggestion on how to get variable name
# # name(dataset) <- deparse(substitute(dataset))
# above: seems heavy...
name(dataset) <- "BNDataset"
# The presence of ONLY data and discreteness, and them being 2 strings, mean that two files are passed:
# - data file (data)
# - header file (discreteness)
if ( is.null(variables) && is.null(node.sizes) &&
!is.null(data) && !is.null(discreteness) &&
length(discreteness) == 1 && is.character(discreteness) &&
length(data) == 1 && is.character(data) ) {
dataset <- read.dataset(dataset, data, discreteness, ...)
validObject(dataset)
return(dataset)
}
other.args <- list(...)
if ("starts.from" %in% names(other.args))
starts.from <- other.args$starts.from
else
starts.from <- 1
if ("num.time.steps" %in% names(other.args))
num.time.steps <- other.args$num.time.steps
else
num.time.steps <- 1
num.time.steps(dataset) <- num.time.steps
if(length(variables) > 1)
{
vars <- variables
if (length(vars) == ncol(as.matrix(data))) {
variables(dataset) <- vars
} else if (num.time.steps > 1 && length(vars) * num.time.steps == ncol(as.matrix(data))) {
copyvars <- c()
for (t in 1:num.time.steps) {
for (w in vars) {
copyvars <- c(copyvars, paste(w, as.character(t), sep='_t'))
}
}
variables(dataset) <- copyvars
} else {
stop("Incoherent number of variables in the dataset header.")
}
num.variables(dataset) <- length(variables(dataset))
}
if (length(node.sizes) > 1) {
if (length(node.sizes) == ncol(as.matrix(data))) {
node.sizes(dataset) <- node.sizes
} else if (num.time.steps > 1 && length(node.sizes) * num.time.steps == ncol(as.matrix(data))) {
node.sizes(dataset) <- rep(node.sizes, num.time.steps)
} else {
stop("Incoherent number of variables in the dataset definition.")
}
}
if (length(discreteness) > 1) {
for (d in 1:length(discreteness)) {
if (discreteness[d] %in% c("d","D","T","TRUE")) discreteness[d] <- 'D'
else if (discreteness[d] %in% c("c","C","F","FALSE")) discreteness[d] <- 'C'
else {
SGS.log("Unrecognized status for variable ",variables(dataset)[d],", converting it to discrete.")
discreteness[d] <- 'D'
}
}
if (length(discreteness) == ncol(as.matrix(data))) {
discreteness(dataset) <- discreteness
} else if (num.time.steps > 1 && length(discreteness) * num.time.steps == ncol(as.matrix(data))) {
discreteness(dataset) <- rep(discreteness, num.time.steps)
} else {
stop("Incoherent number of variables in the dataset definition.")
}
}
if (!is.null(data))
{
raw.data(dataset) <- as.matrix(data) + (1 - starts.from)
if (is.null(variables)) {
variables(dataset) <- rownames(data)
warning("Variable names guessed from data. Please check for consistency with your actual data.")
}
if (is.null(node.sizes)) {
node.sizes <- rep(0, length(variables))
for (v in 1:length(variables))
{
node.sizes[v] <- max(data[,v][which(!is.na(data[,v]))]) - min(data[,v][which(!is.na(data[,v]))]) + 1
}
warning("Variable cardinalities guessed from data. Please check for consistency with your actual data. Otherwise, execution may terminate with errors later.")
}
}
num.items(dataset) <- nrow(dataset@raw.data)
validObject(dataset)
if(length(dataset@variables) > 0 && has.raw.data(dataset))
colnames(dataset@raw.data) <- dataset@variables
return(dataset)
}
# validator
setValidity("BNDataset",
function(object)
{
retval <- NULL
if (object@num.variables > 0 && length(object@variables) > 0 && length(object@variables) != object@num.variables)
{
retval <- c(retval, "incoherent number of variable names")
}
if (object@has.raw.data && ncol(object@raw.data) != object@num.variables)
{
retval <- c(retval, "incoherent number of variables in raw dataset")
}
if (object@has.imputed.data && ncol(object@imputed.data) != object@num.variables)
{
retval <- c(retval, "incoherent number of variables in imputed dataset")
}
if(object@num.variables > 0 && length(object@discreteness) > 1 &&
length(object@discreteness) != object@num.variables)
{
retval <- c(retval, "incoherent number of variable statuses")
}
if (object@num.variables > 0 && length(object@node.sizes) == object@num.variables && object@has.raw.data)
{
warn <- c()
halt <- c()
for (var in 1:object@num.variables)
{
if ( object@discreteness[var] &&
(min(object@raw.data[,var][which(!is.na(object@raw.data[,var]))]) > 1 ||
max(object@raw.data[,var][which(!is.na(object@raw.data[,var]))]) < object@node.sizes[var]))
{
warn <- c(warn, var)
}
if ( object@discreteness[var] &&
(min(object@raw.data[,var][which(!is.na(object@raw.data[,var]))]) < 1 ||
max(object@raw.data[,var][which(!is.na(object@raw.data[,var]))]) > object@node.sizes[var]))
{
halt <- c(halt, var)
}
}
if (length(halt) > 0)
{
wrongs <- strcat("Dataset contains values out of bounds for variables ", halt, sep=" ")
retval <- c(retval, wrongs)
} else if (length(warn) > 0)
{
wrongs <- strcat("Not all of the possible values have been observed for variables ", warn, sep = " ")
warning(wrongs)
}
}
if (object@num.variables > 0 && length(object@node.sizes) == object@num.variables && object@has.imputed.data)
{
warn <- c()
halt <- c()
for (var in 1:object@num.variables)
{
if ( object@discreteness[var] &&
(min(object@imputed.data[,var][which(!is.na(object@imputed.data[,var]))]) > 1 ||
max(object@imputed.data[,var][which(!is.na(object@imputed.data[,var]))]) < object@node.sizes[var]))
{
warn <- c(warn, var)
}
if ( object@discreteness[var] &&
(min(object@imputed.data[,var][which(!is.na(object@imputed.data[,var]))]) < 1 ||
max(object@imputed.data[,var][which(!is.na(object@imputed.data[,var]))]) > object@node.sizes[var]))
{
halt <- c(halt, var)
}
}
if (length(halt) > 0)
{
wrongs <- strcat("Dataset contains values out of bounds for variables ", halt, sep=" ")
retval <- c(retval, wrongs)
} else if (length(warn) > 0)
{
wrongs <- strcat("Not all of the possible values have been observed for variables ", warn, sep= " ")
warning(wrongs)
}
}
if (object@num.time.steps < 1) {
retval <- c(retval, "impossible number of time steps in the dataset")
}
if (length(object@quantiles) > 1 && length(object@quantiles) != length(object@variables)) {
retval <- c(retval, "incorrect list of quantiles")
}
if (is.null(retval)) return (TRUE)
return(retval)
}
)
#' @rdname name
#' @aliases name,BNDataset
setMethod("name", "BNDataset", function(x) { return(slot(x, "name")) } )
#' @rdname num.variables
#' @aliases num.variables,BNDataset
setMethod("num.variables", "BNDataset", function(x) { return(slot(x, "num.variables")) } )
#' @rdname variables
#' @aliases variables,BNDataset
setMethod("variables", "BNDataset", function(x) { return(slot(x, "variables")) } )
#' @rdname discreteness
#' @aliases discreteness,BNDataset
setMethod("discreteness",
"BNDataset",
function(x)
{
return(slot(x, "discreteness"))
})
#' @aliases quantiles,BNDataset
#' @rdname quantiles
setMethod("quantiles",
"BNDataset",
function(x)
{
return(slot(x, "quantiles"))
})
#' @rdname node.sizes
#' @aliases node.sizes,BNDataset
setMethod("node.sizes", "BNDataset", function(x) { return(slot(x, "node.sizes")) } )
#' @rdname header.file
#' @aliases header.file,BNDataset
setMethod("header.file", "BNDataset", function(x) return(slot(x, "header.file")))
#' @rdname data.file
#' @aliases data.file,BNDataset
setMethod("data.file", "BNDataset", function(x) return(slot(x, "data.file")))
#' @rdname num.variables
#' @aliases num.variables,BNDataset
setMethod("num.variables","BNDataset", function(x) return(slot(x, "num.variables")))
#' @rdname num.items
#' @aliases num.items,BNDataset
setMethod("num.items", "BNDataset", function(x) return(slot(x, "num.items")))
#' @rdname has.boots
#' @aliases has.boots,BNDataset
setMethod("has.boots", "BNDataset", function(x) return(slot(x, "has.boots")))
#' @rdname has.imputed.boots
#' @aliases has.imputed.boots,BNDataset
setMethod("has.imputed.boots", "BNDataset", function(x) return(slot(x, "has.imputed.boots")))
#' @rdname boots
#' @aliases boots,BNDataset
setMethod("boots", "BNDataset", function(x) return(slot(x, "boots")))
#' @rdname imp.boots
#' @aliases imp.boots,BNDataset
setMethod("imp.boots", "BNDataset", function(x) return(slot(x, "imp.boots")))
#' @rdname num.boots
#' @aliases num.boots,BNDataset
setMethod("num.boots", "BNDataset", function(x) return(slot(x, "num.boots")))
#' @rdname num.time.steps
#' @aliases num.time.steps,BNDataset
setMethod("num.time.steps", "BNDataset", function(x) return(slot(x, "num.time.steps")))
#' @name name<-
#' @aliases name<-,BNDataset-method
#' @docType methods
#' @rdname name-set
setReplaceMethod("name",
"BNDataset",
function(x, value)
{
slot(x, "name") <- value
validObject(x)
return(x)
})
#' @name variables<-
#' @aliases variables<-,BNDataset-method
#' @docType methods
#' @rdname variables-set
setReplaceMethod("variables",
"BNDataset",
function(x, value)
{
slot(x, "variables") <- value
num.variables(x) <- length(value)
validObject(x)
return(x)
})
#' @name discreteness<-
#' @aliases discreteness<-,BNDataset-method
#' @docType methods
#' @rdname discreteness-set
setReplaceMethod("discreteness",
"BNDataset",
function(x, value)
{
if (is.logical(value))
slot(x, "discreteness") <- value
if (is.integer(value) || is.numeric(value))
{
d <- rep(F, num.variables(x))
d[value] <- T
slot(x, "discreteness") <- value
}
if (is.character(value))
slot(x, "discreteness") <- sapply(1:length(value), FUN=function(i){ !is.na(match(value[i],c('d',"D"))) })
validObject(x)
return(x)
})
#' @name quantiles<-
#' @aliases quantiles<-,BNDataset-method
#' @docType methods
#' @rdname quantiles-set
setReplaceMethod("quantiles",
"BNDataset",
function(x, value)
{
slot(x, "quantiles") <- value
validObject(x)
return(x)
})
#' @name node.sizes<-
#' @aliases node.sizes<-,BNDataset-method
#' @docType methods
#' @rdname node.sizes-set
setReplaceMethod("node.sizes",
"BNDataset",
function(x, value)
{
slot(x, "node.sizes") <- value
validObject(x)
return(x)
})
#' @rdname has.raw.data
#' @aliases has.raw.data,BNDataset
setMethod("has.raw.data",
"BNDataset",
function(x)
{
return(slot(x, "has.raw.data"))
})
#' @rdname has.imputed.data
#' @aliases has.imputed.data,BNDataset
setMethod("has.imputed.data",
"BNDataset",
function(x)
{
return(slot(x, "has.imputed.data"))
})
#' @rdname raw.data
#' @aliases raw.data,BNDataset
setMethod("raw.data",
"BNDataset",
function(x)
{
if (has.raw.data(x))
return (x@raw.data)
stop("The dataset contains no data.")
})
#' @rdname imputed.data
#' @aliases imputed.data,BNDataset
setMethod("imputed.data",
"BNDataset",
function(x)
{
if (has.imputed.data(x))
return (x@imputed.data)
stop("The dataset contains no imputed data. ",
"Please impute data before learning.\nSee > ?impute for help.")
})
#' @name header.file<-
#' @aliases header.file<-,BNDataset-method
#' @docType methods
#' @rdname header.file-set
setReplaceMethod("header.file",
"BNDataset",
function(x, value)
{
slot(x, "header.file") <- value
return(x)
})
#' @name data.file<-
#' @aliases data.file<-,BNDataset-method
#' @docType methods
#' @rdname data.file-set
setReplaceMethod("data.file",
"BNDataset",
function(x, value)
{
slot(x, "data.file") <- value
return(x)
})
#' @name num.variables<-
#' @aliases num.variables<-,BNDataset-method
#' @docType methods
#' @rdname num.variables-set
setReplaceMethod("num.variables",
"BNDataset",
function(x, value)
{
slot(x, "num.variables") <- value
validObject(x)
return(x)
})
#' @name num.items<-
#' @aliases num.items<-,BNDataset-method
#' @docType methods
#' @rdname num.items-set
setReplaceMethod("num.items",
"BNDataset",
function(x, value)
{
slot(x, "num.items") <- value
validObject(x)
return(x)
})
#' @name boots<-
#' @aliases boots<-,BNDataset-method
#' @docType methods
#' @rdname boots-set
setReplaceMethod("boots",
"BNDataset",
function(x, value)
{
slot(x, "boots") <- value
slot(x, "num.boots") <- length(value)
slot(x, "has.boots") <- TRUE
validObject(x)
return(x)
})
#' @name num.boots<-
#' @aliases num.boots<-,BNDataset-method
#' @docType methods
#' @rdname num.boots-set
setReplaceMethod("num.boots",
"BNDataset",
function(x, value)
{
slot(x, "num.boots") <- value
validObject(x)
return(x)
})
#' @name num.time.steps<-
#' @aliases num.time.steps<-,BNDataset-method
#' @docType methods
#' @rdname num.time.steps-set
setReplaceMethod("num.time.steps",
"BNDataset",
function(x, value)
{
slot(x, "num.time.steps") <- value
validObject(x)
return(x)
})
#' @name imp.boots<-
#' @aliases imp.boots<-,BNDataset-method
#' @docType methods
#' @rdname imp.boots-set
setReplaceMethod("imp.boots",
"BNDataset",
function(x, value)
{
slot(x, "imp.boots") <- value
slot(x, "num.boots") <- length(value)
slot(x, "has.imputed.boots") <- TRUE
validObject(x)
return(x)
})
#' @name raw.data<-
#' @aliases raw.data<-,BNDataset-method
#' @docType methods
#' @rdname raw.data-set
setReplaceMethod("raw.data",
"BNDataset",
function(x, value)
{
slot(x, "raw.data") <- value
slot(x, "has.raw.data") <- TRUE
num.items(x) <- nrow(value)
validObject(x)
return(x)
})
#' @name imputed.data<-
#' @aliases imputed.data<-,BNDataset-method
#' @docType methods
#' @rdname imputed.data-set
setReplaceMethod("imputed.data",
"BNDataset",
function(x, value)
{
slot(x, "imputed.data") <- value
slot(x, "has.imputed.data") <- TRUE
num.items(x) <- nrow(value)
validObject(x)
return(x)
})
#' @rdname complete
#' @aliases complete,BNDataset
setMethod("complete",
"BNDataset",
function(x, complete.vars=seq_len(num.variables(x)))
{
y <- x
rd <- raw.data(y)
raw.data(y) <- rd[complete.cases(rd[,complete.vars]),]
num.items(y) <- nrow(raw.data(y))
slot(y, "imputed.data") <- matrix(c(0))
slot(y, "has.imputed.data") <- FALSE
slot(y, "boots") <- list(NULL)
slot(y, "has.boots") <- FALSE
slot(y, "imp.boots") <- list(NULL)
slot(y, "has.imputed.boots") <- FALSE
slot(y, "num.boots") <- 0
validObject(y)
return(y)
})
# redefinition of print() for BNDataset objects
# ' print a \code{\link{BNDataset}} to \code{stdout}.
#'
#' @method print BNDataset
#' @name print
#'
# ' @param x a \code{\link{BNDataset}}.
#' @param show.raw.data if \code{x} is a \code{\link{BNDataset}}, print also raw dataset, if available.
#' @param show.imputed.data if \code{x} is a \code{\link{BNDataset}}, print also imputed dataset, if available.
# ' @param ... potential other arguments.
#'
#' @rdname print
#' @aliases print,BNDataset print.BNDataset,BNDataset
#' @export
#setMethod("print.BNDataset",
# "BNDataset",
print.BNDataset <- function(x, show.raw.data = FALSE, show.imputed.data = FALSE, ...)
{
str <- "\nDataset: \n"
#str <- paste(str, name(x), sep = '')
#str <- paste(str, "\n", sep = '')
cat(str)
str <- "\nnum.variables "
str <- paste(str, num.variables(x), sep = '')
str <- paste(str, "\n", sep = '')
cat(str)
str <- "\nvariables\n"
cat(str)
cat(variables(x))
str <- "\ndiscreteness\n"
cat(str)
cat(discreteness(x))
str <- "\nnode.sizes\n"
cat(str)
cat(node.sizes(x))
str <- "\nnum.items\n"
cat(str)
cat(num.items(x))
str <- "\nimputation\n"
cat(str)
cat(has.imputed.data(x))
str <- "\nhas.boots\n"
cat(str)
cat(has.boots(x))
str <- "\nhas.imputed.boots\n"
cat(str)
cat(has.imputed.boots(x))
str <- "\nnum.boots\n"
cat(str)
cat(num.boots(x))
if (num.time.steps(x) > 1) {
str <- "\ntime steps\n"
cat(str)
cat(num.time.steps(x))
}
if (show.raw.data == TRUE && has.raw.data(x))
{
cat("\nRaw data:\n")
print(raw.data(x))
}
if (show.imputed.data == TRUE && has.imputed.data(x))
{
cat("\nImputed data:\n")
print(imputed.data(x))
}
cat("\n")
}#)
#' @rdname impute
#' @aliases impute,BNDataset
setMethod("impute",
"BNDataset",
function(object, k.impute = 10)
{
# assumes raw data is ok
SGS.start.log("performing imputation ...")
object@imputed.data <- knn.impute(object@raw.data, k.impute,
setdiff(1:length(object@node.sizes), c()))
object@has.imputed.data <- TRUE
SGS.end.log("imputation finished.")
return(object)
})
#' @rdname bootstrap
#' @aliases bootstrap,BNDataset
setMethod("bootstrap",
"BNDataset",
function(object, num.boots = 100, seed = 0, imputation = FALSE, k.impute = 10)
{
if (imputation)
SGS.start.log("Generating bootstrap samples with imputation ...")
else
SGS.start.log("Generating bootstrap samples ...")
# assumes raw data is ok
object@has.boots <- TRUE
object@num.boots <- num.boots
set.seed(seed)
if (num.boots >= 1)
{
boot.sample <- matrix(sample.int(object@num.items,
size = num.boots * object@num.items,
replace=TRUE),
object@num.items, num.boots)
if (imputation)
object@has.imputed.boots <- TRUE
for (i in 1:num.boots)
{
object@boots[[i]] <- object@raw.data[boot.sample[,i],]
if (imputation)
object@imp.boots[[i]] <- knn.impute(object@boots[[i]],
k.impute,
setdiff(1:length(object@node.sizes),c()) )
}
}
SGS.end.log("Bootstrap samples generated.")
return(object)
})
#' @rdname boot
#' @aliases boot,BNDataset
setMethod("boot",
c("BNDataset", "numeric"),
function(dataset, index, use.imputed.data = FALSE)
{
if (!use.imputed.data && !dataset@has.boots)
stop('No bootstrap samples available for dataset.')
if (use.imputed.data && !dataset@has.imputed.boots)
stop('No imputed bootstrap samples available for dataset. ',
"Please impute data before learning.\nSee > ?impute for help.")
if (index <= 0 || index > dataset@num.boots)
stop('Sample index out of range for dataset.\n')
if (use.imputed.data)
return(dataset@imp.boots[[index]])
return(dataset@boots[[index]])
})