4b_onestage_analysis.R 8.26 KB
Newer Older
1
# Working directory with temperature data
luroth's avatar
luroth committed
2
path_home <- 'E:/Scripts/htfp_data_processing'
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
path_simulation <- 'E:/Simulation/Runs'
setwd(path_home)


# Libraries to use
library(readr)
library(tidyr)
library(purrr)
library(ggplot2)
library(lubridate)
library(gridExtra)
library(plyr)
library(stringr)
library(asreml)

library(dplyr)

source("R/Model/FitREML.R")
source("R/Model/Graphs.R")

start_run <- 1
max_runs <- 500
#500

number_of_cpus <- 5

sigma_error <- 10

# Plot control overview
plot_ids <- c(
  "FIP20150006",
  "FIP20160002",
  "FIP20170009",
  "FIP20180013",
  "FIP20190003")



## Measurement frequencies
measurement_dates_freq_1d <- c(
  format(seq.Date(from = as.Date("2020-03-01"), as.Date("2020-07-20"), by = 1), "%m%d")
)

measurement_dates_freq_2d <- c(
  format(seq.Date(from = as.Date("2020-03-01"), as.Date("2020-07-20"), by = 2), "%m%d")
)

measurement_dates_freq_3d <- c(
  format(seq.Date(from = as.Date("2020-03-01"), as.Date("2020-07-20"), by = 3), "%m%d")
)

measurement_dates_freq_4d <- c(
  format(seq.Date(from = as.Date("2020-03-01"), as.Date("2020-07-20"), by = 4), "%m%d")
)

measurement_dates_freq_5d <- c(
  format(seq.Date(from = as.Date("2020-03-01"), as.Date("2020-07-20"), by = 5), "%m%d")
)

measurement_dates_freq_6d <- c(
  format(seq.Date(from = as.Date("2020-03-01"), as.Date("2020-07-20"), by = 6), "%m%d")
)

measurement_dates_freq_7d <- c(
  format(seq.Date(from = as.Date("2020-03-01"), as.Date("2020-07-20"), by = 7), "%m%d")
)


measurement_dates_freq_9d <- c(
  format(seq.Date(from = as.Date("2020-03-01"), as.Date("2020-07-20"), by = 9), "%m%d")
)

measurement_dates_freq_11d <- c(
  format(seq.Date(from = as.Date("2020-03-01"), as.Date("2020-07-20"), by = 11), "%m%d")
)

measurement_dates_freq_13d <- c(
  format(seq.Date(from = as.Date("2020-03-01"), as.Date("2020-07-20"), by = 13), "%m%d")
)



measurement_dates_sets <- list(
  "3 d" = measurement_dates_freq_3d)

# Read data
df_designs <- read_csv('Simulation/designs.csv')
df_designs <- df_designs %>% mutate(plot.discrete_x = plot.row * if_else(plot.replication > 1, 2, 1),
                                    plot.discrete_y = plot.range * if_else(plot.replication > 1, 2, 1))

df_genotypes <- read_csv('Simulation/genotypes.csv')
df_temp <- read_csv('Simulation/covariate_temp.csv')



