-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathKINOMO.R
1943 lines (1609 loc) · 63.6 KB
/
KINOMO.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
#' @include KINOMOstd-class.R
#' @include KINOMOSet-class.R
#' @include registry-seed.R
#' @include registry-algorithms.R
#' @include parallel.R
NULL
setGeneric('KINOMO', function(x, rank, method, ...) standardGeneric('KINOMO') )
setMethod('KINOMO', signature(x='data.frame', rank='ANY', method='ANY'),
function(x, rank, method, ...)
{
# replace missing values by NULL values for correct dispatch
if( missing(method) ) method <- NULL
if( missing(rank) ) rank <- NULL
# apply KINOMO to the the data.frame converted into a matrix
KINOMO(as.matrix(x), rank, method, ...)
}
)
setMethod('KINOMO', signature(x='matrix', rank='numeric', method='NULL'),
function(x, rank, method, seed=NULL, model=NULL, ...)
{
# a priori the default method will be used
method <- KINOMO.getOption('default.algorithm')
# use default seeding method if seed is missing
if( is.null(seed) ){
# seed <- KINOMO.getOption('default.seed')
}else{
# get reference object from which to infer model type
refobj <- if( is.KINOMO(seed) ) seed else if( is.KINOMO(model) ) model
if( !is.null(refobj) ){
mtype <- modelname(refobj)
# try to find the algorithm suitable for the seed's KINOMO model
method.potential <- selectKINOMOMethod(model=mtype, exact=TRUE, quiet=TRUE)
if( is.null(method.potential) )
stop("KINOMO::KINOMO - Found no algorithm defined for model '", mtype, "'")
if( length(method.potential) == 1 ) # only one to choose
method <- method.potential
else if( !is.element(method, method.potential) ){# several options, none is default
method <- method.potential[1]
warning("KINOMO::KINOMO - Selected algorithm '", method, "' to fit model '", mtype, "'."
, "\n Alternatives are: "
, str_out(method.potential[-1], Inf)
, call.=FALSE, immediate.=TRUE)
}
}
}
KINOMO(x, rank, method, seed=seed, model=model, ...)
}
)
setMethod('KINOMO', signature(x='matrix', rank='numeric', method='list'),
function(x, rank, method, ..., .parameters = list())
{
# apply each KINOMO algorithm
k <- 0
n <- length(method)
# setup/check method specific parameters
ARGS <- NULL
.used.parameters <- character()
if( !is.list(.parameters) )
stop("KINOMO::KINOMO - Invalid value for argument `.parameters`: must be a named list.")
if( length(.parameters) && (is.null(names(.parameters)) || any(names(.parameters) == '')) )
stop("KINOMO::KINOMO - Invalid value for argument `.parameters`: all elements must be named.")
t <- system.time({
res <- lapply(method,
function(meth, ...){
k <<- k+1
methname <- if( isString(meth) ) meth else name(meth)
cat("Compute KINOMO method '", methname, "' [", k, "/", n, "] ... ", sep='')
# restore RNG on exit (except after last method)
# => this ensures the methods use the same stochastic environment
orng <- RNGseed()
if( k < n ) on.exit( RNGseed(orng), add = TRUE)
# look for method-specific arguments
i.param <- 0L
if( length(.parameters) ){
i.param <- charmatch(names(.parameters), methname)
if( !length(i.param <- seq_along(.parameters)[!is.na(i.param)]) )
i.param <- 0L
else if( length(i.param) > 1L ){
stop("Method name '", methname, "' matches multiple method-specific parameters "
, "[", str_out(names(.parameters)[i.param], Inf), "]")
}
}
#o <- capture.output(
if( !i.param ){
res <- try( KINOMO(x, rank, meth, ...) , silent=TRUE)
}else{
if( is.null(ARGS) ) ARGS <<- list(x, rank, ...)
.used.parameters <<- c(.used.parameters, names(.parameters)[i.param])
res <- try( do.call(KINOMO, c(ARGS, method = meth, .parameters[[i.param]]))
, silent=TRUE)
}
#)
if( is(res, 'try-error') )
cat("ERROR\n")
else
cat("OK\n")
return(res)
}
, ...)
})
# filter out bad results
ok <- sapply(res, function(x){
if( is(x, 'KINOMO.rank') ) all(sapply(x$fit, isKINOMOfit))
else isKINOMOfit(x)
})
if( any(!ok) ){ # throw warning if some methods raised an error
err <- lapply(which(!ok), function(i){ paste("'", method[[i]],"': ", res[[i]], sep='')})
warning("KINOMO::KINOMO - Incomplete results due to ", sum(!ok), " errors: \n- ", paste(err, collapse="- "), call.=FALSE)
}
res <- res[ok]
# TODO error if ok is empty
# not-used parameters
if( length(.used.parameters) != length(.parameters) ){
warning("KINOMO::KINOMO - Did not use methods-specific parameters ", str_out(setdiff(names(.parameters), .used.parameters), Inf))
}
# add names to the result list
names(res) <- sapply(res, function(x){
if( is(x, 'KINOMO.rank') ) x <- x$fit[[1]]
algorithm(x)
})
# return list as is if surveying multiple ranks
if( length(rank) > 1 ) return(res)
# wrap the result in a KINOMOList object
# DO NOT WRAP anymore here: KINOMOfitX objects are used only for results of multiple runs (single method)
# the user can still join on the result if he wants to
#res <- join(res, runtime=t)
res <- new('KINOMOList', res, runtime=t)
# return result
return(res)
}
)
setMethod('KINOMO', signature(x='matrix', rank='numeric', method='character'),
function(x, rank, method, ...)
{
# if there is more than one methods then treat the vector as a list
if( length(method) > 1 ){
return( KINOMO(x, rank, as.list(method), ...) )
}
# create the KINOMOStrategy from its name
strategy <- KINOMOAlgorithm(method)
# apply KINOMO using the retrieved strategy
KINOMO(x, rank, method=strategy, ...)
}
)
setMethod('KINOMO', signature(x='matrix', rank='numeric', method='function'),
function(x, rank, method, seed, model='KINOMOstd', ..., name, objective='euclidean', mixed=FALSE){
model_was_a_list <- is.list(model)
if( is.character(model) )
model <- list(model=model)
if( !is.list(model) ){
stop("KINOMO - Invalid argument `model`: must be NULL or a named list of initial values for slots in an KINOMO model.")
}
# arguments passed to the call to KINOMOStrategyFunction
strat <- list('KINOMOStrategyFunction'
, algorithm = method
, objective = objective
, mixed = mixed[1]
)
## Determine type of KINOMO model associated with the KINOMOStrategy
# All elements of `model` (except the model class) will be passed to
# argument `model` of the workhorse `KINOMO` method, which will use them
# to create the KINOMO model in a call to `KINOMOModel`
if( length(model) > 0L ){
if( !is.null(model$model) ){
strat$model <- model$model
model$model <- NULL
}else if( isKINOMOclass(model[[1]]) ){
strat$model <- model[[1]]
# use the remaining elements to instanciate the KINOMO model
model <- model[-1]
}
# all elements must be named
if( !hasNames(model, all=TRUE) ){
stop("KINOMO::KINOMO - Invalid argument `model`: all elements must be named, except the first one which must then be an KINOMO model class name")
}
}
##
# if name is missing: generate a temporary unique name
if( missing(name) ) name <- basename(tempfile("KINOMO_"))
# check that the name is not a registered name
if( existsKINOMOMethod(name) )
stop("Invalid name for custom KINOMO algorithm: '",name,"' is already a registered KINOMO algorithm")
strat$name <- name
# create KINOMOStrategy
strategy <- do.call('new', strat)
# full validation of the strategy
validObject(strategy, complete=TRUE)
if( missing(seed) ) seed <- NULL
if( !model_was_a_list && length(model) == 0L ) model <- NULL
# call method 'KINOMO' with the new object
KINOMO(x, rank, strategy, seed=seed, model=model, ...)
}
)
setMethod('KINOMO', signature(x='matrix', rank='KINOMO', method='ANY'),
function(x, rank, method, seed, ...){
if( !missing(seed) ){
if( isNumber(seed) ){
set.seed(seed)
}else if( !is.null(seed) ){
warning("KINOMO::KINOMO - Discarding value of argument `seed`: directly using KINOMO model supplied in `rank` instead.\n"
, " If seeding is necessary, please use argument `model` pass initial model slots, which will be filled by the seeding method.")
}
# # pass the model via a one-off global variable
# .KINOMO_InitModel(rank)
}
# replace missing method by NULL for correct dispatch
if( missing(method) ) method <- NULL
KINOMO(x, nbasis(rank), method, seed=rank, ...)
}
)
.KINOMO_InitModel <- oneoffVariable()
setMethod('KINOMO', signature(x='matrix', rank='NULL', method='ANY'),
function(x, rank, method, seed, ...){
if( missing(seed) || !is.KINOMO(seed) )
stop("KINOMO::KINOMO - Argument `seed` must be an KINOMO model when argument `rank` is missing.")
# replace missing method by NULL for correct dispatch
if( missing(method) ) method <- NULL
KINOMO(x, nbasis(seed), method, seed=seed, ...)
}
)
setMethod('KINOMO', signature(x='matrix', rank='missing', method='ANY'),
function(x, rank, method, ...){
# replace missing method by NULL for correct dispatch
if( missing(method) ) method <- NULL
KINOMO(x, NULL, method, ...)
}
)
setMethod('KINOMO', signature(x='matrix', rank='numeric', method='missing'),
function(x, rank, method, ...){
KINOMO(x, rank, NULL, ...)
}
)
setMethod('KINOMO', signature(x='matrix', rank='matrix', method='ANY'),
function(x, rank, method, seed, model=list(), ...)
{
if( is.character(model) )
model <- list(model=model)
if( !is.list(model) )
stop("KINOMO - Invalid argument `model`: must be NULL or a named list of initial values for slots in an KINOMO object.")
if( !hasNames(model, all=TRUE) )
stop("KINOMO - Invalid argument `model`: all elements must be named")
# remove rank specification if necessary
if( !is.null(model$rank) ){
warning("KINOMO - Discarding rank specification in argument `model`: use value inferred from matrix supplied in argument `rank`")
model$rank <- NULL
}
# check compatibility of dimensions
newseed <-
if( nrow(rank) == nrow(x) ){
# rank is the initial value for the basis vectors
if( length(model)==0L ) KINOMOModel(W=rank)
else{
model$W <- rank
do.call('KINOMOModel', model)
}
}else if( ncol(rank) == ncol(x) ){
# rank is the initial value for the mixture coefficients
if( length(model)==0L ) KINOMOModel(H=rank)
else{
model$H <- rank
do.call('KINOMOModel', model)
}
}else
stop("KINOMO - Invalid argument `rank`: matrix dimensions [",str_out(dim(x),sep=' x '),"]"
, " are incompatible with the target matrix [", str_out(dim(x),sep=' x '),"].\n"
, " When `rank` is a matrix it must have the same number of rows or columns as the target matrix `x`.")
# replace missing values by NULL values for correct dispatch
if( missing(method) ) method <- NULL
if( missing(seed) ) seed <- NULL
#KINOMO(x, nbasis(newseed), method, seed=seed, model=newseed, ...)
KINOMO(x, newseed, method, seed=seed, ...)
}
)
setMethod('KINOMO', signature(x='matrix', rank='data.frame', method='ANY'),
function(x, rank, method, ...){
# replace missing values by NULL values for correct dispatch
if( missing(method) ) method <- NULL
KINOMO(x, as.matrix(rank), method, ...)
}
)
setMethod('KINOMO', signature(x='formula', rank='ANY', method='ANY'),
function(x, rank, method, ..., model=NULL){
# replace missing values by NULL values for correct dispatch
if( missing(method) ) method <- NULL
if( missing(rank) ) rank <- NULL
# if multiple numeric rank: use KINOMORestimateRank
if( is.vector(rank) && is.numeric(rank) ){
if( length(rank) > 1L ){
return( KINOMOEstimateRank(x, rank, method, ..., model=model) )
}
}
# build formula based model
model <- KINOMOModel(x, rank, data=model)
KINOMO(attr(model, 'target'), nbasis(model), method, ..., model=model)
}
)
.as.numeric <- function(x){
suppressWarnings( as.numeric(x) )
}
.translate.string <- function(string, dict){
res <- list()
dict <- as.list(dict)
if( nchar(string) == 0 ) return(res)
opt.val <- TRUE
last.key <- NULL
buffer <- ''
lapply(strsplit(string, '')[[1]],
function(c){
if( c=='-' ) opt.val <<- FALSE
else if( c=='+' ) opt.val <<- TRUE
else if( opt.val && !is.na(.as.numeric(c)) )
buffer <<- paste(buffer, c, sep='')
else if( !is.null(dict[[c]]) ){
# flush the buffer into the last key if necessary
if( nchar(buffer) > 0 && !is.null(last.key) && !is.na(buffer <- .as.numeric(buffer)) ){
res[[dict[[last.key]]]] <<- buffer
buffer <<- ''
}
res[[dict[[c]]]] <<- opt.val
last.key <<- c
}
}
)
# flush the buffer into the last key
if( nchar(buffer) > 0 && !is.null(last.key) && !is.na(buffer <- .as.numeric(buffer)) )
res[[dict[[last.key]]]] <- buffer
# return result
return(res)
}
checkErrors <- function(object, element=NULL){
# extract error messages
errors <-
if( is.null(element) ){
lapply(seq_along(object), function(i){
x <- object[[i]]
if( is(x, 'error') ) c(i, x)
else NA
})
}else{
lapply(seq_along(object), function(i){
x <- object[[i]][[element, exact=TRUE]]
if( is(x, 'error') ) c(i, x)
else NA
})
}
errors <- errors[!is.na(errors)]
nerrors <- length(errors)
res <- list(n = nerrors)
# format messages
if( nerrors ){
ierrors <- sapply(errors, '[[', 1L)
msg <- sapply(errors, '[[', 2L)
ierrors_unique <- ierrors[!duplicated(msg)]
res$msg <- str_c(" - ", str_c("run #", ierrors_unique, ': ', msg[ierrors_unique], collapse="\n - "))
}
# return error data
res
}
setMethod('KINOMO', signature(x='matrix', rank='numeric', method='KINOMOStrategy'),
#function(x, rank, method, seed='random', nrun=1, keep.all=FALSE, optimized=TRUE, init='KINOMO', track, verbose, ...)
function(x, rank, method
, seed=KINOMO.getOption('default.seed'), rng = NULL
, nrun=if( length(rank) > 1L ) 30 else 1, model=NULL, .options=list()
, .pbackend=KINOMO.getOption('pbackend')
, .callback=NULL #callback function called after a run
, ...)
{
fwarning <- function(...) KINOMO_warning('KINOMO', ...)
fstop <- function(...) KINOMO_stop('KINOMO', ...)
n <- NULL
RNGobj <- NULL
# if options are given as a character string, translate it into a list of booleans
if( is.character(.options) ){
.options <- .translate.string(.options,
c(t='track', v='verbose', d='debug'
, p='parallel', P='parallel.required'
, k='keep.all', r='restore.seed', f='dry.run'
, g='garbage.collect'
, c='cleanup', S='simplifyCB'
, R='RNGstream', m='shared.memory'))
}
# get seeding method from the strategy's defaults if needed
seed <- defaultArgument(seed, method, KINOMO.getOption('default.seed'), force=is.null(seed))
.method_defaults <- method@defaults
.method_defaults$seed <- NULL
#
# RNG specification
if( isRNGseed(seed) ){
if( !is.null(rng) )
warning("Discarding RNG specification in argument `rng`: using those passed in argument `seed`.")
rng <- seed
seed <- 'random'
}
#
# setup verbosity options
debug <- if( !is.null(.options$debug) ) .options$debug else KINOMO.getOption('debug')
verbose <- if( debug ) Inf
else if( !is.null(.options$verbose) ) .options$verbose
else KINOMO.getOption('verbose')
# show call in debug mode
if( debug ){
.ca <- match.call()
message('# KINOMO call: ', paste(capture.output(print(.ca)), collapse="\n "))
}
# KINOMO over a range of values: pass the call to KINOMOEstimateRank
if( length(rank) > 1 ){
if( verbose <= 1 )
.options$verbose <- FALSE
return( KINOMOEstimateRank(x, range = rank, method = method, nrun = nrun
, seed = seed, rng = rng, model = model
, .pbackend = .pbackend, .callback = .callback
, verbose=verbose, .options=.options, ...) )
}
.OPTIONS <- list()
# cleanup on exit
.CLEANUP <- .options$cleanup %||% TRUE
# tracking of objective value
.OPTIONS$track <- if( !is.null(.options$track) ) .options$track
else KINOMO.getOption('track')
# dry run
dry.run <- .options$dry.run %||% FALSE
# call the garbage collector regularly
opt.gc <- if( !is.null(.options$garbage.collect) ) .options$garbage.collect
else KINOMO.getOption('gc')
if( is.logical(opt.gc) && opt.gc )
opt.gc <- ceiling(max(nrun,50) / 3)
.options$garbage.collect <- opt.gc
# keep results from all runs?
keep.all <- .options$keep.all %||% FALSE
# shared memory?
shared.memory <- if( !is.null(.options$shared.memory) ) .options$shared.memory else KINOMO.getOption('shared.memory')
# use RNG stream
.options$RNGstream <- .options$RNGstream %||% TRUE
# discard .callback when not used
if( is.function(.callback) ){
w <- if( nrun==1 ) "discarding argument `.callback`: not used when `nrun=1`."
else if( keep.all )
"discarding argument `.callback`: not used when option `keep.all=TRUE`."
if( !is.null(w) ){
.callback <- NULL
fwarning(w, immediate.=TRUE)
}
# wrap into another function if necessary
if( is.function(.callback) ){
# default is to simplify
.options$simplifyCB <- .options$simplifyCB %||% TRUE
args <- formals(.callback)
if( length(args) <= 2L ){
if( length(args) < 2L || '...' %in% names(args) ){
.CALLBACK <- .callback
.callback <- function(object, i) .CALLBACK(object)
}
}
# define post-processing function
processCallback <- function(res){
# check errors
errors <- checkErrors(res, '.callback')
if( errors$n > 0 ){
fwarning("All KINOMO fits were successful but ", errors$n, "/", nrun, " callback call(s) threw an error.\n"
,"# ", if(errors$n>10) "First 10 c" else "C", "allback error(s) thrown:\n"
, errors$msg
)
}
# add callback values to result list
sapply(res, '[[', '.callback'
, simplify=.options$simplifyCB && errors$n == 0L)
}
}
}
## ROLLBACK PROCEDURE
exitSuccess <- exitCheck()
on.exit({
if( verbose > 1 ) message("# KINOMO computation exit status ... ", if( exitSuccess() ) 'OK' else 'ERROR')
if( verbose > 2 ){
if( exitSuccess() ){
message('\n## Running normal exit clean up ... ')
}else{
message('\n## Running rollback clean up ... ')
}
}
}, add=TRUE)
# RNG restoration on error
.RNG_ORIGIN <- getRNG()
on.exit({
if( !exitSuccess() ){
if( verbose > 2 ) message("# Restoring RNG settings ... ", appendLF=verbose>3)
setRNG(.RNG_ORIGIN)
if( verbose > 3 ) showRNG(indent=' #')
if( verbose > 2 ) message("OK")
}
}, add=TRUE)
# Set debug/verbosity option just for the time of the run
old.opt <- KINOMO.options(debug=debug, verbose=verbose, shared.memory = shared.memory);
on.exit({
if( verbose > 2 ) message("# Restoring KINOMO options ... ", appendLF=FALSE)
KINOMO.options(old.opt)
if( verbose > 2 ) message("OK")
}, add=TRUE)
# make sure rank is an integer
rank <- as.integer(rank)
if( length(rank) != 1 ) fstop("invalid argument 'rank': must be a single numeric value")
if( rank < 1 ) fstop("invalid argument 'rank': must be greater than 0")
# option 'restore.seed' is deprecated
if( !is.null(.options$restore.seed) )
fwarning("Option 'restore.seed' is deprecated and discarded since version 0.5.99.")
if( verbose ){
if( dry.run ) message("*** fake/dry-run ***")
message("KINOMO algorithm: '", name(method), "'")
}
##START_MULTI_RUN
# if the number of run is more than 1, then call itself recursively
if( nrun > 1 )
{
if( verbose ) message("Multiple runs: ", nrun)
if( verbose > 3 ){
cat("## OPTIONS:\n")
sapply(seq_along(.options)
, function(i){
r <- i %% 4
cat(if(r!=1) '\t| ' else "# ", names(.options)[i],': ', .options[[i]], sep='')
if(r==0) cat("\n# ")
})
if( length(.options) %% 4 != 0 )cat("\n")
}
## OPTIONS: parallel computations
# option require-parallel: parallel computation is required if TRUE or numeric != 0
opt.parallel.required <- !is.null(.options$parallel.required) && .options$parallel.required
# determine specification for parallel computations
opt.parallel.spec <-
if( opt.parallel.required ){ # priority over try-parallel
# option require-parallel implies and takes precedence over option try-parallel
.options$parallel.required
}else if( !is.null(.options$parallel) ) .options$parallel # priority over .pbackend
else !is_NA(.pbackend) # required only if backend is not trivial
# determine if one should run in parallel at all: TRUE or numeric != 0, .pbackend not NA
opt.parallel <- !is_NA(.pbackend) && (isTRUE(opt.parallel.spec) || opt.parallel.spec)
##
if( opt.parallel ){
if( verbose > 1 )
message("# Setting up requested `foreach` environment: "
, if( opt.parallel.required ) 'require-parallel' else 'try-parallel'
, ' [', quick_str(.pbackend) , ']')
# switch doMC backend to doParallel
if( isString(.pbackend, 'MC', ignore.case=TRUE) ){
.pbackend <- 'par'
}
# try setting up parallel foreach backend
oldBackend <- setupBackend(opt.parallel.spec, .pbackend, !opt.parallel.required, verbose=verbose)
opt.parallel <- !isFALSE(oldBackend)
# setup backend restoration if using one different from the current one
if( opt.parallel && !is_NA(oldBackend) ){
on.exit({
if( verbose > 2 ){
message("# Restoring previous foreach backend '", getDoBackendName(oldBackend) ,"' ... ", appendLF=FALSE)
}
setDoBackend(oldBackend, cleanup=TRUE)
if( verbose > 2 ) message('OK')
}, add=TRUE)
}#
# From this point, the backend is registered
# => one knows if we'll run a sequential or parallel foreach loop
.MODE_SEQ <- is.doSEQ()
MODE_PAR <- .MODE_PAR <- !.MODE_SEQ
}
# check seed method: fixed values are not sensible -> warning
.checkRandomness <- FALSE
if( is.KINOMO(seed) && !is.empty.KINOMO(seed) ){
.checkRandomness <- TRUE
}
# start_RNG_all
# if the seed is numerical or a rstream object, then use it to set the
# initial state of the random number generator:
# build a sequence of RNGstreams: if no suitable seed is provided
# then the sequence use a random seed generated with a single draw
# of the current active RNG. If the seed is valid, then the
#
# setup the RNG sequence
# override with standard RNG if .options$RNGstream=FALSE
resetRNG <- NULL
if( !.options$RNGstream && (!opt.parallel || .MODE_SEQ) ){
.RNG.seed <- rep(list(NULL), nrun)
if( isNumber(rng) ){
resetRNG <- getRNG()
if( verbose > 2 ) message("# Force using current RNG settings seeded with: ", rng)
set.seed(rng)
}else if( verbose > 2 )
message("# Force using current RNG settings")
}else{
.RNG.seed <- setupRNG(rng, n = nrun, verbose=verbose)
# restore the RNG state on exit as after RNGseq:
# - if no seeding occured then the RNG has still been drawn once in RNGseq
# which must be reflected so that different unseeded calls use different RNG states
# - one needs to restore the RNG because it switched to L'Ecuyer-CMRG.
resetRNG <- getRNG()
}
stopifnot( length(.RNG.seed) == nrun )
# update RNG settings on exit if necessary
# and only if no error occured
if( !is.null(resetRNG) ){
on.exit({
if( exitSuccess() ){
if( verbose > 2 ) message("# Updating RNG settings ... ", appendLF=FALSE)
setRNG(resetRNG)
if( verbose > 2 ) message("OK")
if( verbose > 3 ) showRNG()
}
}, add=TRUE)
}
#end_RNG_all
####FOREACH_KINOMO
if( opt.parallel ){
if( verbose ){
if( verbose > 1 )
message("# Using foreach backend: ", getDoParName()
," [version ", getDoParVersion(),"]")
# show number of processes
if( getDoParWorkers() == 1 ) message("Mode: sequential [foreach:",getDoParName(),"]")
else message("Mode: parallel ", str_c("(", getDoParWorkers(), '/', parallel::detectCores()," core(s))"))
}
# check shared memory capability
.MODE_SHARED <- !keep.all && setupSharedMemory(verbose)
# setup temporary directory when not keeping all fits
if( !keep.all || verbose ){
KINOMO_TMPDIR <- setupTempDirectory(verbose)
# delete on exit
if( .CLEANUP ){
on.exit({
if( verbose > 2 ) message("# Deleting temporary directory '", KINOMO_TMPDIR, "' ... ", appendLF=FALSE)
unlink(KINOMO_TMPDIR, recursive=TRUE)
if( verbose > 2 ) message('OK')
}, add=TRUE)
}
}
run.all <- function(x, rank, method, seed, model, .options, ...){
## 1. SETUP
# load some variables from parent environment to ensure they
# are exported in the foreach loop
MODE_SEQ <- .MODE_SEQ
MODE_SHARED <- .MODE_SHARED
verbose <- verbose
keep.all <- keep.all
opt.gc <- .options$garbage.collect
CALLBACK <- .callback
.checkRandomness <- .checkRandomness
# check if single or multiple host(s)
hosts <- unique(getDoParHosts())
if( verbose > 2 ) message("# Running on ", length(hosts), " host(s): ", str_out(hosts))
SINGLE_HOST <- length(hosts) <= 1L
MODE_SHARED <- MODE_SHARED && SINGLE_HOST
if( verbose > 2 ) message("# Using shared memory ... ", MODE_SHARED)
# setup mutex evaluation function
mutex_eval <- if( MODE_SHARED ) ts_eval(verbose = verbose > 4) else force
# Specific thing only if one wants only the best result
if( !keep.all ){
KINOMO_TMPDIR <- KINOMO_TMPDIR
# - Define the shared memory objects
vOBJECTIVE <- gVariable(as.numeric(NA), MODE_SHARED)
# the consensus matrix is computed only if not all the results are kept
vCONSENSUS <- gVariable(matrix(0, ncol(x), ncol(x)), MODE_SHARED)
}
## 2. RUN
# ensure that the package KINOMO is in each worker's search path
.packages <- setupLibPaths('KINOMO', verbose>3)
# export all packages that contribute to KINOMO registries,
# e.g., algorithms or seeding methods.
# This is important so that these can be found in worker nodes
# for non-fork clusters.
if( !is.null(contribs <- registryContributors(package = 'KINOMO')) ){
.packages <- c(.packages, contribs)
}
# export dev environment if in dev mode
# .export <- if( isDevNamespace('KINOMO') && !is.doSEQ() ) ls(asNamespace('KINOMO'))
# in parallel mode: verbose message from each run are only shown in debug mode
.options$verbose <- FALSE
if( verbose ){
if( debug || (.MODE_SEQ && verbose > 1) )
.options$verbose <- verbose
if( (!.MODE_SEQ && !debug) || (.MODE_SEQ && verbose == 1) ){
if( verbose == 1 ){
# create progress bar
pbar <- txtProgressBar(0, nrun+1, width=50, style=3, title='Runs:'
, shared=KINOMO_TMPDIR)
}else{
cat("Runs: ")
}
}
}
# get options from master process to pass to workers
KINOMO.opts <- KINOMO.options()
# load extra required packages for shared mode
if( MODE_SHARED )
.packages <- c(.packages, 'bigmemory', 'synchronicity')
res.runs <- foreach(n=1:nrun
, RNGobj = .RNG.seed
, .verbose = debug
, .errorhandling = 'pass'
, .packages = .packages
# , .export = .export
# , .options.RNG=.RNG.seed
) %dopar% { #START_FOREACH_LOOP
# Pass options from master process
KINOMO.options(KINOMO.opts)
# in mode sequential or debug: show details for each run
if( MODE_SEQ && verbose > 1 )
cat("\n## Run: ",n, "/", nrun, "\n", sep='')
# set the RNG if necessary and restore after each run
if( MODE_SEQ && verbose > 2 )
message("# Setting up loop RNG ... ", appendLF=FALSE)
setRNG(RNGobj, verbose=verbose>3 && MODE_SEQ)
if( MODE_SEQ && verbose > 2 )
message("OK")
# limited verbosity in simple mode
if( verbose && !(MODE_SEQ && verbose > 1)){
if( verbose >= 2 ) mutex_eval( cat('', n) )
else{
# update progress bar (in mutex)
mutex_eval(setTxtProgressBar(pbar, n))
#
}
}
# check RNG changes
if( n == 1 && .checkRandomness ){
.RNGinit <- getRNG()
}
# fit a single KINOMO model
res <- KINOMO(x, rank, method, nrun=1, seed=seed, model=model, .options=.options, ...)
if( n==1 && .checkRandomness && rng.equal(.RNGinit) ){
warning("KINOMO::KINOMO - You are running multiple non-random KINOMO runs with a fixed seed")
}
# if only the best fit must be kept then update the shared objects
if( !keep.all ){
# initialise result list
resList <- list(filename=NA, residuals=NA, .callback=NULL)
##LOCK_MUTEX
mutex_eval({
# check if the run found a better fit
.STATIC.err <- vOBJECTIVE()
# retrieve approximation error
err <- deviance(res)
if( is.na(.STATIC.err) || err < .STATIC.err ){
if( n>1 && verbose ){
if( MODE_SEQ && verbose > 1 ) cat("## Better fit found [err=", err, "]\n")
else if( verbose >= 2 ) cat('*')
}
# update residuals
vOBJECTIVE(err)
# update best fit on disk: use pid if not using shared memory
resfile <- hostfile("fit", tmpdir=KINOMO_TMPDIR, fileext='.rds', pid=!MODE_SHARED)
if( MODE_SEQ && verbose > 2 )
message("# Serializing fit object in '", resfile, "' ... ", appendLF=FALSE)
saveRDS(res, file=resfile, compress=FALSE)
if( MODE_SEQ && verbose > 2 ){
message(if( file.exists(resfile) ) 'OK' else 'ERROR')
}
# store the filename and achieved objective value in the result list
resList$filename <- resfile
resList$residuals <- err
}
## CONSENSUS
# update the consensus matrix
if( MODE_SHARED && SINGLE_HOST ){
# on single host: shared memory already contains consensus
vCONSENSUS(vCONSENSUS() + connectivity(res, no.attrib=TRUE))
}else{
# on multiple hosts: must return connectivity and aggregate at the end
resList$connectivity <- connectivity(res, no.attrib=TRUE)
}
## CALLBACK
# call the callback function if necessary (return error as well)
if( is.function(CALLBACK) ){
resList$.callback <- tryCatch(CALLBACK(res, n), error=function(e) e)
}
})
##END_LOCK_MUTEX
# discard result object
res <- NULL
# return description list
res <- resList
}
# garbage collection if requested
if( opt.gc && n %% opt.gc == 0 ){
if( verbose > 2 ){
if( MODE_SEQ )
message("# Call garbage collector")
else{
mutex_eval( cat('%') )
}
}
gc(verbose= MODE_SEQ && verbose > 3)
}
# return the result
res
}
## END_FOREACH_LOOP
if( verbose && !debug ){
if( verbose >= 2 ) cat(" ... DONE\n")
else{
setTxtProgressBar(pbar, nrun+1)
pbar$kill(.CLEANUP)
}
}
## 3. CHECK FIT ERRORS
errors <- checkErrors(res.runs)
if( errors$n > 0 ){
fstop(errors$n,"/", nrun, " fit(s) threw an error.\n"
,"# Error(s) thrown:\n", errors$msg)
}
## 4. WRAP UP
if( keep.all ){ # result is a list of fits
# directly return the list of fits
res <- res.runs
}else{ # result is a list of lists: filename, .callback
# loop over the result files to find the best fit
if( verbose > 2 ) message("# Processing partial results ... ", appendLF=FALSE)
ffstop <- function(...){ message('ERROR'); fstop(...) }
# get best fit index
idx <- which.min(sapply(res.runs, '[[', 'residuals'))
if( length(idx) == 0L )
ffstop("Unexpected error: no partial result seem to have been saved.")
resfile <- res.runs[[idx]]$filename
# check existence of the result file
if( !file_test('-f', resfile) )
ffstop("could not find temporary result file '", resfile, "'")
# update res with a better fit
res <- readRDS(resfile)
if( !isKINOMOfit(res) )
ffstop("invalid object found in result file '", resfile, "'")
if( verbose > 2 ) message('OK')
# wrap the result in a list: fit + consensus
res <- list(fit=res, consensus=NA)
# CONSENSUS MATRIX
if( !is.null(res.runs[[1]]$connectivity) ){ # not MODE_SHARED
# aggregate connectivity matrices
con <- matrix(0, ncol(x), ncol(x))
sapply(res.runs, function(x){
con <<- con + x$connectivity
})
res$consensus <- con
}else{ # in MODE_SHARED: get consensus from global shared variable
res$consensus <- vCONSENSUS()
cn <- colnames(x)
if( is.null(cn) ) dimnames(res$consensus) <- NULL
else dimnames(res$consensus) <- list(cn, cn)
}
# CALLBACKS
if( !is.null(.callback) ){
res$.callback <- processCallback(res.runs)
}