Surr_Train.R 94.2 KB
Newer Older
Marco De Lucia's avatar
Marco De Lucia committed
1
2
3
4
##  Functions for dealing with surrogate simulations

### Marco De Lucia, delucia@gfz-potsdam.de, 2009-2018
### Janis Jatnieks, janisj@gfz-potsdam.de, jatnieks@janis.es
5
### Time-stamp: "Last modified 2018-05-09 01:01:30 delucia"
Marco De Lucia's avatar
Marco De Lucia committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
### Licence: LGPL version 2.1

## resolve dependencies automatically
## put neccessary packages here, they will be checked, loaded and autoinstalled if neccessary
##' @export
start_up <- function(session_path=FALSE, ## to disable set to a non-string
                     list.of.packages = c(## infrastructure and data manipulation
                         "zoo","plyr","sqldf","dtplyr","foreach",
                         "data.table",
                         ## multi-method learning meta-packages
                         "DiceEval","caret", #,"caretEnsemble" 
                         ## actual learning method packages
                         "mda","gam","polspline","rpart","MASS",
                         "elasticnet","e1071","ipred",
                         "deepnet","kernlab","pls","fastICA","lars",
                         "monomvn","RSNNS","qrnn",
                         "party","quantregForest","arm","brnn",
                         "lattice","ggplot2","plotrix", ## viz prototyping 
                         ## testing
                         "cluster","stringr","gtools", #"ftsa", 
                         "amap"),
27
                     install=TRUE,
Marco De Lucia's avatar
Marco De Lucia committed
28
29
30
31
32
33
34
35
36
37
38
                     use_cores=4)
{
    gc()
    
    if (Sys.info()[['sysname']]=="Linux") {
        cat("\nYou are not on Windows, loading doMC!\n")
        list.of.packages = c(list.of.packages,"doMC")
    }
    
    ## load session data first
    if (class(session_path)[1]=="character" & file.exists(session_path) ) { 
39
        msg("Loading...",session_path)
Marco De Lucia's avatar
Marco De Lucia committed
40
        load(session_path, .GlobalEnv)
41
        msg(" OK")
Marco De Lucia's avatar
Marco De Lucia committed
42
43
44
    }
    ## loading the right data is important!
    ## check install and load neccessary packages
45
    msg("Checking for required packages...")
Marco De Lucia's avatar
Marco De Lucia committed
46
47
48
49
50
51

    new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
    
    if(length(new.packages)) {
        cat("Need to install these packages:",new.packages,"\n")
        if (install) {
52
53
54
            libpath <- readline(prompt="Please specify the absolute path where the packages will be installed (e.g., '~/Rdevel'): \n")
            cat(" Afterwards, remember to store this path somewhere for R to find it again, such as R_LIBS_USER='~/Rdevel' in ~/.Renviron\n")
            install.packages(new.packages, lib=libpath)
Marco De Lucia's avatar
Marco De Lucia committed
55
        }
56
    } else msg("Package checks OK!")
Marco De Lucia's avatar
Marco De Lucia committed
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
    
    loadsuccess <- lapply(list.of.packages, require, character.only=TRUE)
    
    if (!Sys.info()[["sysname"]]=="Windows") {
        cat(":: Registering parallelization with ", use_cores, "cores\n")
        registerDoMC( use_cores ) ## set up parallelization
    }


    ### MDL: some global definitions
    ## we use this to swich calls between Dice and caret or direct calls
    ## to others
    DiceMethods <<- c('Linear','Additive','MARS','MARS3',
                      'PolyMARS','PolyMARS3','StepLinear','PolyMARS_GCV1')
    
    ## I enumerate them here so that no large text blocks 
    ## would repeat in pre- and post- processing code
    specific_preprocessing_methods <<- c(
        "(0,1) scaled rolling deltas",                 ## 1
        "(-1,1) scaled rolling deltas",                ## 2, usually not worth it
        "z-scaled rolling deltas",                     ## 3
        "z-scaled",                                    ## 4
        "deltas on z-scaled",                          ## 5
        "deltas on (0,1) scaled",                      ## 6
        "deltas on (-1,1) scaled",                     ## 7, usually not worth it
        "(0,1) scaled",                                ## 8
        "(0,10) scaled",                               ## 9
        "(-10,10) scaled",                             ## 10
        "(0,10) scaled rolling deltas",                ## 11
        "(-10,10) scaled rolling deltas",              ## 12
        "(0,1) scaled substract",                      ## 13
        "(0,10) scaled substract",                     ## 14
        "(-10,10) scaled substract",                   ## 15
        "z-scaled substract",                          ## 16
        "no",                                          ## 17
        "pca",                                         ## 18
        "ica",                                         ## 19
        "BoxCox",                                      ## 20
        "YeoJohnson",                                  ## 21
        "expoTrans",                                   ## 22
        "range",                                       ## 23
        "scale",                                       ## 24
        "spatialSign",                                 ## 25
        "center and scale"                             ## 26
    )
    
    msg("Startup OK!")
}


##' @export
SelectColsByPredix <- function(table, prefix)
{
    subset(table, select=grepl(prefix,colnames(table)))
}

