-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.R
2080 lines (1755 loc) · 101 KB
/
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
InitializeMain <- function() {
Load_Packages <- function() {
# data loading external file formats
library(R.matlab); library(data.table);
# data manipulation
library(tidyverse); library(glue);
# analysis & visualization
library(psycho); library(ggplot2); library(hrbrthemes); library(shiny);
}
Load_Packages()
options(warn = 1) # we want to display warnings as they occur, so that it's clear which file caused which warnings
source(paste0(projects_folder, "settings.R")) # user variables
rat_archive <<- fread(paste0(projects_folder, "rat_archive.csv"), na.strings = c("N/A","NA"))
load(paste0(projects_folder, "run_archive.Rdata"), .GlobalEnv)
}
Process_File <- function(file_to_load, name, weight, observations, exclude_trials = "", old_file = FALSE, ignore_name_check = FALSE, use_shiny = FALSE, file_name_override = NULL, scientist = "", weightProblem = "", rxnProblem = "") {
Import_Matlab <- function(file_to_load) {
Unlist_Matlab_To_Dataframe <- function(li) {
return(t(apply(li, 1, unlist)) %>% as.data.frame())
}
Get_Stim_Encoding_Table <- function() {
Validate_Stim_Encoding_Table <- function () {
# Check that all stims are unique
stim_not_unique = stim_encoding_table %>%
dplyr::group_by(`Freq (kHz)`, `Inten (dB)`, `Dur (ms)`, `Type`) %>%
dplyr::filter(n() > 1) %>%
summarize(n = n(), .groups = 'drop')
# Warning
if (nrow(stim_not_unique) != 0) {
warn = paste0("ACTION REQUIRED: Multiple (", nrow(stim_not_unique), ") identical stims.")
warning(paste0(warn, "\n"))
warnings_list <<- append(warnings_list, warn)
}
only_one_frequency = length(unique(stim_encoding_table$`Freq (kHz)`)) == 1
# Check StimSource against Frequency
if (only_one_frequency) {
freq_current = unique(stim_encoding_table$`Freq (kHz)`)
source_current = unique(stim_encoding_table$`Stim Source`)
# Check for gap or BBN matching frequncy 0
if (xor(freq_current == 0, source_current %in% c("BBN", "gap"))) {
warn = paste0("ACTION REQUIRED: Source (", source_current, ") does not match single Frequency (", freq_current, " kHz).")
warning(paste0(warn, "\n"))
warnings_list <<- append(warnings_list, warn)
if (freq_current == 0) source_corrected = "BBN"
else source_corrected = "tone"
stim_encoding_table <<- stim_encoding_table %>%
dplyr::mutate(`Stim Source` = stringr::str_replace(`Stim Source`, source_current, source_corrected))
warn = paste0("Overriding Stim Source: Old (", source_current, ") to New (", source_corrected, ") based on single Frequency (", freq_current, " kHz).")
warning(paste0(warn, "\n"))
warnings_list <<- append(warnings_list, warn)
}
}
}
# create short (~50) table of all possible stimulus configurations (with delay specified as an allowed window)
stim_encoding_table = trial_collection$source.list
# remove sublists and transform into proper data frame
# from: https://stackoverflow.com/questions/15930880/unlist-all-list-elements-in-a-dataframe
stim_encoding_table = Unlist_Matlab_To_Dataframe(stim_encoding_table)
# add Column names
names(stim_encoding_table) = append(unlist(trial_collection$stim.tag.list), "Repeat_number", after = 0)
# fix column types to reflect contents (i.e. character -> numeric)
stim_encoding_table = stim_encoding_table %>% dplyr::mutate_at(
vars(Repeat_number, Type, `Freq (kHz)`, `Inten (dB)`, `Dur (ms)`, `Nose Out TL (s)`, `Time Out (s)`),
~as.numeric(.))
# Add identifying number (for decoding)
stim_encoding_table = dplyr::mutate(stim_encoding_table, "Stim_ID" = row_number())
Validate_Stim_Encoding_Table()
return(stim_encoding_table)
}
Get_Run_Properties <- function() {
Get_Stim_Filename <- function() {
r =
trial_collection$name[1] %>%
# remove excess info (i.e. .mat and then file location)
stringr::str_remove(pattern = ".mat @ .*$", string = .)
if (use_shiny) shiny::showNotification(glue("{r}")) #TODO replace default with shinyfeedback colored ones
cat("Stim file:", r, sep = "\t", fill = TRUE)
return(r)
}
Get_Rat_Name <- function() {
if (is.null(file_name_override)) {
# greedy group: (.*) to strip off as much as possible
# then the main capture group which contains
# lookbehind for either \ (escaped once because R, and then again cause regex, to \\\\) or / character, specified length 1 because r: (?<=[\\/]{1})
# important! \\\\ is specific to R, for testing this pattern in e.g. RegExr you have to use \\ but remember to change it back to \\\\ for r!
# capture of the rat name, lazy to avoid underscores: .+?
# lookahead for a _: (?=_)
pattern = "(.*)((?<=[\\\\/]{1}).+?(?=_))"
filename = file_to_load
} else {
# shiny app provides a path to a temporary file and renames the file itself, so we have to work around that behavior
# we could alternatively use the system file loader, but that has other downsides - it's difficult to get it to remember the current folder, and it doesn't give feedback of a file selected
pattern = "^.+?(?=_)" # beginning up to underscore, lazy
filename = file_name_override
ignore_name_check = TRUE
}
#print(filename)
r = stringr::str_match_all(filename, pattern = pattern) %>%
unlist(recursive = TRUE) %>%
tail (n = 1)
r_compare = r %>%
str_replace_all(" ", "") %>%
str_to_lower()
if (!ignore_name_check) {
name_compare = name %>% str_replace_all(" ", "") %>% str_to_lower() # from undergraduate.R
}
if (rlang::is_empty(r)) stop("ERROR: system filename improper: ", filename)
if (!ignore_name_check && r_compare != name_compare) stop(paste0("ABORT: Rat name given (", name_compare, ") does not match chosen file (", r_compare, ")."))
return(r)
}
Get_Rat_ID = function(check_name, creation_time) {
date = creation_time %>% stringr::str_sub(1,8) %>% as.numeric()
rats_with_name <- rat_archive %>%
dplyr::filter(Rat_name %>% str_to_upper() == check_name %>% str_to_upper())
if(nrow(rats_with_name) == 0) {
stop(paste0("ABORT: No rats with name ", check_name, " found in archive."))
} else {
rat_ID = rats_with_name %>%
dplyr::filter(start_date <= date) %>%
dplyr::filter(date <= end_date | is.na(end_date)) %>% .$Rat_ID
if(length(rat_ID) > 1) stop(paste0("ABORT: Overlapping rats on date ", date, " with name ", check_name, ". Cannot determine Rat ID."))
if(length(rat_ID) == 0) stop("ABORT: No rats with name ", check_name, " were active on ", date, ".")
return(rat_ID)
}
}
Get_Box_Number <- function() {
if (is.null(file_name_override)) {
filename = file_to_load
} else {
filename = file_name_override
}
# check for presence of BOX.ID setting to allow backwards compatibility
in_file = purrr::pluck(current_mat_file, "log") %>% dimnames %>% .[[1]] %>% is.element("BOX.ID") %>% any()
if(in_file) {
# Get BOX from run file settings
r = purrr::pluck(current_mat_file, "log") %>% .["BOX.ID",,] %>% flatten_chr() %>%
#remove BOX label
str_remove(pattern = "BOX#[0]+") %>%
# covert to a numeric
as.numeric()
if(rlang::is_empty(r)) stop("ERROR: reported box id is not a number.")
} else {
# Get BOX from file name
# greedy group: (.*) to strip off as much as possible
# then the main capture group which contains
# lookbehind for a _BOX#: (?<=_BOX#)
# capture of the box number: [:digit:]+
# lookahead for the extension: (?=.mat)
r = stringr::str_match_all(filename, pattern="(.*)((?<=_BOX#)[:digit:]+(?=.mat))") %>%
unlist(recursive = TRUE) %>%
tail (n = 1) %>%
as.numeric()
if(rlang::is_empty(r)) stop("ERROR: system filename improper: ", filename)
}
return(r)
}
Get_Delay_Range <- function() {
if (stim_type == "train") {
r = stim_encoding_table %>% dplyr::filter(Repeat_number > 0) %>% .$`Delay (s)` %>% unique()
} else {
r = unique(stim_encoding_table$`Delay (s)`)
}
if (length(r)>1) {
warn = paste0("ACTION REQUIRED: Multiple delay windows (", r, ").")
warning(paste0(warn, "\n"))
warnings_list <<- append(warnings_list, warn)
}
return(r)
}
run_properties = trial_collection$para[,,1]
# Background Type
if (is.na(run_properties$BG.sound[[1]][1]) == TRUE) {
background_dB = "None"
background_file = "None"
background_type = "None"
} else {
background_dB = run_properties$BG.sound.inten[1]
background_file = run_properties$BG.sound["filepath",,]$filepath["filename",,]$filename[1]
background_type =
background_file %>%
stringr::str_remove(pattern = "^BG_", string = .) %>%
stringr::str_remove(pattern = ".mat", string = .)
background_type = switch(background_type,
"PKN" = "Pink",
"PNK" = "Pink",
"WN" = "White",
"BBN" = "Broadband",)
}
stim_type = unique(stim_encoding_table["Stim Source"])
if (nrow(stim_type) > 1) {
if ("train" %in% stim_type$`Stim Source`) {
stim_type = "train"
}
# if multiple types of go stimulus warn because mutliple types are excpected for oddball training but it should be go/nogo
else if (nrow(filter(stim_encoding_table, Type == 1)) > 1) {
warn = paste0("WARNING: Multiple non-oddball stim types: ", stim_type)
warning(paste0(warn, "\n"))
warnings_list <<- append(warnings_list, warn)
stim_type = stim_encoding_table %>% filter(Type == "1") %>% .$`Stim Source`
} else {stim_type = stim_encoding_table %>% filter(Type == "1") %>% .$`Stim Source`}
} else {
stim_type = stim_type %>% as.character()
}
rat_name = Get_Rat_Name()
#hoist the datestamp out of the loaded .mat file
#note this is hard coded and changes in the matlab file alter it.
creation_time = pluck(current_mat_file, "log") %>% .["save.time",,] %>% pluck(1, 2) %>% .[1,1]
r = list(
rat_name = rat_name,
rat_ID = Get_Rat_ID(rat_name, creation_time),
box = Get_Box_Number(),
stim_filename = Get_Stim_Filename(),
stim_block_size = sum(stim_encoding_table["Repeat_number"]),
stim_type = stim_type,
background_dB = background_dB,
background_file = background_file,
background_type = background_type,
# Maximum number of back to back no go trials (0 or blank is infinite)
nogo_max_touching = ifelse(is_empty(run_properties$no.go.trial.max.num), "0",
run_properties$no.go.trial.max.num[[1]]),
# settings from run_properties$stim_encoding_table
lockout = unique(stim_encoding_table$`Time Out (s)`)[unique(stim_encoding_table$`Time Out (s)`) > 0],
nogo_lockout =
stim_encoding_table %>%
filter(Type==0) %>% #nogo trials are type 0
.$`Time Out (s)` %>%
max(.),
delay = Get_Delay_Range(),
duration = unique(stim_encoding_table["Dur (ms)"]), # List of length of go sound - can be up to 3 values (50, 100, & 300) in our current file system
# DTW setting in the behavior program or TR in file names
# DTW = detect time window & TR = Trigger
# In either case, this is not to be confused with the response window (above)
# i.e. how long the rat has post trial start to respond
# This is how long the nose must remain out to be counted as 'withdraw' or
# response. Response time is for the withdraw.
trigger_sensitivity = `if`(all(is.na(run_properties$detect.time.win)), #if dtw is undefined, use 200
200,
run_properties$detect.time.win[[1]] %>% as.numeric()),
# Nose light operational?
nose_light = run_properties$nose.light[[1]] %>% as.logical(),
stim_encoding_table = stim_encoding_table,
creation_time = creation_time
)
#dynamically add stim notes here not as a sub-table
Get_Stim_Notes <- function() {
# to make this not hard coded, I am dealing with an mixed data type so its ugly hack
para = current_mat_file$stim %>% .["para", , ] %>% .$para
# now force set names as they should be so I can call them (still ugly hack)
para = setNames(para, dimnames(para)[[1]])
# This has the notes that need to be added to the run_properties
stim_note =
para$stim.note %>%
# TODO: automatically pull any possible note
# break apart if there is more than one note
str_split(pattern = "; ") %>%
#to handle multiple notes:
# remove the trailing ; from the last note
sapply(function(x) str_remove(string = x, pattern = ";")) %>%
# break each note into its named component and then its stored value
sapply(function(x) str_extract(string = x, pattern = "(?<name>.+): (?<value>.+)", group = c(1:2))) %>%
# force for next step
as.data.frame() %>%
# create a named list by column
apply(2, function(df) setNames(df["value"], paste0(df["name"])) %>% as.list) %>% flatten
return(stim_note)
}
# dynamically append any stim_notes to r
if(length(Get_Stim_Notes()) > 0) r = r %>% append(Get_Stim_Notes())
filename_TR = stringr::str_extract(r$stim_filename,"_TR[:digit:]+ms") %>% str_extract("[:digit:]+") %>% as.numeric()
if (!is.na(filename_TR)) if (filename_TR != r$trigger_sensitivity) {
warn = paste0("ACTION REQUIRED: Mismatched trigger window in filename (", filename_TR, ") and user_settings (", r$trigger_sensitivity, ").")
warning(paste0(warn, "\n"))
warnings_list <<- append(warnings_list, warn)
if (r$trigger_sensitivity != 200) {
newname = stringr::str_replace(r$stim_filename,"_TR[:digit:]+ms",paste0("_TR", r$trigger_sensitivity, "ms"))
}
else {
newname = stringr::str_replace(r$stim_filename,"_TR[:digit:]+ms","")
}
warn = paste0("Overriding File Name: Old (", r$stim_filename, ") to New (", newname, ") based on trigger_sensitivity.")
warning(paste0(warn, "\n"))
warnings_list <<- append(warnings_list, warn)
r$stim_filename = newname
}
if (length(r$response_window) > 1) stop("ABORT: Multiple response windows:", r$response_window,". Aborting.")
return(r)
}
Get_trial_data <- function() {
Get_Delay_DF <- function(trial_data) {
num_trials = nrow(trial_data)
delay_df = Unlist_Matlab_To_Dataframe(trial_collection$queue.list)[6]
delay_df = head(delay_df, n = num_trials)
names(delay_df) = "Delay (s)"
return(delay_df)
}
# Verify that the file's summary table (final.result) agrees with counting the raw data directly
Validate_Mat_Summary <- function() {
# file's summary table (matlab's work)
results_total_trials = current_mat_file$final.result[,,1]$go.trial.num[1] + current_mat_file$final.result[,,1]$no.go.trial.num[1]
results_hits = current_mat_file$final.result[,,1]$hit.num[1]
results_misses = current_mat_file$final.result[,,1]$miss.num[1]
results_CR = current_mat_file$final.result[,,1]$CR.num[1]
results_FA = current_mat_file$final.result[,,1]$FA.num[1]
# summary calculated from actual df (R's work)
total_trials = trial_data %>% dplyr::count() %>% as.numeric()
hits_calc = trial_data %>% dplyr::filter(Response == "Hit") %>% dplyr::count() %>% as.numeric()
misses_calc = trial_data %>% dplyr::filter(Response == "Miss") %>% dplyr::count() %>% as.numeric()
CRs_calc = trial_data %>% dplyr::filter(Response == "CR") %>% dplyr::count() %>% as.numeric()
FAs_calc = trial_data %>% dplyr::filter(Response == "FA") %>% dplyr::count() %>% as.numeric()
trial_count_go = trial_data %>% dplyr::filter(Trial_type != 0) %>% dplyr::count() %>% as.numeric()
trial_count_nogo = trial_data %>% dplyr::filter(Trial_type == 0) %>% dplyr::count() %>% as.numeric()
hit_percent = hits_calc / trial_count_go * 100
FA_from_all_trials = trial_data %>% dplyr::filter(Trial_type == 5) %>% dplyr::count() %>% as.numeric() > 0 # catch oddball style where go trials can FA
if (FA_from_all_trials) FA_percent = FAs_calc / total_trials * 100
else if (trial_count_nogo > 0) FA_percent = FAs_calc / trial_count_nogo * 100
else FA_percent = NA
# Added to compare to written record at request of Undergrads
writeLines(paste0("Trials: ", total_trials, "\tHit%: ", round(hit_percent, digits = 1), "\tFA%: ", round(FA_percent, digits = 1)))
if (use_shiny) shiny::showNotification(glue("Trials: {total_trials}"))
if (use_shiny) shiny::showNotification(glue("Hit%: {round(hit_percent, digits = 1)}"))
if (use_shiny) shiny::showNotification(glue("FA%: {round(FA_percent, digits = 1)}"))
if (results_total_trials == 0 | run_properties$stim_type == "train") {
cat("Validate_Mat_Summary: Skipped (no summary)", sep = "\t", fill = TRUE)
}
else {
# Check calculated stats against MATLAB summary stats
if (total_trials != results_total_trials) stop(paste0("ABORT: Trial count summary (", results_total_trials, ") does not match Data (", total_trials, ")."))
if (hits_calc != results_hits) stop(paste0("ABORT: Hit count summary (", results_hits, ") does not match Data (", hits_calc, ")."))
if (misses_calc != results_misses) stop(paste0("ABORT: Miss count summary (", results_misses, ") does not match Data (", misses_calc, ")."))
if (CRs_calc != results_CR) stop(paste0("ABORT: Correct rejection count summary (", results_CR, ") does not match Data (", CRs_calc, ")."))
if (FAs_calc != results_FA) stop(paste0("ABORT: False alarm count summary (", results_FA, ") does not match Data (", FAs_calc, ")."))
}
}
trial_data_encoded = data.frame(current_mat_file$result)
# The MATLAB file has 2 extra columns for some unknown reason
if (all(trial_data_encoded[7:8] != "0")) {
stop("ABORT: Two extra columns. What are these columns storing?")
} else {
trial_data_encoded = trial_data_encoded[1:6]
}
names(trial_data_encoded) = list("Time_since_file_start_(s)", "Stim_ID", "Trial_type", "Attempts_to_complete", "Response", "Reaction_(s)")
trial_data_encoded = trial_data_encoded %>%
dplyr::mutate(Response = dplyr::case_when(Response == 1 ~ "Hit",
Response == 2 ~ "Miss",
Response == 3 ~ "FA",
Response == 4 ~ "CR",
TRUE ~ "ERROR"))
trial_data = dplyr::left_join(x = trial_data_encoded,
y = dplyr::select(run_properties$stim_encoding_table, -Repeat_number, -`Delay (s)`),
by = "Stim_ID")
trial_data = dplyr::bind_cols(trial_data, Get_Delay_DF(trial_data))
#TODO: detect same day same rat data, renumber blocks in this list AND in master dataframe to continuous chronological order
#see also: CheckMultipartRun
block_list = rep(1:ceiling(nrow(trial_data)/run_properties$stim_block_size), each = run_properties$stim_block_size)
trial_data = trial_data %>% dplyr::mutate(Trial_number = row_number(),
Block_number = head(block_list, n = nrow(trial_data)))
Validate_Mat_Summary()
return(trial_data)
}
# These are typically demos or could trials that are ruled invalid by an observer.
Omit_Trials <- function() {
Query_Omitted_Trials <- function() {
suppressMessages({
omit_list = exclude_trials %>%
stringr::str_replace_all(string = ., pattern = "[:space:]", replacement = "") %>%
stringr::str_split(string = ., pattern = ",") %>%
as_tibble(.name_repair = c("universal")) %>%
dplyr::filter(...1 != "")
})
whole_numbers = omit_list %>%
dplyr::filter(!str_detect(string = ...1, pattern = "-")) %>%
as.list() %>% unlist(recursive = TRUE) %>% as.numeric()
ranges = omit_list %>%
dplyr::filter(str_detect(string = ...1, pattern = "-"))
if(nrow(ranges)) {
ranges = ranges %>%
rowwise() %>%
mutate(min = stringr::str_extract(string = ...1, pattern = "[:digit:]+(?=-)") %>% as.numeric(),
max = stringr::str_extract(string = ...1, pattern = "(?<=-)[:digit:]+") %>% as.numeric(),
s = list(seq(min,max))) %>%
.$s %>% as.list() %>% unlist(recursive = TRUE)
omit_list = c(whole_numbers, ranges)
} else {
omit_list = whole_numbers
}
omit_list = sort(omit_list)
old_omit_list = unlist(tail(run_archive$omit_list, n = 1), recursive = TRUE)
if (identical(omit_list, old_omit_list)) stop(paste0("ERROR: Stale exclude/omit list detected.\nPrior ",
tail(run_archive$rat_name, n = 1), " omitted trials: ",
paste(old_omit_list, collapse = " "), "\n",
"Current file ", run_properties$rat_name, " omitting: ",
paste(omit_list, collapse = " "), "\n",
"Please correct omit list and try again."))
return(omit_list)
}
Remove_Trials <- function(omit_list) {
# filter lines out of data
omitted = trial_data %>% dplyr::filter(row_number() %in% omit_list)
# TODO shove omitted to nonrat permanent rdata
r = trial_data %>% dplyr::filter(!row_number() %in% omit_list)
# get number of trials omitted
omit_count = length(omit_list) %>% as.numeric()
# calculate expected trials
Trials_expected = trial_data %>% dplyr::count() %>% as.numeric() - omit_count
# Calculate # of kept trials
Trials = dplyr::count(r) %>% as.numeric()
# check
if (Trials != Trials_expected) stop("ABORT: Expected kept count does not match.")
return(r)
}
omit_list = ""
r = trial_data
if (exclude_trials != "") omit_list = Query_Omitted_Trials()
run_properties$omit_list <<- list(omit_list)
if (rlang::is_empty(omit_list)) r = Remove_Trials(omit_list)
return(r)
}
Number_Complete_Blocks <- function() {
r = trial_data
block_status = r %>%
dplyr::group_by(Block_number) %>%
dplyr::summarise(Block_number = unique(Block_number), size = n(), complete = size == run_properties$stim_block_size) %>%
dplyr::filter(complete) %>%
dplyr::mutate(complete_block_number = row_number()) %>%
dplyr::select(Block_number, complete_block_number)
r = dplyr::left_join(r, block_status, by = "Block_number")
return(r)
}
# Import Workflow ---------------------------------------------------------
cat("Loading file...", file_to_load, sep = "\t", fill = TRUE)
current_mat_file = R.matlab::readMat(file_to_load)
trial_collection = current_mat_file$stim[,,1] # all (1000) trial configurations, and the parameters specified to generate individual trials
stim_encoding_table = Get_Stim_Encoding_Table() # the complete combinatoric list of trial configurations
run_properties <- Get_Run_Properties()
# l data from .mat file
trial_data <- Get_trial_data()
trial_data <- Omit_Trials()
trial_data <- Number_Complete_Blocks()
return(list("run_properties" = run_properties, "trial_data" = trial_data))
}
Identify_Analysis_Type <- function() {
Get_File_Summary_BBN_Tone <- function() {
# Make summary data table with step size
run_properties$summary = file_frequency_ranges %>%
dplyr::group_by(`Freq (kHz)`, `Delay (s)`, `Type`) %>%
dplyr::summarise(dB_min = min(dB),
dB_max = max(dB),
dB_step_size = dB - lag(dB, default = first(dB)),
duration = list(run_properties$duration),
.groups = 'keep')
# still grouped following this step, which is needed to remove the 1st row of each table that has a 0 step_size that is wrong for files with actual step_sizes
if (!identical(run_properties$summary$dB_min, run_properties$summary$dB_max)) {
run_properties$summary = run_properties$summary %>%
dplyr::slice(-1) %>% # Drop 1st row of each sub-table
.[!duplicated(.), ] # reduce to unique rows. Should be 1 row per frequency unless something is screwed up
}
# Check for mismatched step size
if (length(unique(run_properties$summary$dB_step_size)) != 1) {
warn = paste0("ACTION REQUIRED: Mismatched step size (", unique(run_properties$summary$dB_step_size), ").")
warning(paste0(warn, "\n"))
warnings_list <<- append(warnings_list, warn)
}
return(run_properties$summary)
}
Get_File_Summary_Simple <- function() {
# Make basic summary data table with same columns as Tone/BBN summary table
run_properties$summary = file_frequency_ranges %>%
dplyr::group_by(`Freq (kHz)`, `Delay (s)`, `Type`) %>%
dplyr::summarise(dB_min = min(dB),
dB_max = max(dB),
dB_step_size = NA_real_, #to be type double
temp = unique(Type),
duration = list(filter(run_properties$stim_encoding_table, Type == temp)$`Dur (ms)` %>% unique %>% as.data.frame()),
.groups = 'keep') %>%
select(-temp)
return(run_properties$summary)
}
Get_File_Summary_Oddball <- function() {
# Make summary data table with step size
go_freq = run_properties$stim_encoding_table %>%
filter(Type == 1) %>%
.$`Freq (kHz)`
go_number = run_properties$stim_encoding_table %>%
filter(Type == 1) %>%
.$Stim_ID %>% as.character()
spacer_number = run_properties$stim_encoding_table %>%
filter(Type == 0 & `Dur (ms)` >= user_settings$oddball_wait_min & `Dur (ms)` < user_settings$oddball_wait_max) %>%
.$Stim_ID %>% as.character()
nogo_freq = run_properties$stim_encoding_table %>%
filter(Type == 0 & `Dur (ms)` < user_settings$oddball_wait_min) %>%
.$`Freq (kHz)`
go_dB = run_properties$stim_encoding_table %>%
filter(Type == 1) %>%
.$`Inten (dB)`
nogo_dB = run_properties$stim_encoding_table %>%
filter(Type == 0 & `Dur (ms)` < user_settings$oddball_wait_min) %>%
.$`Inten (dB)`
go_position_range = run_properties$stim_encoding_table %>%
filter(`Train Setting` != "" & Repeat_number != 0 & Type != 0) %>%
dplyr::rowwise() %>%
dplyr::mutate(Temp_Position = stringr::str_remove_all(`Train Setting`, paste0("[", spacer_number, " ]")), # strip characters from train so we can determine go tone position directly
Position = stringr::str_locate(pattern = go_number, Temp_Position)) %>% # positions of go tones
.$Position %>% as.data.frame() %>% .[,1] # str_locate gives start and stop positions, we just need either one
catch = run_properties$stim_encoding_table %>%
filter(Type == 0 & Repeat_number > 0) %>%
nrow() > 0
odds = run_properties$stim_encoding_table %>%
filter(Type == 5) %>%
.$Repeat_number %>% unique() %>%
tibble(odds = ., position = go_position_range)
run_properties$summary = c(
go_freq = go_freq,
go_dB = go_dB,
nogo_freq = nogo_freq,
nogo_dB = nogo_dB,
go_position_start = min(go_position_range),
go_position_stop = max(go_position_range),
catch = catch,
odds = odds
)
return(run_properties$summary)
}
ID_Tonal <- function() {
r = NULL
# Determine if it has custom ranges (i.e. not all frequencies have the same range)
has_different_dB_ranges_for_frequencies = length(unique(run_properties$summary$dB_min)) != 1 | length(unique(run_properties$summary$dB_max)) != 1
# Determine if octave file (in that case one of the normal intensity (dB) should be 0 or non-rewarded)
# Note that for each type 1 and type 0 the min & max should be equal (i.e. one intensity) but not necessarily between type 1 & 0
has_audible_NoGo = any(run_properties$summary$Type == 0)
# Test octave files have multiple types of No Go trials in the audible range
has_more_than_one_NoGo = length(unique(dplyr::filter(run_properties$summary, Type == 0)$`Freq (kHz)`)) > 1
# Does the file have only a single frequency
has_only_one_frequency = length(unique(run_properties$stim_encoding_table$`Freq (kHz)`)) == 1
# Does the file have only a single intensity (dB), i.e. training
has_one_dB = unique(run_properties$summary$dB_min == run_properties$summary$dB_max)
# 50ms is used for Oddball training while 300ms is used for Octave training
short_duration = run_properties$summary %>% unnest(duration) %>% .$`Dur (ms)` %>% unique == 50
# For tonal files (octaves, or mainly 4-32kHz)
# DO NOT CHANGE THE TEXTUAL DESCRIPTIONS OR YOU WILL BREAK COMPARISONS LATER
if (!has_audible_NoGo & has_different_dB_ranges_for_frequencies) r = "Tone (Thresholding)"
else if (has_one_dB & has_only_one_frequency) r = "Training - Tone"
else if (has_audible_NoGo & has_more_than_one_NoGo) r = "Octave"
else if (has_audible_NoGo & !has_more_than_one_NoGo & short_duration) r = "Training - Oddball"
else if (has_audible_NoGo & !has_more_than_one_NoGo & !short_duration) r = "Training - Octave"
else if (!has_audible_NoGo & has_only_one_frequency ) r = "Tone (Single)"
else if (!has_audible_NoGo) r = "Tone (Standard)"
else (stop("ABORT: Unknown tonal file type."))
return(r)
}
ID_BBN <- function() {
r = NULL
has_one_dB = all(unique(run_properties$summary$dB_min) == unique(run_properties$summary$dB_max)) #all test checks for one dB in both go and no go
has_multiple_durations = length(unique(run_properties$stim_encoding_table$`Dur (ms)`)) > 1
# For broadband files (training or otherwise)
# DO NOT CHANGE THE TEXTUAL DESCRIPTIONS OR YOU WILL BREAK COMPARISONS LATER
if (has_one_dB & !has_multiple_durations) r = "Training - BBN"
# else if (has_one_dB & has_multiple_durations) r = "Duration Testing"
else if (has_multiple_durations) r = "BBN Mixed Duration"
else r = "BBN (Standard)"
return(r)
}
ID_Gap <- function() {
r = NULL
has_one_dB = all(unique(run_properties$summary$dB_min) == unique(run_properties$summary$dB_max)) #all test checks for one dB in both go and no go
has_multiple_durations = length(unique(filter(run_properties$stim_encoding_table, Type == 1)$`Dur (ms)`)) > 1
# For gap detection files (training or otherwise)
# DO NOT CHANGE THE TEXTUAL DESCRIPTIONS OR YOU WILL BREAK COMPARISONS LATER
if (has_one_dB & !has_multiple_durations) r = "Training - Gap"
else if (has_one_dB & has_multiple_durations) r = "Gap (Standard)"
else (stop("ABORT: Unknown gap file type."))
return(r)
}
ID_AM <- function() {
r = NULL
has_one_Freq = length(unique(run_properties$summary$`Freq (kHz)`)) == 1
# Note that its the dB slot but actually represents %
has_one_dB = all(unique(run_properties$summary$dB_min) == unique(run_properties$summary$dB_max)) #all test checks for one dB in both go and no go
# For amplitude modulation detection files (training or otherwise)
# DO NOT CHANGE THE TEXTUAL DESCRIPTIONS OR YOU WILL BREAK COMPARISONS LATER
if (has_one_dB & has_one_Freq) r = "Training - AM"
else if (! has_one_dB) r = "AM (Standard)"
else (stop("ABORT: Unknown amplitude modulation (AM) file type."))
return(r)
}
ID_Oddball <- function() {
r = NULL
# Determine if catch trials
has_catch_trials = run_properties$summary$catch
# Determine if even odds
has_uneven_trial_odds = length(unique(run_properties$summary$odds.odds)) > 1
has_BG = run_properties$background_file != "None"
# For Oddball files (training or otherwise)
# DO NOT CHANGE THE TEXTUAL DESCRIPTIONS OR YOU WILL BREAK COMPARISONS LATER
if (has_catch_trials & has_uneven_trial_odds) r = "Oddball (Uneven Odds & Catch)"
else if (has_uneven_trial_odds) r = "Oddball (Uneven Odds)"
else if (has_catch_trials) r = "Oddball (Catch)" # Note: includes _probe and _catch both!
else if (has_BG) r = "Oddball (Background)"
else if (!has_catch_trials & !has_uneven_trial_odds) r = "Oddball (Standard)"
else stop("ABORT: Unknown Oddball file type.")
return(r)
}
# Identify Analysis Workflow ----------------------------------------------
# Get ranges for each frequency
file_frequency_ranges = run_properties$stim_encoding_table %>%
dplyr::filter(`Inten (dB)` != -100) %>% # Remove No-Go from range
dplyr::group_by(`Freq (kHz)`, `Delay (s)`, `Type`, `Repeat_number`) %>%
dplyr::reframe(dB = unique(`Inten (dB)`))
if(run_properties$stim_type == "Tone") {run_properties$stim_type <<- "tone"}
if (run_properties$stim_type %in% c("BBN", "tone", "gap")) run_properties <<- append(run_properties, list(summary = Get_File_Summary_BBN_Tone()))
else if (run_properties$stim_type %in% c("AM")) run_properties <<- append(run_properties, list(summary = Get_File_Summary_Simple()))
else if (run_properties$stim_type == "train") run_properties <<- append(run_properties, list(summary = Get_File_Summary_Oddball()))
else stop(paste0("ABORT: Unknown stim type: ", run_properties$stim_type))
r = NULL
if (run_properties$stim_type == "tone") r = ID_Tonal()
if (run_properties$stim_type == "BBN") r = ID_BBN()
if (run_properties$stim_type == "gap") r = ID_Gap()
if (run_properties$stim_type == "AM") r = ID_AM()
if (run_properties$stim_type == "train") r = ID_Oddball()
if (is.null("r")) stop("ABORT: Unknown file type. Can not proceed with analysis")
r = list(type = r,
minimum_trials = user_settings$minimum_trials[[r]])
return(r)
}
Build_Filename <- function() {
Check_Delay <- function(expected_delay) {
if (run_properties$delay != expected_delay) {
warn = paste0("ACTION REQUIRED: wrong delay window (", run_properties$delay, ") does not match expectation (", expected_delay, ")")
warning(paste0(warn, "\n"))
warnings_list <<- append(warnings_list, warn)
}
}
Tonal_Filename <- function() {
if (analysis$type == "Tone (Standard)") {
go_kHz_range = paste0(run_properties$summary %>% dplyr::filter(Type == 1) %>% .$`Freq (kHz)` %>% min(), "-",
run_properties$summary %>% dplyr::filter(Type == 1) %>% .$`Freq (kHz)` %>% max(), "kHz")
go_dB_range = paste0(run_properties$summary %>% dplyr::filter(Type == 1) %>% .$dB_min %>% unique(), "-",
run_properties$summary %>% dplyr::filter(Type == 1) %>% .$dB_max %>% unique(), "dB")
computed_file_name = paste0(go_kHz_range, "_", go_dB_range, "_", run_properties$duration, "ms_", run_properties$lockout, "s")
}
else if (analysis$type == "Tone (Single)") {
go_kHz = paste0(run_properties$summary %>% dplyr::filter(Type == 1) %>% .$`Freq (kHz)`, "kHz")
go_dB_range = paste0(run_properties$summary %>% dplyr::filter(Type == 1) %>% .$dB_min %>% unique(), "-",
run_properties$summary %>% dplyr::filter(Type == 1) %>% .$dB_max %>% unique(), "dB")
computed_file_name = paste0(go_kHz, "_", go_dB_range, "_", run_properties$duration, "ms_", run_properties$lockout, "s")
}
else if (analysis$type == "Tone (Thresholding)") {
go_kHz_range = paste0(run_properties$summary %>% dplyr::filter(Type == 1) %>% .$`Freq (kHz)` %>% min(), "-",
run_properties$summary %>% dplyr::filter(Type == 1) %>% .$`Freq (kHz)` %>% max(), "kHz")
dB_step_size = unique(run_properties$summary$dB_step_size) %>% as.numeric()
if (dB_step_size == 5) {
go_dB_range = "MIX5stepdB"
analysis$prepend_name <<- TRUE
}
else if (dB_step_size == 10) {
go_dB_range = "MIXdB"
analysis$prepend_name <<- TRUE
}
else stop("ABORT: Tone (Thresholding): Unrecognized dB_step_size (", dB_step_size,"). Aborting.")
rat_ID = stringr::str_split(run_properties$stim_filename, "_") %>% unlist() %>% .[1]
computed_file_name = paste0(rat_ID, "_", go_kHz_range, "_", go_dB_range, "_", run_properties$duration, "ms_", run_properties$lockout, "s")
}
else if (analysis$type == "Training - Oddball")
{
go_kHz = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 1) %>% .$`Freq (kHz)`, "kHz_")
nogo = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 0) %>% .$`Freq (kHz)`)
nogo_kHz = if_else(nogo == 0, "BBN_", paste0(nogo, "kHz_"))
go_dB = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 1) %>% .$`Inten (dB)`, "dB_")
nogo_dB = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 0) %>% .$`Inten (dB)`, "dB_")
catch_number = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 0) %>% .$Repeat_number)
delay = run_properties$delay %>% stringr::str_replace(" ", "-")
computed_file_name = paste0(go_kHz, go_dB, nogo_kHz, nogo_dB, run_properties$duration, "ms_", run_properties$lockout, "s")
if (delay != "1-4") {
computed_file_name = paste0(computed_file_name, "_", delay, "s")
assigned_file = filter(rat_archive, Rat_ID == run_properties$rat_ID)$Assigned_Filename
if(assigned_file != "") {
expected_delay_temp = str_extract(assigned_file, "(?<=dB_)([:digit:]|[:punct:])+?-([:digit:]|[:punct:])+") %>%
str_replace("-", " ")}
if(!is.na(expected_delay_temp)) expected_delay <<- expected_delay_temp
}
analysis$minimum_trials <<- user_settings$minimum_trials$`Training - Oddball`
}
else if (analysis$type == "Training - Tone") {
go_kHz = paste0(run_properties$summary %>% dplyr::filter(Type == 1) %>% .$`Freq (kHz)`, "kHz_")
go_dB = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 1) %>% .$`Inten (dB)`, "dB_")
catch_number = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 0) %>% .$Repeat_number) %>% as.numeric()
delay = run_properties$delay %>% stringr::str_replace(" ", "-")
lockout = ifelse(length(run_properties$lockout) > 0, run_properties$lockout, 0)
computed_file_name = paste0(go_kHz, go_dB)
if (length(catch_number) == 0) {
computed_file_name = paste0(computed_file_name, delay, "s_0catch")
delay_in_filename <<- TRUE
}
else if (catch_number > 0) {
if(rat_archive[rat_archive$Rat_ID == run_properties$rat_ID,]$Assigned_Detail == "Oddball" |
rat_archive[rat_archive$Rat_ID == run_properties$rat_ID,]$Assigned_Phase == "Octave" ) {
computed_file_name = paste0(computed_file_name, run_properties$duration, "ms_", lockout, "s")
delay_in_filename <<- FALSE
analysis$minimum_trials <<- user_settings$minimum_trials$`Tone (Single)`
} else {
if(delay == "1-4") computed_file_name = paste0(computed_file_name, catch_number, "catch_", lockout, "s")
else {
computed_file_name = paste0(computed_file_name, delay, "s_", catch_number, "catch_", lockout, "s")
assigned_file = filter(rat_archive, Rat_ID == run_properties$rat_ID)$Assigned_Filename
if(assigned_file != "") {
expected_delay_temp = str_extract(assigned_file, "(?<=dB_)([:digit:]|[:punct:])+?-([:digit:]|[:punct:])+") %>%
str_replace("-", " ")}
else {expected_delay_temp = "0.5 1.5"}
if(!is.na(expected_delay_temp)) expected_delay <<- expected_delay_temp
}
# delay_in_filename <<- FALSE
if (catch_number >= 3) {
analysis$minimum_trials <<- user_settings$minimum_trials$`Tone (Single)`
}
}
}
}
else if (analysis$type == "Octave")
{
go_kHz = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 1) %>% .$`Freq (kHz)`, "-")
nogo_kHz = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 0) %>% dplyr::arrange(Stim_ID) %>% tail(n = 1) %>% .$`Freq (kHz)`, "kHz_")
nogo_kHz2 = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 0) %>% dplyr::arrange(Stim_ID) %>% tail(n = 2) %>% head(n = 1) %>% .$`Freq (kHz)` %>% round(digits = 1), "kHz_")
go_dB = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 1) %>% .$`Inten (dB)`)
nogo_dB = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 0) %>% dplyr::arrange(Stim_ID) %>% tail(n = 1) %>% .$`Inten (dB)`)
has_dB_range = go_dB != nogo_dB
has_BG = run_properties$background_type != "None"
computed_file_name1 = paste0(go_kHz, nogo_kHz)
computed_file_name2 = paste0(go_kHz, nogo_kHz2)
if (has_dB_range) {
computed_file_name1 = paste0(computed_file_name1, go_dB, "-")
computed_file_name2 = paste0(computed_file_name2, go_dB, "-")
}
computed_file_name1 = paste0(computed_file_name1, nogo_dB, "dB_", run_properties$duration, "ms_", run_properties$lockout, "s")
computed_file_name2 = paste0(computed_file_name2, nogo_dB, "dB_", run_properties$duration, "ms_", run_properties$lockout, "s")
# computed_file_name = list(computed_file_name, computed_file_name2) # list should be safe from the later pastes because they shouldn't fire
# Test for 1/6 or the zoom in on 1/12. If it is 1/12 then there will be odd steps
stim_in_octave = run_properties$stim_encoding_table %>% mutate(octave_fraction = log(as.numeric(str_extract(go_kHz, pattern = "[:digit:]+"))/`Freq (kHz)`)/log(2),
octave_step = abs(round(octave_fraction * 12)),
even = (octave_step %% 2) == 0)
is_6th_of_octave = all(stim_in_octave$even == TRUE)
if(is_6th_of_octave) computed_file_name = computed_file_name1
else computed_file_name = computed_file_name2
if (has_BG) {
BG = paste0(stringr::str_remove(pattern = ".mat", string = run_properties$background_file), "_", run_properties$background_dB, "dB")
computed_file_name = paste0(computed_file_name, "_", BG)
}
return(computed_file_name)
}
else if (analysis$type == "Training - Octave")
{
go_kHz = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 1) %>% .$`Freq (kHz)`, "kHz_")
nogo_kHz = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 0) %>% .$`Freq (kHz)`, "kHz_")
go_dB = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 1) %>% .$`Inten (dB)`, "dB_")
nogo_dB = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 0) %>% .$`Inten (dB)`, "dB_")
catch_number = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 0) %>% .$Repeat_number)
computed_file_name = paste0(go_kHz, go_dB, nogo_kHz, nogo_dB, run_properties$duration, "ms_", run_properties$lockout, "s")
if (catch_number != 3) computed_file_name = paste0(computed_file_name, "_c", catch_number)
}
catch_number = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 0) %>% .$Repeat_number) %>% as.numeric()
not_3_catches = catch_number != 3
response_window = unique(run_properties$stim_encoding_table["Nose Out TL (s)"]) %>% as.numeric()
has_Response_window = response_window != 2
has_TR = ifelse(analysis$type == "Training - Tone" & is_empty(catch_number),
run_properties$trigger_sensitivity != 100,
run_properties$trigger_sensitivity != 200)
has_BG = run_properties$background_type != "None"
BG = if (has_BG) paste0(stringr::str_remove(pattern = ".mat", string = run_properties$background_file), "_", run_properties$background_dB, "dB")
if (has_Response_window) computed_file_name = paste0(computed_file_name, "_", response_window, "s")
if (has_TR) computed_file_name = paste0(computed_file_name, "_", "TR", run_properties$trigger_sensitivity, "ms")
if (not_3_catches) computed_file_name = paste0(computed_file_name, "_c", catch_number)
if (has_BG) computed_file_name = paste0(computed_file_name, "_", BG)
return(computed_file_name)
}
BBN_Filename <- function() {
if (analysis$type == "Training - BBN") {
go_dB = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 1) %>% .$`Inten (dB)`, "dB_")
catch_number = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 0) %>% .$Repeat_number) %>% as.numeric()
delay = run_properties$delay %>% stringr::str_replace(" ", "-")
lockout = ifelse(length(run_properties$lockout) > 0, run_properties$lockout, 0)
# Warning States, i.e. not the expected default
response_window = unique(run_properties$stim_encoding_table["Nose Out TL (s)"]) %>% as.numeric()
has_Response_window = response_window != 2
computed_file_name = paste0("BBN_", go_dB)
if (length(catch_number) == 0) {
computed_file_name = paste0(computed_file_name, delay, "s_0catch")
has_TR = run_properties$trigger_sensitivity != 100 #prior to no go introduction we want trials to be as sensitive as possible so only 100ms
delay_in_filename <<- TRUE
}
else if (catch_number > 0) {
if(delay == "1-4") {
computed_file_name = paste0(computed_file_name, catch_number, "catch_", lockout, "s")
delay_in_filename <<- FALSE
}
else {
computed_file_name = paste0(computed_file_name, delay, "s_", catch_number, "catch_", lockout, "s")
assigned_file = filter(rat_archive, Rat_ID == run_properties$rat_ID)$Assigned_Filename
if(assigned_file != "") {
expected_delay_temp = str_extract(assigned_file, "(?<=dB_)([:digit:]|[:punct:])+?-([:digit:]|[:punct:])+") %>%
str_replace("-", " ")}
else {expected_delay_temp = "0.5 1.5"}
if(!is.na(expected_delay_temp)) expected_delay <<- expected_delay_temp
}
has_TR = run_properties$trigger_sensitivity != 200
if (catch_number >= 3) {
analysis$minimum_trials <<- user_settings$minimum_trials$`BBN (Standard)`
}
}
# Warning States, i.e. not the expected default
if (has_Response_window) computed_file_name = paste0(computed_file_name, "_", response_window, "s")
if (has_TR) computed_file_name = paste0(computed_file_name, "_", "TR", run_properties$trigger_sensitivity, "ms")
}
else
{
has_one_dB = all(unique(run_properties$summary$dB_min) == unique(run_properties$summary$dB_max)) #all test checks for one dB in both go and no go
has_duration_range = nrow(unique(run_properties$duration)) > 1
if(has_one_dB) {
go_dB_range = paste0(run_properties$summary %>% dplyr::filter(Type == 1) %>% .$dB_min %>% unique(), "dB")
} else {
go_dB_range = paste0(run_properties$summary %>% dplyr::filter(Type == 1) %>% .$dB_min %>% unique(), "-",
run_properties$summary %>% dplyr::filter(Type == 1) %>% .$dB_max %>% unique(), "dB")
}
if (has_duration_range) {
duration = paste0(min(run_properties$duration), "-",
max(run_properties$duration), "")
} else {
duration = run_properties$duration
}
response_window = unique(run_properties$stim_encoding_table["Nose Out TL (s)"]) %>% as.numeric()
catch_number = paste0(run_properties$stim_encoding_table %>% dplyr::filter(Type == 0) %>% .$Repeat_number) %>% as.numeric()
not_3_catches = catch_number != 3
has_Response_window = response_window != 2
has_TR = run_properties$trigger_sensitivity != 200
has_BG = run_properties$background_type != "None"
BG = if (has_BG) paste0(stringr::str_remove(pattern = ".mat", string = run_properties$background_file), "_", run_properties$background_dB, "dB")
computed_file_name = paste0("BBN_", go_dB_range, "_", duration, "ms_", run_properties$lockout, "s")
if (has_Response_window) computed_file_name = paste0(computed_file_name, "_", response_window, "s")
if (has_TR) computed_file_name = paste0(computed_file_name, "_", "TR", run_properties$trigger_sensitivity, "ms")
if (not_3_catches) computed_file_name = paste0(computed_file_name, "_c", catch_number)
if (has_BG) computed_file_name = paste0(computed_file_name, "_", BG)
}