-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodelsR6.R
2729 lines (2191 loc) · 91.3 KB
/
modelsR6.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
library(R6)
library(foreach)
library(ggplot2)
FitResult <- R6Class(
"FitResult",
lock_objects = FALSE,
private = list(
fitHist = NULL,
beginStep = NULL
),
public = list(
initialize = function(paramNames) {
cols <- c("begin", "end", "duration", paramNames)
private$fitHist <- matrix(nrow = 0, ncol = length(cols))
colnames(private$fitHist) <- cols
private$beginStep <- NA
self$begin <- NA
self$end <- NA
self$duration <- NA
self$optResult <- NA
},
getParamNames = function() {
colnames(private$fitHist)
},
start = function() {
self$begin <- as.numeric(Sys.time())
invisible(self)
},
finish = function() {
self$end <- as.numeric(Sys.time())
self$duration <- self$end - self$begin
invisible(self)
},
setOptResult = function(optResult) {
self$optResult <- optResult
invisible(self)
},
startStep = function(verbose = FALSE) {
now <- Sys.time()
if (verbose) {
cat(paste0("Starting step at ", now, "\n"))
}
private$beginStep <- as.numeric(now)
invisible(self)
},
stopStep = function(resultParams, verbose = FALSE) {
end <- Sys.time()
if (verbose) {
cat(paste0("Stopping step at ", end, ", with resultParams of: ", paste0(round(resultParams, 5), collapse = ", "), "\n"))
}
duration <- end - private$beginStep
private$fitHist <- rbind(private$fitHist, c(private$beginStep, end, duration, resultParams))
invisible(self)
},
lastStep = function() {
utils::tail(private$fitHist)
},
getFitHist = function() {
private$fitHist
},
getBest = function(paramName, lowest = TRUE) {
func <- if (lowest) which.min else which.max
fh <- self$getFitHist()
stopifnot(is.character(paramName) && paramName %in% colnames(fh))
fh[func(fh[, paramName]),, drop = FALSE]
},
clearFitHist = function() {
nr <- nrow(private$fitHist)
if (nr > 0) {
private$fitHist <- private$fitHist[-(1:nr), ]
}
invisible(self)
},
plot_loss = function() {
self$plot(paramNames = "loss", logY = FALSE)
},
plot_logloss = function() {
self$plot(paramNames = "loss", logY = TRUE)
},
plot = function(paramNames = colnames(self$getFitHist()), logY = TRUE) {
stopifnot(is.character(paramNames) && length(paramNames) > 0 && all(paramNames %in% colnames(self$getFitHist())))
fh <- self$getFitHist()
df <- as.data.frame(fh[, paramNames])
colnames(df) <- paramNames
df$x <- seq_len(length.out = nrow(df))
g <- ggplot2::ggplot(data = df)
for (pn in paramNames) {
g <- g + ggplot2::geom_line(mapping = ggplot2::aes_string(
x = "x", y = pn, color = factor(x = pn, levels = paramNames)))
}
if (logY) {
g <- g + ggplot2::scale_y_log10()
}
g + ggplot2::labs(x = "Step", y = "Value", color = "Params", subtitle = "FitResult")
},
#' Imports a result from optimParallel:
fromOptimParallel = function(optR) {
self$initialize(paramNames = c(names(optR$par), "loss"))
for (idx in seq_len(nrow(optR$loginfo))) {
self$startStep()
self$stopStep(resultParams = optR$loginfo[
idx, c(paste0("par", seq_len(length.out = length(optR$par))), "fn")])
}
invisible(self)
}
)
)
MultilevelModelReferenceCalibrator <- R6Class(
"MultilevelModelReferenceCalibrator",
lock_objects = FALSE,
inherit = LinearInequalityConstraints,
private = list(
scoreAggCallback = NULL,
lastTandemStep = NA
),
public = list(
initialize = function(
mlm, scoreAggCallback = function(sa) sa$aggregateUsing_Honel(),
mlmYInterceptFit = NA
) {
stopifnot(inherits(mlm, "MultilevelModel") && R6::is.R6(mlm))
stopifnot(is.matrix(mlm$boundariesCalibrated) && !any(is.na(mlm$boundariesCalibrated)))
stopifnot(is.function(scoreAggCallback) && length(methods::formalArgs(scoreAggCallback)) == 1)
self$mlm <- mlm
# Let's copy it over. During optimization, we will do our affine
# transformations and then set the data back to the MLM, before
# we call its compute()-method.
self$refData <- mlm$refData[, ]
# Needed later in fit()
private$scoreAggCallback <- scoreAggCallback
stopifnot(length(mlm$refBoundaries) > 0 && all(is.numeric(mlm$refBoundaries) & !is.na(mlm$refBoundaries)))
bounds <- sort(unique(c(0, 1, mlm$refBoundaries)))
# For each variable, we add the current intercept with each boundary
# from left to right, including the 0,1 boundaries.
# Each variable has 'numIntervals' + 1 y-values we can adjust.
theta <- mlm$boundaries[1, ]
for (t in levels(mlm$refData$t)) {
tFunc <- (function() {
d <- mlm$refData[mlm$refData$t == t, ]
f <- stats::approxfun(x = d$x, y = d$y, ties = "ordered")
return(function(x) {
if (x < min(d$x)) d$y[1]
if (x > max(d$x)) utils::tail(d$y, 1)
f(x)
})
})()
for (bIdx in 1:length(bounds)) {
newC <- c()
newC[paste(t, bIdx, sep = "_")] <- tFunc(bounds[bIdx])
theta <- c(theta, newC)
}
}
super$initialize(theta = theta)
self$refTheta <- theta
colnames(self$linIneqs) <- c(names(theta), "CI")
self$setMLMforRef_YInterceptFit(mlm = mlmYInterceptFit)
private$computeResult <- NA
# Can be written to from outside. These files will be
# sourced in the parallel foreach loop.
self$sourceFiles <- c()
},
setMLMforRef_YInterceptFit = function(mlm = NA) {
stopifnot((inherits(mlm, "MultilevelModel") && R6::is.R6(mlm)) || is.na(mlm))
self$mlmYIntercepts <- mlm
invisible(self)
},
resetTheta = function() {
self$setTheta(theta = self$refTheta)
},
#' Transfers over the MLM's boundary constraints into our matrix.
copyBoundaryConstraints = function() {
for (rIdx in rownames(self$mlm$linIneqs)) {
newC <- rep(0, ncol(self$linIneqs))
newC[1:self$mlm$numBoundaries] <- self$mlm$linIneqs[rIdx, 1:self$mlm$numBoundaries]
newC[length(newC)] <- self$mlm$linIneqs[rIdx, self$mlm$numBoundaries + 1]
self$setLinIneqConstraint(name = rIdx, ineqs = newC)
}
invisible(self)
},
addDefaultVariableYConstraints = function() {
idxOffset <- length(self$mlm$getTheta())
bounds <- sort(unique(c(0, 1, self$mlm$refBoundaries)))
lvls <- levels(self$mlm$refData$t)
for (t in lvls) {
lvlIdx <- which(t == lvls)
for (bIdx in 1:length(bounds)) {
newC <- rep(0, ncol(self$linIneqs))
newC[idxOffset + (lvlIdx - 1) * length(bounds) + bIdx] <- 1
newC[length(newC)] <- 0
# >= 0:
self$setLinIneqConstraint(name = paste0(t, "_", bIdx, "_geq_v"), ineqs = newC)
# .. and <= 1:
newC <- -1 * newC
newC[length(newC)] <- -1
self$setLinIneqConstraint(name = paste0("-", t, "_", bIdx, "_geq_v"), ineqs = newC)
}
}
invisible(self)
},
computeRefData = function(bbFlatIfBelow = 1e-3, onlyForVar = NA) {
hasOnlyVar <- !missing(onlyForVar) || !is.na(onlyForVar)
stopifnot(!hasOnlyVar || onlyForVar %in% levels(self$refData$t))
# Here, we need the calibrated boundaries -- we use them as the reference!
# I.e., these are superior to the user-set reference boundaries!
stopifnot(is.matrix(self$mlm$boundariesCalibrated) && !any(is.na(self$mlm$boundariesCalibrated)))
# Current values for all boundaries and y-intersections (in that order).
theta <- self$getTheta()
# Needed to re-slice the reference data.
refBounds <- sort(unique(c(0, 1, self$mlm$boundariesCalibrated[1, ])))
# The current bounds that are used to transform the reference data.
newBounds <- sort(unique(c(0, 1, theta[1:self$mlm$numBoundaries])))
refData <- NULL
varNames <- if (hasOnlyVar) onlyForVar else levels(self$mlm$refData$t)
for (t in varNames) {
for (bIdx in 1:self$mlm$numIntervals) {
xyData <- self$refData[
self$refData$t == t & self$refData$interval == self$mlm$intervalNames[bIdx], ]
xyData <- xyData[order(xyData$x), ]
xRange_ref <- range(xyData$x)
xExtent_ref <- xRange_ref[2] - xRange_ref[1]
bStart <- newBounds[bIdx]
bEnd <- newBounds[bIdx + 1]
xRange <- c(bStart, bEnd)
xExtent <- bEnd - bStart
xData <- xyData$x - xRange_ref[1]
if (xExtent_ref > 0) {
xData <- xData / xExtent_ref
}
if (xExtent > 0) {
xData <- xData * xExtent
}
# For re-fitting Y, we do not need X.
yExtent_ref <- range(xyData$y)
yStart_ref <- xyData$y[1]
yEnd_ref <- xyData$y[length(xyData$y)]
yDiff_ref <- yEnd_ref - yStart_ref
yStart_new <- theta[paste0(t, "_", bIdx)]
yEnd_new <- theta[paste0(t, "_", bIdx + 1)]
yDiff_new <- yEnd_new - yStart_new
yData <- xyData$y
# If the reference bounding box is flat, the current
# sub-pattern should be regarded as a flat line. Otherwise,
# we may amplify small deviations of an otherwise flat line
# way beyond its proportions. So if we encounter a flat
# line, we change its slope rather doing a linear affine
# transformation with the sub-pattern.
if (abs(max(yData) - min(yData)) < bbFlatIfBelow) {
# Note that if yDiff_new is flat, we only squeeze
# the pattern, and the else-branch will work.
yDiffBefore <- yData[length(yData)] - yData[1]
yDiffAfter <- yEnd_new - yStart_new
yDiff <- yDiffBefore - yDiffAfter
yData <- yData - sapply(xData, function(x) {
x / xExtent * yDiff
})
} else {
yScale <- yDiff_new / yDiff_ref
yData <- yData * yScale
}
yData <- yData - yData[1] + yStart_new
# Do this ALWAYS last!
xData <- xData + xRange[1]
refData <- rbind(refData, data.frame(
x = xData,
y = yData,
t = t,
interval = self$mlm$intervalNames[bIdx],
stringsAsFactors = FALSE
))
}
}
refData$interval <- factor(
x = refData$interval,
levels = levels(self$refData$interval),
ordered = is.ordered(self$refData$interval))
refData$t <- factor(
x = refData$t,
levels = levels(self$refData$t),
ordered = is.ordered(self$refData$t))
refData
},
#' Using the current theta, we derive the reference data, which
#' is then given to the MLM and its compute() is called.
compute = function(verbose = FALSE, forceSeq = NULL) {
stopifnot(is.matrix(self$mlm$boundariesCalibrated) && !any(is.na(self$mlm$boundariesCalibrated)))
# This is not that important, because the MLM does not slice the reference
# data according to these, but rather by the 't'-column in it.
self$mlm$refBoundaries <- self$theta[1:self$mlm$numBoundaries]
refData <- self$computeRefData()
self$mlm$setAllBoundaries(values = self$theta[1:self$mlm$numBoundaries])
self$mlm$refData <- refData
# .. then compute using those!
cArgs <- list()
if (!missing(verbose)) {
cArgs[["verbose"]] <- verbose
}
if (!missing(forceSeq)) {
cArgs[["forceSeq"]] <- forceSeq
}
sa <- do.call(what = self$mlm$compute, args = cArgs)
private$computeResult <- sa
sa
},
#' Alters the underlying MLMs reference data and boundaries to
#' produce a best fit between the model and all of its data.
#' This method is extremely expensive and should probably never
#' be used directly, but rather called from an external optimization
#' process that sets theta and then calls compute in a highly
#' parallel fashion. We keep this method as a reference, but it is
#' mostly here for academic purposes.
fit = function(verbose = FALSE, reltol = sqrt(.Machine$double.eps), method = c("Nelder-Mead", "SANN")[1], callback = NULL) {
stopifnot(self$validateLinIneqConstraints())
# callback must take MLMRC, MLM, fitHist, score_raw
stopifnot(missing(callback) ||
(is.function(callback) && 4 == length(methods::formalArgs(callback))))
histCols <- c("begin", "end", "duration", "score_raw", "score_log", names(self$theta))
fitHist <- matrix(nrow = 0, ncol = length(histCols))
colnames(fitHist) <- histCols
scoreAgg_best <- NA
score_raw_best <- 0
beginOpt <- as.numeric(Sys.time())
optR <- stats::constrOptim(
control = list(
reltol = reltol,
maxit = 2e4
),
method = method,
ui = self$getUi(),
theta = self$getTheta(),
ci = self$getCi(),
grad = NULL,
f = function(x) {
names(x) <- names(self$theta)
if (verbose) {
cat(paste0("Params (", length(x), "): ", paste0(sapply(x, function(p) {
format(p, nsmall = 3, digits = 3)
}), collapse = ", ")))
}
# Set all parameters!
self$setTheta(theta = x)
begin <- as.numeric(Sys.time())
scoreAgg <- self$compute()
score_raw <- private$scoreAggCallback(scoreAgg)
score_log <- -log(score_raw)
finish <- as.numeric(Sys.time())
fitHist <<- rbind(fitHist, c(
begin, finish, finish - begin, score_raw, score_log, x
))
if (verbose) {
cat(paste0(" -- Value: ", format(score_log, digits = 10, nsmall = 5),
" -- Duration: ", format(finish - begin, digits = 2, nsmall = 2), "s\n"))
}
if (is.function(callback)) {
callback(self, self$mlm, fitHist, score_raw)
}
# Let's update the compute-result: we set it to the current best
if (!R6::is.R6(scoreAgg_best) || (score_raw > score_raw_best)) {
scoreAgg_best <- scoreAgg
score_raw_best <- score_raw
}
score_log
}
)
finishOpt <- as.numeric(Sys.time())
# Set compute-result to best fit and also update boundaries:
private$computeResult <- scoreAgg_best
self$setTheta(theta = optR$par)
list(
begin = beginOpt,
end = finishOpt,
duration = finishOpt - beginOpt,
fitHist = fitHist,
optResult = optR
)
},
#' Part of the fit-tandom approach, in which we either fit the
#' reference's boundaries, or the Y-intersections of each variable
#' with its boundaries.
#'
#' In this method, we fit the reference's boundaries, and treat
#' all Y-intersections as constant.
fit_refBoundaries = function(verbose = FALSE, method = c("Nelder-Mead", "BFGS", "SANN")[1], forceSeq = NULL) {
nb <- self$mlm$numBoundaries
ui <- self$getUi()[, 1:nb]
uiInUse <- rownames(ui)[apply(ui, 1, function(r) sum(r != 0) > 0)]
ui <- ui[uiInUse, ]
ci <- self$getCi()[uiInUse]
theta <- self$getTheta()[1:nb]
theta[theta == 0] <- .Machine$double.eps
cArgs <- list(verbose = FALSE)
if (!missing(forceSeq)) {
cArgs[["forceSeq"]] <- forceSeq
}
fr <- FitResult$new(paramNames = c("is_grad", "score_raw", "score_log", colnames(ui)))
fr$start()
objF <- function(x, isGrad = FALSE) {
if (verbose && !isGrad) {
cat(paste0("Boundaries (", length(x), "): ", paste0(sapply(x, function(p) {
format(p, nsmall = 3, digits = 3)
}), collapse = ", ")))
}
fr$startStep()
# Only sets the boundaries, the other params are held constant!
self$theta[1:nb] <- x
scoreAgg <- do.call(what = self$compute, args = cArgs)
score_raw <- private$scoreAggCallback(scoreAgg)
score_log <- -log(score_raw)
fr$stopStep(resultParams = c(if (isGrad) 1 else 0, score_raw, score_log, x))
lastStep <- fr$lastStep()
if (verbose) {
cat(paste0(" -- Value: ", format(score_log, digits = 10, nsmall = 5),
" -- Duration: ", format(lastStep[, "duration"], digits = 2, nsmall = 2), "s\n"))
}
score_log
}
optRes <- stats::constrOptim(
theta = theta, ui = ui, ci = ci,
control = list(maxit = 5000), # TODO
f = objF, method = method, grad = function(x) {
numDeriv::grad(func = objF, x = x, isGrad = TRUE)
})
fr$finish()$setOptResult(optResult = optRes)
},
#' Part of the fit-tandom approach, in which we either fit the
#' reference's boundaries, or the Y-intersections of each variable
#' with its boundaries.
#'
#' In this method, we fit the Y-intersections with the boundaries,
#' and treat the boundaries as constant.
fit_refYIntercepts = function(
varNames = levels(self$refData$t),
verbose = FALSE,
method = c("Nelder-Mead", "BFGS", "SANN")[1],
nestedParallel = 0,
forceSeq = NULL
) {
stopifnot(all(varNames %in% levels(self$refData$t)))
cArgs <- list(verbose = verbose, method = method)
if (!missing(forceSeq)) {
cArgs[["forceSeq"]] <- forceSeq
}
foreachOp <- if (missing(forceSeq) || forceSeq != TRUE) foreach::`%dopar%` else foreach::`%do%`
varFrs <- foreachOp(foreach::foreach(
varName = varNames, # we can optimize each variable independently,
.inorder = FALSE, # .. in any order
.verbose = verbose,
.export = c("self"),
.packages = c("dtw", "Metrics", "numDeriv",
"philentropy", "pracma", "rootSolve",
"SimilarityMeasures", "stats", "utils")
), {
for (file in self$sourceFiles) {
fileAbs <- normalizePath(file, mustWork = FALSE)
if (!file.exists(fileAbs) || file.access(fileAbs, mode = 4) != 0) {
stop(paste0("Cannot source file: ", file, " -- cwd: ", getwd()))
}
source(file = file)
}
res <- list()
if (nestedParallel > 0) {
res[[varName]] <- doWithParallelCluster(expr = {
for (f in self$sourceFiles) {
source(file = f, echo = FALSE)
}
do.call(self$fit_variable, args = append(cArgs, list(name = varName)))
}, numCores = nestedParallel)
} else {
res[[varName]] <- do.call(
self$fit_variable, args = append(cArgs, list(name = varName)))
}
res
})
# Now we have a list of FitResult objects, one for each variable. However,
# the list is nested and the indexes currently are numeric, so let's remove
# one level in this list, so that the resulting list's keys are the variables'
# names and the value is the FitResult.
unlist(varFrs)
},
fit_variable = function(name, ignoreOtherVars = TRUE, ignoreMetaModels = TRUE, verbose = FALSE, method = c("BFGS", "Nelder-Mead", "SANN")[1], forceSeq = NULL) {
refVars <- levels(self$refData$t)
stopifnot(name %in% refVars)
cArgs <- list()
if (!missing(forceSeq)) {
cArgs[["forceSeq"]] <- forceSeq
}
# When this function is entered, we assume that all other thetas
# have been set to their designated value, which will be held
# constant over time.
mlmrc <- self$clone(deep = TRUE)
# It could be that we have an extra configured MLM just for this
# task of fitting the Y-Intercepts. If this is the case, then we
# will copy over all of its sub-models and replace the one of the
# default MLM.
mlmV <- mlmrc$mlm
if (R6::is.R6(mlmrc$mlmYIntercepts)) {
if (verbose) {
cat("Using extra MLM for Y-intercepts.\n")
}
# First, let's remove all sub-models:
for (smName in mlmV$getSubModelsInUse(
includeOrdinarySubModels = TRUE, includeMetaSubModels = TRUE)) {
mlmV$removeSubModel(model = mlmV$getSubModel(name = smName))
}
# .. then, add those from the extra model:
for (smName in mlmrc$mlmYIntercepts$getSubModelsInUse(
includeOrdinarySubModels = TRUE, includeMetaSubModels = TRUE)) {
mlmV$setSubModel(model = mlmrc$mlmYIntercepts$getSubModel(name = smName))
}
}
# Let's conditionally remove unwanted sub-models:
if (ignoreOtherVars || ignoreMetaModels) {
mlmVModels <- mlmV$getSubModelsInUse(
includeOrdinarySubModels = ignoreOtherVars, includeMetaSubModels = ignoreMetaModels)
rmModels <- mlmVModels[!grepl(pattern = paste0(name, "_"), x = mlmVModels)]
for (rmModel in rmModels) {
mlmV$removeSubModel(mlmV$getSubModel(name = rmModel))
}
}
# Now that we have our stripped-down model, let's also strip
# down the constraints to those we actually need. The names of
# the constraints follow the scheme VAR_IDX.
numBounds <- mlmV$numBoundaries + 2 # 0, .., 1
uiVars <- paste0(paste0(name, "_"), 1:numBounds)
ui <- self$getUi()[, uiVars]
uiInUse <- rownames(ui)[apply(ui, 1, function(r) sum(r != 0) > 0)]
ui <- ui[uiInUse, ]
ci <- self$getCi()[uiInUse]
thetaVars <- self$getTheta()[uiVars]
# Strictly zero is not allowed.
thetaVars[thetaVars == 0] <- .Machine$double.eps
fr <- FitResult$new(paramNames = c("is_grad", "score_raw", "score_log", colnames(ui)))
fr$start()
objF <- function(x, isGrad = FALSE) {
if (verbose && !isGrad) {
cat(paste0("Var (", name, "): ", paste0(sapply(x, function(p) {
format(p, nsmall = 3, digits = 3)
}), collapse = ", ")))
}
fr$startStep()
theta <- mlmrc$getTheta()
theta[uiVars] <- x
mlmrc$setTheta(theta = theta)
scoreAgg <- do.call(mlmrc$compute, args = cArgs)
score_raw <- private$scoreAggCallback(scoreAgg)
score_log <- -log(score_raw)
fr$stopStep(resultParams = c(if (isGrad) 1 else 0, score_raw, score_log, x))
lastStep <- fr$lastStep()
if (verbose && !isGrad) {
cat(paste0(" -- Value: ", format(score_log, digits = 10, nsmall = 5),
" -- Duration: ", format(lastStep[, "duration"], digits = 2, nsmall = 2), "s\n"))
}
score_log
}
optRes <- stats::constrOptim(
theta = thetaVars, ui = ui, ci = ci, method = method,
control = list(maxit = 5000), # TODO
f = objF, grad = function(x) {
numDeriv::grad(func = objF, x = x)
})
fr$finish()$setOptResult(optResult = optRes)
},
fit_tandem = function(updateThetaAfter = TRUE, nestedParallel = 0, methodRefBounds = c("Nelder-Mead", "BFGS")[1], methodRefYIntercepts = c("BFGS", "Nelder-Mead")[1]) {
res <- NULL
if (is.na(private$lastTandemStep) || private$lastTandemStep == "y") {
res <- self$fit_refBoundaries(method = methodRefBounds)
private$lastTandemStep <- "b" # so the next step is "y"
if (updateThetaAfter) {
theta <- self$getTheta()
nb <- self$mlm$numBoundaries
# Named vector ahead:
varTheta <- res$optResult$par
theta[names(varTheta)] <- varTheta
self$setTheta(theta = theta)
}
} else {
res <- self$fit_refYIntercepts(
nestedParallel = nestedParallel, method = methodRefYIntercepts)
private$lastTandemStep <- "y" # so the next step is "b"
if (updateThetaAfter) {
# res is a list where the keys are the variables' names,
# and each is a FitResult. We need to update theta with
# the results of the optimization of each variable.
theta <- self$getTheta()
nb <- self$mlm$numBoundaries + 2 # 0, .., 1
for (varName in names(res)) {
# This is a named vector.
varTheta <- res[[varName]]$optResult$par
theta[names(varTheta)] <- varTheta
}
self$setTheta(theta = theta)
}
}
res
},
fit_tandem_iter = function(verbose = TRUE, nestedParallel = 0, maxSteps = 10, beginStep = c("b", "y")[1], stopIfImproveBelow = NA_real_, callback = NA, methodRefBounds = c("Nelder-Mead", "BFGS")[1], methodRefYIntercepts = c("BFGS", "Nelder-Mead")[1]) {
stopifnot(beginStep %in% c("b", "y"))
# If we want to begin in b, the last step would have been y, and vice versa
private$lastTandemStep <- if (beginStep == "b") "y" else "b"
fr <- FitResult$new(
paramNames = c("AIC", "AICc", "BIC", "BICc", "score_raw", "score_log", names(self$getTheta())))
fr$start()
# Store the initial score:
fr$startStep(verbose = verbose)
tempSa <- self$compute()
score <- private$scoreAggCallback(tempSa)
score_log <- -log(score)
fr$stopStep(resultParams = c(score, score_log, self$getTheta()), verbose = verbose)
if (verbose) {
cat(paste0("Computed initial score of -- ", score, ", log-score of -- ", score_log, ", -- using parameters: ", paste0(round(self$getTheta(), 5), collapse = ", "), "\n"))
}
lastScore <- score_log
bestTheta <- self$getTheta()
bestCompute <- tempSa
for (i in 1:maxSteps) {
if (verbose) {
cat(paste0("Starting next type of step: ", if (private$lastTandemStep == "b") "Y-Intercepts" else "Boundaries", "\n"))
}
fr$startStep(verbose = verbose)
frTandem <- self$fit_tandem(
nestedParallel = nestedParallel,
updateThetaAfter = TRUE,
methodRefBounds = methodRefBounds,
methodRefYIntercepts = methodRefYIntercepts)
# Note the last step was setting the theta, but the computation
# is missing. The computation is necessary to actually update
# the reference data.
tempSa <- self$compute(verbose = verbose)
score <- private$scoreAggCallback(tempSa)
score_log <- -log(score)
fr$stopStep(
resultParams = c(
stats::AIC(self), # classic AIC
self$AICc(countAllObs = FALSE),
stats::BIC(self),
self$BICc(),
score, score_log, self$getTheta()), verbose = verbose)
if (is.function(callback)) {
callback(fr)
}
# Also check if we should stop:
if (is.numeric(stopIfImproveBelow) && stopIfImproveBelow > 0 &&
((lastScore - score_log) < stopIfImproveBelow)) {
break
}
if (score_log < lastScore) {
bestTheta <- self$getTheta()
bestCompute <- tempSa
}
lastScore <- score_log
}
# Set compute-result to best fit and also update all params:
self$setTheta(theta = bestTheta)
private$computeResult <- bestCompute
fr$finish()
},
logLik = function(countAllObs = FALSE) {
stopifnot(R6::is.R6(private$computeResult))
ll <- log(private$scoreAggCallback(private$computeResult))
attr(ll, "df") <- self$npar()
attr(ll, "nobs") <- self$nobs(countAllObs = countAllObs)
ll
},
npar = function() {
self$numParams
},
nobs = function(countAllObs = FALSE) {
self$mlm$nobs(countAllObs = countAllObs)
},
AICc = function(countAllObs = FALSE) {
aic <- stats::AIC(self)
k <- self$npar()
n <- self$nobs(countAllObs = countAllObs)
denom <- n - k - 1
if (denom == 0) {
denom <- .Machine$double.eps
}
aic + ((2 * k^2 + 2 * k) / denom)
},
BICc = function() {
stats::AIC(self, k = log(self$nobs(countAllObs = TRUE)))
}
)
)
#' S3-method for the logLik()-method of an MLM.
logLik.MultilevelModelReferenceCalibrator <- function(mlmrc, ...) mlmrc$logLik(...)
#' S3-method for the nobs()-method of an MLM.
nobs.MultilevelModelReferenceCalibrator <- function(mlmrc, ...) mlmrc$nobs(...)
LinearInequalityConstraints <- R6Class(
"LinearInequalityConstraints",
lock_objects = FALSE,
public = list(
initialize = function(theta) {
stopifnot(is.numeric(theta) && length(theta) > 0)
self$numParams <- length(theta)
self$linIneqs <- matrix(nrow = 0, ncol = self$numParams + 1) # +1 for theta-column
self$theta <- theta
},
hasLinIneqConstraint = function(name) {
stopifnot(is.character(name) && nchar(name) > 0)
name %in% rownames(self$linIneqs)
},
removeLinIneqConstraint = function(name) {
stopifnot(self$hasLinIneqConstraint(name))
rIdx <- which(rownames(self$linIneqs) == name)
self$linIneqs <- self$linIneqs[-rIdx, ]
invisible(self)
},
setLinIneqConstraint = function(name, ineqs) {
stopifnot(is.vector(ineqs) && length(ineqs) == self$numParams + 1)
stopifnot(all(is.numeric(ineqs)) && !any(is.na(ineqs)))
# Set or replace semantics:
if (!self$hasLinIneqConstraint(name)) {
newRow <- matrix(ncol = self$numParams + 1, nrow = 1)
rownames(newRow) <- name
self$linIneqs <- rbind(self$linIneqs, newRow)
}
self$linIneqs[name, ] <- ineqs
invisible(self)
},
flushLinIneqConstraints = function() {
self$linIneqs <- self$linIneqs[-1:-nrow(self$linIneqs), ]
invisible(self)
},
setTheta = function(theta) {
stopifnot(is.numeric(theta) && length(theta) == length(self$theta))
names(theta) <- names(self$theta)
self$theta <- theta
invisible(self)
},
getTheta = function() {
self$theta
},
getUi = function() {
self$linIneqs[, 1:self$numParams]
},
getCi = function() {
self$linIneqs[, self$numParams + 1]
},
validateLinIneqConstraints = function() {
theta <- self$getTheta()
ui <- self$getUi()
ci <- self$getCi()
res <- ui %*% theta - ci
!any(is.na(res)) && all(res >= 0)
}
)
)
#' The model we use to describe, fit and score arbitrary many time
#' series is a Multilevel model.
#'
#' @source {https://en.wikipedia.org/wiki/Multilevel_model}
MultilevelModel <- R6Class(
"MultilevelModel",
inherit = LinearInequalityConstraints,
lock_objects = FALSE,
private = list(
subModels = NULL,
scoreAggCallback = NULL
),
public = list(
#' @param intervalNames ordered character of intervals, i.e.,
#' the first interval's name is the first interval. If there
#' are m intervals, there must be m-1 boundaries.
initialize = function(
referenceData,
intervalNames = levels(referenceData$interval),
referenceBoundaries = NULL,
boundaryNames = if (missing(referenceBoundaries)) NULL else names(referenceBoundaries),
scoreAggCallback = function(sa) sa$aggregateUsing_Honel()
) {
stopifnot(is.data.frame(referenceData) && nrow(referenceData) > 0)
stopifnot(is.numeric(referenceData$x) && is.numeric(referenceData$y))
stopifnot(is.factor(referenceData$t))
stopifnot(is.factor(referenceData$interval) && length(levels(referenceData$interval)) > 1)
stopifnot(all(is.character(intervalNames) & nchar(intervalNames) > 0))
stopifnot(length(intervalNames) == length(levels(referenceData$interval)))
stopifnot(all(intervalNames %in% levels(referenceData$interval)))
stopifnot(length(intervalNames) > 1)
stopifnot(missing(referenceBoundaries) || (all(
is.numeric(referenceBoundaries) &
referenceBoundaries >= 0 &
referenceBoundaries <= 1)))
stopifnot(missing(boundaryNames) || (length(intervalNames) == 1 + length(boundaryNames)))
stopifnot(is.function(scoreAggCallback) && length(methods::formalArgs(scoreAggCallback)) == 1)
# Order by x ascending
self$refData <- referenceData[order(referenceData$x), ]
self$numVars <- length(levels(referenceData$t))
# For each series, we may have different data.
self$queryData <- list()
self$refBoundaries <- referenceBoundaries
self$intervalNames <- intervalNames
self$numIntervals <- length(intervalNames)
# Now for n intervals, there will be n-1 boundaries.
# We do not initialize them, however.
self$numBoundaries <- length(levels(referenceData$interval)) - 1
self$boundaries <- matrix(nrow = 1, ncol = self$numBoundaries)
colnames(self$boundaries) <- boundaryNames # NULL is OK
if (!missing(referenceBoundaries)) {
self$boundaries[1, ] <- referenceBoundaries
}
# Now that we know the amount of boundaries, we can
# initialize a structure for the linear inequalities:
super$initialize(theta = if (missing(referenceBoundaries)) rep(NA_real_, self$numBoundaries) else referenceBoundaries)
# Next step is to generate slots for the sub-models.
# For each variable in each interval, there may or
# may not be a sub-model. The entire Multilevel Model
# can only be fit if at least one sub-model is present.
# The sub-models must be set using the naming scheme
# "VARIABLE_INTERVAL", with the same names as in the
# reference data.
private$subModels <- list()
for (t in levels(referenceData$t)) {
for (i in levels(referenceData$interval)) {
private$subModels[[paste(t, i, sep = "_")]] <- NA
}
}
# We also allow additional sub-models that do not have
# to capture a tuple of variable and interval. These
# are called meta-models and are computed exactly as
# the regular models.
private$metaSubModels <- list()