-
Notifications
You must be signed in to change notification settings - Fork 0
/
GFA_Evaluation.R
3238 lines (3111 loc) · 165 KB
/
GFA_Evaluation.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
#! /usr/bin/env Rscript --vanilla
# DO NOT REMOVE THE ABOVE COMMENT LINE. It is required for using the script via
# the command line/shell.
# Nach Vorlage von 'Grünfläche_Verlauf.R' und 'Grünflächenanalyse_v3.R'
# abgewandelt zur Anwendung im Rahmen des Versuches 2 meines Praktikums
#
#
#
# ~CA
#
#
#
# Libraries 1 -------------------------------------------------------------
library(optparse) # required for allowing command line interaction to the script
library(stringr)
# Libraries CLI Setup 1 ---------------------------------------------------
if (sys.nframe() == 0) { ## check if script is run by rscript -> this will return 0. If it returns >0, it is either sourced or run directly. if it is run via bash, this will return 0
option_list <- list(
make_option(c("-i", "--input"),
type = "character", default = NULL, metavar = "filepath",
help = "Full path to configuration File."
),
make_option(c("-d", "--returnDays"),
type = "integer", default = 0,
help = "pseudo-boolean Flag, either numerical 1 or 0 [Default: %default].\n\t\tToggles execution of per-day analyses", metavar = "[integer]"
),
make_option(c("-f", "--saveFigures"),
type = "integer", default = 0,
help = "pseudo-boolean Flag, either numerical 1 or 0 [Default: %default].\n\t\tToggles whether or not figures generated are saved to disk or not. Files are saved to a subfolder relative to configuration file supplied via the option '-i'", metavar = "[integer]"
),
make_option(c("-e", "--saveExcel"),
type = "integer", default = 0,
help = "pseudo-boolean Flag, either numerical 1 or 0 [Default: %default].\n\t\tToggles whether or not statistical evaluation and results generated are saved to disk as an '.xlsx'-file or not. Files are saved to a subfolder relative to configuration file supplied via the option '-i'", metavar = "[integer]"
),
make_option(c("-r", "--saveRDATA"),
type = "integer", default = 0,
help = "pseudo-boolean Flag, either numerical 1 or 0 [Default: %default].\n\t\tToggles whether or not all generated data (plots, loaded configuration data, relevant evaluation functions) are saved to an '.RData'-file or not. Files are saved to a subfolder relative to configuration file supplied via the option '-i'", metavar = "[integer]"
),
make_option(c("-w", "--warning"),
type = "integer", default = 1,
help = "numerical Flag, between -1<=x<=2 [Default: %default].\n\n\t\tIt is not recommended to change the default value if the results are unknown and not validated,\n\t\tinstead it is recommended to only mute all warnings if the calculation must be repeated and the console output is supposed to be as clean as possible. Does not affect errors.\n\n\t\t-1:\tAll Warnings are ignored and will not be printed\n\t\t 0:\tWarnings will print after top-level function has completed.\n\t\t 1:\tWarnings are printed as they occur.\n\t\t 2:\tTreat all warnings as errors."
),
make_option(c("-c", "--overwriteEncoding"),
type = "character", default = "UTF-16LE",
help = "string [Default: %default].\n\t\tManual override for forcing a different file-encoding when loading in the configuration file.\n\t\tOnly use when necessary, and if the automatic encoding detection failed. This argument must be provided if the configuration-file supplied via the option '-i' was saved with an encoding DIFFERENT than 'UTF-16LE'", metavar = "[string]"
),
make_option(c("-l", "--strictLimits"),
type = "integer", default = 0,
help = "pseudo-boolean Flag, either numerical 1 or 0 [Default: %default].\n\t\tManual override for forcing _exactly_ the Y-limits defined in configuration, fully disabling any precautionary adjustments against overlapping elements. Primarily used if dimensions are known and the user only wants to rerun.", metavar = "[integer]"
),
make_option(c("-m", "--strictLimitsDaily"),
type = "integer", default = 0,
help = "pseudo-boolean Flag, either numerical 1 or 0 [Default: %default].\n\t\tAnalogue for daily Plots. See flag '-l' for further details.", metavar = "[integer]"
)
)
Object_Key <- str_c("", "Object Key", "1: Summary Plot", "2: Titles", "3: Daily Analyses", "4: Dates", "5: configuration", "6: configuration-path", "7: RDATA_Path", "8: function 'getRelative_change()'", "9: function 'getAbsolute_change()'", "10: function\t 'formatPValue()'", sep = "\n")
retDocs <- str_c("return\t\t\t\t\t\t Object containing the following elements\t\t\t\t\t\t\t\t [list]",
"return[[1]]\t\t\t\t\t Summary-Plot displaying progression over time\t\t\t\t\t\t\t\t [ggplot]",
"return[[2]]\t\t\t\t\t plot_title, plot_subtitle, min age and max age\t\t\t\t\t\t\t\t [list]",
"return[[3]]\t\t\t\t\t Daily Analyses\t\t\t\t\t\t\t\t\t\t\t\t [list]",
"\t$'dd.mm.YYYY' \t\t\t\t Day-Object containing all results for a specified date, f.e. return[[3]]$'30.05.2023'\t\t\t [list]",
"\t\t$boxplot\t\t\t figure for the date. contains p-values and sample-sizes\t\t\t\t\t\t [ggplot]",
"\t\t$Outlierplot\t\t\t rudimentary outlier-plot. Outliers are marked red.\t\t\t\t\t\t\t [ggplot]",
"\t\t$Res\t\t\t\t all statistical data for a given date\t\t\t\t\t\t\t\t\t [list]",
"\t\t\t $Data\t\t\t data loaded IN from the respective Excel-Sheet.\t\t\t\t\t\t\t [tbl_df]",
"\t\t\t $Outlier\t\t returns outliers as identified via 'identify_outliers()' (rstatix)\t\t\t\t\t [tbl_df]",
"\t\t\t $data_wo_Outliers\t returns data minus the outliers present in $Outlier\t\t\t\t\t\t\t [tbl_df]",
"\t\t\t $Norm\t\t\t Result of the Normality-Tests\t\t\t\t\t\t\t\t\t\t [list]",
"\t\t\t $BT\t\t\t Result of the Bartlett-Tests\t\t\t\t\t\t\t\t\t\t [list]",
"\t\t\t $T.Test \t\t Result of the T.Tests\t\t\t\t\t\t\t\t\t\t\t [list]",
"\t\t\t $summary \t\t Result of the 'summary'-Command\t\t\t\t\t\t\t\t\t [list].\n\t\t\t\t\t\t NOTE: Additionally, the absolute [cm^2] and relative [%] change relative to\n\t\t\t\t\t\t the previous measuring-date is printed for measurement dates 2+.",
"return[[4]] \t\t\t\t\t returns the dates in ISO-format\t\t\t\t\t\t\t\t\t [Date]",
"return[[5]] \t\t\t\t\t configuration used during execution, as loaded from the configuration path provided.\t\t\t [list]",
"return[[6]] \t\t\t\t\t path to the configuration-file loaded\t\t\t\t\t\t\t\t\t [string]",
"return[[7]] \t\t\t\t\t path to the RDATA-file containing this object (if saveRDATA=1, otherwhise this path does not exist)\t [string]",
"return[[8]] - getRelative_change\t\t refer to documentation for details\t\t\t\t\t\t\t\t\t [function]",
"return[[9]] - getAbsolute_change\t\t refer to documentation for details\t\t\t\t\t\t\t\t\t [function]",
"return[[10]] - formatPValue\t\t\t refer to documentation for details\t\t\t\t\t\t\t\t\t [function]",
sep = "\n"
)
opt_parser <- OptionParser(option_list = option_list, epilogue = str_c("returnValue 'return':\n", retDocs))
opt <- parse_args(opt_parser)
if (is.null(opt$i)) { ## check if at least one argument is supplied.
print_help(opt_parser)
stop("At least one argument must be supplied when executing via command line interface (input file).", call. = FALSE)
}
}
# Libraries 2 -------------------------------------------------------------
library(car)
# leveneTest
# library(writexl)
# library(lubridate)
# library(svDialogs)
library(ggpubr)
# clean_theme
# font
# ggboxplot
# grids
# labs_pubr
# stat_pvalue_manual
# theme_pubclean
# theme_pubr
#
#
#
library(ggthemes)
# theme_tufte
#
library(knitr)
# kable
library(rstatix)
# add_significance
# add_xy_position
# identify_outliers
# t_test
# wilcox_test
# levene_test
library(RColorBrewer)
# brewer.pal
# library(tidyverse)
# library(broom)
# library(conflicted)
# library(cli)
# library(dbplyr)
library(dplyr)
# summarise
# tibble
# anti_join
# if_else
# group_by
# library(dtplyr)
# library(forcats)
library(ggplot2)
# aes
# element_rect
# element_text
# facet_grid
# geom_boxplot
# geom_point
# ggplot
# ggsave
# ggtitle
# guide_axis
# guide_legend
# guides
# labs
# position_dodge
# position_jitterdodge
# scale_colour_manual
# scale_fill_manual
# scale_x_continuous
# scale_x_date
# scale_x_discrete
# scale_y_discrete
# stat
# stat_summary
# theme
# theme_bw
# library(googledrive)
# library(googlesheets4)
# library(haven)
# library(hms)
# library(httr)
# library(jsonlite)
library(lubridate)
# dmy
# now
# library(magrittr)
# library(modelr)
# library(pillar)
# library(purrr)
# library(ragg)
# library(readr)
# library(readxl)
# library(reprex)
# library(rlang)
# library(rstudioapi)
# library(rvest)
library(stringr)
# str_c
# str_count
# str_detect
# str_extract
# str_flatten_comma
# str_length
# str_pad
# str_replace
# str_replace_all
# str_split
# tr_sub
# str_trim
library(tibble)
library(tidyr)
# pivot_longer
# library(xml2)
# library(tidyverse)
# library(forcats)
# library(purrr)
library(readr)
# guess_encoding
# library(tibble)
library(readxl)
# read_xlsx
library(ini)
# read.ini
library(psych)
# describeBy
library(plyr)
# round_any
library(ini)
# read.ini
library(tools)
# file_path_sans_ext
library(openxlsx)
# createComment
# loadWorkbook
# saveWorkbook
# write.xlsx
# writeComment
library(checkmate)
# testSubset
library(utils)
# file_test
# hasName
# read.csv
library(formatdown)
# format_power
library(stats)
# bartlett.test
# shapiro.test
# user-facing auxiliary functions -----------------------------------------
#' calculate relative and absolute change between successive dates
#'
#' calculateChange() wrapper around both `getRelative_change()` & `getAbsolute_change()`.
#' Calculate the absolute and relative change per group relative to the previous
#' date.
#' Optionally, output this as a knitr-friendly table, or modify the DailyAnalysis-
#' Object initially fed to it.
#'
#' @param DailyAnalyses DailyAnalysis-Object, found in index 3 of the return-value of GFA_main()
#' @param ChosenDays Vector of dates, found in index 4 of the return-value of GFA_main()
#' @param returnTable boolean to control whether or not to render a table and return it. Alternatively,it will return the DailyAnalysis-Object with the change-values added in
#'
#' @return
#' @keywords export
#' @export
#'
#' @examples
#' GFA_DailyAnalyses <- calculateChange(GFA_DailyAnalyses, ChosenDays, returnTable = F)
#' change <- calculateChange(GFA_2[[3]], unlist(GFA_2[[4]]), T)
#' kable(change, caption = "Calculate the consecutive absolute and relative
#' changes within each groups across all days.")
calculateChange <- function(DailyAnalyses, ChosenDays, returnTable = F,ini="") {
# calculateChange
dayID <- 1
ChosenDays <- str_trim(ChosenDays)
table <- as.data.frame(list())
SortedFormattedDates <- format.Date(sort(format.Date(as.Date(str_trim(ChosenDays), tryFormats = c("%d.%m.%Y","%Y-%m-%d")))),format="%Y-%m-%d")
if (isFALSE(returnTable)) {
# print("Changes in Leaf-Area relative to the previous day: ")
}
names <- c("Time", "Groups", "Last mean [cm^2]", "abs. Change [cm^2]", "rel. Change [%]", "this mean [cm^2]")
for (curr_day in SortedFormattedDates) {
if (dayID == 1) {
ld <- curr_day
dayID <- dayID + 1
lastVals <- DailyAnalyses[[str_trim(curr_day)]]
lastmean <- lastVals$Res$summary$mean
name <- lastVals$Res$summary$name
next
} else {
lastVals <- DailyAnalyses[[str_trim(ld)]]
lastmean <- lastVals$Res$summary$mean
thisVals <- DailyAnalyses[[str_trim(curr_day)]]
thismean <- thisVals$Res$summary$mean
absolute_change <- (thismean - lastmean)
relative_change <- absolute_change / abs(lastmean) * 100
name <- lastVals$Res$summary$name
console_print <- str_c(ld, " -> ", curr_day, str_pad(name, width = max(str_length(name)) + 1), " Mean: ", str_pad(signif(lastmean, digits = 12), width = 12, side = "right"), " -> ", str_pad(signif(thismean, digits = 11), side = "left", width = 12), str_pad(" [cm^2]", width = 13, side = "left"), " |absC: ", absolute_change, " [cm^2]", " |relC: ", relative_change, " [%]")
CurrSum <- DailyAnalyses[[str_trim(curr_day)]]$Res$summary
CurrSum$relative_change <- relative_change
CurrSum$absolute_change <- absolute_change
DailyAnalyses[[str_trim(curr_day)]]$Res$summary <- CurrSum # todo: figure out how to do this right!!
if (isTRUE(as.logical(ini==""))) {
DailyAnalyses[[str_trim(curr_day)]]$PreviousDay <- format.Date(as.Date(str_trim(ld),tryFormats = c("%d.%m.%Y","%Y-%m-%d")),"%Y-%m-%d")
} else {
DailyAnalyses[[str_trim(curr_day)]]$PreviousDay <- format.Date(as.Date(str_trim(ld),tryFormats = c("%d.%m.%Y","%Y-%m-%d",ini$Experiment$filename_date_format,ini$Experiment$figure_date_format)),"%Y-%m-%d")
}
if (isTRUE(returnTable)) {
table2 <- dplyr::tibble(
Change = str_c(ld, " -> ", curr_day),
Name = as.character(thisVals$Res$summary$name),
LastMean = as.character(lastmean),
Abs_change = as.character(absolute_change),
Rel_change = as.character(relative_change),
ThisMean = as.character(thismean)
)
table2 <- as.data.frame(table2)
table <- rbind(table, table2)
}
ld <- curr_day
}
}
if (isFALSE(returnTable)) {
return(DailyAnalyses)
} else {
colnames(table) <- names
return(table)
}
}
#' fixscient - scientific notation-formatted latex-expression for numbers
#'
#' fixscient is a simple function for formating values with scientific
#' latex-notation with controllable number of decimals before the power-notation
#'
#' @param number number to render in scientific notation
#' @param number_of_decimals number of decimals before the "*10^X"
#' @param fp_format passthrough of parameter "format" for format_power
#' @param renderpositive_sign boolean to control whether or not a positive sign is forcefully rendered forin the latex-string returned.
#'
#' @return latex-formatted string, e.g. $3.4 \\times 10^-12$
#' @keywords export
#' @export
#'
#' @examples
#' fixscient(mean(GFA_2[[3]]$"05.06.2023"$Res$summary$mean[4]), number_of_decimals = 3)
fixscient <- function(number, number_of_decimals = 2, fp_format = "sci", renderpositive_sign = F) {
checkSign <- function(x) {
return(ifelse(x >= 0, T, F))
}
fixdecimalplaces <- function(x, k) {
return(trimws(format(round(x, k), nsmall = k)))
}
if (str_count(number, "e")) {
if (str_count(number, "e-")) {
split <- strsplit(as.character(number), split = "e-")
Power <- split[[1]][[2]]
value <- split[[1]][[1]]
value <- round(as.numeric(value), number_of_decimals)
if (renderpositive_sign) {
if (checkSign(value)) {
str <- str_c("$+", value, " \\times 10^{-", Power, "}$")
} else {
str <- str_c("$", value, " \\times 10^{-", Power, "}$")
}
} else {
str <- str_c("$", value, " \\times 10^{-", Power, "}$")
}
} else {
split <- strsplit(as.character(number), split = "e+")
if (length(split) == 1) {
Power <- split[[1]][[2]]
Power <- str_replace(Power, "\\+", "")
value <- split[[1]][[1]]
value <- round(as.numeric(value), number_of_decimals)
if (renderpositive_sign) {
if (checkSign(value)) {
str <- str_c("$+", value, " \\times 10^{", Power, "}$")
} else {
str <- str_c("$", value, " \\times 10^{", Power, "}$")
}
} else {
str <- str_c("$", value, " \\times 10^{", Power, "}$")
}
return(str)
}
Power <- split[[1]][[2]]
Power <- str_replace(Power, "\\+", "")
if (isFALSE((Power > 20) || (-20 > Power))) {
# print("normal")
return(format_power(number, format = fp_format))
}
value <- split[[1]][[1]]
value <- round(as.numeric(value), number_of_decimals)
if (renderpositive_sign) {
if (checkSign(value)) {
str <- str_c("$+", value, " \\times 10^{", Power, "}$")
} else {
str <- str_c("$", value, " \\times 10^{", Power, "}$")
}
} else {
str <- str_c("$", value, " \\times 10^{", Power, "}$")
}
}
} else {
value <- round(as.numeric(number), number_of_decimals)
value <- fixdecimalplaces(number, number_of_decimals)
if (renderpositive_sign) {
if (checkSign(value)) {
str <- str_c("$+", value, "$")
} else {
str <- str_c("$", value, "$")
}
} else {
str <- str_c("$", value, "$")
}
}
return(str)
}
#' Function to calculate the relative change between two dates of a
#' DailyAnalyses-Object
#'
#' @param this first date
#' @param last previous date
#' @param Object either boolean FALSE, or an object containing subobjects with names 'this' and 'last', as formatted by GFA_main()
#' @param returnTable boolean to control whether or not to render a table and return it. Alternatively,it will return the DailyAnalysis-Object with the change-values added in
#'
#' @return vector of doubles
#' @keywords export
#' @export
#'
#' @examples
#' getRelative_change(this = "05.06.2023", last = "30.05.2023", Object = GFA_2[[3]])
getRelative_change <- function(this, last, Object = FALSE, returnTable = FALSE) {
# getRelative_change
# Funktion berechnet die relative Veränderung zwischen zwei Werten.
# Fall 1: Parameter 'this' und 'last' sind numerisch: der relative Unterschied dieser beiden Werte wird zurückgegeben
# Fall 2: Parameter 'this' und 'last' sind Datenangaben im Format "%d.%m.%Y": der relative Unterschied von allen Versuchsgliedern zu den beiden gegebenen Zeitpunkten wird zurückgegeben
if (isFALSE(Object)) { # compare values
if (is.numeric(this) && is.numeric(last)) {
# a <- as.character(thisVals$Res$summary$name)
relative_change <- (this - last) / abs(last) * 100
b <- as.character(last)
c <- as.character(relative_change)
d <- as.character(this)
names <- c("Last mean", "rel. Change [%]", "this mean")
table <- dplyr::tibble(b, c, d)
table <- as.data.frame(table)
colnames(table) <- names
kable <- kable(table)
if (returnTable) {
return(table)
} else {
print(kable)
return(relative_change)
}
} else {
wrnopt <- getOption("warn")
options(warn = overwriteWarnings)
warning(str_c(
"getRelativeChange() [user-defined]: your value for ",
ifelse(!is.numeric(this), str_c("[this]: '", this), str_c("[last]: '", last)),
"' is not numeric, and thus cannot be used for comparison.",
"\nYou may try again after coercing it to numeric."
))
options(warn = wrnopt)
}
} else { # compare values of a dailyAnalyses-Object
thisVals <- Object[[str_trim(this)]]
lastVals <- Object[[str_trim(last)]]
if (is.null(lastVals)) {
lastmean <- last
} else {
lastmean <- lastVals$Res$summary$mean
}
if (is.null(thisVals)) {
thismean <- this
} else {
thismean <- thisVals$Res$summary$mean
}
relative_change <- (thismean - lastmean) / abs(lastmean) * 100
}
names <- c("Groups", "Last mean", "rel. Change [%]", "this mean")
table <- dplyr::tibble(
as.character(thisVals$Res$summary$name),
as.character(lastmean),
as.character(relative_change),
as.character(thismean)
)
table <- as.data.frame(table)
colnames(table) <- names
kable <- kable(table)
if (returnTable) {
return(table)
} else {
print(kable)
return(relative_change)
}
}
#' Function to calculate the absolute change between two dates of a
#' DailyAnalyses-Object
#'
#' @param this first date
#' @param last previous date
#' @param Object either boolean FALSE, or an object containing subobjects with names 'this' and 'last', as formatted by GFA_main()
#' @param returnTable boolean to control whether or not to render a table and return it. Alternatively,it will return the DailyAnalysis-Object with the change-values added in
#'
#' @return vector of doubles
#' @keywords export
#' @export
#'
#' @examples
#' getAbsolute_change(this = "05.06.2023", last = "30.05.2023", Object = GFA_2[[3]])
getAbsolute_change <- function(this, last, Object = FALSE, returnTable = FALSE) {
# getAbsoluteChange
# Funktion berechnet die absolute Veränderung zwischen zwei Werten.
# Fall 1: Parameter 'this' und 'last' sind numerisch: der absolute Unterschied dieser beiden Werte wird zurückgegeben
# Fall 2: Parameter 'this' und 'last' sind Datenangaben im Format "%d.%m.%Y": der relative Unterschied von allen Versuchsgliedern zu den beiden gegebenen Zeitpunkten wird zurückgegeben
if (isFALSE(Object)) { # compare values
if (is.numeric(this) && is.numeric(last)) {
# a <- as.character(thisVals$Res$summary$name)
absolute_change <- (this - last)
b <- as.character(last)
c <- as.character(absolute_change)
d <- as.character(this)
names <- c("Last mean", "abs. Change [cm^2]", "this mean")
table <- dplyr::tibble(b, c, d)
table <- as.data.frame(table)
colnames(table) <- names
kable <- kable(table)
if (returnTable) {
return(table)
} else {
print(kable)
return(absolute_change)
}
} else {
wrnopt <- getOption("warn")
options(warn = overwriteWarnings)
warning(str_c(
"getRelativeChange() [user-defined]: your value for ",
ifelse(!is.numeric(this), str_c("[this]: '", this), str_c("[last]: '", last)),
"' is not numeric, and thus cannot be used for comparison.",
"\nYou may try again after coercing it to numeric."
))
options(warn = wrnopt)
}
} else { # compare values of a dailyAnalyses-Object
thisVals <- Object[[str_trim(this)]]
lastVals <- Object[[str_trim(last)]]
if (is.null(lastVals)) {
lastmean <- last
} else {
lastmean <- lastVals$Res$summary$mean
}
if (is.null(thisVals)) {
thismean <- this
} else {
thismean <- thisVals$Res$summary$mean
}
absolute_change <- (thismean - lastmean)
}
names <- c("Groups", "Last mean", "abs. Change [cm^2]", "this mean")
table <- dplyr::tibble(
as.character(thisVals$Res$summary$name),
as.character(lastmean),
as.character(absolute_change),
as.character(thismean)
)
table <- as.data.frame(table)
colnames(table) <- names
kable <- kable(table)
if (returnTable) {
return(table)
} else {
print(kable)
return(absolute_change)
}
}
#' Function to calculate the mean of explicit elements returned by
#' getAbsolute_change() and getRelative_change() respectively.
#' Can in principle be used for all one-dimensional vectors.
#'
#'
#' @param Vector vector to operate upon.
#' @param Elements subset of 'Vector' to calculate the mean of
#'
#' @return double
#' @keywords export
#' @export
#'
#' @examples
#' getMeanofVectorElements(getRelative_change(this = "05.06.2023", last = "30.05.2023", Object = GFA_2[[3]]), Elements = c(1, 2, 3))
getMeanofVectorElements <- function(Vector, Elements) {
lenVector <- length(Vector)
map <- rep(0, lenVector)
map <- replace(map, Elements, 1)
map <- as.logical(map)
selection <- subset(Vector, map)
mean <- mean(selection)
return(mean)
}
# GFA_main ----------------------------------------------------------------
#' GFA_main: entry-point function for the utility
#'
#' Front-facing main function. Used to initiate the utility. Returns an
#' object containing comprehensive data - results, figures, inputs, meta-
#' data, several helper-functions.
#'
#' @param folder_path Despite the name, it is recommended to provide the file-path to a properly configured .ini-file. If the user provides a folder, the function looks for a configuration file with the name `GFA_conf.ini` instead.
#' @param returnDays boolean to enable evaluation of per-day analyses
#' @param saveFigures boolean to enable saving figures to disk
#' @param saveExcel boolean to enable saving excel to disk
#' @param saveRDATA boolean to enable saving RDATA to disk
#' @param overwriteEncoding string containing a specific file-encoding to be used when loading the configuration-file.
#' @param overwriteWarnings integer to control warning behaviour. Refer to `?options -> warn for more details
#'
#' @return list containing all results.
#' @keywords export
#' @export
#'
#' @examples
GFA_main <- function(folder_path, returnDays = FALSE, saveFigures = FALSE, saveExcel = FALSE, saveRDATA = FALSE, overwriteEncoding = "", overwriteWarnings = 1,strictLimitsValidation = FALSE,strictLimitsValidation_Daily = FALSE) {
# internal functions ------------------------------------------------------
## define local functions
# These functions are used internally by GFA_main, and are not used internally by RunDetailed.
# They are set up as local functions so that the environment beecomes less cluttered visually.
formatFontsizes <- function(ggplot,ini) {
if (ini$General$Debug) {
ggplot <- ggplot + theme(plot.subtitle = element_text(size = 5))
} else {
ggplot <- ggplot + theme(plot.subtitle = element_text(size = 5))
}
if (hasName(ini$Fontsizes, "Fontsize_General")) {
ggplot <- ggplot + theme(text = element_text(size = as.numeric(ini$Fontsizes$Fontsize_General)))
} else {
ggplot <- ggplot + theme(text = element_text(size = 10), title = element_text(size = 10))
}
if (hasName(ini$Fontsizes, "Fontsize_XAxisTicks")) {
ggplot <- ggplot + theme(axis.text.x = element_text(size = as.numeric(ini$Fontsizes$Fontsize_XAxisTicks)))
} else {
ggplot <- ggplot + theme(axis.text.x = element_text(size = 10))
}
if (hasName(ini$Fontsizes, "Fontsize_YAxisTicks")) {
ggplot <- ggplot + theme(axis.text.y = element_text(size = as.numeric(ini$Fontsizes$Fontsize_YAxisTicks)))
} else {
ggplot <- ggplot + theme(axis.text.y = element_text(size = 10))
}
if (hasName(ini$Fontsizes, "Fontsize_XAxisLabel")) {
ggplot <- ggplot + theme(axis.title.x = element_text(size = as.numeric(ini$Fontsizes$Fontsize_XAxisLabel)))
} else {
ggplot <- ggplot + theme(axis.title.x = element_text(size = 10))
}
if (hasName(ini$Fontsizes, "Fontsize_YAxisLabel")) {
ggplot <- ggplot + theme(axis.title.y = element_text(size = as.numeric(ini$Fontsizes$Fontsize_YAxisLabel)))
} else {
ggplot <- ggplot + theme(axis.title.y = element_text(size = 10))
}
if (hasName(ini$Fontsizes, "Fontsize_LegendText")) {
ggplot <- ggplot + theme(legend.text = element_text(size = as.numeric(ini$Fontsizes$Fontsize_LegendText)))
} else {
ggplot <- ggplot + theme(legend.text = element_text(size = 10))
}
if (hasName(ini$Fontsizes, "Fontsize_LegendTitle")) {
ggplot <- ggplot + theme(legend.title = element_text(size = as.numeric(ini$Fontsizes$Fontsize_LegendTitle)))
} else {
ggplot <- ggplot + theme(legend.title = element_text(size = 10))
}
return(ggplot)
}
generateYLabel <- function(unit_y,ini) {
if (isFALSE(is.null(ini$Experiment$YLabel))) {
y_label <- str_c(ini$Experiment$YLabel[[1]], " [", unit_y, "]")
} else {
level <- deparse(sys.calls()[[sys.nframe()-1]])
level <- str_replace(level[[1]],"\\(.*","()")
warning <- str_c(
"generateYLabel() [user-defined,called from '",level,"']: Task: generating Y-label string",
"\nThe required configuration-key 'YLabel' in the section 'Experiment' is not set.",
"\nIt controls the Y-label for the current ggplot",
"\n",
"\nA generic default Y-label is generated instead. Code-execution will continue."
)
warning(warning,immediate. = T)
y_label <- if_else(as.logical(ini$Experiment$Normalise),
if_else(as.logical(ini$General$language == "German"),
true = str_c("Normalisierte Grünfläche [", unit_y, "]"),
false = str_c("normalised green plant area [", unit_y, "]"),
missing = str_c("normalised green plant area [", unit_y, "]")
),
if_else(as.logical(ini$General$language == "German"),
true = str_c("Grünfläche [", unit_y, "]"),
false = str_c("Green plant area [", unit_y, "]"),
missing = str_c("Green plant area [", unit_y, "]")
)
)
}
return(y_label)
}
#' Title
#'
#' @param ChosenDays
#' @param Files
#' @param PotsPerGroup
#' @param numberofGroups
#' @param groups_as_ordered_in_datafile
#' @param folder_path
#' @param Conditions
#' @param ini
#' @param data_all_dailies
#' @param saveFigures
#' @param saveExcel
#' @param saveRDATA
#' @param overwriteWarnings
#'
#' @return list of daily analyses for all dates found. For each date, statistical information, an outlier-plot and a proper plot are returned.
#' @keywords internal
#'
#' @examples
RunDetailed <- function(ChosenDays, Files, PotsPerGroup, numberofGroups, groups_as_ordered_in_datafile, folder_path, Conditions, ini, data_all_dailies, saveFigures = FALSE, saveExcel = FALSE, saveRDATA = FALSE, overwriteWarnings = 1, strictLimitsValidation_Daily = FALSE) {
generateDailyPlotFilename <- function(Day,Theme_Index,ini) {
filename <- str_c(
ini$Experiment$Filename_Prefix, "Einzelanalyse",
" (",
ini$Experiment$Name,
", ",
format(as.Date(str_trim(Day), tryFormats = c("%d.%m.%Y","%Y-%m-%d",ini$Experiment$filename_date_format,ini$Experiment$figure_date_format)), format = ini$Experiment$filename_date_format),
") norm",
if_else(as.logical(ini$Experiment$Normalise),
"1",
"0"
),
"_relColNms",
if_else(as.logical(ini$General$RelativeColnames),
"1",
"0"
),
"_",
ini$General$language,
"_",
Theme_Index,
").jpg"
)
return(filename)
}
generateXLabelDaily <- function(ini) {
if (isFALSE(is.null(ini$Experiment$XLabel_Daily))) {
x_label <- str_c(ini$Experiment$XLabel_Daily[[1]])
} else {
level <- deparse(sys.calls()[[sys.nframe()-1]])
level <- str_replace(level[[1]],"\\(.*","()")
Warning <- str_c(
"generateXLabelDaily() [user-defined,called from '",level,"']: Task: generating X-label string",
"\nThe required configuration-key 'XLabel_Daily' in the section 'Experiment' is not set.",
"\nIt controls the X-label for the current ggplot",
"\n",
"\nA generic default X-label is generated instead. Code-execution will continue."
)
warning(warning,immediate. = T)
x_label <- if_else(as.logical(ini$General$language == "German"),
true = str_c("Versuchs-Gruppen"),
false = str_c("Treatment groups"),
missing = if_else(as.logical(ini$General$RelativeColnames),
true = str_c("Versuchs-Gruppen"),
false = str_c("Treatment groups")
)
)
}
return(x_label)
}
generateYAxisUnitsDaily <- function(ini) {
unit_y <- str_split(ini$General$axis_units_y_Daily, ",")
unit_y <- if_else(as.logical(ini$General$language == "German"),
true = unit_y[[1]][1],
false = unit_y[[1]][2]
)
return(unit_y)
}
generateXAxisUnitsDaily <- function(ini) {
# assemble label strings
unit_x <- str_split(ini$General$axis_units_x_Daily, ",")
unit_x <- if_else(as.logical(ini$General$language == "German"),
true = unit_x[[1]][1],
false = unit_x[[1]][2]
)
return(unit_x)
}
generateColorPalettesDaily <- function(numberofGroups,ini) {
# Select the required number of colours from a sequencial color palette
Palette_Boxplot <- getLastNElementsOfPalette("Reds", numberofGroups)
Palette_Lines <- getLastNElementsOfPalette("Reds", numberofGroups)
Palette_Boxplot <- replace(Palette_Boxplot, list = 1, "white")
Palette_Lines <- replace(Palette_Lines, list = 1, "#112734")
if (hasName(ini$Experiment, "Palette_Boxplot2")) {
Palette_Boxplot <- unlist(str_split(ini$Experiment$Palette_Boxplot2, ","))
}
if (hasName(ini$Experiment, "Palette_Lines2")) {
Palette_Lines <- unlist(str_split(ini$Experiment$Palette_Lines2, ","))
}
return(list(Lines = Palette_Lines,Boxplot = Palette_Boxplot))
}
generatePlotTitleDaily <- function(curr_day,ini) {
if (isFALSE(is.null(ini$Experiment$Title_Daily))) {
plot_Title <- str_c(ini$Experiment$Title_Daily[[1]], " (", format(as.Date(str_trim(curr_day), "%d.%m.%Y"), format = ini$Experiment$figure_date_format), ")")
} else {
level <- deparse(sys.calls()[[sys.nframe()-1]])
level <- str_replace(level[[1]],"\\(.*","()")
warning <- str_c(
"generatePlotTitleDaily() [user-defined,called from '",level,"']: Task: generating plot title string",
"\nThe required configuration-key 'Title_Daily' in the section 'Experiment' is not set.",
"\nIt controls the plot-title for the current ggplot",
"\n",
"\nA generic default plot-title is generated instead. Code-execution will continue."
)
warning(warning,immediate. = T)
plot_Title <- if_else(as.logical(ini$General$language == "German"),
true = str_c("Grünfläche (", format(as.Date(str_trim(curr_day), "%d.%m.%Y"), format = ini$Experiment$figure_date_format), ")"),
false = str_c("Green area (", format(as.Date(str_trim(curr_day), "%d.%m.%Y"), format = ini$Experiment$figure_date_format), ")")
)
}
return(plot_Title)
}
generatePlotSubTitleDaily <- function(PotsPerGroup,set_theme,Theme_Index,Palette_Boxplot,Palette_Lines,curr_day,ini) {
if (as.logical(ini$General$Debug)) {
plot_SubTitle <- str_c(
"Experiment: ", ini$Experiment$Name,
"\nT0: ", ini$Experiment$T0,
# , "\nrelative column names: ", as.logical(ini$General$RelativeColnames)
, "\nNormalised: ", as.logical(ini$Experiment$Normalise),
"\nPots per Group: ", PotsPerGroup,
"\nFigure generated: ", format.POSIXct(now(),format = "%Y-%m-%d %H:%M:%S"),
"\n Theme: ", set_theme, " (", Theme_Index, ")",
"\n Sample-Size: ", str_c(as.logical(ini$General$PlotSampleSize), " Only Irregular:", as.logical(ini$General$ShowOnlyIrregularN)),
"\n Palette: ", str_c(str_c(Palette_Boxplot, collapse = ", "), " || ", str_c(Palette_Lines, collapse = ", "))
)
} else {
if (isFALSE(is.null(ini$Experiment$SubTitle_Daily))) {
plot_SubTitle <- str_c(ini$Experiment$SubTitle_Daily[[1]], " (", format(as.Date(str_trim(curr_day), "%d.%m.%Y"), format = ini$Experiment$figure_date_format), ")")
} else {
level <- deparse(sys.calls()[[sys.nframe()-1]])
level <- str_replace(level[[1]],"\\(.*","()")
warning <- str_c(
"generatePlotSubTitleDaily() [user-defined,called from '",level,"']: Task: generating plot subtitle string",
"\nThe required configuration-key 'SubTitle_Daily' in the section 'Experiment' is not set.",
"\nIt controls the plot-subtitle for the current ggplot",
"\n",
"\nA generic default plot-subtitle is generated instead. Code-execution will continue."
)
warning(warning,immediate. = T)
plot_SubTitle <- str_c(
"Experiment: ", ini$Experiment$Name,
if_else(as.logical(ini$General$language == "German"),
true = str_c(
"\nUmtopfen: ", format(as.Date(str_trim(ini$Experiment$T0), "%d.%m.%Y"), format = ini$Experiment$figure_date_format),
"\nSample-Size: ", PotsPerGroup
),
false = str_c(
"\nDate of Repotting: ", format(as.Date(str_trim(ini$Experiment$T0), "%d.%m.%Y"), format = ini$Experiment$figure_date_format),
"\nSample-Size: ", PotsPerGroup
)
),
"",
""
)
}
}
return(plot_SubTitle)
}
loadData <- function(Files) {
for (curr_file in Files) {
fn <- basename(curr_file)
#print(fn)
#print(curr_day)
if (isFALSE(as.logical(str_count(fn,str_trim(curr_day))))) {
####
#TODO: BUGGED SECTION START
#format_count <- 0
#potential_date_formats <- c("%Y-%m-%d","%d.%m.%Y","%Y-%Y-%m-%d",ini$Experiment$filename_date_format,ini$Experiment$figure_date_format)
#guessed_format <- lubridate::guess_formats(str_trim(curr_day),orders = c("ymd","dmy"))
# for (format in potential_date_formats) {
# matching_date <- try_default(format.Date(as.Date(str_trim(curr_day),format),format),default = NULL,quiet = T)
# if (is.null(matching_date)) {
# next
# }
# if (is.na(matching_date)) {
# next
# }
# #matching_date <- format.Date(as.Date(str_trim(curr_day),tryFormats = potential_date_formats,optional = TRUE),format="%Y-%m-%d")
# print(fn)
# print(matching_date)
# print(str_count(fn,matching_date))
Date <- str_extract(fn, "\\d+(\\.|\\-)\\d+(\\.|\\-)\\d+")
Date <- as.Date.character(Date, tryFormats = c("%Y-%m-%d", "%d.%m.%Y"))
if (str_count(str_trim(Date),str_trim(curr_day))) {
nextFile <- FALSE
#break
} else {
nextFile <- TRUE
#break
}
# }
if (nextFile) {
next
}
#TODO: BUGGED SECTION END
####
}
# TODO: why does the code above not properly select the right xlsx-path?
# Data <- as.data.frame(importCSV_Data1(curr_file,""))
if (ini$General$used_filesuffix == "csv") {
csv1 <- read.csv(curr_file, sep = ";")
} else {
csv1 <- read_xlsx(curr_file, .name_repair = "unique_quiet")
}
if (isFALSE(hasName(csv1,ini$Experiment$used_plant_area))) {
Error <- simpleError(str_c(str_c("The type of plant_area which is supposed to be loaded ('",ini$Experiment$used_plant_area,"') could not be found in the data-file",file,"."), ErrorString, sep = "\n"))
stop(Error)
}
if (hasName(csv1, "plant_area")) {
csv1$plant_area <- str_replace(csv1$plant_area, ",", ".")
csv1$plant_area <- as.numeric(csv1$plant_area)
}
if (hasName(csv1, "plant_area_drought")) {
csv1$plant_area_drought <- str_replace(csv1$plant_area_drought, ",", ".")
csv1$plant_area_drought <- as.numeric(csv1$plant_area_drought)
}
if (hasName(csv1, "plant_area_green")) {
csv1$plant_area_green <- str_replace(csv1$plant_area_green, ",", ".")
csv1$plant_area_green <- as.numeric(csv1$plant_area_green)
}
if (hasName(csv1, "plant_area_complete")) {
csv1$plant_area_complete <- str_replace(csv1$plant_area_complete, ",", ".")
csv1$plant_area_complete <- as.numeric(csv1$plant_area_complete)
}
if (hasName(csv1, "pixel_area")) {
csv1$pixel_area <- str_replace(csv1$pixel_area, ",", ".")
csv1$pixel_area <- as.numeric(csv1$pixel_area)
}
if (hasName(csv1, "plant_pixel_count")) {
csv1$plant_pixel_count <- str_replace(csv1$plant_pixel_count, ",", ".")
csv1$plant_pixel_count <- as.numeric(csv1$plant_pixel_count)
}
if (hasName(csv1, "drought_fraction")) {
csv1$drought_fraction <- str_replace(csv1$drought_fraction, ",", ".")
csv1$drought_fraction <- as.numeric(csv1$drought_fraction)
}
Data <- FALSE
Data <- csv1
Values <- csv1[[ini$Experiment$used_plant_area]] ## extract the plant_area values that we need, based on the config-key
if (ini$Experiment$Normalise) {
if (hasName(Data, "plant_area_normalised")) {
if (hasName(Data,"plants_in_pot")) {
Values <- Values / Data$plants_in_pot
} else {
simpleError("Manually setting data-column 'plant_area_normalised' has been deprecated.\nPlease ensure that each data-file contains the column 'plants_in_pot' to normalise your data.\n\nThe script will exit now, please ensure the column 'plants_in_pot' exists")
}
} else {
if (hasName(Data, "plants_in_pot")) {
Values <- Values / Data$plants_in_pot
} else {
ErrorString <- ""
Error <- simpleError(str_c(str_c(" Data-file: '", file, "' does not contain the column 'plants_in_pot' to normalise automatically.\nPlease ensure this column exists.\nThe script cannot generate a plot when 'Normalise=T' if this column does not exist.\nPlease resolve this issue in the displayed data-file, or turn off normalisation."), ErrorString, sep = "\n"))
stop(Error)
}
}
Data$plant_area_plotted <- Values # TODO: Verify that this is correct. Also find out where the normalised area is loaded for the develoment-plot so I can use that logic here instead.
} else {
Data$plant_area_plotted <- Values # TODO: Verify that this is correct. Also find out where the normalised area is loaded for the develoment-plot so I can use that logic here instead.
}
break
}
if (isFALSE(Data)) {
level <- deparse(sys.calls()[[sys.nframe()-1]])
level <- str_replace(level[[1]],"\\(.*","()")
error <- simpleError(str_c(
"loadData() [user-defined,called from '",level,"']: Task: loading csv-/xlsx-files",
"\nNo data could be read from the any file.",
"\nThe following files:",
"\n",
str_flatten(Files,collapse = '""\n""'),
"\n could not be loaded.",
"\n"
))
stop(error)
}
return(Data)
}
labelOutliers <- function(y) {
o <- boxplot.stats(y)$out
if (length(o) == 0) NA else o
}
# Create objects
ret <- list() # for returning all results from this functions
retOutliers <- list()
RObj <- list() # for keeping all results of a day together
# 1. Load Data
for (curr_day in ChosenDays) {
Data <- loadData(Files)
# Data <- cbind(Data,Gruppe,Nummer)
if (ini$Experiment$Facet2D) {
Nummer <- rep(c(1:PotsPerGroup), times = numberofGroups)
if (as.integer(PotsPerGroup) * length(groups_as_ordered_in_datafile) == dim(Data)[1]) {
Gruppe <- rep(groups_as_ordered_in_datafile, each = as.integer(PotsPerGroup))