run <- 19
for(run in start_run:max_runs) {

  #try({
  # Validation data
  df_genotypes_true <- read_csv(paste0(path_simulation, "/", run, "/genotypes_params.csv"))
  df_genotypes_true <- df_genotypes_true %>% mutate(
    bplm_slope = bplm_Asym / (bplm_cOpt- bplm_c0))
  df_genotypes_true <- df_genotypes_true %>%
    pivot_longer(c(start_growth, stop_growth, bplm_c0, bplm_cOpt, bplm_Asym, bplm_slope), names_to = "parameter")
  
  
  print(paste0("Run ", run))
  
  
  i <- length(measurement_dates_sets)
  for(i in length(measurement_dates_sets):1) {
    measurement_dates_set_name = names(measurement_dates_sets)[[i]]
    measurement_dates_set = measurement_dates_sets[[i]]
    set <- paste0("set", str_replace_all(measurement_dates_set_name, " ", ""))
    print(paste0("Set: ", measurement_dates_set_name))
    
    
    files <- Sys.glob(paste0(path_simulation, "/", run, "/", set, "*_genotype_true_versus_predict_onestage.csv"))
    
    if(TRUE | length(files)==0) {
      
      df_all_params <- read_csv(paste0(path_simulation, "/", run, "/", set, "_plot_true_versus_predict.csv"))
      df_all_params <- df_all_params %>% filter(model %in% c("spline"), parameter != "final_height")
      
      #----------------------------------------------------------------
      # Adjusted means in one stage
      
      df <- df_all_params %>%
        mutate(year_site.UID_ = year_site.UID) %>%
        group_by(parameter, model) %>%
        nest()
      df <- df$data[[1]]
      
      fit_onestage_asreml <- function(df) {
        # Set factors
        df <- df %>% mutate(genotype = as.factor(genotype.id), year_site.UID = as.factor(year_site.UID),
                            plot.discrete_x = as.factor(plot.discrete_x), plot.discrete_y = as.factor(plot.discrete_y))
        # Filter out genotypes that exist in only one year-site:
        genotype_set <- df %>%
          ungroup() %>%
          select(genotype, year_site.UID) %>%
          unique() %>%
          group_by(genotype) %>%
          summarize(n = n()) %>%
          filter(n > 1) %>%
          ungroup() %>%
          select(genotype) %>%
          unique()
        df <- df %>% filter(genotype %in% genotype_set$genotype)
        
        # Remove NA values
        df <- df %>% filter(!is.na(value))
        # Re-expand to genotype and year-site set to have full design matrix
        genotype_set <- expand_grid(year_site.UID = df$year_site.UID %>% unique(),
                                    genotype = df$genotype %>% unique())
        df <- left_join(genotype_set, df, by = c("year_site.UID", "genotype"))
        
        # Drop unused (genotype) levels
        df <- droplevels(df)
        
        # Arrange df
        df <- df %>% arrange(year_site.UID, genotype)
        
        weights_ <- 1/df$se^2
        maxiter <- 1500
        
        df_BLUE <- data.frame()
        
        fit_BLUE <- NULL
        try({
        fit_BLUE <- asreml(value ~ 1 + genotype + year_site.UID, data = df, trace = F,
                           random = ~ at(year_site.UID):ar1v(plot.discrete_x):ar1(plot.discrete_y),
                           residual = ~dsum(~units | year_site.UID),
                           weights = weights_,
                           na.action = list(y = "include", x = "omit"),
                           maxit = maxiter,
                           fail="soft")
        summary(fit_BLUE)
        g.predBLUE <- predict(fit_BLUE, classify = "genotype")
        df_BLUE_ <- data.frame(g.predBLUE$pvals[, c(1, 2)])
        names(df_BLUE_) <- c("genotype.id", "BLUE")
        })
        if(is.null(fit_BLUE)) {
          df_BLUE_ <- data.frame(genotype.id = df$genotype.id %>% unique(), BLUE =NA)
        }
        
        df_BLUE_ <- df_BLUE_ %>% mutate(genotype.id = as.numeric(as.character(genotype.id)))
        df_BLUE_$stage1 <- "weighted"
        df_BLUE_$stage2 <- "onestage"
        df_BLUE <- bind_rows(df_BLUE, df_BLUE_)
        
        fit_BLUE <- NULL
        try({
        fit_BLUE <- asreml(value ~ 1 + genotype + year_site.UID, data = df, trace = F,
                           random = ~at(year_site.UID):plot.discrete_x:plot.discrete_y + at(year_site.UID):ar1v(plot.discrete_x):ar1(plot.discrete_y),
                           residual = ~dsum(~units | year_site.UID),
                           na.action = list(y = "include", x = "omit"),
                           maxit = maxiter,
                           fail="soft")
        summary(fit_BLUE)
        g.predBLUE <- predict(fit_BLUE, classify = "genotype")
        df_BLUE_ <- data.frame(g.predBLUE$pvals[, c(1, 2)])
        names(df_BLUE_) <- c("genotype.id", "BLUE")
        })
        if(is.null(fit_BLUE)) {
          df_BLUE_ <- data.frame(genotype.id = df$genotype.id %>% unique(), BLUE =NA)
        }
        
        df_BLUE_ <- df_BLUE_ %>% mutate(genotype.id = as.numeric(as.character(genotype.id)))
        df_BLUE_$stage1 <- "not weighted"
        df_BLUE_$stage2 <- "onestage"
        df_BLUE <- bind_rows(df_BLUE, df_BLUE_)
        return(df_BLUE)
      }
      
      df_all <- df_params_yearsite_weighted <- df_all_params %>%
        mutate(year_site.UID_ = year_site.UID) %>%
        group_by(parameter, model) %>%
        nest() %>%
        mutate(BLUEs = map(data, fit_onestage_asreml)) %>%
        select(-data)
      df_all <- df_all %>% unnest(BLUEs)
        
      df_BLUES <- df_all %>% rename(predict = BLUE)
      
      # Validate with true values
      df_BLUES_validate <- inner_join(df_genotypes_true, df_BLUES, by=c("genotype.id", "parameter"))
      
      df_BLUES_validate <- df_BLUES_validate %>% mutate(label = paste(parameter, model, stage1, stage2, sep="_"))
      
      df_BLUES_validate$set <- set
      write_csv(df_BLUES_validate, paste0(path_simulation, "/", run, "/", set, "_genotype_true_versus_predict_onestage.csv"))
      
      
      plot <- ggplot(data = df_BLUES_validate, aes(value, predict)) +
       geom_point() +
       geom_abline(intercept = 0, slope=1) +
       facet_wrap(~label, scales ="free") +
       ggtitle(paste("Run:", run, set))
      plot(plot)
      
    } else {
      print("Results present, skip")
    }
  }
  #})
}