4_stage_analysis.R 10.4 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
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(SpATS)

library(dplyr)

library(multidplyr)

source("R/Model/Spline_QMER.R")
source("R/Model/Dose_response.R")
source("R/Model/FitREML.R")
source("R/Model/FitSpATS.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')



# Use mutliprocessing for model fits
  
cluster <- new_cluster(number_of_cpus)
cluster_library(cluster, c("dplyr", "purrr", "SpATS"))
cluster_copy(cluster, c("fit_SpATS", "compute.mAIC", "compute.mBIC"))


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.csv"))
    
    if(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("asym_simple", "bplm_simple", "percentile")))
      
      #----------------------------------------------------------------
      # Adjusted means with SpATS: Stage 1
      
      print("Fit stage 1 (SpATS)")
      df_all_params <- df_all_params %>% mutate(value_true = value, value = predict)
      
      df_params_yearsite_weighted <- df_all_params %>%
        mutate(year_site.UID_ = year_site.UID) %>%
        group_by(year_site.UID_, parameter, model) %>%
        nest() %>%
        partition(cluster) %>%
        mutate(BLUEs = map(data, fit_SpATS, paste(model, parameter), use_weights =TRUE, use_checks=TRUE)) %>%
        collect()
luroth's avatar
luroth committed
153
154
155
156
157
158
159
160
161
162

      df_params_yearsite_weightedpost <- df_all_params %>%
        mutate(year_site.UID_ = year_site.UID) %>%
        mutate(se = sepost) %>%
        group_by(year_site.UID_, parameter, model) %>%
        nest() %>%
        partition(cluster) %>%
        mutate(BLUEs = map(data, fit_SpATS, paste(model, parameter), use_weights =TRUE, use_checks=TRUE)) %>%
        collect()

163
164
165
166
167
168
169
170
171
172
173
      df_params_yearsite_not_weighted <- df_all_params %>%
        mutate(year_site.UID_ = year_site.UID) %>%
        group_by(year_site.UID_, parameter, model) %>%
        nest() %>%
        partition(cluster) %>%
        mutate(BLUEs = map(data, fit_SpATS, paste(model, parameter), use_weights =FALSE, use_checks=TRUE)) %>%
        collect()
      
      df_params_BLUES_yearsite_weighted <- df_params_yearsite_weighted %>% unnest(BLUEs)
      df_params_BLUES_yearsite_weighted <- df_params_BLUES_yearsite_weighted %>% select(-data)
      df_params_BLUES_yearsite_weighted$stage1 <- "weighted"
luroth's avatar
luroth committed
174
175
176
      df_params_BLUES_yearsite_weightedpost <- df_params_yearsite_weightedpost %>% unnest(BLUEs)
      df_params_BLUES_yearsite_weightedpost <- df_params_BLUES_yearsite_weightedpost %>% select(-data)
      df_params_BLUES_yearsite_weightedpost$stage1 <- "weighted (posterior simulation)"
177
178
179
180
      df_params_BLUES_yearsite_not_weighted <- df_params_yearsite_not_weighted %>% unnest(BLUEs)
      df_params_BLUES_yearsite_not_weighted <- df_params_BLUES_yearsite_not_weighted %>% select(-data)
      df_params_BLUES_yearsite_not_weighted$stage1 <- "not weighted"
      