## supply a vector or list of data str names to remove from global env
## only remove those that exist to avoid tons of warnings; also assert
## that none of the specifed structures really are in env after rm
## call
##' @export
mrm <- function(v, verbose=FALSE)
{
    to_remove <- v[laply(v,.fun=function(i) exists(i,where=.GlobalEnv))]
    ## only do something if any of given datastrs are bound to the env
    if ( length(to_remove)>0 ) { 
        if ( verbose )
            cat("\nRemoving existing datastructures:",to_remove)
        rm( list = to_remove, envir=.GlobalEnv ) 
        not_exist <- v[ laply(v,.fun=function(i) !( exists(i,where=.GlobalEnv)) ) ]
        if ( identical( v, not_exist) ) {if (verbose) cat("...check clean!\n")
        } else if (verbose) {
            cat("...unable to remove:",v," from ",not_exist,"\n")
        }
    }
}

## construct formula string from all column names in dataframe/table
##' @export
cfa <- function(y, table) {
    paste(y,'~',striplast(paste( colnames(Cout),"+",collapse=" ")),collapse=" ")
}

## construct formula sting from all column names in dataframe/table
##' @export
cf <- function(i,table) {
    paste(colnames(table)[i],'~.',collect="") }

## extract named or numbered vector from data table, frame or matrix
##' @export
dt2v <- function(sd=fitOUT, name="Ca") { as.vector(as.matrix( subset(sd, select=name) ))  }

## round every col differently according to spec given in list with
## corresponding names
##' @export
roundbycol <- function(t,spec) {
    ## check if columns in spec are also in the table then do it
    round_names <- intersect(names(spec),colnames(t))
    out<-as.data.table(llply(round_names,.fun=function(colname){
        round(dt2v(t,colname),spec[[colname]])},.parallel=TRUE) )
    colnames(out)<-round_names
    return(out)
}

##' @export
smartround <- function(t, roundto=Inf ) {
    if (!roundto==Inf) {
        
        if ( class(roundto)=="list" ) { 
            out <- roundbycol(t,roundto) }
        else { 
                out <- round(t, roundto) }
    }
    else { out <- t }
    return(out)
}

## check head and tail of the surrogate output to response table
##' @export
CHT <- function(real_out=data.table(valOUT), s_outp=SRes) { 
    ## print( real_out )
    ## print( s_outp )
    ident <- identical(real_out,s_outp)
    cat("\nIDENTICAL OUTPUTS?:",ident,"\n")
    if (!ident) {
    }
}

### Parameter overlap determination
## we check for prediction errors, find their indices thus determining
## the parameter space regions where they reside
##' @export
paralap <- function(real_out=data.table(valOUT), s_outp=SRes, inp=data.table(valIN) ) { 
    ## 1. substract output values from predictions
    dif <<- outminus(SRes,data.table(real_out)) 
    ## 2. get the indexes where difference>0 for each output column 
    colerridx <<- llply(seq(ncol(dif)), .fun=function(i) {seq(nrow(dif))[dt2v(dif,i)>0]},.parallel=TRUE )
    names(colerridx)<<-colnames(real_out)
    ## all error indexes 
    allerridx <<- sort(unique(unlist(colerridx,use.names=F)))
    ## 3. collect actual values that are mispredicted at their idx locations
    allcolerrvals <<- llply(seq(ncol(dif)), .fun=function(i) { dt2v(SRes,i)[ colerridx[[i]] ]},.parallel=T )
    colerrvals    <<- llply(allcolerrvals,.fun=function(vals) {sort(unique(vals))} )
    colerrfreq    <<- llply(seq(ncol(dif)), .fun=function(i) { as.numeric(ftable(allcolerrvals[i])) })
    names(colerrvals)   <<-colnames(real_out)
    names(allcolerrvals)<<-colnames(real_out)
    names(colerrfreq)   <<-colnames(real_out)
    ## uniqerrvals<<-llply(colerrvals, .fun=function(vals) { unique(vals) },.parallel=T )
    ## 4. how many real values are the same as the error values
    overlapcount <<- llply(seq(ncol(dif)), .fun=function(i) { 
        ## for each error value find where its duplicates are
        as.numeric( 
            llply(colerrvals[[i]],.fun=function(errval) {
                ## how many real values overlap the with the mispredicted value
                sum( dt2v(real_out,i)==errval )
            }))
    },.parallel=T )
    ## 5. collect input parameters for the erroenous predictions
    errparas <<- llply(seq(ncol(dif)), .fun=function(i) { inp[ colerridx[[i]], ]},.parallel=TRUE )
    return(overlapcount)
}

## unique values in column, to retrieve samples from design table
## takes data.table or data.frame
##' @export
uvc <- function(t) { 
    out <- llply( colnames(t), .fun=function(col) { unique( dt2v(t,col) ) }, .parallel=TRUE )
    names(out) <- colnames(t)
    return(out)
}

##' @export
uvcm <- function(t){ lapply(uvc(t),FUN=function(col) min(col) ) }

## unique column value dataframe
##' @export
uvt <- function( inT, outT, fun=coluniratio ) { 
    common_names <<- base::intersect( colnames(inT), colnames(outT))
    data.frame(OUT = fun( subset(outT,select=common_names) ),
               IN  = fun( subset(inT, select=common_names) ),
               row.names=common_names) }

# ratio of unique values among all 
##' @export
coluniratio <- function(t, roundto=Inf) {
    round(coluniquevals(t,roundto=roundto)/nrow(t),4)
}

##' @export
coluniquevals <- function(t, roundto=Inf) {
    laply(colnames(t), .fun=function(col) {
        if (!roundto==Inf) {colvals <- round ( dt2v(t,col), roundto )}
        else {colvals <- dt2v(t,col)}
        uvals   <- length( unique(colvals) )
        return(uvals)
    })
}

