/
tvcm-utils.R
2784 lines (2412 loc) · 104 KB
/
tvcm-utils.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
## --------------------------------------------------------- #
## Author: Reto Buergin
## E-Mail: rbuergin@gmx.ch
## Date: 2017-08-21
##
## Description:
## Workhorse functions for the 'tvcm' function.
##
## Overview:
##
## Workhorse functions for partitioning:
## tvcm_complexity: computes the complexity of the model
## tvcm_grow: main function for growing the trees
## tvcm_grow_fit: fits the current model
## tvcm_grow_update: refits the model (with utility function
## 'glm.doNotFit')
## tvcm_getNumSplits get cutpoints of numeric variables
## tvcm_getOrdSplits get cutpoints of ordinal variables
## tvcm_getNomSplits get cutpoints of nominal variables
## tvcm_grow_setsplits: get current splits
## tvcm_setsplits_sctest: update splits after tests
## tvcm_setsplits_splitnode:
## tvcm_setsplits_rselect: randomly select partitions, variables and nodes
## tvcm_grow_sctest: run coefficient constancy tests
## tvcm_grow_exsearch: compute the 'dev' statistics
## tvcm_grow_splitnode: split in variable x.
## tvcm_formula: extract separate formulas for
## model and partitioning from
## input formula.
## tvcm_grow_setcontrol: update the control argument before
## fitting the tree.
## tvcm_grow_setparm: update the 'parm' slot
##
## Utility functions used by various functions:
## tvcm_get_node: extract node vectors and assign the contrasts
## tvcm_get_terms: creates a list which assigns coefficients
## to the corresponding type, partition etc.
## tvcm_get_vcparm: extracts the names of the predictors on
## 'vc' terms
## tvcm_get_estimates: extracts the estimates from a fitted
## 'tvcm' object and creates a list with
## an entry for each different type of
## estimate ('fe', 'vc' or 're')
## tvcm_print_vclabs: creates short labels for 'vc' terms
##
## Functions for pruning:
## tvcm_prune_node: main function for pruning 'partynode'
## objects
## tvcm_prune_maxstep: recursive function for pruning
## tvcm_prune_terminal: prunes branches
## tvcm_grow_splitpath: creates a 'splitpath.tvcm' object
##
## Last modifications:
## 2017-10-16: add argument 'singular.ok' for 'glm.doNotFit', see mail
## of Martin Maechler, 2017-09-30
## 2017-08-21: - rename arguments for 'tvcm_get_terms'.
## - bug fix for 'tvcm_get_estimates' for situations where
## 'fe' terms include factor variables or operators
## 2017-08-19: improve tvcm_formula.
## 2017-08-17: - set model.frame in 'tvcm_get_node' for splitting variables
## - delete model.frame.tvcm calls
## 2017-08-14: simplify function 'tvcm_formula'.
## 2016-01-08: change in 'tvcm_grow_fit' to allow fitting the approximate
## search modell locally. For now only for 'glm' fits!
## 2015-11-31: enable the setting 'mtry <- Inf'
## 2015-10-15: add function 'tvcm_grow_setparm'
## 2015-08-25: replace 'fit' argument in 'tvcm_formula' by 'family'.
## 2015-08-21: - small changes in 'tvcm_grow_fit'.
## - replace 'family' argument in 'tvcm_formula' by 'fit'.
## 2015-02-25: add check for fixed effects model matrix in
## 'tvcm_grow_update'.
## 2015-02-24: - improved 'tvcm_getNumSplits' (bugs for the upper limits)
## 2014-12-10: - added 'drop = FALSE' commands in 'tvcm_exsearch_nomToOrd'
## which produced errors
## - 'tvcm_getNumSplits' yielded sometimes more than
## 'maxnumsplit'
## values. Now a random selection is applied for these cases
## 2014-12-09: implemented accurate search model. Involves changes in
## 'tvcm_formula', 'tvcm_grow_exsearch', 'tvcm_exsearch_dev'
## and 'tvcm_control'.
## 2014-11-11: modified transformation of nominal into ordinal variables
## to accelerate exhaustive search. There is now a function
## 'tvcm_exsearch_nomToOrd'.
## 2014-11-05: parallelized 'estfun.olmm' call in 'tvcm_grow_sctest'
## 2014-10-14: - modify dev-grid structure obtained from
## 'tvcm_grow_exsearch'
## each combination of part/node/var has now a list of three
## elements where the first contains the cuts, the second the
## the loss reduction and the third the difference in
## the number of parameters. Modifications concerned:
## - tvcm_grow_setsplits
## - tvcm_setsplits_sctest
## - tvcm_setsplits_rselect
## - print.splitpath
## - tvcm_setsplits_splitnode allocates for the splitted
## node a list structure (before it was a empty list
## on the node level)
## - small modifications in getSplits function
## - deleted 'tvcm_setsplits_validcats'
## - added 'tvcm_getNumSplits', 'tvcm_getOrdSplits' and
## 'tvcm_getNomSplits'
## 2014-09-22: deleted unnecessary 'subs' object in 'tvcm_grow_exsearch'
## which I didn't remove when removing the 'keepdev'
## option
## 2014-09-17: - delete 'keepdev' argument (also for prune.tvcm)
## - add function 'tvcm_complexity'
## 2014-09-15: changed 'dev' labels to 'dev' etc.
## 2014-09-10: - add 'control' argument for 'tvcm_grow_update'
## to allow the control of variable centering
## - add variable centering in 'tvcm_grow_update'
## (which was not implemented for some curious reasons)
## 2014-09-08: substitute 'rep' function by 'rep.int' or 'rep_len'
## 2014-09-07: - added 'tvcm_get_vcparm' function
## - set default values in 'glm.doNotFit'
## 2014-09-06: modified function names for 'tvcm_fit_model' and
## 'tvcm_refit_model' for consistency reasons. The
## new names are 'tvcm_grow_fit' and 'tvcm_grow_update'
## 2014-09-06: added new function 'tvcm_grow', which was formerly
## in 'tvcm'
## 2014-09-04: added new function 'tvcm_print_vclabs'
## 2014-09-02: modifications on 'tvcm_get_node' to accelerate
## the code
## 2014-08-10: modifications to speed-up the code
## - update formulas of 'tvcm_formula' are now
## always identical
## - if 'doFit = FALSE', the call of 'glm.fit'
## is avoided
## 2014-08-08: correct bug in 'tvcm_get_terms' for cases where
## multiple vc() terms with equal 'by' arguments
## are present
## 2014-08-08: correct bug in 'tvcm_grow_setsplits' regarding
## 'keepdev'
## 2014-08-08: add suppressWarnings in tvcm_grow_fit
## 2014-07-22: the list of splits is now of structure
## partitions-nodes-variables
## 2014-07-22: AIC and BIC are no longer criteria and therefore
## multiple functions were adjusted
## 2014-07-22: modified some function names
## 2014-07-06: implement method to deal with many nominal categories
## 2014-06-30: implement random selection if split is not unique
## 2014-06-23: correct bug for 'start' argument in 'tvcm_grow_exsearch'
## 2014-06-17: modify documentation style
## 2014-06-16: deleted several 'tvcm_prune_XXX' functions
## 2014-06-03: modify 'tvcm_formula' to allow partition-wise
## trees
## 2014-04-27: complete revision and improved documentation
## 2014-04-01: rename 'fluctest' to 'sctest'
## 2013-12-02: remove 'tvcm_grow_setupnode'
## 2013-11-01: modify 'restricted' and 'terms' correctly in
## 'tvcm_modify_modargs'
##
## Bottleneck functions:
## - tvcm_grow_sctest
## - tvcm_grow_setsplits
## - tvcm_grow_exsearch
##
## To do:
## - fitting local models when 'fast = TRUE' for 'olmm'
## objects
## --------------------------------------------------------- #
## --------------------------------------------------------- #
##' Compute the complexity of the model.
##'
##' @param npar the number of coefficients
##' @param dfpar the degree of freedom per parameter
##' @param nsplit the number of splits
##' @param dfsplit the degree of freedom per split
##'
##' @return a scalar giving the complexity of the model
tvcm_complexity <- function(npar, dfpar, nsplit, dfsplit)
return(dfsplit * nsplit + dfpar * npar)
## --------------------------------------------------------- #
##' Growing a 'tvcm' tree.
##'
##' @param object a 'tvcm' object
##' @param subset an integer vector indicating the subset on which
##' the model is to be fitted. Used by 'cvloss.tvcm'. Entries
##' may represent replicates (e.g., for \code{subset = c(1, 1, 2)}
##' the first record is taken twice).
##' @param weights a vector of weights corresponding to the
##' subset entries. Must be of same length as \code{subset}.
##'
##' @return A 'tvcm' object.
##'
##' @details Used in 'cvloss.tvcm'
tvcm_grow <- function(object, subset = NULL, weights = NULL) {
mcall <- object$info$mcall
environment(mcall) <- environment()
formList <- object$info$formula
model <- object$info$model
md <- object$info$data
partData <- object$data
control <- object$info$control
family <- model$family
if (!is.null(subset)) {
md <- md[subset,,drop = FALSE]
partData <- partData[subset,, drop = FALSE]
}
if (!is.null(weights)) {
mcall$weights <- weights
} else {
weights <- weights(model)
}
## get number of partitions
nPart <- length(formList$vc)
## get partitioning variables
partVars <-
lapply(formList$vc, function(x) attr(terms(x$cond), "term.labels"))
varid <- lapply(partVars, function(x) {
as.integer(sapply(x, function(x) which(colnames(partData) == x))) })
## set the root node
nodes <-
replicate(
nPart, partynode(id = 1L, info = list(dims = nobs(model),
depth = 0L)))
names(nodes) <- names(formList$vc)
where <- vector("list", length = nPart)
partid <- seq(1, nPart, length.out = nPart)
spart <- 0 # pseudo value
## allocate 'splits'
splits <- lapply(seq_along(partid), function(pid) {
lapply(1L, function(nid, pid) {
lapply(seq_along(varid[[pid]]), function(x) {
vector("list", 3)
})
}, pid = pid)
})
## allocate 'splitpath'
splitpath <- list()
run <- 1L
step <- 0L
while (run > 0L) {
step <- step + 1L; nstep <- step;
test <- NULL; dev <- NULL;
## get current partitions and add them to the model data
for (pid in seq_along(nodes)) {
where[[pid]] <- factor(fitted_node(nodes[[pid]], partData))
if (nlevels(where[[pid]]) > 1L)
contrasts(where[[pid]]) <-
contr.wsum(where[[pid]], weights)
md[, paste0("Node", LETTERS[pid])] <- where[[pid]]
}
nodeid <- lapply(nodes, function(x) 1:width(x))
if (control$verbose) cat("\n* starting step", step, "...")
## --------------------------------------------------- #
## Step 1: fit the current model
## --------------------------------------------------- #
vcRoot <- sapply(nodeid, length) == 1L
ff <- tvcm_formula(formList, vcRoot, family,
environment(formList$original))
model <- try(tvcm_grow_fit(mcall))
if (inherits(model, "try-error")) stop(model)
control <- tvcm_grow_setcontrol(
control, model, formList, vcRoot, TRUE)
if (control$verbose) {
cat("\n\nVarying-coefficient(s) of current model:\n")
if (length(unlist(control$parm)) > 0L) {
print(data.frame(
Estimate = coef(model)[unique(unlist(control$parm))]),
digits = 2)
} else {
cat("<no varying-coefficients>\n")
}
}
## compute / update splits
splits <- tvcm_grow_setsplits(splits, partid, nodeid, varid, model,
nodes, where, partData, control)
## check if there is at least one admissible split
if (length(unlist(splits)) == 0L | step > control$maxstep |
length(control$parm) == 0L) {
run <- 0L
if (step > control$maxstep) {
stopinfo <- "maximal number of steps reached"
} else if (length(control$parm) == 0L) {
stopinfo <- "no varying coefficients"
} else {
stopinfo <-
"no admissible splits (exceeded tree size parameters)"
}
nstep <- step - 1L
}
## random selection (used by 'fvcm')
if (control$mtry < .Machine$integer.max)
splits <- tvcm_setsplits_rselect(splits, control)
if (run > 0L && control$sctest) {
## --------------------------------------------------- #
## Step 2: variable selection via coefficient constancy tests
## --------------------------------------------------- #
## get raw p-values
test <- try(tvcm_grow_sctest(
model, nodes, where, partid, nodeid, varid,
splits, partData, control), TRUE)
## return error if test failed
if (inherits(test, "try-error")) {
run <- 0L
stopinfo <- test
} else {
testAdj <-
tvcm_sctest_bonf(test,ifelse(control$bonferroni,
"nodewise", "none"))
run <- 1L * (min(c(1.0 + .Machine$double.eps,
unlist(testAdj)),
na.rm = TRUE) <= control$alpha)
}
if (run > 0L) {
## extract the selected partition
testAdjPart <-
tvcm_sctest_bonf(
test, ifelse(control$bonferroni,
"partitionwise","none"))
minpval <- min(unlist(testAdjPart), na.rm = TRUE)
spart <-
which(sapply(testAdjPart,
function(x)
any(sapply(x,identical,minpval))))
if (length(spart) > 1L) spart <- sample(spart, 1L)
## select variable and node
minsubs <- which(sapply(test[[spart]], identical,
min(test[[spart]], na.rm = TRUE)))
if (length(minsubs) > 1L) minsubs <- sample(minsubs, 1L)
svar <- ceiling(minsubs / nrow(test[[spart]]))
snode <- minsubs - (svar - 1L) * nrow(test[[spart]])
## print results
if (control$verbose) {
## tests
cat("\nCoefficient constancy tests (p-value):\n")
for (pid in seq_along(nodes)) {
cat(paste0("\nPartition ", LETTERS[pid], ":\n"))
print(data.frame(format(testAdj[[pid]],
digits = 2L)))
}
## selections
cat("\nPartition:", LETTERS[spart])
cat("\nNode:", levels(where[[spart]])[snode])
cat("\nVariable:",
names(partData)[varid[[spart]][svar]], "\n")
}
## set dev statistic of not to selected nodes to 'Inf'
## to avoid model evaluations
splits <- tvcm_setsplits_sctest(splits, partid, spart,
nodeid, snode, varid, svar)
} else {
stopinfo <-
"p-values of coefficient constancy tests exceed alpha"
}
}
if (run > 0L) {
## ------------------------------------------------- #
## Step 3: search a cutpoint
## ------------------------------------------------- #
## compute the dev of all candidate splits and extract
## the best split
dev <- try(tvcm_grow_exsearch(splits, partid, nodeid, varid,
model, nodes, where, partData,
control, mcall, formList, step),
silent = TRUE)
## handling stops
if (inherits(dev, "try-error")) {
run <- 0L
stopinfo <- dev
nstep <- step - 1L
} else {
splits <- dev$grid
spart <- dev$partid
if (is.null(dev$cut)) {
run <- 0L
stopinfo <- "found no admissible split"
nstep <- step - 1L
}
if (run > 0L) {
if (dev$pendev < control$mindev) {
run <- 0
stopinfo <- paste("no split with",
if (control$cp > 0) "penalized",
"loss reduction > mindev")
nstep <- nstep - 1L
}
}
}
}
## incorporate the split into 'nodes'
if (run > 0L)
nodes <- tvcm_grow_splitnode(nodes, where, dev, partData,
step, weights)
if (run > 0L)
splits <- tvcm_setsplits_splitnode(
splits, dev$partid, dev$nodeid, nodeid)
## update 'splitpath' to make the splitting process traceable
if (run >= 0L)
splitpath[[step]] <-
list(step = step,
dev = control$lossfun(model),
npar = extractAIC(model)[1L],
nsplit = step - 1L)
if (!inherits(test, "try-error"))
splitpath[[step]]$sctest <- test
if (!inherits(dev, "try-error") && run > 0L)
splitpath[[step]] <- append(splitpath[[step]], dev)
## print the split
if (control$verbose) {
if (run > 0L) {
if (!control$sctest) {
cat("\n\nPartition:", LETTERS[dev$partid])
cat("\nNode:", levels(where[[dev$partid]])[dev$nodeid])
cat("\nVariable:", names(partData)[dev$varid])
} else {
cat("\n")
}
cat("\nCutpoint:\n")
print(as.data.frame(matrix(
dev$cut, 1L,
dimnames = list(dev$cutid,
names(dev$cut)))))
cat("Model comparison:\n")
print(data.frame(
cbind("loss" = c(
round(control$lossfun(model), 2),
round(control$lossfun(model) - dev$dev, 2L)),
## if 'cp == 0'
"dev" = if (control$cp == 0)
c("", round(dev$dev, 2L)),
## if 'cp > 0'
"penalized dev" =
if (control$cp > 0)
c("", round(dev$pendev, 2L)),
deparse.level = 2),
row.names = paste("step", step + c(-1, 0)),
check.names = FALSE))
} else {
cat("\n\nStopping partitioning.\nMessage:",
as.character(stopinfo), "\n")
if (inherits("try-error", stopinfo))
warning(as.character(stopinfo))
}
}
}
## inscribe original node names for later pruning
for (pid in seq_along(nodes)) {
nodes[[pid]] <- as.list(nodes[[pid]])
for (nid in 1:length(nodes[[pid]])) {
nodes[[pid]][[nid]]$info$id$original <- nodes[[pid]][[nid]]$id
nodes[[pid]][[nid]]$info$id$last <- nodes[[pid]][[nid]]$id
}
nodes[[pid]] <- as.partynode(nodes[[pid]])
}
## prepare the title
title <- c("Tree-Based Varying Coefficients Model")
## modify splitpath
splitpath <-
tvcm_grow_splitpath(splitpath, varid, nodes, partData, control)
## the output object
if (nPart == 0L) {
tree <- model
} else {
## delete environments
environment(mcall) <- NULL
environment(object$info$call) <- NULL
formList <- vcrpart_formula_delEnv(formList)
attr(attr(partData, "terms"), ".Environment") <- NULL
## attach terms to possibly modified data
md[, paste0("Node", LETTERS[seq_along(nodes)])] <- NULL
attr(md, "terms") <- attr(object$info$data, "terms")
attr(attr(md, "terms"), ".Environment") <- NULL
attr(partData, "terms") <- attr(object$data, "terms")
attr(attr(partData, "terms"), ".Environment") <- NULL
## build 'tvcm' object
tree <- party(nodes[[1L]],
data = partData,
fitted = data.frame(
"(response)" = model.response(model.frame(model)),
"(weights)" = weights(model),
check.names = FALSE),
terms = terms(formList$original, keep.order = TRUE),
info = list(
title = title,
call = object$info$call,
mcall = mcall,
formula = formList,
data = md,
direct = object$info$direct,
fit = object$info$fit,
family = family,
control = control,
info = stopinfo,
model = model,
node = nodes,
grownode = nodes,
nstep = nstep,
splitpath = splitpath,
dotargs = object$info$dotargs))
class(tree) <- c("tvcm", "party")
}
return(tree)
}
## --------------------------------------------------------- #
##' Avoid calling glm.fit if 'fit == FALSE'
##'
##' @param call an object of class call
##' @param doFit a logical indicating whether the parameters
##' have to be optimized.
##'
##' @return A list of formulas ('root', 'tree' and 'original').
##'
##' @details Used in 'tvcm' and 'tvcm_grow_sctest'. 'glm.doNotFit'
##' is just an utility function to skip \code{\link{glm.fit}}
##' if \code{doFit = FALSE}
glm.doNotFit <- function(x, y, weights = NULL, start = NULL,
etastart = NULL,
mustart = NULL, offset = NULL, family = gaussian(),
control = list(), intercept = TRUE,
singular.ok = TRUE) {
coefficients <- rep.int(0, NCOL(x))
names(coefficients) <- colnames(x)
if (is.null(weights)) weights <- rep.int(1.0, NROW(x))
if (is.null(offset)) offset <- rep.int(0.0, NROW(x))
if (!is.null(start)) {
if (!is.null(names(start))) {
start <- start[intersect(names(coefficients), names(start))]
coefficients[names(start)] <- start
} else {
if (length(start) > length(coefficients))
start <- start[seq_along(coefficients)]
coefficients[seq_along(start)] <- start
}
}
return(list(coefficients = coefficients, residuals = NULL,
effect = NULL, R = NULL, rank = NULL,
qr = NULL, family = family,
linear.predictor = etastart,
deviance = NULL, aic = NULL, null.deviance = NULL,
iter = 0, weights = NULL, prior.weights = weights,
df.residual = NULL, df.null = NULL, y = y,
converged = TRUE, boundary = TRUE))
}
tvcm_grow_fit <- function(mcall, doFit = TRUE) {
## extract information from 'mcall'
env <- environment(mcall)
## set mcall if coefficients are not to optimized
if (!doFit) {
fit <- deparse(mcall$name)
if (fit == "olmm") {
mcall$doFit <- FALSE
} else if (fit == "glm") {
mcall$method <- glm.doNotFit # skips glm.fit
}
}
## fit model
object <- suppressWarnings(eval(mcall, env))
## return error if fitting failed
if (inherits(object, "try-error")) stop("model fitting failed.")
if (doFit && !is.null(object$converged) && !object$converged)
stop("no convergence")
## delete heavy objects
if (inherits(object, "glm")) {
attr(attr(object$model, "terms"), ".Environment") <- NULL
environment(object$formula) <- NULL
attr(object$terms, ".Environment") <- NULL
}
## return model
return(object)
}
## --------------------------------------------------------- #
##' Updates the model matrix and re-fits the current node
##' model. Used for the grid-search in 'tvcm_grow_exsearch'.
##'
##' @param object a prototype model
##' @param mcall the mcall for the prototype model
##'
##' @return A list of formulas ('root', 'tree' and 'original').
##'
##' @details Used in 'tvcm' and 'tvcm_grow_exsearch'. Note that the
##' function will modify the slots of the original object as well!
##'
##' To do:
##' Improve performance for non 'olmm' objects
tvcm_grow_update <- function(object, control, subs = NULL) {
if (inherits(object, "olmm")) {
## set new partition
data <- model.frame(object)
nodeVars <- grep("Node[A-Z]", colnames(data), value = TRUE)
object$frame[, nodeVars] <- data[, nodeVars]
## get terms
termsFeCe <- terms(object, "fe-ce")
termsFeGe <- terms(object, "fe-ge")
## get constrasts
contrasts <- object$contrasts
conCe <-
contrasts[intersect(names(contrasts), all.vars(termsFeCe))]
if (length(conCe) == 0L) conCe <- NULL
conGe <-
contrasts[intersect(names(contrasts), all.vars(termsFeGe))]
if (length(conGe) == 0L) conGe <- NULL
## update model matrix
object$X <-
olmm_merge_mm(x = model.matrix(termsFeCe, object$frame, conCe),
y = model.matrix(termsFeGe, object$frame, conGe),
TRUE)
object$X <- olmm_check_mm(object$X)
if (control$center) {
## extract interaction predictors to be centered
## (the ones with 'Left' and 'Right')
cColsCe <- which(rownames(attr(termsFeCe, "factors")) %in%
c("Left", "Right"))
if (length(cColsCe) > 0L) {
cColsCe <-
which(colSums(attr(termsFeCe, "factors")[
cColsCe,,drop = FALSE]) > 0 &
!colnames(attr(termsFeCe, "factors")) %in%
c("Left", "Right"))
cColsCe <-
which(attr(object$X, "assign") %in%
cColsCe & attr(object$X, "merge") == 1)
}
cColsGe <- which(rownames(attr(termsFeGe, "factors")) %in%
c("Left", "Right"))
if (length(cColsGe) > 0L) {
cColsGe <-
which(colSums(attr(termsFeGe, "factors")[
cColsGe,,drop = FALSE]) > 0 &
!colnames(attr(termsFeGe, "factors")) %in%
c("Left", "Right"))
cColsGe <-
which(attr(object$X, "assign") %in%
cColsGe & attr(object$X, "merge") == 2)
}
## center the predictors
object$X[, c(cColsCe, cColsGe)] <-
scale(object$X[, c(cColsCe, cColsGe)],
center = TRUE, scale = FALSE)
}
## prepare optimization
optim <- object$optim
optim[[1L]] <- object$coefficients
optim[[4L]] <- object$restricted
environment(optim[[2L]]) <- environment()
if (!object$dims["numGrad"]) environment(optim[[3L]]) <-
environment()
optim$env <- environment()
FUN <- optim$fit
subs <- which(names(optim) == "fit")
optim <- optim[-subs]
## run optimization
output <- try(suppressWarnings(do.call(FUN, optim)), TRUE)
## check optimized model
if (!inherits(output, "try-error")) {
object$output <- output
object$conv <-
switch(object$optim$fit,
optim = object$output$convergence == 0,
nlminb = object$output$convergence == 0,
ucminf = object$output$convergence %in% c(1, 2, 4))
if (!object$conv) object <- try(stop("not converged"), TRUE)
} else {
object <- output
}
} else {
## extract interaction predictors to be centered
## (the ones with 'Left' and 'Right')
X <- model.matrix(object$formula, model.frame(object))
if (control$center) {
## get the columns of 'X' to be centered
terms <- terms(object$formula)
cCols <- which(rownames(attr(terms, "factors")) %in%
c("Left", "Right"))
if (length(cCols) > 0L) {
cCols <- which(
colSums(attr(terms, "factors")[
cCols,,drop = FALSE]) > 0 &
!colnames(attr(terms, "factors")) %in%
c("Left", "Right"))
cCols <- which(attr(X, "assign") %in% cCols)
}
## centering
X[, cCols] <- scale(X[, cCols], center = TRUE, scale = TRUE)
}
## if 'fast = TRUE' model is fitted locally (thereby nuisance
## parameter is left as a free parameter)
if (!control$fast | is.null(subs)) subs <- rep(TRUE, nrow(X))
start <- if (control$fast) object$coefficients else NULL
##subs <- rep(TRUE, nrow(X))
object <- try(suppressWarnings(
glm.fit(x = X[subs,,drop=FALSE],
y = object$y[subs],
weights = object$prior.weights[subs],
start = start,
offset = object$offset[subs],
family = object$family,
control = object$control,
intercept = TRUE)), TRUE)
if (!inherits(object, "try-error")) {
class(object) <- c("glm", "lm")
if (!object$conv) object <- try(stop("not converged"), TRUE)
}
}
## return model
return(object)
}
tvcm_grow_gefp <- gefp.olmm # see 'olmm-methods.R'
## --------------------------------------------------------- #
##' Computes cutpoints of 'numeric' partitioning variables
##'
##' @param z a numeric vector
##' @param w a numeric vector of weights
##' @param minsize numerical scalar. The minimum node size.
##' @param maxnumsplit integer scalar. The maximum number
##' of cutpoints.
##'
##' @return A matrix with one column and one row for each
##' cutpoint
##'
##' @details Used in 'tvcm_grow_setsplits'.
tvcm_getNumSplits <- function(z, w, minsize, maxnumsplit) {
## order the partitioning variable
ord <- order(z)
z <- z[ord]; w <- w[ord];
cw <- cumsum(w)
## result if there is no split
rval0 <- matrix(numeric(), ncol = 1L)
colnames(rval0) <- "cut"
attr(rval0, "type") <- "dev"
## get the first index
subsL <- which(cw >= minsize)
if (length(subsL) < 1L) return(rval0)
subsL <- min(subsL)
## get the last index
subsR <- cw < (cw[length(cw)] - minsize + 1)
if (!any(subsR)) return(rval0)
if (any(!subsR)) subsR <- subsR & z < min(z[!subsR])
if (!any(subsR)) return(rval0)
subsR <- max(which(subsR))
if (subsL <= subsR && z[subsL] <= z[subsR]) {
## valid splits available
z <- z[subsL:subsR]
cw <- cw[subsL:subsR] - cw[subsL] + w[subsL]
## apply a cutpoint reduction if necessary
if (length(unique(z)) > maxnumsplit) {
nq <- maxnumsplit - 1
rval <- c()
cw <- cw / cw[length(cw)]
while (length(unique(rval)) < maxnumsplit) {
nq <- nq + 1L
q <- (1:nq) / (nq + 1L)
rval <-
unique(sapply(q, function(p) z[max(which(cw <= p))]))
}
} else {
rval <- unique(z)
}
## sometimes the while loop yields too many values ...
if (length(rval) > maxnumsplit)
rval <- sort(sample(rval, 9))
} else {
## no valid splits
rval <- numeric()
}
## prepare return value
rval <- matrix(rval, ncol = 1L)
colnames(rval) <- "cut"
attr(rval, "type") <- "dev"
## return matrix with cutpoints
return(rval)
}
## --------------------------------------------------------- #
##' Computes cutpoints of 'ordinal' partitioning variables
##'
##' @param z a vector of class 'ordered'
##' @param w a numeric vector of weights
##' @param minsize numerical scalar. The minimum node size.
##' @param maxordsplit integer scalar. The maximum number
##' of cutpoints.
##'
##' @return A matrix with one column for each category and
##' one row for each cutpoint
##'
##' @details Used in 'tvcm_grow_setsplits'.
tvcm_getOrdSplits <- function(z, w, minsize, maxordsplit) {
## get integer cutpoints using 'tvcm_getNumSplits'
nl <- nlevels(z) # all levels
cuts <- tvcm_getNumSplits(as.integer(z), w, minsize, maxordsplit)
zdlev <- 1:nl %in% as.integer(cuts)
## create a matrix to apply categorical splits
rval <- diag(nl)
rval[lower.tri(rval)] <- 1L
rval <- rval[zdlev,, drop = FALSE]
## prepare return value
colnames(rval) <- levels(z)
attr(rval, "type") <- "dev"
## return matrix with cutpoints
return(rval)
}
## --------------------------------------------------------- #
##' Computes cutpoints of 'nominal' partitioning variables
##'
##' @param z a vector of class 'factor'
##' @param w a numeric vector of weights
##' @param minsize numerical scalar. The minimum node size.
##' @param maxnomsplit integer scalar. The maximum number
##' of cutpoints.
##'
##' @return A matrix with one column for each category and
##' one row for each cutpoint
##'
##' @details Used in 'tvcm_grow_setsplits'.
tvcm_getNomSplits <- function(z, w, minsize, maxnomsplit) {
zdlev <- 1 * (levels(z) %in% levels(droplevels(z)))
if (sum(zdlev) < maxnomsplit) {
## exhaustive search
rval <- .Call("tvcm_nomsplits",
as.integer(zdlev),
PACKAGE = "vcrpart")
type <- "dev"
} else {
## Heuristic reduction of splits: in tvcm_grow_exsearch,
## the 'isolated' coefficients of each category are
## computed. The coefficients are used for ordering
## the categories and finally the variable is treated
## as ordinal. See tvcm_grow_exsearch
rval <- diag(nlevels(z))
type <- "coef"
}
## remove splits according to 'minsize'
sumWTot <- sum(w)
sumWCat <- tapply(w, z, sum)
sumWCat[is.na(sumWCat)] <- 0
valid <- apply(rval, 1, function(x) {
all(c(sum(sumWCat[x > 0]), sumWTot - sum(sumWCat[x > 0])) > minsize)
})
rval <- rval[valid,, drop = FALSE]
## return matrix with cutpoints
colnames(rval) <- levels(z)
attr(rval, "type") <- type
return(rval)
}
## --------------------------------------------------------- #
##' Computes candidate splits for the current step
##'
##' @param splits a list. The former list of splits
##' @param partid a vector of candidate partitions for splitting.
##' @param spart integer scalar. The partition in which the
##' last split was employed
##' @param varid a \code{list} with a vector for each partition that
##' that specifies candidate variables for splitting.
##' @param nodeid a \code{list} with a vector for each partition that
##' that specifies candidate nodes for splitting.
##' @param model a fitted model of class \code{\link{olmm}} or
##' \code{\link{glm}}.
##' @param nodes a \code{list} with a \code{\link{partynode}}
##' object for each partition.
##' @param where a \code{list} with a factor vector for each
##' partition that the assigns observations to nodes.
##' @param partData a data frame with variables for
##' splitting.
##' @param control a \code{list} of control parameters as produced
##' by 'tvcm_control.'
##'
##' @return A list of splits. Entries for splits that
##' exceed the tuning parameters are a vector of length
##' zero.
##'
##' @details Used in 'tvcm'.
tvcm_grow_setsplits <- function(splits, partid, nodeid, varid,
model, nodes, where,
partData, control) {
## get tree size criteria of current tree(s)