luroth's avatar
luroth committed
181
      df_params_BLUES_yearsite <- bind_rows(df_params_BLUES_yearsite_weighted, df_params_BLUES_yearsite_not_weighted, df_params_BLUES_yearsite_weightedpost)
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
      
      
      #----------------------------------------------------------------
      # Adjusted means with asreml: Stage 2
      
      print("Fit stage 2 (asreml-R)")
      
      df_BLUEs_weights <- df_params_BLUES_yearsite %>% filter(!is.na(use_weights)) %>%
        mutate(year_site.UID = year_site.UID_) %>% group_by(parameter, model, stage1) %>%
        nest() %>% mutate(BLUEs = map(data, fit_REML, parameter = paste(parameter, model), use_weights=T)) %>%
        select(-data) %>% unnest(BLUEs) %>% unnest(BLUE)
      df_BLUEs_weights$stage2 <- "weighted"
      
      df_BLUEs_no_weights <- df_params_BLUES_yearsite %>% filter(!is.na(use_weights)) %>%
        mutate(year_site.UID = year_site.UID_) %>% group_by(parameter, model, stage1) %>%
        nest() %>% mutate(BLUEs = map(data, fit_REML, parameter = paste(parameter, model), use_weights=F)) %>%
        select(-data) %>% unnest(BLUEs) %>% unnest(BLUE)
      df_BLUEs_no_weights$stage2 <- "not weighted"
      
      df_BLUES <- bind_rows(df_BLUEs_weights, df_BLUEs_no_weights)
      df_BLUES <- df_BLUES %>% 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="_"))
      
      # 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)
      
      df_BLUES_validate$set <- set
      write_csv(df_BLUES_validate, paste0(path_simulation, "/", run, "/", set, "_genotype_true_versus_predict.csv"))
      
      
      if (FALSE & run == 1 & set == "set3d") {
        
        df_spline_predicts <- read_csv(paste0(path_simulation, "/", run, "/", set, "_spline_predict.csv"))
        
        params_course_bplm_long <- df_BLUES_validate %>% filter(model == "bplm_course", stage1 == "weighted", stage2 == "weighted") %>%
          select(genotype.id, parameter, predict) %>% pivot_wider(names_from = parameter, values_from = predict) %>%
          filter(bplm_cOpt >0)
        params_course_asym_long <- df_BLUES_validate %>% filter(model == "asym_course", stage1 == "weighted", stage2 == "weighted") %>%
          select(genotype.id, parameter, predict) %>% pivot_wider(names_from = parameter, values_from = predict)
        
        # Growth response curves
        df_growth_response <- data.frame(
          temp = seq(0, 30, 0.01))
        df_growth_response <- expand_grid(df_growth_response, params_course_bplm_long)
        df_growth_response <- df_growth_response %>%
          mutate(sim_lm =
                   growth_response_bp_linear(df_growth_response$temp, bplm_c0, bplm_cOpt, bplm_Asym))
        
        df_growth_response <- data.frame(
          temp = seq(0, 30, 0.01))
        df_growth_response <- expand_grid(df_growth_response, params_course_asym_long)
        df_growth_response <- df_growth_response %>%
          mutate(sim_lm =
                   growth_response_asym(df_growth_response$temp, bplm_Asym, bplm_slope, bplm_c0))          
        
        df_growth_response$sim <- "Genotypic"
        plot_models <- ggplot(data = df_growth_response) +
          geom_line(aes(x = temp, y = sim_lm, group = genotype.id), alpha = 0.4) +
          scale_y_continuous(expression(paste("Fitted growth rate (", mm ~ h^-1, ")"))) +
          scale_x_continuous(expression(paste("Temperature (", degree * C, ")"))) +
          facet_wrap(~sim ) +
          theme +
          theme(legend.position = "bottom")
        
        df_spline_ <- df_spline_predicts
        df_spline_ <- inner_join(df_spline_, df_designs)
        #df_growth_phase_predicts_ <- inner_join(df_growth_phase_predicts, df_designs)
        plot_growth <- ggplot(data = df_spline_, aes(x = timestamp, y = predict / 1000, group = plot.UID)) +
          geom_line(alpha=0.2) +
          facet_wrap(~year_site.harvest_year, scales = "free_x") +
          scale_x_datetime(NULL) +
          scale_y_continuous("Fitted canopy height (m)") +
          theme
        
        plot_all <- grid.arrange(plot_models, plot_growth, widths = c(1, 2))
        
        ggsave(filename = paste0("Graphs/Simulation/Overview_fits.pdf"), plot_all, width = 14, height = 6)
      }
      
      
    } else {
      print("Results present, skip")
    }
  }
  #})
}