##' @export
allcoluniquevals <- function(t, roundto=8, para=TRUE) {
    auvals <- llply(colnames(t), .fun=function(col) {
        colvals <- round ( dt2v(t,col), roundto )
        uvals   <- sort(unique(colvals))
        return(uvals)
    },.parallel=para)
    names(auvals) <- colnames(t)
    return(auvals)
}

## how many values are shared between training and validation sets
##' @export
sharedvalues <- function(t1,t2, roundto=Inf, para=TRUE) {
    if (! (length(intersect( colnames(t1),colnames(t2)))==length(colnames(t1))  ))  {
        stop("ERROR: The given tables have different column names!")}
    svals <- llply(colnames(t1), .fun=function(col) {
        col1 <- dt2v( t1, col )
        col2 <- dt2v( t2, col )
        length( intersect(col1,col2) )/(nrow(t1) + nrow(t2))
    },.parallel=para)
    names(svals) <- colnames(t1)
    return(svals)
}

##' @export
SelectActiveColumns <- function(t) {
    ## return the data.frame/ table where columns have more than 1 value
    coluvals <- coluniquevals(t)
    ## cat("\nColumn unique val counts:\n",coluvals,"\n\n")
    subset(t, select=seq(ncol(t))[!(coluvals==1)] )
}

## return the data.frame/ table where columns have more than 1 value
##' @export
SelectMinActiveColumns <- function(t,mincount=5) {
    coluvals <- coluniquevals(t)
    ## cat("\nColumn unique val counts:\n",coluvals,"\n\n")
    subset(t, select=seq(ncol(t))[!(coluvals<mincount)] )
}

##' @export
nan.to.zero <- function(dfrm) { d2 <- dfrm
                                d2[is.nan(d2 <- dfrm)] <- 0
                                d2 
}

##' @export
na.to.zero <- function(dfrm) { d2 <- dfrm
                               d2[is.na(d2 <- dfrm)] <- 0
                               d2 
}

##' @export
to.zero <- function(dfrm,testfunc=is.na) { 
  d2 <- dfrm
  d2[testfunc(dfrm)] <- 0
  d2 
}

##' @export
colwise_RSS <- function( t1,t2 ) {
    cols <- union( colnames(t1), colnames(t2) ) # make sure we compare the same stuff
    data.frame( RSS=laply(cols,.fun=function(colname) { 
        sum( (subset(t1,select=colname)-subset(t2,select=colname))^2 )
    },.parallel=TRUE),row.names=cols )
}

##' @export
RSS <- function(v1,v2) { sum( (v1-v2)^2 ) }

## abs max error
##' @export
AME <- function(v1,v2) { max(abs(v1-v2)) }

## sum of absolute deviations
##' @export
SAD <- function(v1,v2) { sum( abs(v1-v2) ) }

## mean of absolute deviations
##' @export
MAD <- function(v1,v2) { mean( abs(v1-v2) ) }

##' @export
namewithin <- function(s1,number,s2) { paste0(s1,number,s2,collect="") }

##' @export
striplast <- function(s) { striplastx(s,1) }

##' @export
striplastx <- function(s,n=1) { substr(s,1,nchar(s)-n) }

## random sample of idxes from supplied number of rows in design dable
## and percentage ratio of how much should be sampled
##' @export
rsi <- function(n,ratio) { sample( n, n*ratio ) }

## col-wise rolling deltas
##' @export
Deltas <- function(dfrm) {
    dfrm[2:nrow(dfrm),]-dfrm[1:nrow(dfrm)-1,]
}

## Obtain min max and max-min range of data frame columns
##' @export
GetRanges <- function(dfrm) {
    savenames <- names(dfrm)
    ranges <- ldply(dfrm,.fun=function(col) { mm=range(as.numeric(col),na.rm=T,finite=T); c("min"=mm[1], "max"=mm[2] ) },
                    .parallel=TRUE,.id=NULL )
    rownames(ranges) <- savenames
    return(ranges)
}

## DATA EXTRACTION AND RESHAPING FOR MARCO'S RT EXAMPLE - Note, the
## res_full from Marco's example script must be loaded reshaping the
## data makes it easier to work with
##' @export
TByElem <- function(list_of_elems, nested_index=1,
                    attach_transport_timesteps=FALSE,
                    attach_element_numbers=FALSE)
{ 
    
    if (nested_index>0) { 
        elems <- nrow(list_of_elems[[1]][[nested_index]]) # get the number of elems in nested str
        out <- data.table( ldply( seq( length(list_of_elems)-1),.fun=function(i) {
            list_of_elems[[i]][[nested_index]]}
            )) 
    } else { 
        elems <- nrow(list_of_elems[[1]])
        out <- data.table( ldply(list_of_elems))
    }
  
    if (attach_transport_timesteps) {
        if (nested_index==1) {
            timesteps <- length(list_of_elems)-1 
            Ts <- rep( seq(1,timesteps,1), elems )
            out[,timestep:=Ts]
        }
    }
  
    if (attach_element_numbers) {
        elems <- sort(Ts)
        out[,ELEM:=elems]
        keycols=c("ELEM","timestep")
        keycols=c("timestep")
        setcolorder(out, union( keycols, setdiff(names(out),keycols )))
        if (nested_index==1) {out[,timestep:=Ts]}
    } 
    return(out)
}

