-
Notifications
You must be signed in to change notification settings - Fork 0
/
EZTr_main.R
1964 lines (1538 loc) · 75.3 KB
/
EZTr_main.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##################
# EZTr_main #
# This framework is developed as part of the research article:
# Automated Discretization of ‘Transpiration Restriction to Increasing VPD’ Features from Outdoors High-Throughput Phenotyping Data
#
# Soumyashree Kar, Ryokei Tanaka, Lijalem Balcha Korbu, Jana Kholová, Hiroyoshi Iwata, Surya S. Durbha, J. Adinarayana, Vincent Vadez
##################
#' HTP data processing
#'
#' Convert gravimetric sensors or load cells (LC) time series into
#' Evapotranspiration (ETr) and Transpiration (Tr) time series.
#'
#' The function iterates over the different time points (at 15 min interval) of
#' each sector or pot to generate a matrix of Tr values. Fifteen biologically
#' relevant features are extracted from the Tr time series for each day,
#' followed by computation of feature heritability.
#'
#' The entire process comprises four steps: 1st - Conversion of LC data to ETr;
#' 2nd - Calculation of reference i.e. Penman Monteith ET for the given weather
#' condition, and filtering ETr based on reference ET; 3rd - Generating smooth
#' ETr time series; 4th - Extraction of Tr from smooth ETr, Tr features and
#' each feature's broad-sense heritability estimate.
#'
#' Input Files required:
#' 1.Loadcells²
#' 2.Loadcells metadata
#' 3.Sensor climate data
#' 4.Sensor unit map
#' 5.Plant eye
#'
#' #' Functions used for each step:
#' Step1 - extractRawLCmatrix(), curateRawLCgetET(), filterETrExtremeCols();
#' Step2 - extractWthrVar(), prepcsWthr(), calculateETref(),generateETrRatio(),
#' genThreshVal(), dataPART(), threshETr(), ordFiltETr();
#' Step3 - smoothETr();
#' Step4 - calculateTr(), getFeatures(), getFeatureHe().
#'
#'
#' The function includes seven inputs, 'data' includes LC data,
#' experimental design and genotype-replicate information in metadata, weather
#' data and genotype-replicate specific leaf area data; first (Date1) and
#' last (Date2) dates of the experiment; 'irrg.dts' is a vector of dates when
#' plants were irrigated; 'opPATH' and opPATH.smth to store intermediate
#' feature-specific files.
#'
#' @param HTP_data /code{list} of 5 dataframes composed of input files
#' a) loadcell data with unit, genotype, g_alias, treatment, timestamp
#' and Mass(g) columns
#' b) metadata with unit, old_unit, Experiment, Treatment, Species
#' Genotype, G. Alias and Replicates columns
#' c) weather data with sensor, variable, timestamp, value columns
#' d) solar radiation data is stored in separate dataframe in format c)
#' e) leaf area data with Sector, Experiment, Treatment, Species,
#' Genotype, G..Alias, Replicates, timestamp and leaf area columns
#'
#' @param lastDate /code{string} containing last date of experiment
#' in YYYY-MM-DD format.
#'
#' @param irrg.dts /code{vector} of irrigation dates, each date mentioned as
#' string in YYYY-MM-DD format. If no such date is needed, same as the last date.
#'
#' @param Date1 /code{string} value specifying first date of time series in
#' YYYY-MM-DD hh:mm:ss format.
#'
#' @param Date2 /code{string} value specifying last date of time series in
#' YYYY-MM-DD hh:mm:ss format.
#'
#' @param opPATH /code{string} value specifying the directory path for
#' intermediate results to be stored.
#'
#' @param opPATH.smth /code{string} value specifying the directory path for
#' feature-specific results to be stored.
#'
#' @return Return:
#'
#' The function returns a list of fifteen outcomes:
#' LCraw_tsmeta = Matrix of time stamp values present in raw load cell data,
#' LCraw = Matrix of raw load cell data,
#' ETrmm_Obs = Matrix of raw or observed ETr in mm
#' ETr_Obs_ERR.SEC.nms = Matrix of sector names with very high proportion of extreme values,
#' ETmm_Obs_FINAL = Matrix of ETr in mm after removing the erroneous sectors,
#' Wthr_agg15min = Matrix of all weather variables aggregated for 15 minutes interval,
#' Wthr.ETref.ETobs = Matrix of combined time series of Reference ET, ETr, weather values,
#' ETrRatio_TW1_ThreshVALS = Matrix of filtered values of Day-time ref ET/ETr ratios,
#' ETrRatio_TW2_ThreshVALS = Matrix of filtered values of Night-time ref ET/ETr ratios,
#' IrrgFilt_ETr = Matrix of Irrigation filtered ETr matrix,
#' IrrgFilt_ETr_Imptd = Matrix of irrigation filtered ETr matrix imputed,
#' ETr_smth = Matrix of smooth ETr time series,
#' Tr = Matrix of Tr time series,
#' featureH2 = Matrix of each feature heritability estimate on each day,
#' eachFeature_TS = List of each feature's time series for all genotypes.
#'
#' @author Soumyashree Kar email<[email protected]>
#'
#' @references
#'
#' Vadez, V., Kholová, J., Hummel, G., Zhokhavets, U., Gupta, S. K., &
#' Hash, C. T. (2015). LeasyScan: a novel concept combining 3D imaging and
#' lysimetry for high-throughput phenotyping of traits controlling plant water
#' budget. Journal of Experimental Botany, 66(18), 5581-5593.
####### Stage 0 : Libraries, packages, definition of parameters #######
## Load libraries
library("easypackages")
libraries("readxl", "hms", "xts", "dplyr","mgcv","PerformanceAnalytics", "wavelets",
"signal", "tidyverse", "zoo", "h2o", "sqldf", "ggplot2", "plyr",
"lubridate", "BioFTF", "plantecophys", "highfrequency", "stringr",
"chron", "nonlinearTseries", "tsfeatures", "splitstackshape", "psych", "fixr", "dplyr")
library(SpATS)
library(reshape2)
library("tidyr")
library(tidyr) # data management
library(nlme) # nonlinear model
library(locfit) # local regression
library(gss) # smoothing splines
library(factoextra)
library(gridExtra)
library(mgcv)
library(statgenHTP)
library(magick)
library(segmented)
library(MASS)
library(tidyverse)
library(rstatix)
library(stringr)
library(statgenSTA)
library(berryFunctions )
## Working directory
setwd(dir = "C:/Users/2021lg003/Documents/UPDATE_KAR_PIPELINE_LEASYSCAN_EZTr/")
# Load all the functions #
# Functions needed for processing Stage-I: LC to ETr extraction
source('./functions/extractRawLCmatrix.R') # Included 'Treatment col in meta.d'
source('./functions/curateRawLC.R')
source('./functions/filterLCExtremeCols.R')
source('./functions/getETr.R')
source('./functions/convETr.R')
source('./functions/filterETrExtremeCols.R')
# Functions needed for processing Stage-II: ETref extraction and ETr thresholding
source('./functions/extractWthrVar.R')
source('./functions/prepcsWthr.R')
source('./functions/calculateETref.R')
source('./functions/generateETrRatio.R')
source('./functions/genThreshVal.R')
source('./functions/dataPART.R')
source('./functions/threshETr.R')
source('./functions/ordFiltETr.R')
# Functions needed for processing Stage-III: raw and smooth Tr, Tr-features and feature-H2 extraction
# source('./functions/calculateTr.R')
source('./functions/getFeatures.R')
source('./functions/getFeatureHe.R')
source('./functions/smoothETr.R')
colMax <- function(data) sapply(data, max, na.rm = TRUE) ##function to find max values on the entire dataset
colMin <- function(data) sapply(data, min, na.rm = TRUE) ##function to find min values on the entire dataset
### Parameters need to be defined :
## Last date
ldt <- readline(prompt = "Enter LAST DATE of experiment (YYYY-MM-DD): ")
lastDate=as.Date(as.character(ldt)) # follow this format 2023-10-18
## First date
# NOTE 1: Enter the day BEFORE the start of the experiment. Otherwise the next steps will "cut" the first day of measurement
fdt <- readline(prompt = "Enter FIRST DATE of experiment (YYYY-MM-DD): ")
firstDate=as.Date(as.character(fdt)) # format 2023-09-27
## Time interval between two measurements
seq_by <- readline(prompt = "Enter desired time (in min) interval, e.g. 15/30/45/60: ")
seq_by=as.numeric(seq_by)
## Expected weight on the LC in grams
avg_wgt <- readline(prompt = "Enter the expected weight (in grams) on the LC: ")
avg_wgt=as.numeric(avg_wgt) ## format 70000
## Irrigation dates (format required : "2023-09-30")
# NOTE 1: Enter date(s) of irrigation or when data is extremely noisy.
# NOTE 2: If no such date, enter LAST DATE of experiment
# NOTE 3: The entire date will be deleted : in the case of evening irrigation, it is not necessary to delete the entire date.
irrg.dts <- c("2023-09-30","2023-10-03","2023-10-06", "2023-10-10", "2023-10-13", "2023-10-17", "2023-10-18")
## Date 1 and 2 : format "YYYY-MM-DD HH:MM:SS"
Date1="2023-09-26 23:46:00" # Day before 'firstDate'(For 15min, "2021-04-19 23:46:00")
Date2="2023-10-18 23:45:00" #'lastDate'(For 15min, "2021-04-29 23:45:00")
### Define path to store results
opPATH.obj= "./saved_objects/"
opPATH <- "./results/"
opPATH.smth="./results/smthFeaturesTimeSeries/"
opPATH.raw="./results/rawFeaturesTimeSeries/"
opPATH.profile="./results/profile/"
opPATH.spats="./results/STAGENHTP/"
#### Prepare the LC data and meta data
# Load data
load("./data/Exp_60_LEASYSCAN_LAURA.RData")
allData <- IRD_data_Exp_NEW
# Get load cells data i.e. weights of sector
m.lc <- allData$m.lc
# Get Genotype and Exp design metadata
meta.d <- allData$meta.d
meta.d <- distinct(meta.d) #remove duplicate entries
meta.d <- meta.d[,1:8]
# Get the list of species from the metadata
species.nm <- unique(meta.d$Species)
# Include the species ID e.g. 1 for 'Sorghum' as per the data
meta.d.sp <- meta.d[meta.d$Species==species.nm[1], ]
# Find sectors with missing metadata
noEntrySecs <- which(!unique(m.lc$unit) %in% unique(meta.d.sp$unit))
noEntrySecNms <- unique(m.lc$unit)[noEntrySecs]
# Remove sectors-without-metadata from original loadcells file
m.lc <- m.lc[! m.lc$unit %in% noEntrySecNms, ]
####### Stage-I: Process LC data and generate ETr matrix #######
st.time <- Sys.time()
# Extract matrix of loadcell data #
LC.MAT.OP <- extractRawLCmatrix(x = m.lc, y = meta.d.sp,
s=firstDate, z = lastDate,
inter = seq_by)
# save(LC.MAT.OP, file = paste(opPATH.obj, "LC.MAT.OP.RData", sep = ""))
load( file = paste(opPATH.obj, "LC.MAT.OP.RData", sep = ""))
LC.MAT.f <- LC.MAT.OP$LC.MAT.f
LC.MAT.TSinfo <- LC.MAT.OP$LC_tsmeta
# Outliers detection
check_for_negative_values(LC.MAT.f) ### LC.MAT.f can contain negative weights
max_df=as.data.frame(colMax(LC.MAT.f)) ### LC.MAT.f can contain outliers weights
max(max_df[6:nrow(max_df),]) #is this a possible weight?
# Draw the weight profile of the first LC to follow the data cleaning process (0-LC.MAT.f).
data=(LC.MAT.f)
pdf(file = paste(opPATH.profile,"1-WEIGHT_RAW.pdf", sep = ""), width = 4,height = 4)
plot<-
ggplot(data =data, aes(data$TS, data[,2]))+
ylab("Weight (g)")+
xlab("Timestamp")+
labs(title = paste("RAW DATA",colnames(data)[2]))+
geom_point()
print(plot)
dev.off()
# Add metadata to LC matrix :
# select from Metadata: "unit", "old_unit", 'Trtmt', "Genotype, "G..Alias", "Replicates"
meta.d.LCmat <- meta.d.sp[meta.d.sp$unit %in% colnames(LC.MAT.f)[-1],
c(1,2,4,6,7,8)]
LC.MAT.f.t <- as.data.frame(t(LC.MAT.f))
colnames(LC.MAT.f.t) <- LC.MAT.f$TS
# save(TS, file = paste(opPATH.obj, "TS.RData", sep = ""))
LC.MAT.f.t <- LC.MAT.f.t[-1,]
# reorder rows of 'meta.d.sp' according to rownames/unit of LC.MAT.f.t
meta.LCDF <- meta.d.LCmat[order(match(meta.d.LCmat$unit, rownames(LC.MAT.f.t))), ]
LC.MAT.raw <- as.data.frame(cbind(meta.LCDF, LC.MAT.f.t))
save(LC.MAT.raw, file = paste(opPATH.obj, "LC.MAT.raw.RData", sep = ""))
write.table(LC.MAT.raw, paste0(opPATH, "OP-1","_LCraw_wNA.csv"), sep = ";", row.names = F)
# Start outlier detection, removal and imputation of LC Matric to generate ETr profiles #
## STEP 1. Replace outliers by NA. Outliers if : negative weight + weight out the +/- 30% average weight + outlier defined boxplot of each LC,
## STEP 2. Linear imputation ,
## STEP 3. Identify remain columns with maximum missing, replace by NA
## STEP 4. Keep if 30% of values
imputed.DF.final <- curateRawLC(x = LC.MAT.f, y = meta.LCDF, z= avg_wgt) ## +/- 30 % DONE
save(imputed.DF.final, file = paste(opPATH.obj, "imputed.DF.final.RData", sep = ""))
load(file = paste(opPATH.obj, "imputed.DF.final.RData", sep = ""))
# Outliers detection post curateRawLC
check_for_negative_values(imputed.DF.final) ##imputed.DF.final should not contain negative values
max_df=as.data.frame(colMax(imputed.DF.final[7:ncol(imputed.DF.final)]))
max(max_df[1:nrow(max_df),]) ##max of imputed.DF.final should not be an outlier value
write.table(imputed.DF.final, paste0(opPATH,"OP-2","_LC_olrm_imputed.csv"), sep = ";", row.names = F)
# Identify the highly extreme valued sectors #
err.sec.info <- filterLCExtremeCols(x = imputed.DF.final, y = meta.LCDF)
err.sec.nm <- err.sec.info$err.sec.NM
err.sec.meta <- err.sec.info$err.sec.META
write.table(err.sec.meta, paste0(opPATH, "OP-3","_LCimp_errorUnits.csv"), sep = ";", row.names = F)
# Remove the err.cols i.e. sectors with extreme values
impData.errSEC.rmvd <- imputed.DF.final[!imputed.DF.final$unit %in% err.sec.nm, ]
# save(impData.errSEC.rmvd, file = paste(opPATH.obj, "impData.errSEC.rmvd.RData", sep = ""))
# Now, the weight profile should be cleaned. Verify on the first LC
data=t(impData.errSEC.rmvd)
colnames(data)=data[1,]
data=data[-c(1:6),]
data<- as.data.frame(apply(data, 2, as.numeric))
data$TS= colnames(impData.errSEC.rmvd)[7:ncol(impData.errSEC.rmvd)]
data$TS =ymd_hms(data$TS)
pdf(file = paste(opPATH.profile,"2-WEIGHT_FILTERED.pdf", sep = ""), width = 4,height = 4)
plot<-
ggplot(data =data, aes(TS, data[,1]))+
ylab("Weight (g)")+
xlab("Timestamp")+
labs(title = paste("WEIGHT AFTER FILTERING",colnames(data)[1]))+
geom_point()
print(plot)
dev.off()
# Generate ETr profiles from "impData.errSEC.rmvd" dataframe #
et.vals <- getETr(x = impData.errSEC.rmvd)
save(et.vals, file = paste(opPATH.obj, "et.vals.RData", sep = ""))
# load(file = paste(opPATH.obj, "et.vals.RData", sep = ""))
et.obs <- et.vals$obsETr_core
ETr_Meta <- et.vals$obsETr_meta
# Convert ETr in grams to mm (Y/N) # ## !! careful to put the Y or N in CAPITAL LETTER
ETr_F <- convETr(x = ETr_Meta, y = et.obs) ## AJOUTER UNE PARTIE ADAPTEE pour L'IRD (surface LC differente avec ICRISAT)
save(ETr_F , file = paste(opPATH.obj, "ETr_F.RData", sep = ""))
load(file = paste(opPATH.obj, "ETr_F.RData", sep = ""))
# # Draw the profile of a LC (weight/ETr) to follow the data cleaning process (2-ETr_F).
data=t(ETr_F)
colnames(data)=data[1,]
data=data[-c(1:6),]
TS=rownames(data)
data_num <- as.data.frame(apply(data, 2, as.numeric))
data=as.data.frame(data)
data=data_num
data$TS= TS
data$TS =ymd_hms(data$TS )
pdf(file = paste(opPATH.profile,"3-ET_RAW_VALUES.pdf", sep = ""), width = 4,height = 4)
plot<-
ggplot(data =data, aes(TS, data[,1]))+
ylab("ET (mm.15min-1)")+
xlab("Timestamp")+
labs(title = paste("RAW ET DATA",colnames(data)[1]))+
geom_point()
print(plot)
dev.off()
write.table(ETr_F, paste0(opPATH, "OP-5","_ETr_Obs.csv"), col.names = TRUE, row.names = FALSE, sep = ";", dec = ".")
####### Stage-II: Process Weather data to obtain ETref + filter ETr based on ETref #######
wthr.DFagg15min <- IRD_data_Exp_NEW$climate
wthr.DFagg15min$Date <- lubridate::dmy(wthr.DFagg15min$Date) #Format here
wthr.DFagg15min <- wthr.DFagg15min[wthr.DFagg15min$Date>=firstDate &
wthr.DFagg15min$Date<=lastDate,]
wthr.DFagg15min$TS <- ymd_hms(paste0(as.character(wthr.DFagg15min$Date),
wthr.DFagg15min$TS))
wthr.DFagg15min <- wthr.DFagg15min[,-1]
wthr.DFagg15min= wthr.DFagg15min[-c(2061: nrow(wthr.DFagg15min)),] ## there is empty row at the end of dataset .. why? need to be removed
# Create empty base matrix for weather variables
end.seq_hhmm <- '23:45'
if (seq_by == '15'){
end.seq_hhmm <- '23:45'
} else if(seq_by == '30'){
end.seq_hhmm <- '23:30'
} else if(seq_by == '45'){
end.seq_hhmm <- '23:15'
} else if(seq_by == '60'){
end.seq_hhmm <- '23:00'}
TS_base<-as.data.frame(as.character(seq(ymd_hm(paste0(firstDate," ",'00:00')),
ymd_hm(paste0(lastDate," ",end.seq_hhmm)),
by = paste0(seq_by, " ", "mins"))))
#
# TS_base<-as.data.frame(as.character(seq(ymd_hm(paste0(firstDate," ",'00:00')),
# ymd_hm(paste0(lastDate," ",'23:45')), by = '15 mins')))
names(TS_base)[1]<-c("int.val")
TS_base$time <- strftime(TS_base$int.val, format="%H:%M:%S", tz="UTC")
# Since, the hms values slightly differ in the orginal dataset than the ideal 15min interval values,
# replace them with the TS_base strftime (hms) values
hms.ts.base<-unique(TS_base$time)
names(hms.ts.base)<-c("time")
print("Climate matrix timestamp mapping status")
i<-nrow(wthr.DFagg15min)
pbar <- create_progress_bar('text')
pbar$init(i)
for(i in 1:nrow(wthr.DFagg15min))
{
if(! wthr.DFagg15min$TS[i] %in% hms.ts.base)
{
j <- which.min(abs(chron(times=hms.ts.base) -
chron(times=format(wthr.DFagg15min$TS[i],format = "%H:%M:%S")))) # find which value in ts-base-vector is nearest to each-DP
# assign the nearest ts-base-vector value to that DP
dd <- date(wthr.DFagg15min$TS[i])
wthr.DFagg15min$TS[i] <- ymd_hms(paste0(dd, TS_base$time[j]))}
pbar$step()
}
# TS_ALL<-as.data.frame(as.character(seq(ymd_hm(paste0(firstDate," ",'00:00')),
# ymd_hm(paste0(lastDate," ",'23:45')), by = '15 mins')))
TS_ALL<-as.data.frame(as.character(seq(ymd_hm(paste0(firstDate," ",'00:00')),
ymd_hm(paste0(lastDate," ",end.seq_hhmm)),
by = paste0(seq_by, " mins"))))
names(TS_ALL)[1]<-c("TS.n") # MUST be the same as in original data set m.lc.df
TS_ALL$TS.n <- ymd_hms(TS_ALL$TS.n)
# create empty dataframe to store all values
Wthr.MAT <- as.data.frame(matrix(nrow = length(TS_ALL$TS.n),
ncol = ncol(wthr.DFagg15min)))
Wthr.MAT[ ,1] <- TS_ALL$TS.n; names(Wthr.MAT)[1] <- "TS"
colnames(Wthr.MAT)[2:ncol(Wthr.MAT)] <- names(wthr.DFagg15min)[2:ncol(wthr.DFagg15min)]
df <- merge(x = wthr.DFagg15min, y = Wthr.MAT, by = "TS", all = TRUE) # perform outer join to merge by id=TS.n
df.new <- df[,1:6]; names(df.new)[2:6]<-names(wthr.DFagg15min)[2:6]
df.new <- df.new[!duplicated(df.new[c("TS")]),]
# colnames(df.new)[2] <- names(wthr.DFagg15min)[1]
etrDTS <- as.data.frame(colnames(ETr_F)[7:ncol(ETr_F)])
names(etrDTS) <- "TS"
etrDTS$TS <- ymd_hms(etrDTS$TS)
df.new <- df.new[df.new$TS %in% etrDTS$TS, ] # subset after outer join to ensure that NAs don't add extra rows
# Pre-process weather
df.new$Temp <- if(sum(is.na(df.new$Temp))>0){df.new$Temp<-na.aggregate.default(df.new$Temp)}
df.new$RH <- if(sum(is.na(df.new$RH))>0){df.new$RH<-na.aggregate.default(df.new$RH)}
df.new$SR <- if(sum(is.na(df.new$SR))>0){df.new$SR<-na.aggregate.default(df.new$SR)}
df.new$WS <- if(sum(is.na(df.new$WS))>0){df.new$WS<-na.aggregate.default(df.new$WS)}
wthr.DFagg15min.filt <- df.new
# Compute VPD and insert into the weather DF #
SVP <- 610.7*(10^(7.5*wthr.DFagg15min.filt[ ,2]/(237.3+wthr.DFagg15min.filt[ ,2])))
VPD <- ((1 - (wthr.DFagg15min.filt[ ,3]/100))*SVP)/1000
wthr.DFagg15min.filt[ ,4] <- VPD
et.obs <- ETr_F
save(et.obs, file = paste(opPATH.obj, "et.obs.RData", sep = ""))
# Calculate Penman Monteith ET #
wthr.df1 <- calculateETref(x=wthr.DFagg15min.filt)
max(wthr.df1$ETref) ## possible or outlier?
wthr.ETref.df <- as.data.frame(wthr.df1)
empty.MAT <- matrix(nrow = 8,
ncol = (ncol(et.obs)-nrow(wthr.df1)))
# select columns "Temp" "RH" "VPD" "SR" "WS" "Tmax" "Tmin" "ETref"
empty.MAT.wthr.ETref <- as.data.frame(cbind(empty.MAT, t(wthr.ETref.df[,c(2:6, 9:11)])))
colnames(empty.MAT.wthr.ETref) <- colnames(et.obs)
wthr.ETref.ETobs <- as.data.frame(rbind(empty.MAT.wthr.ETref, et.obs))
save(wthr.ETref.ETobs, file = paste(opPATH.obj, "wthr.ETref.ETobs.RData", sep = ""))
# Remove irrigation dates #
file.colnms <- colnames(wthr.ETref.ETobs)
wthr.ETref.ETobs <- wthr.ETref.ETobs[ ,!substr(file.colnms,1,10) %in% irrg.dts]
save(wthr.ETref.ETobs, file = paste(opPATH.obj, "wthr.ETref.ETobs.RData", sep = ""))
## save some parts of wthr.ETref.ETobs dataframe to reuse after (the format of wthr.ETref.ETobs will be use for the features extraction)
TS= colnames(wthr.ETref.ETobs[7:ncol(wthr.ETref.ETobs)])
save(TS,file= paste(opPATH.obj, "TS.RData", sep = "") )
LC= wthr.ETref.ETobs[9:nrow(wthr.ETref.ETobs),1]
save(LC,file= paste(opPATH.obj, "LC.RData", sep = "") )
metad_emptyrows= wthr.ETref.ETobs[,1:6]
save(metad_emptyrows, file = paste(opPATH.obj,"metad_emptyrows.RData", sep = ""))
weather= wthr.ETref.ETobs[1:8,]
save(weather, file = paste(opPATH.obj,"weather.RData", sep = ""))
## Filter ETobs based on ETREF values on solar radiation values (SR) instead of hours (in the initial version)
### if SR = 0 --> night period --> ET = 0
### if SR > 0 --> day period --> -0.01<ET<ETref
ET_ratio_mat <- generateETrRatio(x = wthr.ETref.ETobs)
save(ET_ratio_mat, file = paste(opPATH.obj,"ET_ratio_mat.RData", sep = ""))
ET_ratio_mat[, 9:ncol(ET_ratio_mat) ]= round(ET_ratio_mat[, 9:ncol(ET_ratio_mat) ] , 3)
rownames(ET_ratio_mat)= TS
colnames(ET_ratio_mat)[9:ncol(ET_ratio_mat)]= LC
# come back to wthr.ETref.ETobs format: with metadata + a dataframe (TS in col, LC in row)
wthr.ETref.ETobs_ratio= t(ET_ratio_mat)
ETr_smth_metad= cbind(metad_emptyrows, wthr.ETref.ETobs_ratio) ## ET filtered non normalized, with the expected format (wthr.ETref.ETobs format)
save(ETr_smth_metad, file = paste(opPATH.obj,"ETr_smth_metad.RData", sep = ""))
load(file = paste(opPATH.obj,"ETr_smth_metad.RData", sep = ""))
write.table(ETr_smth_metad, paste0(opPATH, "ETr_smth_metad.csv"), sep = ";", row.names = F, dec = ".")
# Outliers detection
check_for_negative_values(ETr_smth_metad[(9:nrow(ETr_smth_metad)),(7:ncol(ETr_smth_metad))])
max_df=as.data.frame(colMax(ETr_smth_metad[(9:nrow(ETr_smth_metad)),(7:ncol(ETr_smth_metad))]))
max(max_df[1:nrow(max_df),])
# # Identify error plots from ETr values using the similar method as above #
ETr_err.sec.info <- filterETrExtremeCols(x = ETr_smth_metad, y = meta.LCDF) ## FILTRER APRES LA PARTIE ET ETREF !!!
err.sec.nm <- ETr_err.sec.info$ETr_err.sec.NM
err.sec.meta <- ETr_err.sec.info$ETr_err.sec.META
if(length(err.sec.nm)>0){write.table(err.sec.meta,
paste0(opPATH, "OP-6","_ET_Obs_ERR.SEC.nms.csv"), sep = ";", row.names = F, dec = ".")}
# Remove the err.cols i.e. sectors with extreme values #
ETr_Meta_ERRsec.rmvd <- ETr_smth_metad
ETr_Meta_ERRsec.rmvd <- ETr_Meta_ERRsec.rmvd[!ETr_Meta_ERRsec.rmvd$unit %in% err.sec.nm, ]
write.table(ETr_Meta_ERRsec.rmvd, paste0(opPATH,
"OP-7","_ETr_Obs_FINAL.csv"), sep = ";", row.names = F, dec = ".")
save(ETr_Meta_ERRsec.rmvd, file = paste(opPATH.obj,"ETr_Meta_ERRsec.rmvd.RData", sep = ""))
load(paste(opPATH.obj,"ETr_Meta_ERRsec.rmvd.RData", sep = ""))
# Outliers detection
max_df=as.data.frame(colMax(ETr_Meta_ERRsec.rmvd[(9:nrow(ETr_Meta_ERRsec.rmvd)),(7:ncol(ETr_Meta_ERRsec.rmvd))]))
max(max_df[1:nrow(max_df),])
## END of filtering process
# Now the ET profile should be cleaned. Draw the ET profile of the first LC
data=t(ETr_Meta_ERRsec.rmvd)
data=data[,-c(1:8)]
data=data[-c(1:6),]
data_num <- as.data.frame(apply(data, 2, as.numeric))
data=data_num
data= cbind(TS, data)
data$TS =ymd_hms(data$TS )
colnames(data)[2:ncol(data)]=LC
pdf(file = paste(opPATH.profile, "4-ET_PROFIL_FILTERED.pdf", sep = ""), width = 4,height = 4)
plot<-
ggplot(data =data, aes(TS, data[,2]))+
ylab("ET mm.15min-1")+
xlab("Timestamp")+
labs(title = paste("ETr profile filtered",colnames(data)[2]))+
geom_point()+
geom_line()+
ggplot2::scale_x_datetime(labels = scales::date_format(format = "%d-%m"), date_breaks = "1 days")+
theme(axis.text.x=element_text(angle = -45, hjust = 0))
print(plot)
dev.off()
####### STAGE III: Process Plant Eye data with spatial correction #######
## some inputs come from V. Garin work LS
## https://github.com/ICRISAT-GEMS/platformDataAnalysis
library("easypackages")
libraries("dplyr","LoadCellDataProcessing", "statgenHTP", "platformDataAnalysis" ,
"ggplot2", "lubridate", "SpATS", "reshape2", "tidyr", "nlme", "locfit",
"gss","factoextra", "gridExtra","mgcv", "magick", "segmented", "MASS",
"tidyverse","rstatix")
##Input pe data and spatial correction
pe_data <- read.csv(file = "./data/Exp60 Sorghum Ref set IRD Trial Sep 2023-477 mm_20231027_planteye.csv", sep=";")
## !! note that pe_data have been prepared with position line and
colnames(pe_data) ## 1] "barcode","n","r", "old_unit", "unit", "Line" , "Plot", "ID","genotype", "timestamp","timeNumber", "Digital_biomass",...
##SI BESOIN DE RETOURNER au design
# LABEL <- read.csv("C:/Users/2021lg003/Documents/LEASYSCAN_EXP_INDE_2023/DATASET/FULL_DATASET/Label_SPATS.csv", header=T, sep=";", dec = ".")
# LABEL=na.omit(LABEL)
# LABEL= LABEL[-3] ## removed Variety ID
# Label_geno <- read.csv("C:/Users/2021lg003/Documents/LEASYSCAN_EXP_INDE_2023/DATASET/FULL_DATASET/Label_Genotype.csv", header=T, sep=";")
#save for later
d_exp= read.csv2( "./data/d_exp_template.csv")
save(d_exp,file = paste(opPATH.obj,"d_exp.RData", sep = ""))
pe_data$genotype<-as.factor(pe_data$genotype) ##321 genotypes
pe_data$treatment<-as.factor(pe_data$treatment)
pe_data=na.omit(pe_data)
pe_data$timestamp= dmy_hm(pe_data$timestamp)
pe_data$date= date(pe_data$timestamp)
pe_data<-pe_data %>% arrange(timestamp) ##trie par ordre croissant
start=which((pe_data$date) == "2023-09-28")
end=which((pe_data$date) == "2023-10-17")
pe_data=pe_data[(start[1]):(end[length(end)]),]
pe_data$timeNumber= as.character(pe_data$timeNumber)
unique(pe_data$timeNumber)
for (i in 1:length(unique(pe_data$timeNumber))) {
pe_data$timeNumber[pe_data$timeNumber== unique(pe_data$timeNumber)[i]] <- i
}
pe_data$timeNumber = as.factor(pe_data$timeNumber)
for (i in levels(pe_data$timeNumber)){
Data <- pe_data %>%
dplyr::filter(pe_data$timeNumber == i)
DF= Data[duplicated(Data$ID), ] ##
Data$timestamp = Data$timestamp[1] ## ne mettre qu'un seul timestamp commun pour tout le numero de scan
Data_unique= Data[!duplicated(Data$ID), ] ##
write.table(DF,file = paste(opPATH,"DOUBLONS.csv", sep = ""), append = TRUE, col.names = FALSE, row.names = FALSE, sep = ";")
write.table(Data_unique,file = paste(opPATH,"pe_data_unique.csv", sep = ""), append = TRUE, col.names = FALSE, row.names = FALSE, sep = ";")
}
pe_data_unique= read.csv2(file = paste(opPATH,"pe_data_unique.csv", sep = ""), header = FALSE)
colnames(pe_data_unique) = c("barcode", "n", "r", "old_unit", "unit", "Line", "Plot", "PlotId","genotype", "g_alias", "treatment", "geno_trt","timestamp", "timeNumber",
"Digital_biomass" ,"greenness.average","greenness.bin0" ,"greenness.bin1" , "greenness.bin2" ,"greenness.bin3", "greenness.bin4" , "greenness.bin5" , "Height" , "Height.Max..mm.",
"hue.average..Â..", "hue.bin0" , "hue.bin1" , "hue.bin2" , "hue.bin3",
"hue.bin4" , "hue.bin5" , "Leaf_angle" , "Leaf_area" , "Leaf_area_index",
"Leaf_area_projected" , "Leaf_inclination" , "Light_penetration_depth", "NDVI.average", "NDVI.bin0" ,
"NDVI.bin1" , "NDVI.bin2" , "NDVI.bin3" , "NDVI.bin4" , "NDVI.bin5" ,
"NPCI.average" , "NPCI.bin0" , "NPCI.bin1" , "NPCI.bin2" , "NPCI.bin3" ,
"NPCI.bin4" , "NPCI.bin5" , "PSRI.average" , "PSRI.bin0" , "PSRI.bin1" ,
"PSRI.bin2" , "PSRI.bin3" , "PSRI.bin4" , "PSRI.bin5" )
pe_data_unique$timeNumber=as.numeric(pe_data_unique$timeNumber)
pe_data=pe_data_unique
rm(pe_data_unique)
## plotId has to be unique within each time point for TP_PE : check
colnames(pe_data) <- mdf_raw_pe_colnames(colnames = colnames(pe_data))
ref_trait_nm <- c("Digital_biomass", "Height", "Leaf_angle", "Leaf_area",
"Leaf_area_index", "Leaf_area_projected", "Leaf_inclination",
"Light_penetration_depth")
pe_data <- pe_data %>% select(timeNumber, timestamp, unit, genotype, treatment,
Digital_biomass, Height, Leaf_angle, Leaf_area, Leaf_area_index,
Leaf_area_projected, Leaf_inclination, Light_penetration_depth)
pe_data[, 6:ncol(pe_data)] <- sapply(pe_data[, 6:ncol(pe_data)], as.numeric)
pe_data$timestamp= lubridate::ymd_hms(pe_data$timestamp)
colnames(pe_data) <- c("timeNumber", "timePoint", "unit", "genotype", "treatment","Digital_biomass", "Height", "Leaf_angle", "Leaf_area",
"Leaf_area_index", "Leaf_area_projected", "Leaf_inclination",
"Light_penetration_depth")
# add extra columns from the experimental design
pe_data <- add_exp_des_col(data = pe_data, d_exp_des = d_exp,
data_unit = "unit",
d_exp_unit = "new_unit",
col_add = c("rowNum", "colNum", "block", "plotId"))
# arrange the columns in a certain order
pe_data <- pe_data %>% select(timeNumber, timePoint, block, rowNum, colNum, plotId,
genotype, Digital_biomass, Height,
Leaf_angle, Leaf_area, Leaf_area_index,
Leaf_area_projected, Leaf_inclination,
Light_penetration_depth)
# PE pipeline: remove tp with too high missing values
pe_data$Leaf_area= as.numeric(pe_data$Leaf_area)
pe_data$timeNumber=as.numeric(pe_data$timeNumber)
pdf(file = paste(opPATH.profile, "3D_leaf_area_over_time.pdf", sep = ""), width = 4,height = 4)
plot<- plot_trend(data = pe_data, trait = "Leaf_area")
print(plot)
dev.off()
# PE pipeline: trim the time series
# remove days progressively the end of the exp until obtain a linear regression
sel_tp <- sort(unique(pe_data$timePoint)) # all timePoint in the TS
sel_tp<-sel_tp[order(sel_tp)]
sel_tp
sel_tp <- sel_tp[-c(29:length(sel_tp))] # remove last days one by one, We decide to keep only the linear part at the start of the exp, until the "2023-10-11 ", where we see a inflexion point
sel_tp
pe_data <- pe_data[pe_data$timePoint %in% sel_tp, ]
save(pe_data,file = paste(opPATH.obj,"pe_data.RData", sep = ""))
load(file = paste(opPATH.obj,"pe_data.RData", sep = ""))
pdf(file = paste(opPATH.profile, "3D_leaf_area_over_time_rmd_out.pdf", sep = ""), width = 4,height = 4)
plot =plot_trend(data = pe_data, trait = "Leaf_area") ## visualize to keep only the linear part at the start
print(plot)
dev.off()
# PE pipeline: Creation of TP object
TP_PE <- createTimePoints(dat = pe_data,
experimentName = "EXP60",
genotype = "genotype",
timePoint = "timePoint",
plotId = "plotId",
rowNum = "rowNum", colNum = "colNum")
summary(TP_PE)
save(TP_PE, file=paste(opPATH.obj,"TP_PE.RData", sep = ""))
load(file=paste(opPATH.obj,"TP_PE.RData", sep = ""))
# PE pipeline: Spatial adjustment
Timepoint <- getTimePoints(TP_PE)
save(Timepoint, file =paste(opPATH.obj, "Timepoint.RData", sep = ""))
## Plot the layout for the each point.
for (i in 1:nrow(Timepoint)) {
png(file = paste(opPATH.spats,i, "_PE_LAYOUT.png", sep = ""))
plot<-
plot(TP_PE,
plotType = "layout",
timePoints = i,
traits = "Leaf_area")
print(plot)
dev.off()
}
modPhenoSpGDP <- NULL
modPhenoSpGDP <- fitModels(TP = TP_PE,
trait = "Leaf_area",
timePoints = c(1:nrow(Timepoint)) )
save(modPhenoSpGDP, file = paste(opPATH.obj,"modPhenoSpGDP.RData", sep = ""))
load(file = paste(opPATH.obj,"modPhenoSpGDP.RData", sep = ""))
summary(modPhenoSpGDP)
### plot SPATS results over timePoint
for (i in 1:nrow(Timepoint)) {
png(file = paste(opPATH.spats,i, "_SPATS.png", sep = ""))
plot(modPhenoSpGDP,
timePoints = i,
plotType = "spatial",
spaTrend = "percentage",
colorBy = "repId")
dev.off()
}
## Plot heritability over time
png(file = paste(opPATH.spats,i, "_H2_over_time.png", sep = ""))
plot(modPhenoSpGDP,
plotType = "herit",
ylim = c(0.5,1))
getHerit(modPhenoSpGDP)
dev.off()
## Plot residual, column and raw variance over time
png(file = paste(opPATH.spats,i, "_variance_over_time.png", sep = ""))
plot(modPhenoSpGDP,
plotType = "variance")
dev.off()
## Extract the corrected values:
spatCorrSpGDP <- getCorrected(modPhenoSpGDP, timePoints = 1:nrow(Timepoint))
write.table(spatCorrSpGDP, paste(opPATH.spats,"Leaf_Area_Corrected_statgenHTP.csv", sep = ""))
save(spatCorrSpGDP, file = paste(opPATH.obj,"spatCorrSpGDP.RData", sep = "" ))
load(file = paste(opPATH.obj,"spatCorrSpGDP.RData", sep = "" ))
spatCorrSpGDP$genotype= as.factor(spatCorrSpGDP$genotype)
spatCorrSpGDP$timePoint= as.factor(spatCorrSpGDP$timePoint)
## plot 3D-LA raw and 3D-LA corrected over time for each LC
# for (i in levels(spatCorrSpGDP$plotId)) {
i=levels(spatCorrSpGDP$plotId)[1]
exemple_i <- spatCorrSpGDP %>%
dplyr::filter(spatCorrSpGDP$plotId== i)
png(file = paste(opPATH.profile,i,"_LA_corr_raw.png", sep = ""))
plot<-
ggplot(data =exemple_i, aes(timeNumber))+
ylab("LA mm²")+
xlab("Timestamp")+
labs(title = paste("3D-LA and 3D-LA corr"))+
geom_point(aes(y = Leaf_area_corr), color = "steelblue")+
geom_point(aes(y = Leaf_area), color = "darkred")+
geom_line(aes(y = Leaf_area_corr), color="steelblue", linetype="twodash") +
geom_line(aes(y = Leaf_area), color="darkred", linetype="twodash")
print(plot)
dev.off()
print(i)
# }
LB_MEAN_plot <- spatCorrSpGDP %>%
select(plotId, Leaf_area_corr) %>%
group_by(plotId) %>%
summarize_all(funs(mean_Leaf_area_corr = mean (Leaf_area_corr, na.rm=T), n = n(), sd = sd(Leaf_area_corr, na.rm=T), se = sd(.)/sqrt(n-1))) %>%
filter(is.finite(mean_Leaf_area_corr)) %>%
filter(mean_Leaf_area_corr > 0)
LB_MEAN_genotype <- spatCorrSpGDP %>%
select(genotype, Leaf_area_corr) %>%
group_by(genotype) %>%
summarize_all(funs(mean_Leaf_area_corr = mean (Leaf_area_corr, na.rm=T), n = n(), sd = sd(Leaf_area_corr, na.rm=T), se = sd(.)/sqrt(n-1))) %>%
filter(is.finite(mean_Leaf_area_corr)) %>%
filter(mean_Leaf_area_corr > 0)
save(LB_MEAN_genotype, file = paste(opPATH.obj,"LB_MEAN_genotype.RData", sep = ""))
save(LB_MEAN_plot, file = paste(opPATH.obj,"LB_MEAN_plot.RData", sep = ""))
#
# load(file = "LB_MEAN_genotype.RData")
# load(file = "LB_MEAN_plot.RData")
#
#
# LB_MEAN_plot_day<- spatCorrSpGDP %>%
# select(plotId, Leaf_area_corr, date) %>%
# group_by(date, plotId) %>%
# summarize_all(funs(mean_Leaf_area_corr_day = mean (Leaf_area_corr, na.rm=T))) %>%
# filter(is.finite(mean_Leaf_area_corr_day)) %>%
# filter(mean_Leaf_area_corr_day > 0)
# save(LB_MEAN_plot_day, file= "mean_Leaf_area_corr_day.RData")
##make link between pe_data (after spatial correction) and pe.df.ETr dataset used in Kar et al. 2020
## "Sector", "Genotype", "Replicates", "LeafArea3D", "TS", "date"
spatCorrSpGDP$date= date(spatCorrSpGDP$timePoint)
spatCorrSpGDP$date = ymd(spatCorrSpGDP$date)
spatCorrSpGDP= spatCorrSpGDP %>% inner_join(d_exp, by = c('plotId'))
# Rename as the following columns: "Sector", "Genotype", "Replicates", "LeafArea3D", "TS", "date"
colnames(spatCorrSpGDP)[2]= "TS"
colnames(spatCorrSpGDP)[15]= "Genotype"
colnames(spatCorrSpGDP)[18]= "Sector"
colnames(spatCorrSpGDP)[13]= "Replicates"
colnames(spatCorrSpGDP)[3]= "LeafArea3D" ## PE CORRECTED VALUES
colnames(spatCorrSpGDP)[4]= "LeafArea3D_raw" ## PE RAW VALUES
spatCorrSpGDP <- spatCorrSpGDP %>% select(Sector, Genotype, Replicates, LeafArea3D,
LeafArea3D_raw, TS,date)
pe.df.ETr= spatCorrSpGDP
colnames(pe.df.ETr) <- c("old_unit", "Genotype", "Replicates", "LeafArea3D", "LeafArea3D_raw", "TS", "date")
save(pe.df.ETr, file = paste(opPATH.obj,"pe.df.ETr.RData", sep = ""))
load(file = paste(opPATH.obj,"pe.df.ETr.RData", sep = ""))
pe.df.ETr$Genotype <- factor(pe.df.ETr$Genotype)
pe.df.ETr$Replicates <- factor(pe.df.ETr$Replicates)
pe.df.ETr$date=as.factor(pe.df.ETr$date)
# ## should we used 3D LA corrected or 3D-LA raw : ANOVA LA - repetition significant or not ?
# for (i in levels(pe.df.ETr$date)) {
#
# exemple_i <- pe.df.ETr %>%
# dplyr::filter(pe.df.ETr$date== i)
#
# model=lm(LeafArea3D~Replicates*Genotype, data = pe.df.ETr)
# aov<-Anova(model)
# print(aov)
#
# }
####### STAGE IV: Calculation of LAI per day, LAI per TS, observed LA, Transpiration and TRrate #######
# conversion3D-LA --> observed LA
# create files adapted for Kar et al pipeline LAI.mat, sel.secs, subs.d
load(file = "./saved_objects/ETr_Meta_ERRsec.rmvd.RData")
load(file = "./saved_objects/pe.df.ETr.RData")
load(file = "./saved_objects/TS.RData")
load(file = "./saved_objects/wthr.ETref.ETobs.RData")
ETr_smoothFILE = ETr_Meta_ERRsec.rmvd
save(ETr_smoothFILE, file = paste(opPATH.obj,"ETr_smoothFILE.RData", sep = ""))
sel.secs <- unique(na.omit(ETr_smoothFILE$old_unit))
length(sel.secs)
save(sel.secs, file = "./saved_objects/sel.secs.RData")
length(TS)
TS= as.character(TS)
LAI.mat <- matrix(NA, nrow = length(sel.secs), ncol = length(TS))
rownames(LAI.mat) <- sel.secs
colnames(LAI.mat) = TS
save(LAI.mat, file = "./saved_objects/LAI.mat.RData")
unq.dts <- unique(substr(colnames(wthr.ETref.ETobs)[-c(1:6)], 1, 10))
length(unq.dts)
LAI.mat <- LAI.mat[order(match(rownames(LAI.mat),
ETr_smoothFILE[(9:nrow(ETr_smoothFILE)), "old_unit"])),]
LAI.all.dates <- LAI.mat; unq.dts.copy <- unq.dts
LAI.all.dates <- LAI.all.dates[ , c(1:length(unq.dts))]
colnames(LAI.all.dates) <- c(as.character(unq.dts.copy))
################################ 1. CALCUL LEAF AREA INDEX PER DAY ################################
# objectives :
# - calculate the median of 3D PE, converted 3D-PE to observed LA with the relation of Vadez 2015
# - insert planimeter value
# - calculate the relation of LA over time with observed LA and planimeter value + save the slope
# - replace NA value of LA (from last 3D PE scan to planimeter) with previous value +slope
# - plot LAI per day
# 1) LAI when we have PE value (from 28.09.23 to 11.10.23)
for(i in 1:nrow(LAI.mat)){ ## for all unit of LAI.mat
la.df.tmp <- pe.df.ETr[pe.df.ETr$old_unit == rownames(LAI.mat)[i], ] ## select unit in common between pe.data and LAI
la.df.med <- la.df.tmp %>% group_by(date) %>% ## group by date and provide median of LeafArea3D
dplyr::summarise(Med_LeafArea3D = median(LeafArea3D))
date.mat <- data.frame(date = unq.dts, val = rep(NA, length(unq.dts))) ## create df with date, val (empty, length unique date)
date.mat$date = ymd(date.mat$date)
for(j in 1:nrow(date.mat)) ## for all row of this date.mat df
{
ifelse(date.mat$date[j] %in% la.df.med$date,
date.mat$val[j] <- la.df.med$Med_LeafArea3D[la.df.med$date == date.mat$date[j]],
date.mat$val[j] <- NA) ## fill in df with val= median per date
}
# Relation from Vadez et al. 2015 LeasyScan: a novel concept ... )
# y= 3DLA x= Observed LA. Relation species-dependant
# y=0.36x +29.9 --> Observed LA(x) = (3DLA_mm²/0.36)-29.9 for pearl millet
# y=0.36x +63.2 --> Observed LA(x) = (3DLA_mm²/0.36)-63.2 for peanut
# y=0.39x + 302.2 --> Observed LA(x) = (3DLA_mm²/0.39)-302.2 for cowpea
# * 0.26 m² to measure LAI #!! careful; 0.26m² = surface of LC in ICRISAT !! not suitable for IRD platform
sec.lai.dates <- rep(date.mat$val, each =1)
LAI.all.dates[i, ] <- ((((sec.lai.dates/100) - 29.9)/0.36)*(1/0.26)/10000) ##for pearl millet
}
# LAI per day with NA value until limit PE
## 2) insert planimeter value and linked with PE value
### insert planimeter values on excel
LAI = read.csv(file = "./data/LAI_converted_with_NA_planimeter.csv", sep = ";") # (correspond à la date du 19/10/2023)
rownames(LAI)= LAI[,1]
LAI = LAI %>% arrange(LAI$X) ##trie par ordre croissant de nom de LC
LAI$X10.10.2023= NA
LAI$X11.10.2023 = NA ## les données du 10 et 11 oct sont outliers dans certains cas de nombreux cas de LC, mieux vaut les enlever pour améliorer la relation
colnames(LAI)[9:ncol(LAI)]= sub("X","",colnames(LAI)[9:ncol(LAI)])
## removed 38:10:01 and 38:10:02 (row 854 and 855) because there are just planimeter data (PE 3DLA are missing data)
LAI[854,1]
LAI[855,1]
LAI= LAI[-c(854, 855),]
# add a day to unq.dts for planimeter data
unq.dts=colnames(LAI)[9:ncol(LAI)]## there is still irrigation dates (22 days)
unq.dts= dmy(unq.dts)
length(unq.dts)
date.mat <- data.frame(date = unq.dts, val = rep(NA, length(unq.dts))) ## create df with date, val (empty, length unique date)