-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend.R
More file actions
1931 lines (1710 loc) · 94.5 KB
/
Copy pathbackend.R
File metadata and controls
1931 lines (1710 loc) · 94.5 KB
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
library(shiny)
library(tidyr) # for unite
library(ggplot2)
library(data.table) # for filtering with %like%
library(readxl)
library(writexl)
library(plotly)
library(zoo) # for running average methods
library(ggpubr)
library(viridis)
library(dplyr)
library(lubridate)
library(shinyWidgets)
library(htmlwidgets)
library(fs)
library(hash)
require(tidyverse)
library(tools)
library(shinyalert)
library(shinyjs)
################################################################################
# General utilities and plotting utilities
################################################################################
source("inc/util.R")
source("inc/plotting/util.R")
################################################################################
# RMR functions
################################################################################
source("inc/rmr/helper.R") # rmr helper methods
source("inc/rmr/extract_rmr.R") # rmr extraction
source("inc/rmr/extract_rmr_helper.R") # rmr extraction helper
################################################################################
# Importers
################################################################################
source("inc/importers/import_promethion_helper.R") # import for SABLE/Promethion data sets
source("inc/importers/import_pheno_v8_helper.R") # import for PhenoMaster V8 data sets
source("inc/importers/import_cosmed_helper.R") # import for COSMED data sets
source("inc/importers/import_example_data_sets_helper.R") # for example data sets
source("inc/importers/util.R") # for consistency checks of columns
################################################################################
# Locomotion helpers
################################################################################
source("inc/locomotion/locomotion.R") # for locomotion probability heatmap
source("inc/locomotion/locomotion_budget.R") # for locomotion budget
################################################################################
# UI guide and timeline coloring
################################################################################
source("inc/annotations/timeline.R") # for colorizing timeline by day/night rhythm
source("inc/annotations/guide.R") # for guide
source("inc/annotations/style.R") # for styling of basic plots
################################################################################
# Statistics
################################################################################
source("inc/statistics/do_ancova_alternative.R") # for ancova with metadata
################################################################################
# Metadata handling
################################################################################
source("inc/metadata/read_metadata.R")
################################################################################
# Export functionality
################################################################################
source("inc/exporters/default_exporter.R")
################################################################################
# User session management
################################################################################
source("inc/session_management.R")
################################################################################
# Versioning
################################################################################
source("inc/versioning/git_info.R")
################################################################################
# Visualizations
################################################################################
source("inc/visualizations/goxlox.R") # for goxlox
source("inc/visualizations/energy_expenditure.R") # for energy expenditure
source("inc/visualizations/raw_measurement.R") # for raw measurements
source("inc/visualizations/total_energy_expenditure.R") # for total energy expenditure
source("inc/visualizations/resting_metabolic_rate.R") # for resting metabolic rate
source("inc/visualizations/day_night_activity.R") # for day night activity
source("inc/visualizations/estimate_rmr_for_cosmed.R") # for COSMED-based RMR estimation
source("inc/visualizations/body_composition.R") # for body composition
################################################################################
# Selection of calendrical dates
################################################################################
time_start_end <- NULL
start_date <- "1970-01-01"
end_date <- Sys.Date()
################################################################################
# Session global environment to hold user data
################################################################################
global_data <- new.env()
################################################################################
# Configure base plot look and feel with ggpubr
################################################################################
configure_default_plot_look_and_feel <- function() {
theme_pubr_update <- theme_pubr(base_size = 8.5) +
theme(legend.key.size = unit(0.3, "cm")) +
theme(strip.background = element_blank()) +
theme(strip.text = element_text(hjust = 0)) +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
theme_set(theme_pubr_update)
}
################################################################################
# Load data
################################################################################
load_data <- function(file, input, exclusion, output, session) {
#############################################################################
# Detect file type
#############################################################################
detectFileType <- function(filename) {
file_ext(filename)
}
#############################################################################
# Data read-in
#############################################################################
fileFormatTSE <- FALSE
finalC1 <- c()
finalC1meta <- data.frame(matrix(nrow = 0, ncol = 8))
# Supported basic metadata fields from TSE LabMaster/PhenoMaster (these are defined manually by the user exporting the TSE files)
colnames(finalC1meta) <- c("Animal.No.", "Diet", "Genotype", "Box", "Sex", "Weight..g.", "Dob", "Measurement")
# check if we need to use example data or not
use_example_data <- getSession(session$token, global_data)[["use_example_data"]]
if (is.null(use_example_data)) {
storeSession(session$token, "use_example_data", FALSE, global_data)
}
use_example_data <- getSession(session$token, global_data)[["use_example_data"]]
use_example_data_set <- getSession(session$token, global_data)[["example_data_single"]]
num_files <- getSession(session$token, global_data)[["example_data_single_length"]]
if (!use_example_data) {
num_files <- input$nFiles
}
interval_length_list <- getSession(session$token, global_data)[["interval_length_list"]]
metadatafile <- get_metadata_datapath(input, session, global_data)
for (i in 1:num_files) {
file <- input[[paste0("File", i)]]
file <- file$datapath
if (use_example_data) {
if (use_example_data_set) {
example_data_set_name <- getSession(session$token, global_data)[["example_data_single_name"]]
if (example_data_set_name == "UCP1KO") {
file <- paste(Sys.getenv(c("SHINY_DATA_FOLDER")), paste0("example_data/UCP1KO/", "example_data_", i, ".csv"), sep = "")
}
if (example_data_set_name == "DAKO") {
file <- paste(Sys.getenv(c("SHINY_DATA_FOLDER")), paste0("example_data/DAKO/", "example_data_", i, ".csv"), sep = "")
}
}
}
con <- file(file)
line <- readLines(con, n = 2)
if (i == 1) {
fileFormatTSE <- line[2]
studyDescription <- line[1]
have_example_data_with_metadata <- FALSE
if (!is.null(use_example_data)) {
if (use_example_data == TRUE) {
have_example_data_with_metadata <- TRUE
}
}
if (input$havemetadata || have_example_data_with_metadata) {
study_details <- get_study_description_from_metadata(metadatafile)
output$study_name <- renderText(study_details$study_name)
output$lab <- renderText(study_details$lab)
output$mouse_strain <- renderText(study_details$mouse_strain)
output$comment <- renderText(study_details$comment)
output$author <- renderText(study_details$name)
output$date <- renderText(study_details$date)
output$number_of_samples <- renderText(study_details$number_of_samples)
output$number_of_diets <- renderText(study_details$number_of_diets)
output$number_of_genotypes <- renderText(study_details$number_of_genotypes)
output$number_of_sexes <- renderText(study_details$number_of_sexes)
} else {
output$study_name <- renderText(paste("", gsub("[;]", "", studyDescription), sep = " "))
}
output$file_type_detected <- renderText(paste("",gsub("[;,]", "", line[2]), sep = " "))
}
#########################################################################################################
# Detect data type (TSE v6/v7, v5 (Akim/Dominik) or v8 (Jan/Tabea)) or Promethion/Sable (.xlsx) (Jenny))
#########################################################################################################
detectData <- function(filename) {
con <- file(filename, "r")
lineNo <- 1
while (TRUE) {
lineNo <- lineNo + 1
line <- readLines(con, n = 1)
# lines with either only ; or , or combination as spacer between metadata and data per convention in TSE files
if (length(line) == 0 || length(grep("^[;,]+$", line) != 0) ||
line == "") {
return(lineNo)
}
}
}
# Skip metadata before data
toSkip <- detectData(file)
# time diff (interval) or recordings, default if no time diff otherwise found
time_diff <- getSession(session$token, global_data)[["time_diff"]]
# check file extension
fileExtension <- detectFileType(file)
# default
sep <- ";"
dec <- ","
scaleFactor <- 1
# Promethion Live/Sable input needs scale factor of 60 (1 unit is 60 seconds)
if (fileExtension == "xlsx") {
output$study_description <- renderText("")
tmp_file <- tempfile()
if (length(excel_sheets(file)) == 2) {
if (check_for_cosmed(file)) {
output$file_type_detected <- renderText("Input file type detected as: COSMED")
storeSession(session$token, "input_file_type", "COSMED", global_data)
import_cosmed(file, tmp_file)
} else {
output$file_type_detected <- renderText("Unknown file type detected from Excel")
storeSession(session$token, "input_file_type", "Unknown", global_data)
}
} else {
output$file_type_detected <- renderText("Input file type detected as: Promethion/Sable")
updateSelectInput(session, "myr", choices = c("VO2", "VCO2", "RER"))
storeSession(session$token, "input_file_type", "Sable", global_data)
import_promethion(file, tmp_file)
}
file <- tmp_file
toSkip <- detectData(file)
# For COSMED need to scale to minutes
scaleFactor <- 60
}
# LabMaster V5 (horizontal format)
if (grepl("V5", fileFormatTSE)) {
storeSession(session$token, "input_file_type", "LabMaster/V5", global_data)
sep <- ";"
dec <- "."
}
# LabMaster V6
if (grepl("V6", fileFormatTSE)) {
storeSession(session$token, "input_file_type", "LabMaster/V6", global_data)
sep <- ";"
dec <- ","
}
# PhenoMaster V7: Date separated via /, Time Hour:Minutes, decimal separator ., field separator ,
if (grepl("V7", fileFormatTSE)) {
storeSession(session$token, "input_file_type", "PhenoMaster/V7", global_data)
sep <- ","
dec <- "."
}
# PhenoMaster V8
if (grepl("V8", fileFormatTSE)) {
# V8 seems to export sloppy, i.e. non-consistent CSV files, check for this before importing data sets
is_consistent <- check_column_consistency(file, sep=sep)
if (!is_consistent) {
shinyalert("Error", paste("Input data file has different number of columns for rows. Inconsistent format."), showCancelButton=TRUE)
return()
}
storeSession(session$token, "input_file_type", "PhenoMaster/V8", global_data)
tmp_file <- tempfile()
import_pheno_v8(file, tmp_file)
file <- tmp_file
toSkip <- detectData(file)
}
# File encoding matters: Shiny apps crashes due to undefined character entity
C1 <- read.table(file, header = FALSE, skip = toSkip + 1,
na.strings = c("-", "NA"), fileEncoding = "ISO-8859-1", sep = sep, dec = dec)
# Remove NaNs just in case, sloppy TSE systems export
if (input$drop_nan_rows) {
C1 <- C1 %>% drop_na()
}
# Note: We will keep the basic metadata informatiom from TSE files
C1meta <- read.table(file, header = TRUE, skip = 2, nrows = toSkip + 1 - 4,
na.strings = c("-", "NA"), fileEncoding = "ISO-8859-1", sep = sep, dec = dec)
#############################################################################
# Curate data frame
#############################################################################
C1.head <- read.table(file, # input file
header = FALSE, # no header
skip = toSkip - 1, # skip headers up to first animal
nrows = 2, # read only two rows (variable name + unit)
na.strings = c("", "NA"), #transform missing units to NA
as.is = TRUE, # avoid transformation character->vector
check.names = FALSE, # set the decimal separator
fileEncoding = "ISO-8859-1", # file encoding to ISO-8559-1
sep = sep, # separator for columns
dec = dec) # decimal separator
names(C1) <- paste(C1.head[1, ], C1.head[2, ], sep = "_")
# unite data sets
C1 <- C1 %>%
unite(Datetime, # name of the final column
c(Date_NA, Time_NA), # columns to be combined
sep = " ") # separator set to blank
C1$Datetime <- gsub(".", "/", C1$Datetime, fixed = TRUE)
# transform into time format appropriate to experimenters
if (input$correct_clock_change) {
C1$Datetime2 <- as.POSIXct(C1$Datetime, format = "%d/%m/%Y %H:%M", tz="Etc/GMT-1")
} else {
C1$Datetime2 <- as.POSIXct(C1$Datetime, format = "%d/%m/%Y %H:%M")
}
C1$hour <- hour(C1$Datetime2)
C1$minutes <- minute(C1$Datetime2)
if (!is.null(time_start_end)) {
start_date <<- time_start_end$date_start
end_date <<- time_start_end$date_end
}
if (!input$do_select_date_range) {
start_date <<- "1970-01-01"
end_date <<- Sys.Date()
}
C1 <- C1 %>%
group_by(`Animal No._NA`) %>%
arrange(Datetime2) %>%
filter(Datetime2 >= start_date & # From
Datetime2 <= end_date) %>% # To
mutate(MeasPoint = row_number())
C1 <- C1[!is.na(C1$MeasPoint), ]
# Step #1 - calculate the difference between consecutive dates
C1 <- C1 %>%
group_by(`Animal No._NA`) %>% # group by Animal ID
arrange(Datetime2) %>% # sort by Datetime2
# subtract the next value from first value and safe as variable "diff.sec)
mutate(diff.sec = Datetime2 - lag(Datetime2, default = first(Datetime2)))
C1$diff.sec <- as.numeric(C1$diff.sec) # change format from difftime->numeric
# Step #2 - calc the cumulative time difference between consecutive dates
C1 <- C1 %>%
group_by(`Animal No._NA`) %>% # group by Animal ID
arrange(Datetime2) %>% # sort by Datetime2
# calculate the cumulative sum of the running time and
# save as variable "running_total.sec"
mutate(running_total.sec = cumsum(diff.sec))
# Step #3 - transfers time into hours (1 h = 3600 s)
C1$running_total.hrs <- round(C1$running_total.sec / 3600, 1)
# Step #4 - round hours downwards to get "full" hours
C1$running_total.hrs.round <- floor(C1$running_total.hrs)
C1 <- C1 %>%
group_by(`Animal No._NA`) %>% # group by Animal ID
arrange(Datetime2) %>% # sort by Datetime2
# subtract the next value from the first value. Safe as variable diff.sec)
mutate(diff.sec = Datetime2 - lag(Datetime2, default = first(Datetime2)))
C1$diff.sec <- as.numeric(C1$diff.sec) # change format from difftime->numeric
# Step #6 - calculate cumulative time difference between consecutive dates
C1 <- C1 %>%
group_by(`Animal No._NA`) %>% # group by Animal ID
arrange(Datetime2) %>% # sort by Datetime2
# calculate cumulative sum of running time. Save in var. "running_total.sec"
mutate(running_total.sec = cumsum(diff.sec))
# Step #7 - transfers time into hours (1 h = 3600 s)
C1$running_total.hrs <- round(C1$running_total.sec / 3600, 1)
# Step #8 - round hours downwards to get "full" hours
C1$running_total.hrs.round <- floor(C1$running_total.hrs)
# Step #9 - recalculate RER
if (input$recalculate_RER) {
C1$RER_NA = C1$`VCO2(3)_[ml/h]` / C1$`VO2(3)_[ml/h]`
}
#############################################################################
# Consistency check: Negative values
#############################################################################
if (input$negative_values) {
C1_test <- C1
if ("Ref.TD_[°C]" %in% colnames(C1)) {
C1_test <- C1_test %>% select(!`Ref.TD_[°C]`)
}
if ("TD_[°C]" %in% colnames(C1)) {
C1_test <- C1_test %>% select(!`TD_[°C]`)
}
invalid_data <- nrow(C1_test %>% filter(if_any(everything(), ~.x < 0)))
if (invalid_data > 0) {
shinyalert("Error", paste("Negative values encountered in measurements", invalid_data, ".Check your input data.", sep = ""), type = "warning", showCancelButton = TRUE)
}
}
#############################################################################
# Consistency check: Highly fluctuating measurements
#############################################################################
if (input$highly_varying_measurements) {
invalid_data <- nrow(C1 %>% mutate(col_diff = abs(`VO2(3)_[ml/h]` - lag(`VO2(3)_[ml/h]`) / max(`VO2(3)_[ml/h]`, lag(`VO2(3)_[ml/h]`), na.rm = TRUE))) %>% select(col_diff) %>% filter(col_diff > input$threshold_for_highly_varying_measurements))
if (invalid_data > 0) {
shinyalert("Error", paste("Highly varying input measurements detected in O2 signal: ", invalid_data, ". Check your input data", sep = ""), type = "warning", showCancelButton = TRUE)
}
invalid_data <- nrow(C1 %>% mutate(col_diff = abs(`VCO2(3)_[ml/h]` - lag(`VCO2(3)_[ml/h]`) / max(`VCO2(3)_[ml/h]`, lag(`VCO2(3)_[ml/h]`), na.rm = TRUE))) %>% select(col_diff) %>% filter(col_diff > input$threshold_for_highly_varying_measurements))
if (invalid_data > 0) {
shinyalert("Error", paste("Highly varying input measurements detected in CO2 signal: ", invalid_data, ". Check cour input data", sep = ""), type = "warning", showCancelButton = TRUE)
}
}
# Optional running average calculation
# Step #9 - define 1/n-hours steps
if (input$averaging == 10) { # 1/6 hours
C1 <- C1 %>%
mutate(timeintervalinmin = case_when(minutes <= 10 ~ 0,
minutes <= 20 ~ (1 / 6),
minutes <= 30 ~ (2 / 6),
minutes <= 40 ~ (3 / 6),
minutes <= 50 ~ (4 / 6),
minutes > 50 ~ (5 / 6)))
} else if (input$averaging == 20) { # 1/3 hours
C1 <- C1 %>%
mutate(timeintervalinmin = case_when(minutes <= 20 ~ 0,
minutes <= 40 ~ 0.3,
minutes > 40 ~ 0.6))
} else if (input$averaging == 30) { # 1/2 hours
C1 <- C1 %>%
mutate(timeintervalinmin = case_when(minutes <= 30 ~ 0,
minutes > 30 ~ 0.5))
} else { # no averaging at all
C1 <- C1 %>% mutate(timeintervalinmin = minutes)
}
# Step #10 - create a running total with half hour intervals by adding
# the thirty min to the full hours
C1$running_total.hrs.halfhour <- C1$running_total.hrs.round + C1$timeintervalinmin
# heat production equations #1 and #2
f1 <- input$variable1
f2 <- input$variable2
#############################################################################
# Heat production formula #1
#############################################################################
current_cohort_time_diff = 1.0
if (input$kj_or_kcal == "mW") {
# 1000 because from Watts to milli Watts
1000 * current_cohort_time_diff <- get_time_diff(C1, 2, 3, input$detect_nonconstant_measurement_intervals)
}
C1 <- calc_heat_production(f1, C1, "HP", scaleFactor * (1.0 / current_cohort_time_diff))
#############################################################################
# Heat production formula #2 (for comparison in scatter plots)
#############################################################################
if (!is.null(input$variable2)) {
C1 <- calc_heat_production(f2, C1, "HP2", scaleFactor * (1.0 / current_cohort_time_diff))
} else {
C1 <- calc_heat_production(f1, C1, "HP2", scaleFactor * (1.0 / current_cohort_time_diff))
}
# step 11 means
C1.mean.hours <- do.call(data.frame, aggregate(list(HP2 = C1$HP2, # calculate mean of HP2
VO2 = C1$`VO2(3)_[ml/h]`, # calculate mean of VO2
VCO2 = C1$`VCO2(3)_[ml/h]`, # calculate mean of VCO2
RER = C1$`VCO2(3)_[ml/h]` / C1$`VO2(3)_[ml/h]`), # calculate mean of RER
by = list(
Animal = C1$`Animal No._NA`, # groups by Animal ID
Time = C1$running_total.hrs.round), # groups by total rounded running hour
FUN = function(x) c(mean = mean(x), sd = sd(x)))) # calculates mean and standard deviation
# compile final measurement frame
if (input$common_columns_only) {
if (i == 1) {
current_data_cols <- c(colnames(C1))
} else {
current_data_cols <- intersect(current_data_cols, c(colnames(C1)))
}
C1 <- C1 %>% select(all_of(current_data_cols))
}
# interpolate to regular time grid in case a cohort has un-even spacing of data
if (input$regularize_time) {
interpolate_to <- get_time_diff(C1, 2, 3, input$detect_nonconstant_measurement_intervals)
if (input$override_interval_length) {
interpolate_to <- input$override_interval_length_minutes * 60
}
numeric_cols <- names(C1)[sapply(C1, is.numeric) & names(C1) != "running_total.sec" & names(C1) != "Animal No._NA"]
other_cols <- setdiff(names(C1), c("running_total.sec", "Animal No._NA", numeric_cols))
# Note: approx may fail, if there is duplicated values in running_total.sec - should actually never be the case...
# however, to be sure, average duplicated running_total.sec values per Animal No._NA in the next lines
C1 <- C1 %>% group_by(`Animal No._NA`) %>% complete(running_total.sec = seq(min(running_total.sec), max(running_total.sec), by = interpolate_to * 60)) %>%
arrange(`Animal No._NA`, running_total.sec) %>%
mutate(across(all_of(numeric_cols), ~ approx(running_total.sec, .x, xout=running_total.sec, rule=2)$y)) %>%
fill(all_of(other_cols), .direction = "downup") %>%
ungroup()
}
# exclude animals (outliers) from data sets
if (! is.null(exclusion)) {
for (to_exclude_from_list in exclusion) {
C1 <- C1 %>% filter(`Animal No._NA` != as.numeric(to_exclude_from_list))
}
}
# coarsen data set (might need to average later than)
if (input$coarsen_data_sets) {
C1 <- coarsen_data_sets(C1, input$coarsening_factor)
}
# compile final measurement frame
if (input$common_columns_only) {
if (i == 1) {
current_data_cols <- colnames(C1)
} else {
current_data_cols <- intersect(current_data_cols, colnames(C1))
}
C1 <- C1 %>% select(all_of(current_data_cols))
}
# add interval info for each data frame / cohort separately
interval_length_list[[paste0("Cohort #", i)]] <- list(values=c(unique(C1$`Animal No._NA`)), interval_length=get_time_diff(C1, 2, 3, input$detect_nonconstant_measurement_intervals))
if (input$common_columns_only) {
if (!is.null(finalC1)) {
finalC1 <- finalC1 %>% select(all_of(current_data_cols))
}
if (!is.null(C1)) {
C1 <- C1 %>% select(all_of(current_data_cols))
}
}
finalC1 <- rbind(C1, finalC1)
common_cols <- intersect(colnames(finalC1meta), colnames(C1meta))
finalC1meta <- rbind(subset(finalC1meta, select = common_cols), subset(C1meta, select = common_cols))
}
# print master list for interval lengths
storeSession(session$token, "interval_length_list", interval_length_list, global_data)
pretty_print_interval_length_list(interval_length_list)
# remove z-score outliers
if (input$z_score_removal_of_outliers) {
finalC1 <- remove_z_score_outliers(finalC1, input$sds)
}
# remove zero values
if (input$remove_zero_values) {
finalC1 <- remove_zero_values(finalC1, input$eps)
}
# assign metadata
C1meta <- finalC1meta
# rescale to kcal from kj
if (input$kj_or_kcal == "kcal") {
finalC1$HP <- finalC1$HP / 4.184 # to kj
finalC1$HP2 <- finalC1$HP2 / 4.184 # to kj
}
# override light cycle configuration from metadata
if (input$override_metadata_light_cycle) {
# Force override by user from data files if demanded (not all TSE files have light cycle configuration data)
if (! is.null(input$light_cycle)) {
if ("LightC_[%]" %in% colnames(finalC1)) {
`$`(finalC1, "LightC_[%]") <- as.numeric(`$`(finalC1, "LightC_[%]"))
# filter finalC1 by light cycle
if (input$light_cycle == "Night") {
finalC1 <- mutate(`LightC_[%]` = as.numeric(`LightC_[%]`)) %>% filter(finalC1, `LightC_[%]` < input$threshold_light_day)
} else {
finalC1 <- mutate(`LightC_[%]` = as.numeric(`LightC_[%]`)) %>% filter(finalC1, `LightC_[%]` > input$threshold_light_day)
}
}
}
}
# time interval diff for finalC1
storeSession(session$token, "time_diff", get_time_diff(finalC1, 2, 3, input$detect_nonconstant_measurement_intervals), global_data)
# set the time date ranges once for the final data frame
if (is.null(time_start_end)) {
time_start_end <<- get_date_range(finalC1)
output$daterange <- renderUI(dateRangeInput("daterange", "Date", start = time_start_end$date_start, end = time_start_end$date_end))
}
storeSession(session$token, "finalC1", finalC1, global_data)
storeSession(session$token, "finalC1meta", finalC1meta, global_data)
storeSession(session$token, "C1meta", C1meta, global_data)
storeSession(session$token, "scaleFactor", scaleFactor, global_data)
storeSession(session$token, "finalC1cols", colnames(finalC1), global_data)
raw_cols <- getSession(session$token, global_data)[["finalC1cols"]]
raw_cols <- sub("_.*$", "", raw_cols)
raw_cols <- sub("\\(.*$", "", raw_cols)
choices = c("O2", "CO2", "RER", "VO2", "VCO2", "TempL", "Drink1", "Feed1", "Temp", "TempC", "WeightBody", "XT.YT", "DistD", "DistK")
updateSelectInput(session, "myr", choices = c(intersect(unlist(choices), unlist(raw_cols)), "O2"), selected=input$myr)
}
################################################################################
# Create plotly plot
################################################################################
do_plotting <- function(file, input, exclusion, output, session) { # nolint: cyclocomp_linter.
# if data is not loaded, load the data
if (is.null(getSession(session$token, global_data)[["data_loaded"]])) {
load_data(file, input, exclusion, output, session)
storeSession(session$token, "data_loaded", TRUE, global_data)
} else {
# Nothing to load
}
# load default plotting style
if (input$use_default_plot_style) {
configure_default_plot_look_and_feel()
}
# get stored data so far
finalC1 = getSession(session$token, global_data)[["finalC1"]]
finalC1meta = getSession(session$token, global_data)[["finalC1meta"]]
C1meta = getSession(session$token, global_data)[["C1meta"]]
scaleFactor = getSession(session$token, global_data)[["scaleFactor"]]
# Filter out additionally whole calendrical days with given percentage threshold
# However this is currently imcompatible with zeitgeber time utility, which shifts
# based on the assumption that running_total.secs == 0 exists in the data frame to
# find the shift offset with respect to the start of the light cycle (this also means
# that running_total.secs might be negative). If we filter out non-full calendricald
# dates, we might not have running_total.secs == 0 true in our data frame, so the
# zeitgeber_time function in util.R fails accordingly.
# We use && ! input$use_zeitgeber_time to exclude this for now - also in ui.R we
# do not offer the selection of calendrical days if zeitgeber time is used.
# TODO: Remove the if statement once zeitgeber_time function in util.R has been adapted
if (input$only_full_days && !input$use_zeitgeber_time) {
interval_length_list <- getSession(session$token, global_data)[["interval_length_list"]]
storeSession(session$token, "time_diff", get_time_diff(finalC1, 2, 3, input$detect_nonconstant_measurement_intervals), global_data)
finalC1 <- filter_full_days_alternative(finalC1, input$full_days_threshold, interval_length_list)
}
#####################################################################################################################
# Plotting and data output for downstream debugging
#####################################################################################################################
plotType <- input$plot_type
switch(plotType,
#####################################################################################################################
# CompareHeatProductionFormulas
#####################################################################################################################
CompareHeatProductionFormulas = {
p <- ggplot(data = finalC1, aes_string(x = "HP", y = "HP2"))
p <- p + geom_point() + stat_smooth(method = "lm")
p <- p + stat_cor(method = "pearson", aes(label = paste(..rr.label.., ..p.label.., sep = "~`,`~")))
p <- p + ggtitle("Pearson-correlation between energy expenditures as computed by two different formulas")
},
#####################################################################################################################
# FuelOxidation
#####################################################################################################################
FuelOxidation = {
p <- goxlox(finalC1, finalC1meta, input, output, session, global_data, scaleFactor)
p_window = p$window_plot
p <- p$plot
# indicate if plot available
indicate_plot_rendered(p, output)
# style plot
p <- style_plot(p, input)
if (!is.null(p_window)) {
output$windowPlot <- renderPlotly(p_window)
}
},
#####################################################################################################################
### Energy Expenditure
#####################################################################################################################
HeatProduction = {
p <- energy_expenditure(finalC1, finalC1meta, input, output, session, global_data, scaleFactor)
p_window <- p$window_plot
p <- p$plot
# indicate if plot available
indicate_plot_rendered(p, output)
# style plot
p <- style_plot(p, input)
if (!is.null(p_window)) {
output$windowPlot <- renderPlotly(p_window)
}
},
#####################################################################################################################
### RestingMetabolicRate
#####################################################################################################################
RestingMetabolicRate = {
# Check first if RMR can be calculated
if (!getSession(session$token, global_data)[["is_TEE_calculated"]]) {
shinyalert("Error:", "Total heat production needs to be calculated before!")
return()
}
df_returned <- resting_metabolic_rate(finalC1, finalC1meta, input, output, session, global_data, scaleFactor, true_metadata)
finalC1 <- df_returned$finalC1
p <- df_returned$plot
p_window <- df_returned$window_plot
# indicate if plot available
indicate_plot_rendered(p, output)
# style plot
p <- style_plot(p, input)
if (!is.null(p_window)) {
output$windowPlot <- renderPlotly(p_window)
}
},
#####################################################################################################################
### Day Night Activity
#####################################################################################################################
DayNightActivity = {
p <- day_night_activity(finalC1, finalC1meta, input, output, session, global_data, scaleFactor)
# indicate if plot available
indicate_plot_rendered(p, output)
# style plot
p <- style_plot(p, input)
},
#####################################################################################################################
### Locomotion
#####################################################################################################################
Locomotion = {
file <- input[[paste0("File", 1)]]
if (input$have_box_coordinates) {
p <- plot_locomotion(file$datapath, input$x_min_food, input$x_max_food, input$y_min_food, input$y_max_food, input$x_min_scale, input$x_max_scale, input$y_min_scale, input$y_max_scale, input$x_min_bottle, input$x_max_bottle, input$y_min_bottle, input$y_max_bottle)
} else {
p <- plot_locomotion(file$datapath)
}
p <- p + ggtitle("Probability density map of locomotion")
},
#####################################################################################################################
### Locomotion Budget
#####################################################################################################################
LocomotionBudget = {
file <- input[[paste0("File", 1)]]
p <- plot_locomotion_budget(file$datapath)
p <- p + ggtitle("Locomotional budget")
},
#####################################################################################################################
### Estimate RMR for COSMED
#####################################################################################################################
EstimateRMRforCOSMED = {
p <- estimate_rmr_for_cosmed(finalC1, finalC1meta, input, output, session, global_data, scaleFactor)
# indicate if plot available
indicate_plot_rendered(p, output)
# style plot
p <- style_plot(p, input)
},
#####################################################################################################################
### RawMeasurement
#####################################################################################################################
RawMeasurement = {
p <- raw_measurement(finalC1, finalC1meta, input, output, session, global_data, scaleFactor)
p_window <- p$window_plot
p <- p$plot
# indicate if plot available
indicate_plot_rendered(p, output)
# style plot
p <- style_plot(p, input)
if (!is.null(p_window)) {
output$windowPlot <- renderPlotly(p_window)
}
},
#####################################################################################################################
### Total Energy Expenditure
#####################################################################################################################
TotalHeatProduction = {
p <- total_energy_expenditure(finalC1, C1meta, finalC1meta, input, output, session, global_data, scaleFactor)
p_time <- p$time_trace
p_window <- p$window_plot
p <- p$plot
# indicate if main plot available
indicate_plot_rendered(p, output)
# style main plot
p <- style_plot(p, input)
# add time plot as well
if (!is.null(p_time)) {
output$timeTrace <- renderPlotly(p_time)
}
# and windowed plot
if (!is.null(p_window)) {
output$windowPlot <- renderPlotly(p_window)
}
},
#####################################################################################################################
### Metadata
#####################################################################################################################
Metadata = {
p <- body_composition(finalC1, finalC1meta, input, output, session, global_data, scaleFactor)
# indicate if plot available
indicate_plot_rendered(p, output)
# increase plot size
p %>% layout(height=1000)
},
#####################################################################################################################
### Other options
#####################################################################################################################
{
# all other options which should come
}
)
# return data to UI
list("plot" = p, "animals" = `$`(finalC1, "Animal No._NA"), "data" = finalC1, "metadata" = C1meta)
}
#####################################################################################################################
# Create server
#####################################################################################################################
server <- function(input, output, session) {
# keep alive
#output$keepAlive <- renderText({
# invalidateLater(15000, session)
# Sys.time()
#})
# stylize plot
output$stylize_plot_plotting_control <- renderUI({
if (input$stylize_plot) {
add_stylize_plot_plotting_control()
} else {
NULL
}
})
# get git info from repository
output$git_info <- renderText(paste0("Version: ", get_git_information_from_repository()))
# get current session id for user
output$session_id <- renderText(paste0("Session ID: ", session$token))
# store globally the data per session
storeSession(session$token, "time_diff", 5, global_data)
storeSession(session$token, "time_start_end", NULL, global_data)
storeSession(session$token, "start_date", "1970-01-01", global_data)
storeSession(session$token, "end_date", Sys.Date(), global_data)
storeSession(session$token, "selected_days", NULL, global_data)
storeSession(session$token, "selected_animals", NULL, global_data)
storeSession(session$token, "interval_length_list", list(), global_data)
storeSession(session$token, "is_TEE_calculated", FALSE, global_data)
storeSession(session$token, "is_RMR_calculated", FALSE, global_data)
# gender choice = all
output$checkboxgroup_gender <- renderUI(
checkboxGroupInput(inputId = "checkboxgroup_gender", label = "Chosen sexes",
choices = list("male" = "male", "female" = "female"), selected = c("male", "female")))
# observer helpers
observe_helpers()
# observer metadata field
output$metadatafile <- renderUI({
html_ui <- " "
html_ui <- paste0(html_ui,
fileInput("metadatafile",
label = "Metadata file"))
HTML(html_ui)
})
# download data as csv or xlsx. if no data available, no download button is displayed
output$downloadData <- downloadHandler(
filename = function() {
if (! input$export_file_name == "") {
paste(input$export_file_name, ".csv", sep = "")
} else {
extension <- ".csv"
if (input$export_format == "Excel") {
extension <- ".xlsx"
}
paste("data-", Sys.Date(), input$export_format, extension, sep = "")
}
},
content = function(file) {
status_okay <- do_export_alternative(input$export_format, input, output, session, file, do_plotting, global_data)
}
)
# Download handler to get current data frame of displayed plot
output$downloadPlottingData <- downloadHandler(
filename = function() {
if (! input$export_file_name2 == "") {
paste(input$export_file_name2, ".csv", sep = "")
} else {
extension <- ".csv"
paste("plotting_data-", Sys.Date(), extension, sep = "")
}
},
content = function(file) {
status_okay <- do_export_plotting_data(input, output, session, file, do_plotting, global_data)
}
)
# Draw initial number of files -> typically one file
output$nFiles <- renderUI(numericInput("nFiles", "Number of data files", value = 1, min = 1, step = 1))
# Download handler for all data download as zip
output$downloadAllData <- downloadHandler(
filename = function() {
paste0("all_data-", Sys.Date(), ".zip")
},
content = function(file) {
print("Here?")
zip_file = do_export_all_data(input, output, session, file, do_plotting, global_data)
file.copy(zip_file, file)
}
)
# Dynamically create fileInput fields by the number of requested files of the user
observeEvent(input$nFiles, {
output$fileInputs <- renderUI({
html_ui <- " "
for (i in 1:input$nFiles) {
html_ui <- paste0(html_ui, fileInput(paste0("File", i),
label = paste0("Cohort #", i)))
}
HTML(html_ui)
})
})
#####################################################################################################################
# Observer plotly_click (mouse left-click)
#####################################################################################################################
observeEvent(event_data("plotly_click"), {
click_data <- event_data("plotly_click")
if (!is.null(click_data)) {
data <- getSession(session$token, global_data)[["reactive_data"]]()
nearest_idx <- which.min(abs(data$running_total.hrs.halfhour - click_data$x))
# highlight the point
isolate({
p <- plotlyProxy("plot", session) %>% plotlyProxyInvoke("restyle", list(marker=list(color = "red")), list(nearest_idx))
})
isolate({
session$sendCustomMessage(type = "selected_point", nearest_idx)
})
}
})
#####################################################################################################################
# Observer plotly_selected (lasso or rectangle)
#####################################################################################################################
observeEvent(event_data("plotly_selected"), {
selected_data <- event_data("plotly_selected")
if (!is.null(selected_data)) {
data <- getSession(session$token, global_data)[["reactive_data"]]()
# Animal grouping is added last, thus we have an offset of number of traces already in the plot object - number of unique levels in factor
# TODO: Generalize this that it is re-useable in other plots as well. Currently only used in panel RawMeasurement for outlier removal.
all_curves_plotly <- getSession(session$token, global_data)[["all_curves_plotly"]] - length(levels(data$Animals))
curve_to_sampleid_mapping <- levels(data$Animals)
selected_sampleid <- curve_to_sampleid_mapping[selected_data$curveNumber+1-all_curves_plotly]
selected_indices <- which(
data$Animals %in% selected_sampleid &
data$running_total.hrs.halfhour %in% selected_data$x,
data[[input$myr]] %in% selected_data$y
)
isolate({
p <- plotlyProxy("plot", session) %>% plotlyProxyInvoke("restyle", list(marker=list(color = "green")), list(selected_indices))
})
isolate({
session$sendCustomMessage(type = "selected_points", selected_indices)
})
}