## takes a table and returns it scaled to a new range, while allowing
## to define custom starting range for each col this is specific to
## the element-wise surrogate approach because the output is re-used
## as input in other cells they need the same normalization across
## both input and output
##' @export
rescaling <- function(t, old_ranges_table=FALSE, target_min=0,
                      target_max=1, target_ranges_table=FALSE)
{ 
  #TODO: (Fin[1,]-attr(Tin,"scaled:center"))/attr(Tin,"scaled:scale") #MAKE THIS INLINE
  
  ## if target ranges are not supplied for each column, then create
  ## this table from defaul 0 and 1
    if (target_ranges_table==FALSE) { 
        target_ranges <<- data.frame( 
            row.names = rownames(originalIOranges),
            min = rep(target_min,length(rownames(originalIOranges)) ),
            max = rep(target_max,length(rownames(originalIOranges)) )
        )
    }
    ## if ( target_min==NULL || target_max==NULL) stop("error rescaling:: No target range supplied!")
    if ( target_min > target_max)
        stop(paste("error rescaling:: min exceeds max",target_min,target_max))
    if ( !(class(old_ranges_table)== "data.frame") )  {
        old_ranges_table <- GetRanges( t )
        cat("Rescaling calculated initial ranges for columns as no custom ranges supplied!\n")
    }
    sapply(colnames(t),FUN=function(colname) { 
        custom_scaler( dt2v(t,colname),
                      old_ranges_table[colname,"min"],old_ranges_table[colname,"max"],
                      target_ranges[colname,"min"],target_ranges[colname,"max"])
    })
}

## substract columns, but only those dt2v(Deltas(Oout),1) present in
## the output table
##' @export
outminus <- function(inp, outp) {
    ## substract the the output columns from 
    vect <<- llply( colnames(outp),.fun=function(col) { dt2v(outp,col)-dt2v(inp,col) },.parallel=TRUE )
    names(vect) <<- colnames(outp)
    as.data.table(vect)
}


##' @export
colwise_rescale <- function(t, minval=0, maxval=1) {
    data.frame(llply(t,.fun=function(colu) { 
        rescale(colu,c(0,1)) }, .parallel=TRUE ))
}

##' @export
custom_scaler <- function(num_vect,
                          from_min,from_max,
                          to_min,to_max) {
                              ((to_max-to_min)*(num_vect-from_min))/(from_max-from_min)+to_min
}

## Mean absolte scaled error,
## http://robjhyndman.com/papers/foresight.pdf
## http://stackoverflow.com/questions/11092536/forecast-accuracy-no-mase-with-two-vectors-as-arguments
##' @export
MASE <- function(f,y) {
    ## f = vector with forecasts, y = vector with actuals
    if(length(f)!=length(y))
        stop("Vector length is not equal") 

    n <- length(f)
    res <- mean(abs((y - f) / ((1/(n-1)) * sum(abs(y[2:n]-y[1:n-1])))))
    return(res)
}

##' @export
FastClust <- function(dfrm, clustnum=7, g=TRUE, link_type="complete") {
    require(amap) # provides parallel distance calc, default dist stalls with small data

    hc <- hcluster(dfrm, method="euclidean",link=link_type,
                   nbproc=safe_get_cores(), diag=TRUE, upper=FALSE)
    if (g)
        plot(hc)
    
    cms <- data.frame( membership=cutree(hc,clustnum) )
    clusterIDs <- unique( cms$membership )
    llply( clusterIDs, .fun=function(clnum) row.names(subset(cms, subset=(membership==clnum) ) ) )
}


##' @export
safe_get_cores <- function() {
    ## register parallelization backends on anyhing but win, due to missing fork()
    if ( !.Platform$OS.type=='windows') {
        require(doMC)
        require(parallel)
        ## detect using 
        report_cores = detectCores() }
    else report_cores = 1
    return( report_cores )
}

##' @export
BestModelCluster <- function(dt,by="C",criteria="MASE",clusters=10) {
    as.numeric( FastClust(subset(dt[(output == by)],select=criteria), clustnum=clusters)[[1]] )
}

## non-propogating simulation error controller takes all input
## matrices from RT run from simulator and uses SelectedSurrogate on
## each of them seperately to predict the simulator outputs at each
## step. WARNING: this does not imply input-output re-use as
## neccessary for full reactive transport emulation. This is simply
## aimed at debugging!
##' @export
NPSC <- function(simulation_data = res_sim,
                 inputs_name = "T",
                 outputs_name= "C",
                 in_round  = Inf, # re-round input that goes into the predictor
                 out_round = Inf, # round the output that comes out
                 sim_round = Inf, # round the simulator output used for comparison
                 show_head = 0, # show this much in head and tail of the error matrix
                 para=TRUE) {
    r <- llply(seq(length(res_sim)-1),function(i) {
        cat("\n",i," ")
        
        r <- outminus(smartround(simulation_data[[i]][[outputs_name]],sim_round),
                      smartround(
                          SelectedSurrogate(
                              smartround( simulation_data[[i]][[inputs_name]],in_round)),out_round) )
        if (show_head>0) { 
            cat("\n")
            print(head(r,show_head)) 
            print(tail(r,show_head)) 
        }
        return(r)
    },.parallel=para)

    return(r)
}

