-
Notifications
You must be signed in to change notification settings - Fork 0
/
.Rhistory
512 lines (512 loc) · 28.3 KB
/
.Rhistory
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
dx <- matrix(0, nx, 2151); kk <- 0
for(day in dates){
for(k in 0:(nx_dates[which(dates == day)]-1)){
kk <- kk + 1
#f_name <- paste0("~/Dropbox/research/projects/nirs/data/datasets/Burkina NIRS Data/Activity 1 - Age/Experiment 1, comparative age/E1Age_",day,"_", formatC(k, width = 5,flag = 0),".txt")
f_name <- paste0("~/DROPBOX_overflow/research/projects/nirs/data/datasets/Burkina NIRS Data/Activity 1 - Age/Experiment 1, comparative age/E1Age_",day,"_", formatC(k, width = 5,flag = 0),".txt")
dx[kk,] <- read.table(file = f_name, header=T, sep="\t")[,2]
}
}
# average replications
if(Params$avg_replics){
data_X <- c()
for(i in unique_IDs){
if(length(idx[[i]]) > 1){
data_X <- rbind(data_X, colMeans(dx[idx[[i]],]))
}else{
data_X <- rbind(data_X, dx[idx[[i]],])
}
}
}else{
data_X <- dx[select,]
}
# read response (y)
i_y <- select & ((1:nrow(data)) %in% unlist(sapply(idx, "[[", 1)))
data_y <- data[i_y,"Age"]
# raw data
raw_data <- data[i_y,]
return(list(X = data_X, y = data_y, n_replics = n_replics[n_replics != 0], raw_data = raw_data))
# re-save with simple layout
#data_export <- data.frame(y = y, X = X)
#write.table(data_export, file="~/Dropbox/research/projects/nirs/data/datasets/experiments_Tom/A1_sporozoites/DATASET_sporozoites_2017_06_01.txt", sep=",", row.names=F, col.names=T)
}#load_B_A1E1
load_B_A2T2 <- function(Params){
# read data
data <- read.csv(file = "~/Dropbox/research/projects/nirs/data/datasets/Burkina NIRS Data/Activity 2 - Pf Infection/NIRS_TEMPLATE_Activity 2 Test2 New version 300118 MOD pedro.csv", header=T, na.strings = "NA")
target_pos <- Params$tp$B_A2T2 # {1,2,3,4}
select <- (!is.na(data[,"Position"])) & (!is.na(data[,"Infection_status"])) & (!is.na(data[,"Notes"])) & (!is.na(data[,"Notes"]) & data[,"Notes"] != "fallen") & (data[,"Position"] %in% target_pos) & (data[,"Feeding_status"] %in% c("Exposed","Inactivated blood Fed")) & (data[,"Age"] %in% c("D14","D15","D18"))# & (is.na(data[,"Dissect_oocyst"])) #& (data[,"Infection_status"] %in% c("infectious","uninfectious")) #
#select[153:154] <- FALSE # outliers, etc.
unique_IDs <- unique(data[select,"Mosquito_ID"])
# indices of repetitions for each mosquito
idx <- list()
for(i in unique_IDs){
rng <- which(data[,"Mosquito_ID"] == i) #which((data[,"Mosquito_ID"])[data[,"Mosquito_ID"] == i])
aux <- (data[rng,"Position"] %in% target_pos) & !is.na(data[rng,"Position"]) & !is.na(data[rng,"Infection_status"])
idx[[i]] <- rng[aux]
}
n_replics <- unlist(lapply(idx, length)) # store how many repeated observations for each specimen
# read predictor (X)
dates <- c("14Oct17", "04Nov17", "11Nov17", "15Nov17", "07Dec17", "14Dec17")
nx_dates <- c( 211 , 309 , 239 , 21 , 201 , 181 )
nx <- sum(nx_dates) # number of spectra files
dx <- matrix(0, nx, 2151); kk <- 0
for(day in dates){
for(k in 0:(nx_dates[which(dates == day)]-1)){
kk <- kk + 1
f_name <- paste0("~/Dropbox/research/projects/nirs/data/datasets/Burkina NIRS Data/Activity 2 - Pf Infection/Test 2-New version/E1Test2_",day,"_", formatC(k, width = 5,flag = 0),".txt")
dx[kk,] <- read.table(file = f_name, header=T, sep="\t")[,2]
}
}
# average replications
if(Params$avg_replics){
data_X <- c()
for(i in unique_IDs){
if(length(idx[[i]]) > 1){
data_X <- rbind(data_X, colMeans(dx[idx[[i]],]))
}else{
data_X <- rbind(data_X, dx[idx[[i]],])
}
}
}else{
data_X <- dx[select,]
}
# read response (y)
i_y <- select & ((1:nrow(data)) %in% unlist(sapply(idx, "[[", 1)))
data_y <- data[i_y,"Infection_status"] #as.numeric(data[i_y,"Infection_status"] %in% c("infectious","infected"))
# raw data
raw_data <- data[i_y,]
return(list(X = data_X, y = data_y, n_replics = n_replics[n_replics != 0], raw_data = raw_data))
# re-save with simple layout
#data_export <- data.frame(y = y, X = X)
#write.table(data_export, file="~/Dropbox/research/projects/nirs/data/datasets/experiments_Tom/A1_sporozoites/DATASET_sporozoites_2017_06_01.txt", sep=",", row.names=F, col.names=T)
}#load_B_A2T2
load_B_A2E2 <- function(Params){
# read data
data <- read.csv(file = "~/Dropbox/research/projects/nirs/data/datasets/Burkina NIRS Data/Activity 2 - Pf Infection/NIRS_Burkina_A2E2_140518_PEDRO.csv", header=T, na.strings = "NA")
#data <- read.csv(file = "~/DROPBOX_overflow/research/projects/nirs/data/datasets/Burkina NIRS Data [offline copy 27apr2018]/Activity 1 - Age/NIRS_E1A1_300118_(PEDRO).csv", header=T, na.strings = "NA")
target_repl <- c(1,2,3) # {1,2,3} different gemetocytemia levels (1=low, 2=medium, 3=high)
target_pos <- c('head_right', 'head_left') # {head_right, head_left, abdomen_right, abdomen_left}
target_age <- c(3,6) # {3,6} age when fed
# !(data[rng,"Notes"] %in% c('microsporidies','melinization_and_microsporidies')) &
select <- (data[,"Exclude"] != 'y') & (data[,"Position"] %in% target_pos) & (data[,"Replicate"] %in% target_repl) & (data[,"Age_group"] %in% target_age) & (!is.na(data[,"Infection_status"])) & (!is.na(data[,"Position"])) & (!is.na(data[,"Notes"])) # & (is.na(data[,"Dissect_oocyst"])) #& (data[,"Infection_status"] %in% c("infectious","uninfectious")) #
unique_IDs <- unique(data[select,"Mosquito_ID"])
# indices of repetitions for each mosquito
idx <- list()
for(i in unique_IDs){
rng <- which(data[,"Mosquito_ID"] == i) #which((data[,"Mosquito_ID"])[data[,"Mosquito_ID"] == i])
aux <- (data[rng,"Exclude"] != 'y') & (data[rng,"Position"] %in% target_pos) & (data[rng,"Replicate"] %in% target_repl) & (data[rng,"Age_group"] %in% target_age) & (!is.na(data[rng,"Infection_status"])) & !is.na(data[rng,"Position"]) & (!is.na(data[rng,"Notes"]))
idx[[i]] <- rng[aux]
}
n_replics <- unlist(lapply(idx, length)) # store how many repeated observations for each specimen
# read spectra
# replicate 1
dates_A <- c("24Nov17","26Nov17","28Nov17","30Nov17","02Dec17","04Dec17","06Dec17","08Dec17","10Dec17")
nx_dates_A <- c( 481 , 485 , 641 , 485 , 481 , 481 , 513 , 321 , 229 )
nx_A <- sum(nx_dates_A) # number of spectra files
dx_A <- matrix(0, nx_A, 2151); kk <- 0
for(day in dates_A){
for(k in 0:(nx_dates_A[which(dates_A == day)]-1)){
kk <- kk + 1
f_name <- paste0("~/Dropbox/research/projects/nirs/data/datasets/Burkina NIRS Data/Activity 2 - Pf Infection/Experiment 2_replicate 1/E1Test2_",day,"_", formatC(k, width = 5,flag = 0),".txt")
dx_A[kk,] <- read.table(file = f_name, header=T, sep="\t")[,2]
}
}
# replicates 2 and 3
dates_B <- c("26Jan18","28Jan18","30Jan18","01Fev18","03Fev18","05Fev18","07Fev18","09Fev18","11Fev18","13Fev18","19Mars18","21Mars18","23Mars18","25Mars18","27Mars18","29Mars18","31Mars18","02Avr18","04Avr18")
nx_dates_start <- c( 0 , 481 , 963 , 1445 , 1925 , 2407 , 2889 , 3371 , 3853 , 4223 , 4429 , 4671 , 4913 , 5155 , 5357 , 5519 , 5649 , 5731 , 5813 )
nx_dates_end <- c( 480 , 962 , 1444 , 1924 , 2406 , 2888 , 3370 , 3852 , 4222 , 4428 , 4670 , 4912 , 5154 , 5356 , 5518 , 5648 , 5730 , 5812 , 5858 )
nx_dates_B <- nx_dates_end - nx_dates_start + 1
nx_B <- sum(nx_dates_B) # number of spectra files
dx_B <- c()
for(day in dates_B){
dx_B_aux <- matrix(0, nx_dates_B[which(day==dates_B)], 2151); kk <- 1
for(k in nx_dates_start[which(day==dates_B)]:nx_dates_end[which(day==dates_B)]){
f_name <- paste0("~/Dropbox/research/projects/nirs/data/datasets/Burkina NIRS Data/Activity 2 - Pf Infection/Experiment 2_replicate 2 3/E2PfInfection_",day,"_", formatC(k, width = 5,flag = 0),".txt")
dx_B_aux[kk,] <- read.table(file = f_name, header=T, sep="\t")[,2]
kk <- kk + 1
}
dx_B <- rbind(dx_B, dx_B_aux)
}
# merge
dx <- rbind(dx_A, dx_B)
# average replications
if(Params$avg_replics){
data_X <- c()
for(i in unique_IDs){
if(length(idx[[i]]) > 1){
data_X <- rbind(data_X, colMeans(dx[idx[[i]],]))
}else{
data_X <- rbind(data_X, dx[idx[[i]],])
}
}
}else{
data_X <- dx[select,]
}
# read response (y)
i_y <- select & ((1:nrow(data)) %in% unlist(sapply(idx, "[[", 1)))
data_y <- data[i_y,"Infection_status"]
# raw data
raw_data <- data[i_y,]
return(list(X = data_X, y = data_y, n_replics = n_replics[n_replics != 0], raw_data = raw_data))
# re-save with simple layout
#data_export <- data.frame(y = y, X = X)
#write.table(data_export, file="~/Dropbox/research/projects/nirs/data/datasets/experiments_Tom/A1_sporozoites/DATASET_sporozoites_2017_06_01.txt", sep=",", row.names=F, col.names=T)
}#load_B_A2E2
load_B_A4E4 <- function(Params){
# read data
data <- read.csv(file = "~/Dropbox/research/projects/nirs/data/datasets/Burkina NIRS Data/Activity 4/Activity 4 NIRS-TEMPLATE-start season (PEDRO).csv", header=T, na.strings = "NA")
target_pos <- Params$tp$B_A2T2 # {1,2,3,4}
select <- (!is.na(data[,"Scanning_day"])) & (!is.na(data[,"Location"])) & (!is.na(data[,"Species"])) & (!is.na(data[,"Position"])) & (data[,"Position"] %in% target_pos) & (!is.na(data[,"Infection_status"]))
#select[153:154] <- FALSE # outliers, etc.
unique_IDs <- unique(data[select,"Mosquito_ID"])
# indices of repetitions for each mosquito
idx <- list()
for(i in unique_IDs){
rng <- which(data[,"Mosquito_ID"] == i) #which((data[,"Mosquito_ID"])[data[,"Mosquito_ID"] == i])
aux <- (!is.na(data[rng,"Scanning_day"])) & (!is.na(data[rng,"Location"])) & (!is.na(data[rng,"Species"])) & (data[rng,"Position"] %in% target_pos) & !is.na(data[rng,"Position"]) & !is.na(data[rng,"Infection_status"])
idx[[i]] <- rng[aux]
}
n_replics <- unlist(lapply(idx, length)) # store how many repeated observations for each specimen
# read predictor (X)
nx <- nrow(data) # number of spectra files
dx <- matrix(0, nx, 2151)
for(k in 0:(nx-1)){
f_name <- paste0("~/Dropbox/research/projects/nirs/data/datasets/Burkina NIRS Data/Activity 4/Activity 4 - 1st time point/A4E4_Age-inf_", formatC(k, width = 5,flag = 0),".txt")
dx[k+1,] <- read.table(file = f_name, header=T, sep="\t")[,2]
}
# average replications
if(Params$avg_replics){
data_X <- c()
for(i in unique_IDs){
if(length(idx[[i]]) > 1){
data_X <- rbind(data_X, colMeans(dx[idx[[i]],]))
}else{
data_X <- rbind(data_X, dx[idx[[i]],])
}
}
}else{
data_X <- dx[select,]
}
# read response (y)
i_y <- select & ((1:nrow(data)) %in% unlist(sapply(idx, "[[", 1)))
data_y <- data[i_y,"Infection_status"]
# raw data
raw_data <- data[i_y,]
return(list(X = data_X, y = data_y, n_replics = n_replics[n_replics != 0], raw_data = raw_data))
# re-save with simple layout
#data_export <- data.frame(y = y, X = X)
#write.table(data_export, file="~/Dropbox/research/projects/nirs/data/datasets/experiments_Tom/A1_sporozoites/DATASET_sporozoites_2017_06_01.txt", sep=",", row.names=F, col.names=T)
}#load_B_A4E4
#================================ B_A1T1 BURKINA FASO, ACTIVITY 1 EXPERIMENT 1 (AGE, test)
data_B_A1T1 <- load_B_A1T1(Params); X <- data_B_A1T1$X; y <- data_B_A1T1$y; raw_data <- data_B_A1T1$raw_data
######## SET PATHS
loc_data <- "~/Dropbox/research/projects/nirs/typesetting/nirs_paper2_fda/data/"
loc_figures <- "~/Dropbox/research/projects/nirs/typesetting/nirs_paper2_fda/figures/"
######## LOAD DATA
# load data 'B_A1T1' OR 'B_A2E2' from "cleanRealData.R"
######## AUXILIARY FUNCTIONS
get_fname <- function(x, xtype){
if(xtype == "spe"){
return( paste0(paste(strsplit(x[1], split="")[[1]][1:4], collapse=""), "VS", paste(strsplit(x[2], split="")[[1]][1:4], collapse="")) )
}else if (xtype == "gen"){
return(paste0(x, collapse=""))
}
}
######## PLOT SPECTRA
palette(rich.colors(5))
wvlenghts <- 350:2500
# pdf(file = paste0(loc_figures,"fig_spectra_color3.pdf"), height=5, width=10, pointsize=12)
{
X_plot <- X[y %in% c("arabiensis","gambiae"),]
y_plot <- factor(y[y %in% c("arabiensis","gambiae")])
set.seed(52); ii <- sample(nrow(X_plot), size=30)
col_arab <- rgb(0,1,0,0.7); col_gamb <- rgb(0,0,1,0.7)
col_vec <- as.character(y_plot[ii]); col_vec[col_vec=="arabiensis"] <- col_arab; col_vec[col_vec=="gambiae"] <- col_gamb # skyblue rgb(1,0,0,0.6)
offset <- 1; cols <- as.numeric(y_plot[ii]) + offset
matplot(wvlenghts, t(X_plot[ii,]), type="l", col=col_vec, lty=1, lwd=2, xlim=c(350,2500), ylim=c(0.2,1.5), xaxt="n", bty="n", xlab="wavelength (nm)", ylab="absorbance")
legend_labels <- c("An. arabiensis","An. gambiae s.s.")
legend("top", legend=legend_labels, lty=1, lwd=2, seg.len=1.3, col=c(col_arab,col_gamb), title=expression(bold("Species")), horiz=T, bty="n")
axis(1,at=seq(300,2500,len=12))
}
# dev.off()
N_reps <- 100
DATA_TYPE <- "species_A1T1" # {age , species_A1T1, species_A4E4}
V_reduction <- c("pca")
V_smooth <- c(T,F)
V_functional <- c(T,F)
n_modelTypes <- nrow(expand.grid(V_reduction,V_smooth,V_functional))
ALL_RES <- matrix(NA, 8, 13); rownames(ALL_RES) <- c("GLM","sGLM","pGLM","spGLM","fGLM","fsGLM","fpGLM","fspGLM"); colnames(ALL_RES) <- c("K/P","Q","R","lambda","acc","err_cv_smoothest","err_cv_stdev_smoothest","err_cv_ensemble","err_cv_stdev_ensemble","err_alt_smoothest","err_alt_stdev_smoothest","err_alt_ensemble","err_alt_stdev_ensemble")
ALL_RES_BEST <- matrix(NA, 4, 8); rownames(ALL_RES_BEST) <- c("pGLM","spGLM","fpGLM","fspGLM"); colnames(ALL_RES_BEST) <-c("Q","R","lambda","acc","err_cv_best","err_cv_stdev_best","err_alt_best","err_alt_stdev_best")
L_load <- T # ={TRUE,FALSE}, whether to load previous results (TRUE) or generate new results (FALSE)
iii <- 0
vr='pls'
vs=vf=T
if(!(L_load %in% c(T,F))){ stop("'L_load' must be either TRUE or FALSE.") }
L_load
L_load=F
if(!(L_load %in% c(T,F))){ stop("'L_load' must be either TRUE or FALSE.") }
if(DATA_TYPE == "species_A1T1"){
SPE <- c("arabiensis","gambiae") # species: {arabiensis , coluzzii , gambiae}; age: {ARAB , GAMB , COLU}
LOC_train <- c("Longo") # {Longo , Klesso}
LOC_test <- c("Klesso") # {Longo , Klesso}
GEN_train <- c("F0","F1") # {F0 , F1 , F0F1}
#locTrain <- "Longo"
ii <- (raw_data[,"Species"] %in% SPE) & (raw_data[,"Location"] %in% LOC_train) & (raw_data[,"Generation"] %in% GEN_train)
X_subset <- X[ii,]; y_subset <- rep(0, sum(ii)); y_subset[raw_data[ii,"Species"] == SPE[1]] <- 1;
L_task <- "clas"; L_model <- "glm"
}else if(DATA_TYPE == "species_???"){
;
}else if(DATA_TYPE == "age"){
SPE <- "COLU" # species: {ARABvsGAMB , ARABvsCOLU , COLUvsGAMB}; age: {ARAB , GAMB , COLU}
ii <- (raw_data[,"Species"] == "coluzzii")
X_subset <- X[ii,]; y_subset <- y[ii]
L_task <- "regr"; L_model <- "lm"
}else{
stop("'DATA_TYPE' invalid.")
}
#
L_reduction <- vr
L_smooth <- vs
L_functional <- vf
# smooth here, so use 'smooth=F' in fdaML_train()
if(L_smooth){ X_subset <- fdaSmooth(X_subset) }
N <- ifelse( abs(nrow(X_subset)-length(y_subset)) == 0, nrow(X_subset), stop("'nrow(X)' different from 'length(y)'") ); P <- ncol(X_subset); palette(rich.colors(length(unique(y_subset))))
library("mlevcm")
# smooth here, so use 'smooth=F' in fdaML_train()
if(L_smooth){ X_subset <- fdaSmooth(X_subset) }
N <- ifelse( abs(nrow(X_subset)-length(y_subset)) == 0, nrow(X_subset), stop("'nrow(X)' different from 'length(y)'") ); P <- ncol(X_subset); palette(rich.colors(length(unique(y_subset))))
if(L_functional){
B_opt <- 0.1
# tau_K <- 0.01
# vec_basis <- seq(0.1, 1, by=0.1); lb <- length(vec_basis)
# acc_basis <- rep(NA, lb)
# cat("",paste0("DETERMINING OPTIMAL FUNCTIONAL REPRESENTATION:"), sep="\n")
# pb_fda = txtProgressBar(min = 0, max = lb, initial = 0, style = 3);
# for(nb in 1:lb){
# set.seed(17571); obj <- fdaML_train(ll = list(X=X_subset, y=y_subset, Z=NULL, task=L_task, model=L_model, reduction=L_reduction, smooth_w=NULL, intercept=T, lam_cv_type="n", lam_vec=NULL, reps=N_reps, Q_len=NULL, Q_opt=NULL, Q_vec=NULL, split_size=0.5, tau_Q_opt=0.01, balanced=F, estimation_w=NULL, bspline_dim=floor(vec_basis[nb] * ncol(X)), t_range=wvlenghts, verbose=F))
# acc_basis[nb] <- mean(obj$perf_cv[,which(obj$Q_vec == obj$Q_opt)])
# setTxtProgressBar(pb_fda, nb)
# } # plot(vec_basis, acc_basis, type="l", ylim = c(0.99*min(acc_basis), max(acc_basis))); abline(h = max(acc_basis) - 0.01, col="blue")
# B_opt <- vec_basis[which((max(acc_basis) - acc_basis) < tau_K)[1]]
}else{
B_opt <- 1
}
ALL_RES[paste0(ifelse(L_functional,"f",""),ifelse(L_smooth,"s",""),"GLM"), "K/P"] <- B_opt
ALL_RES[paste0(ifelse(L_functional,"f",""),ifelse(L_smooth,"s",""),"pGLM"), "K/P"] <- B_opt
vec_basis <- seq(B_opt, B_opt, by=0.2); lb <- length(vec_basis)
paramsByModel <- list(pls = list(comp_p = floor(seq(16, 40, len=10)), lam_p = round(seq(0.5, 10, len=10), 1),
comp_sp = floor(seq(16, 30, len=10)), lam_sp = round(seq(50, 100, len=10), 1),
comp_fp = floor(seq(16, 30, len=10)), lam_fp = round(seq(25, 100, len=10), 1),
comp_fsp = floor(seq(10, 30, len=10)), lam_fsp = round(seq(5, 150, len=10), 1)),
pca = list(comp_p = floor(seq(30, 63, len=10)), lam_p = round(seq(0.1, 7, len=10), 1), # Q=63 is the largest possible b/c of sample sizes
comp_sp = floor(seq(16, 50, len=10)), lam_sp = round(seq(0.1, 120, len=10), 1),
comp_fp = floor(seq(10, 46, len=10)), lam_fp = round(seq(0.01, 14, len=10), 1),
comp_fsp = floor(seq(6, 50, len=10)), lam_fsp = round(seq(0.01, 14, len=10), 1)))
vec_components <- paramsByModel[[L_reduction]][[paste0("comp_", ifelse(L_functional,"f",""), ifelse(L_smooth,"s",""), "p")]]; lc <- length(vec_components)
vec_lambdas <- paramsByModel[[L_reduction]][[paste0("lam_", ifelse(L_functional,"f",""), ifelse(L_smooth,"s",""), "p")]]; ll <- length(vec_lambdas)
arr_acc <- arr_acc_stdev <- array(NA, c(length(vec_components), length(vec_lambdas), length(vec_basis)), dimnames=list(paste0("c_",vec_components), paste0("l_",vec_lambdas), paste0("b_",vec_basis)))
arr_rough <- arr_roughStd <- arr_acc
L_load
models_list <- list()
saveRDS(models_list, file=paste0("/Volumes/Elements\ 2TB/nirs_paper2_nirsfda/MODELS_LIST_",DATA_TYPE,"_",ifelse(L_functional,"f",""), ifelse(L_smooth,"s",""), toupper(L_model), "_", toupper(L_reduction), "_reps", N_reps, "_", get_fname(SPE,"spe"), "_TrainOn", LOC_train, get_fname(GEN_train,"gen"),".Rdata"))
start_time <- Sys.time()
for(vr in V_reduction){
for(vs in V_smooth){
for(vf in V_functional){
if(!(L_load %in% c(T,F))){ stop("'L_load' must be either TRUE or FALSE.") }
if(DATA_TYPE == "species_A1T1"){
SPE <- c("arabiensis","gambiae") # species: {arabiensis , coluzzii , gambiae}; age: {ARAB , GAMB , COLU}
LOC_train <- c("Longo") # {Longo , Klesso}
LOC_test <- c("Klesso") # {Longo , Klesso}
GEN_train <- c("F0","F1") # {F0 , F1 , F0F1}
#locTrain <- "Longo"
ii <- (raw_data[,"Species"] %in% SPE) & (raw_data[,"Location"] %in% LOC_train) & (raw_data[,"Generation"] %in% GEN_train)
X_subset <- X[ii,]; y_subset <- rep(0, sum(ii)); y_subset[raw_data[ii,"Species"] == SPE[1]] <- 1;
L_task <- "clas"; L_model <- "glm"
}else if(DATA_TYPE == "species_???"){
;
}else if(DATA_TYPE == "age"){
SPE <- "COLU" # species: {ARABvsGAMB , ARABvsCOLU , COLUvsGAMB}; age: {ARAB , GAMB , COLU}
ii <- (raw_data[,"Species"] == "coluzzii")
X_subset <- X[ii,]; y_subset <- y[ii]
L_task <- "regr"; L_model <- "lm"
}else{
stop("'DATA_TYPE' invalid.")
}
#
L_reduction <- vr
L_smooth <- vs
L_functional <- vf
# smooth here, so use 'smooth=F' in fdaML_train()
if(L_smooth){ X_subset <- fdaSmooth(X_subset) }
N <- ifelse( abs(nrow(X_subset)-length(y_subset)) == 0, nrow(X_subset), stop("'nrow(X)' different from 'length(y)'") ); P <- ncol(X_subset); palette(rich.colors(length(unique(y_subset))))
# matplot(wvlenghts, t(X_subset), type="l", col=alpha(as.numeric(sum(y_subset==0)!=0)+y_subset,0.4), lty=1, ylim=c(0,2), xlab="wavelength", ylab="signal"); legend("topright", paste("y=",sort(unique(y_subset)),sep=""), horiz=T, lty=1, seg.len=0.8, col=1:length(unique(y_subset)), bty="n", cex=0.8)
########
################ OPTIMISE {# basis K}
########
if(L_functional){
B_opt <- 0.1
# tau_K <- 0.01
# vec_basis <- seq(0.1, 1, by=0.1); lb <- length(vec_basis)
# acc_basis <- rep(NA, lb)
# cat("",paste0("DETERMINING OPTIMAL FUNCTIONAL REPRESENTATION:"), sep="\n")
# pb_fda = txtProgressBar(min = 0, max = lb, initial = 0, style = 3);
# for(nb in 1:lb){
# set.seed(17571); obj <- fdaML_train(ll = list(X=X_subset, y=y_subset, Z=NULL, task=L_task, model=L_model, reduction=L_reduction, smooth_w=NULL, intercept=T, lam_cv_type="n", lam_vec=NULL, reps=N_reps, Q_len=NULL, Q_opt=NULL, Q_vec=NULL, split_size=0.5, tau_Q_opt=0.01, balanced=F, estimation_w=NULL, bspline_dim=floor(vec_basis[nb] * ncol(X)), t_range=wvlenghts, verbose=F))
# acc_basis[nb] <- mean(obj$perf_cv[,which(obj$Q_vec == obj$Q_opt)])
# setTxtProgressBar(pb_fda, nb)
# } # plot(vec_basis, acc_basis, type="l", ylim = c(0.99*min(acc_basis), max(acc_basis))); abline(h = max(acc_basis) - 0.01, col="blue")
# B_opt <- vec_basis[which((max(acc_basis) - acc_basis) < tau_K)[1]]
}else{
B_opt <- 1
}
ALL_RES[paste0(ifelse(L_functional,"f",""),ifelse(L_smooth,"s",""),"GLM"), "K/P"] <- B_opt
ALL_RES[paste0(ifelse(L_functional,"f",""),ifelse(L_smooth,"s",""),"pGLM"), "K/P"] <- B_opt
########
################ OPTIMISE {# components "Q", penalty parameter "lambda"}
########
#---# Cross-validate (Q,lambda)
vec_basis <- seq(B_opt, B_opt, by=0.2); lb <- length(vec_basis)
paramsByModel <- list(pls = list(comp_p = floor(seq(16, 40, len=10)), lam_p = round(seq(0.5, 10, len=10), 1),
comp_sp = floor(seq(16, 30, len=10)), lam_sp = round(seq(50, 100, len=10), 1),
comp_fp = floor(seq(16, 30, len=10)), lam_fp = round(seq(25, 100, len=10), 1),
comp_fsp = floor(seq(10, 30, len=10)), lam_fsp = round(seq(5, 150, len=10), 1)),
pca = list(comp_p = floor(seq(30, 63, len=10)), lam_p = round(seq(0.1, 7, len=10), 1), # Q=63 is the largest possible b/c of sample sizes
comp_sp = floor(seq(16, 50, len=10)), lam_sp = round(seq(0.1, 120, len=10), 1),
comp_fp = floor(seq(10, 46, len=10)), lam_fp = round(seq(0.01, 14, len=10), 1),
comp_fsp = floor(seq(6, 50, len=10)), lam_fsp = round(seq(0.01, 14, len=10), 1)))
vec_components <- paramsByModel[[L_reduction]][[paste0("comp_", ifelse(L_functional,"f",""), ifelse(L_smooth,"s",""), "p")]]; lc <- length(vec_components)
vec_lambdas <- paramsByModel[[L_reduction]][[paste0("lam_", ifelse(L_functional,"f",""), ifelse(L_smooth,"s",""), "p")]]; ll <- length(vec_lambdas)
arr_acc <- arr_acc_stdev <- array(NA, c(length(vec_components), length(vec_lambdas), length(vec_basis)), dimnames=list(paste0("c_",vec_components), paste0("l_",vec_lambdas), paste0("b_",vec_basis)))
arr_rough <- arr_roughStd <- arr_acc
if(L_load){ # load data
loadedData <- readRDS(file=paste0(loc_data, DATA_TYPE, "_CV_", ifelse(L_functional,"f",""), ifelse(L_smooth,"s",""), toupper(L_model), "_", toupper(L_reduction), "_reps", N_reps, "_", get_fname(SPE,"spe"), "_TrainOn", LOC_train, get_fname(GEN_train,"gen"), ".Rdata"))
arr_acc <- loadedData$arr_acc; arr_acc_stdev <- loadedData$arr_acc_stdev; arr_rough <- loadedData$arr_rough; arr_roughStd <- loadedData$arr_roughStd; vec_basis <- loadedData$vec_basis; vec_components <- loadedData$vec_components; vec_lambdas <- loadedData$vec_lambdas
# models_list <- readRDS(file=paste0("~/Downloads/nirs_paper2_nirsfda/MODELS_LIST_",DATA_TYPE,"_",ifelse(L_functional,"f",""), ifelse(L_smooth,"s",""), toupper(L_model), "_", toupper(L_reduction), "_reps", N_reps, "_", get_fname(SPE,"spe"), "_TrainOn", LOC_train, get_fname(GEN_train,"gen"),".Rdata"))
}else{
cat("",paste0("Parameter set ",(iii+1),"/", n_modelTypes, " (vr=", L_reduction, ",vs=", ifelse(L_smooth==T,"T","F"), ",vf=", ifelse(L_functional==T,"T","F") ,") | CROSS-VALIDATING Q/LAMBDA:"), sep="\n")
pb_cv = txtProgressBar(min = 0, max = lb*lc*ll, initial = 0, style = 3); loopCounter <- 0
models_list <- list()
for(nb in 1:lb){
models_list[[nb]] <- list()
for(nc in 1:lc){
models_list[[nb]][[nc]] <- list()
for(nl in 1:ll){
set.seed(17571); obj <- fdaML_train(ll = list(X=X_subset, y=y_subset, Z=NULL, task=L_task, model=L_model, reduction=L_reduction, smooth_w=NULL, intercept=T, lam_cv_type="ocv", lam_vec=vec_lambdas[nl], reps=N_reps, Q_len=NULL, Q_opt=vec_components[nc], Q_vec=NULL, split_size=0.5, tau_Q_opt=0.01, balanced=F, estimation_w=NULL, bspline_dim=floor(vec_basis[nb] * ncol(X)), t_range=wvlenghts, verbose=F))
arr_acc[nc,nl,nb] <- mean(obj$perf_cv[,which(obj$Q_vec == obj$Q_opt)])
arr_acc_stdev[nc,nl,nb] <- sd(obj$perf_cv[,which(obj$Q_vec == obj$Q_opt)])
arr_rough[nc,nl,nb] <- mean(obj$beta_roughness)
arr_roughStd[nc,nl,nb] <- mean(obj$beta_roughnessStd)
models_list[[nb]][[nc]][[nl]] <- obj
loopCounter <- loopCounter + 1; setTxtProgressBar(pb_cv, loopCounter)
}
}
}
saveRDS(models_list, file=paste0("/Volumes/Elements\ 2TB/nirs_paper2_nirsfda/MODELS_LIST_",DATA_TYPE,"_",ifelse(L_functional,"f",""), ifelse(L_smooth,"s",""), toupper(L_model), "_", toupper(L_reduction), "_reps", N_reps, "_", get_fname(SPE,"spe"), "_TrainOn", LOC_train, get_fname(GEN_train,"gen"),".Rdata"))
cv_list <- list(arr_acc = arr_acc,
arr_acc_stdev = arr_acc_stdev,
arr_rough = arr_rough,
arr_roughStd = arr_roughStd,
vec_basis = vec_basis,
vec_components = vec_components,
vec_lambdas = vec_lambdas)
#saveRDS(cv_list, file=paste0(loc_data, DATA_TYPE,"_CV_", ifelse(L_functional,"f",""), ifelse(L_smooth,"s",""), toupper(L_model), "_", toupper(L_reduction), "_reps", N_reps, "_", get_fname(SPE,"spe"), "_TrainOn", LOC_train, get_fname(GEN_train,"gen"), ".Rdata"))
}
end_time <- Sys.time()
cat("", paste0("cumulative time = ", round(end_time - start_time, 2), " ", attr(end_time - start_time, "units")), sep="\n")
}}}#tmp
9600-3800
(9600-3800)*(1-0.075)
(9600-3800)*(0.075)
(1+0.2)^5
(1+0.15)^5
(1+0.1)^5
(1+0.14)^5
(1+0.15)^5
(1+0.145)^5
(1+0.148)^5
(1+0.149)^5
(1+0.15)^5
url <- GET("http://www.etf.com/etf-finder-funds-api//-aum/0/2000/1")
library(Quandl)
library(scales)
library(gridExtra)
library(TTR)
library(jsonlite)
library(xtable)
library(gtable)
library(grid)
# 2. Load Hadley libraries.
library(tidyverse)
library(httr)
library(readxl)
library(lubridate)
library(reshape2)
?GET
url <- GET("http://www.etf.com/etf-finder-funds-api//-aum/0/2000/1")
etf <- fromJSON(content(url, as = "text"), flatten = TRUE) %>%
fundBasics.segment = str_replace_all(fundBasics.segment, "\\s+", " "),
etf <- fromJSON(content(url, as = "text"), flatten = TRUE) %>%
mutate(fundBasics.issuer = str_replace_all(fundBasics.issuer, "(\\<.*\\>)(.*)(\\<.*\\>)", "\\2"),
fundBasics.segment = str_replace_all(fundBasics.segment, "\\s+", " "),
fundBasics.expenseRatio.value = fundBasics.expenseRatio.value / 10000
etf <- fromJSON(content(url, as = "text"), flatten = TRUE) %>% mutate(fundBasics.issuer = str_replace_all(fundBasics.issuer, "(\\<.*\\>)(.*)(\\<.*\\>)", "\\2"),
fundBasics.segment = str_replace_all(fundBasics.segment, "\\s+", " "),
fundBasics.expenseRatio.value = fundBasics.expenseRatio.value / 10000
etf <- fromJSON(content(url, as = "text"), flatten = TRUE) %>%
etf <- fromJSON(content(url, as = "text"), flatten = TRUE) %>%
mutate(fundBasics.issuer = str_replace_all(fundBasics.issuer, "(\\<.*\\>)(.*)(\\<.*\\>)", "\\2"),
fundBasics.segment = str_replace_all(fundBasics.segment, "\\s+", " "),
fundBasics.expenseRatio.value = fundBasics.expenseRatio.value / 10000
etf <- fromJSON(content(url, as = "text"), flatten = TRUE) %>%
mutate(fundBasics.issuer = str_replace_all(fundBasics.issuer, "(\\<.*\\>)(.*)(\\<.*\\>)", "\\2"),
fundBasics.segment = str_replace_all(fundBasics.segment, "\\s+", " "),
fundBasics.expenseRatio.value = fundBasics.expenseRatio.value / 10000)
install.packages("Quandl")
install.packages("gridExtra")
install.packages("gTTR")
install.packages("TTR")
install.packages("xtable")
install.packages("tidyverse")
install.packages("tidyverse")
install.packages("readxl")
library(Quandl)
library(scales)
library(gridExtra)
library(TTR)
library(jsonlite)
library(xtable)
library(gtable)
library(grid)
# 2. Load Hadley libraries.
library(tidyverse)
library(httr)
library(readxl)
library(lubridate)
library(reshape2)
url <- GET("http://www.etf.com/etf-finder-funds-api//-aum/0/2000/1")
etf <- fromJSON(content(url, as = "text"), flatten = TRUE) %>%
mutate(fundBasics.issuer = str_replace_all(fundBasics.issuer, "(\\<.*\\>)(.*)(\\<.*\\>)", "\\2"),
fundBasics.segment = str_replace_all(fundBasics.segment, "\\s+", " "),
fundBasics.expenseRatio.value = fundBasics.expenseRatio.value / 10000)
url <- GET("http://www.etf.com/etf-finder-funds-api//-aum/0/2000/1")
etf <- fromJSON(content(url, as = "text"), flatten = TRUE) %>%
mutate(fundBasics.issuer = str_replace_all(fundBasics.issuer, "(\\<.*\\>)(.*)(\\<.*\\>)", "\\2"),
fundBasics.segment = str_replace_all(fundBasics.segment, "\\s+", " "),
fundBasics.expenseRatio.value = fundBasics.expenseRatio.value / 10000)
url
ticker_list <- c("VUSA")
df <- data.frame()
n <- 1
for (ticker in ticker_list) {
print(paste0("ETF number ", n, ": ", ticker))
df_temp <- tryCatch(getSymbolsYahoo(ticker),
error = function(e) {
print(paste0("Could not download data for ", ticker))
return(data.frame())
})
df <- bind_rows(df, df_temp)
n <- n + 1
Sys.sleep(runif(1, 1, 2))
}
floor((3+2*1-3)/1)+1