## test surrogate error drift when called repeated on own IO
##' @export
SDrift <- function( start_state = res_sim[[100]][["T"]], r = 50, head=10 ) {
    lastsur <<- SelectedSurrogate(start_state)
    lapply(seq(r),FUN=function(i){
        lastsur <<- head( SelectedSurrogate(lastsur) )
    })
}

##' @export
Tminus <- function(simulator_output=res_sim, 
                   surrogate_output=res_sur, 
                   nested_name="C", 
                   show_head=0 ) {
    if ( length( simulator_output)==length(surrogate_output) ) {
        r <- llply( seq(length(simulator_output)-1),
                   function(i) {
                       cat("\n",i," ")
                       r <- outminus( simulator_output[[i]][[nested_name]], surrogate_output[[i]][[nested_name]] )
                       if (show_head>0) {
                           cat("\n")
                           print( head(r,show_head) ) 
                           print( tail(r,show_head) ) 
                       }
                       return(r)
                   })
    } else {
        cat("FAIL: Simulator and surrogate output length differ!")
    }
}

##' @export
CompareTimesteps <- function(simdata     = res_sim,
                             surdata     = res_sur,
                             timestep    = 100,
                             nested_name = "C",
                             namepref    = paste0(GetModelNames()[[1]]," (",current_method,") ",current_preproc))
{
    tryCatch({
        simres <- simdata[[timestep]][[nested_name]]
        surres <- surdata[[timestep]][[nested_name]]
        
        writecols <- intersect( colnames(simres),colnames(surres) )
        simnewnames <- paste0(writecols, "_simulated")
        surnewnames <- paste0(writecols, "_predicted")
        writedata <- cbind( simres[,writecols], surres[,writecols] )
        
        colnames(writedata) <- c(simnewnames,surnewnames)
        if (!exists("ens_batch_name")) {
            ens_batch_name <<-paste0("SimSur_data/",namepref,"_step_",timestep,"_compare.csv")
        }
        if (!exists("ens_perftop_name")) {
            ens_perftop_name <<-paste0("SimSur_data/",namepref,"_step_",timestep,"_perftop.csv")
        }
        write.csv(writedata,ens_batch_name)
        write.csv(perftop,ens_perftop_name)
        mrm(c("ens_batch_name","ens_perftop_name"))
    },# end of tryCatch
    warning = function(cond) {
        message(cond)
    },
    error = function(cond) {
        cat("\nError when comparing timesteps!\n")
        ## print(head(writedata))
        message(cond)
    })
}

##' @export
ShowTopProfiler <- function(profiler_output, top=100, show=T) {
    profiler_summary <- summaryRprof( filename = profiler_output )
    pr <- head(profiler_summary[[2]],top)
    if (show) {
        cat('Top functions by\n')
        print( pr )
    }
    return(pr)
}

## exclude column using subset and set difference from dfrm/DT/matrix
##' @export
exc <- function(table_like, exc_cols) {
    exclude_cols_actually_present <- exc_cols[exc_cols %in% colnames(table_like)]
    subset(table_like, select <- setdiff(colnames(table_like),exclude_cols_actually_present) )
}

##' @export
SparseChangeCluster <- function(out_dfrm) {
    ## 1. get differences by changing 
    Deltas(out_dfrm)
    ## 2. estiamate initial number of clusters for this output table (can be 1 or more outputs)
    
    ## 3. get input value ranges for the clusters
    
    ## 4. get output value ranges for the clusters
    
    ## return a structure that has input and output clusters
}

##' @export
RangeTableCreator <-function(original_table,extra_table,col=1) {
    ## iterate over member list, take members subset original table by
    ## members, get range write range in return list
    col_member_list <<- FastClust( extra_table[[col]],3)
    col_ranges_list <<- llply(col_member_list,.fun=function(inds) {range(original_table[[col]][as.numeric(inds)]) })
    return(col_ranges_list)
}

## find specific types of columns in data.table/frame
##' @export
coltypes <- function(intable) {
    sapply(intable, FUN=class)
}

##' @export
seekcoltypename <- function(intable, seektype) {
    names(which( coltypes(intable)==seektype))
}

##' @export
seekcoltypeidx <- function(intable, seektype) {
    array(which( coltypes(intable)==seektype))
}

##' @export
f2i <- function(intable,seektype) {
    factcols <- seekcoltypename( intable, seektype )
    rtable <- exc( intable, factcols)
    if (length(factcols)>0) {
        enumcols <- as.data.table(sapply(factcols, FUN=function(fcol) {
            datavals <- dt2v(intable,fcol)
            fmap <- unique(datavals)
            names(fmap) <-seq(length(fmap))
            match(datavals,fmap)
        }))
        out<-cbind(rtable,enumcols)
    }
    else out<-intable
    return(out)
}

##' @export
exc_type <- function(intable, exclude_type="factor") {
    exc(intable, seekcoltypename(intable,exclude_type) )
}

##' @export
take_top_pct_cols <- function(indata, pct=0.33 ) {
    sqrd <- order(indata^2)
    alen <- length(sqrd)
    topx <- sqrd[1:round(alen*pct,0)]
    return(rownames(indata)[topx])
}

##' @export
mda_mars_importance <- function(mda_mars_model) {
    fsum <- colSums(abs(mda_mars_model[["model"]][["factor"]] ))
    names(fsum)[fsum > 0]
}

##' @export
all_mda_mars_impvars <- function( modellist )
{
    sapply( modellist, FUN=mda_mars_importance )
}

##' @export
CheckColsNumValues <- function(dfrmlike)
{
    col_uniq_values <- coluniquevals( dfrmlike )
    names(col_uniq_values) <- colnames(dfrmlike)
    return(col_uniq_values)
}

##' @export
Cols2Fact <- function(dfrmlike, thresh=100, para=TRUE)
{
    cuv <- CheckColsNumValues(dfrmlike)
    cuv <- cuv[cuv<=thresh]
    if (length(names(cuv))>0) {
        cat("Columns with low number of unique values:\n")
        print(cuv)
        fcs <- as.data.table( llply( names(cuv), .fun = function(col) { factor(dt2v(dfrmlike,col)) },.parallel=para ) )
        colnames(fcs) <- names(cuv)
        out <- cbind( subset(dfrmlike,select=setdiff(colnames(dfrmlike),names(cuv)) ), fcs )
    } else {
        out <- dfrmlike
    }
    return(out)
}


########################################################################
#### from here functions dealing with machine learning infrastructure,
#### dice and caret

## caret needs an advanced parameter tuning grid as data.frame for the
## models that depend heavily on funky parametrization for their
## effectiveness multiTuneGrids contain presumably sensible designs of
## such tuning grids singularTuneGrids take the most "epic" tune
## configuration and use it when tuning is disabled on caret train
## call, this means just direct fitting, to supplied data, without
## using the full tunegrid

## TODO: check traincontrol function for automatic fraction and
## resampling. MAYBE not everything is passed in

##' @export
createTuneGrids <- function() {
    cat('\nCreating tuning grids for caret models...\n\n')
    multiTuneGrids  <<- 
        list(
            "bayesglm"      = NULL,
            "rlm"           = NULL, ## tends to perform well and fast sometimes
            ## "gaussprLinear" = NULL ## consumes too much time / resources / dies
            "glm"           = NULL, 
            ##"nnls"          = NULL, ## the predict method is broken for this one, try after update to caret
            "lmStepAIC"     = NULL, ## decent for simpler cases, fast, but fails often too
            "glmStepAIC"    = NULL, ## decent for simpler cases, fast, but fails often too
            "leapBackward"  = list(data.frame ( nvmax = seq( 1, ncol(Fin)-1, 1 ) ) ),
            "leapForward"   = list(data.frame ( nvmax = seq( 1, ncol(Fin)-1, 1 ) ) ),
            "leapSeq"       = list(data.frame ( nvmax = seq( 1, ncol(Fin)-1, 1 ) ) ),
            "treebag"       = NULL,
            "lda"           = NULL,
            "ppr"           = list(data.frame (    nterms=seq(1,round(ncol(Fin)*.8,0),2))),  ## fast, often good
            ## qrnn very slow in training, decently fast and accurate in prediction, but no better than brnn and others good ones
            "qrnn"          = list(data.frame (    n.hidden=ncol(Fin)*2,penalty=2,bag=F ) ), 
            ## very slow in prediction, bad results
            ##"mlp"           = list(data.frame (    size=4 ) ) ## very slow and bad predictions
            ## these rbf guys are slow and give catastrophically horrifying results, maybe their parameters are completely off...
            ##"rbf"           = list(data.frame(size=5 ) ) ## very slow and bad predictions
            ##"rbfDDA"        = list(data.frame(negativeThreshold=0.1 ) ) ## really slow, mostly fails
            ##"Boruta"        = list(data.frame(mtry=ncol(Fin) ) ) ## slow, bad predictions
            "qrf"            = list(data.frame(mtry=7)), ## kind of slow in prediction, sometimes very good results
            "parRF"          = list(data.frame(mtry=7)), ## kind of slow in prediction, sometimes very good results
            "Rborist"        = list(data.frame(predFixed=ncol(Fin))), ## kind of slow in prediction, sometimes very good results
            ##"cforest"       = list(data.frame(mtry=ncol(Fin) ) ) ## resource hog, too slow in prediction, tolerable results, but not very good
            ## blackboost - not bad, but not very good, slowish also
            ##"blackboost"    = list(data.frame (    mstop=50, maxdepth=ncol(Fin) ) ) ## I also killed this one
            "kernelpls"     = list(data.frame(ncomp=seq(1,ncol(Fin)))), 
            ##"gaussprRadial" = list(data.frame(sigma=c(0.5,1) )) ## too slow
            "pcr"           = list(data.frame(ncomp   = seq( 1, ncol(Fin)-1))), ## perform well/decent
            "pls"           = list(data.frame(ncomp   = seq( 1, ncol(Fin)-1))),
            "simpls"        = list(data.frame(ncomp   = seq( 1, ncol(Fin)-1))),
            "enpls"         = list(data.frame(maxcomp = seq( 1, ncol(Fin),1))),
            "icr"           = list(data.frame(n.comp  = seq( 1, ncol(Fin),1))),
            ## lars(es) tends to perform well
            "lars"          = list(data.frame(fraction= c(seq(0.9,0.99,0.01),0.999))), 
            "lars2"         = list(data.frame(step    = seq(1,ncol(Fin),1))),
            "lasso"         = list(data.frame(fraction=c(seq(0.95,0.99,0.01),0.999))),
            "blassoAveraged"= NULL,
            "BstLm"         = list(data.frame(mstop=seq(ncol(Fin)),nu=0.5)), ## takes too long
            "enet"          = list( expand.grid(fraction=rev(seq(0.01,0.5,0.1)),
                                                lambda=seq(0.1,0.5,0.1))), ## bad predictions
            ## brnn good x-validation results, slow in training phase
            "brnn"          = list(data.frame(neurons=ncol(Fin)*2)), 
            ## drnn fast in training, weird tuning:
            "dnn"           = list(data.frame(layer1=100, layer2=100, layer3=1000,
                                              hidden_dropout=0.1,
                                              visible_dropout=0.1)),
            "elm"           = list(expand.grid(nhid=c(50,100),  ## fast in training, weird tuning
                                               actfun=c("purelin","poslin","tribas","tansig","satlins","hardlim",
                                                        "radbas","sin","sig"))),
            "bagEarth"      = list(data.frame(nprune=seq(4,10,1), ## slowish and weak
                                              degree=seq(4,10,1))),
            "bagEarthGCV"   = list(data.frame(degree=seq(1,ncol(Fin),1))),
            ## "nodeHarvest"   = list( expand.grid(    maxinter=rev(seq(1,ncol(Fin),1)),mode="mean") ) ## resource hog, slow with weak results

            ## this guy will need more understanding on tuning, maybe useful, but slow and much work
            "deepboost"     = list(data.frame (num_iter= 100,
                                               tree_depth=ncol(Fin),
                                               beta=0,
                                               lambda=0.00125,
                                               loss_type="e")),
           "logreg"    	 = list(data.frame (treesize =100, ntrees=100)), ## something about predicting binary stuff
           "ANFIS"    	 = list(data.frame (num.labels=5, max.iter=10)), ## way too slow...probably
           "gbm"         = list( expand.grid(n.trees = 1000, 
                                             ## n.cores = 8,
                                             interaction.depth = seq(2,5,1), 
                                             shrinkage = 0.0001, ## important to tune well
                                             n.minobsinnode = rev(seq(6,20,2)))),
           "xgbTree"        = list( expand.grid(nrounds  = c(700,1500,2000),
                                                max_depth = seq(2,30,2),
                                                eta  = c(0.01,0.1,0.15),
                                                gamma = c(0.01,0.05,0.1,0.2),
                                                colsample_bytree = 0.95,
                                                min_child_weight = c(5,10,100,25),
                                                subsample  = 0.95)),
           "xgbLinear"      = list( expand.grid(nrounds  = c(20,50,80,120,150,180,200,250,300,5000),
                                                alpha = 0,
                                                eta  = c(0.01,0.03,0.05,0.1,0.15),
                                                lambda = 0 )), ## performs well on Kaggle stuff, could be faster in running, but not bad
           ## "ctree"          = list(data.frame(mincriterion=0.99 )), ## does not perform well and is a resource hog
           ## "ctree2"         = list(data.frame(maxdepth=seq(2, ncol(Fin)*3, 1))), ## does not perform well
           ## our problem is unsuitable for widekernel
           "widekernelpls"  = list(data.frame(ncomp=seq(2,ncol(Fin)))), 
           ## "rvmLinear"     = NULL ## way way too slow
           ## cubist is really slow like 100x than others with this tunegrid
           "cubist"         = list(data.frame( neighbors=seq(3, 9, 1),committees=seq(3,9,1) )  ),
           ## this model seems to perform badly
           "svmRadialCost"  = list(data.frame(      C=c(  0.1, 0.001, 0.0001 ) ) ), 
           "ridge"          = list(data.frame( lambda=c(0,0.1, 0.001, 0.00001) ) ),
           "foba"           = list( expand.grid( k=seq(1, ncol(Fin) ), lambda=c(0.05)) ),
           "bridge"         = NULL,
           "rpart1SE"       = NULL,
           "rpart2"         = list( expand.grid( maxdepth = seq(1, 30, 1) ),
                                   list( cp=0.00001, minbucket=2,minsplit=2) )
           ## "rpart"         = list(data.frame( cp=c(0.0001,0.00001),  ## tune grid with officially tunable parameters
           ##                   list( minsplit=2, minbucket=2)        ))   ## other parameters that are given to train through passthrough
           ##                   minsplit=2, minbucket=2        ))   ## other parameters that are given to train through passthrough
        )

    ## for this we take the most extreme parameter combinations from the multi tune grid
    singularTuneGrids  <<- lapply( seq(1, length(multiTuneGrids), 1), FUN = function(i) {
        tune_content <- multiTuneGrids[[i]][[1]] ## take the tuneGrid data.frame
        if (class(tune_content)=="NULL") {
            result = NULL
        } else if (class(tune_content)=="data.frame") { 
            lastrow <- nrow(tune_content)
            result <- tune_content[lastrow,,drop=FALSE]
        }   

        if ( length(multiTuneGrids[[i]]) == 1) {
            result <- list( result )
        }

        if ( length(multiTuneGrids[[i]]) == 2) {
            result <- list( result, multiTuneGrids[[i]][[2]] )
        }
        return( result )
    })
    names(singularTuneGrids) <<- names(multiTuneGrids)
}

##' @export
FitWithDice <- function( fit_in, fit_out, m="PolyMARS_GCV1" ) {
  if (m=="MARS3"||m=="PolyMARS3") {
    m = striplast(m)
    model = modelFit( fit_in, fit_out, type=m, degree=ncol(fit_in), penalty=ncol(fit_in), thresh=0.0001, gcv=1, trace=T)
  }
  else if (m=="PolyMARS_GCV1") { 
    m = striplastx(m,5)
    model = modelFit( fit_in, fit_out, type=m, gcv=1) 
  }
  else if (m=="PolyMARS") { 
    model = modelFit( fit_in, fit_out, type=m, gcv=4) 
  }
  else if (m=="MARS") { 
    model = modelFit( fit_in, fit_out, type=m, degree=2) 
  }
  else if (m=="Linear") { 
    model = modelFit( fit_in, fit_out, type=m, degree=2) 
  }
  else { 
    model = modelFit( fit_in, fit_out, type=m ) 
  }
  return(model)
}

## learn the surrogate using supplied methods
##' @export
FitSurrogates <- function(## fitIN, fitOUT,
                          ## indices,
                          method = "MARS", ## assume all are MARS if not given
                          preprocessing_meth_inds = c(),
                          fitting_config=c(),
                          ## dot not fit the variable to self, if names match
                          exclude_self = FALSE,
                          tune = FALSE,
                          para = FALSE)
    ## there are two ways that this is called - in batch screening mode, when the model type is 
    ## 1. always the same, due to how iterators in main are built (the same method for all)
    ## 2. from refit, when the best model types are selected from screening with their preprocessing attached
{ 
    response_vector_names <<- paste0("response_vector_", colnames(Fout),sep="")
    mrm( c("PPCout","PPC","model_list", response_vector_names))
    t <- system.time( model_list <<- llply( seq( ncol(Fout) ), .fun=function(i) {
        ## first get the training data samples
        ## if indices are a list then, for each variable we take different ones    
        ## if ( class(inds)=="list" ) {
        ##  idxes <- inds[[i]]
        ##  fitIN <- Fin[ idxes, ] ## access the i-th column-wise resampling index vector
        ##  fitOUT<-Fout[ idxes, ] ## access the i-th column-wise resampling index vector
        ## } else { #}
        
        ## if ( length(inds)==nrow(Fin) ) { ## if all the data is used for training then just do it
        ##	fitIN <- Fin
        ##	fitOUT<- Fout
        ##} else {
        fitIN <- Fin[ inds, ]
        fitOUT<-Fout[ inds, ]
        ##}
        
        fitIN <- SelectActiveColumns(fitIN)
        fitOUT <- SelectActiveColumns(fitOUT)
        
        ## fit a separate model of this method for each col
        ## select all neccessary data and settings for fitting output-wise surrogate model
        tryCatch({
            outname <- colnames(fitOUT)[i]
            cat( outname,' ') ## show which output 
            resp_name <- response_vector_names[i]
            assign( resp_name, dt2v(fitOUT,outname) )#, envir=.GlobalEnv )
            ## if preprocessing vector has anything specified, then check that it contains 
            ## a spec for every output and then run it through PreProc
            if ( length( fitting_config )>0 ) {
                method  <- as.character( fitting_config[outname,"method"] )
                SelectPreProc( match(fitting_config[outname,"preprocessing"],specific_preprocessing_methods), v=F)
                cat(" ",method,as.character(fitting_config[outname,"preprocessing"]), "\n" )
                fitIN <- as.matrix( PPC(fitIN) )
                if (exclude_self) { 
                    cat("\nexcluding",outname,"\n")
                    fitIN <- exc(fitIN,outname)
                    ## print(head(fitIN))
                }
                ## if output also has to be preprocessed then do it again!
                if (exists("PPCout")) { 
                    ## use assign to create different names for each output response 
                    assign( resp_name, PPCout(fitIN, dt2v(fitOUT,outname) ) )#, envir=.GlobalEnv )
                }} 
            
            ## OK start fitting the models depending on the supplied method descriptions
            ## if (method %in% DiceMethods) { model = FitWithDice(fitIN, get(resp_name,envir=.GlobalEnv), method)  }
            if (method %in% DiceMethods) { model = FitWithDice(fitIN, get(resp_name), method)  }
  
            ## direct calls to some packages
            ## call mars directly with custom parameters
            if (method == "mda_p01")     { model = mars(fitIN, get(resp_name),#,envir=.GlobalEnv),
                                                        thresh=0.0000001,
                                                        ## penalty=ncol(fitIN),
                                                        penalty=round( ncol(fitIN)*0.9,0),
                                                        degree =round( ncol(fitIN)*0.9,0) ) }
            
            ## call mars directly with custom parameters
            if (method == "polymars_p01"){ model = polymars(get(resp_name), fitIN,
                                                            additive=TRUE, gcv=0.01 ) }
            
            ## attempt directly tunable CART fit
            if (method == "rpart_anova_direct")  {
                model <- rpart(cf(i,fitIN), as.data.frame(fitIN), 
                               method="anova",control=rpart.control(minsplit=3,
                                                                    cp=0.00001,
                                                                    minbucket=2))
            }
    
            ## all other that have tuning grids are assumed to be
            ## caret methods and trained through the caret interface
            if (method %in% names(multiTuneGrids)) {
                ## this gets a bit tricky. we support arbitrary
                ## parameters not allowed by train tuneGrid to do this
                ## we build a custom call for train that passes also
                ## these extra named params to tune which then passes
                ## them thruogh to the actual model fit call in the
                ## correct way
                ## if (!tune) { train_call  <<- list( as.name("fitIN"), as.name("response_vector"), method=method,
                if (!tune) {

                    train_call  <- list( as.name("fitIN"), as.name(resp_name), method=method,