-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRstox_utils.R
1978 lines (1680 loc) · 78 KB
/
Rstox_utils.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
# Emergenscy create a funciton for building the pelfoss package, that is a copy of the correponding code for the Rstox package but altered to fit the pelfoss package. We should rather work through the :
build_pelfoss <- function(buildDir, pkgName="pelfoss", version="1.0", Rversion="3.3.1", pckversion=list(), official=FALSE, check=FALSE, exportDir=NULL, suggests=NULL) {
########## Functions ##########
# Function used for writing the README file automatically, including package dependencies, R and pelfoss version and release notes:
writePelfossREADME <- function(READMEfile, NEWSfile, version, Rversion, betaAlpha, betaAlphaString, imports, official=FALSE){
# Write pelfoss and R version in the first two lines. THIS SHOULD NEVER BE CHANGED, SINCE STOX READS THESE TWO LINES TO CHECK VERSIONS:
write(paste0("# pelfoss version: ", version, " (latest ", betaAlphaString, ", ", format(Sys.time(), "%Y-%m-%d"), ")"), READMEfile)
write(paste0("# R version: ", Rversion), READMEfile, append=TRUE)
write("", READMEfile, append=TRUE)
# Package description and installation code:
write("# The package pelfoss contains code to simulate acoustic-trawl surveys based on biomass fields from population dynamic models, and produces survey estimates using the Rstox package:", READMEfile, append=TRUE)
write("", READMEfile, append=TRUE)
write("# IMPORTANT: The package pelfoss stongly depends on the package Rstox. Install Rstox as described on https://github.com/Sea2Data/Rstox", READMEfile, append=TRUE)
write("", READMEfile, append=TRUE)
write("# Install the other packages that perlfoss depends on. Note that this updates all the specified packages to the latest (binary) version:", READMEfile, append=TRUE)
write(paste0("dep.pck <- c(\"", paste0(setdiff(imports, "Rstox"), collapse="\", \""), "\")"), READMEfile, append=TRUE)
write("install.packages(dep.pck, repos=\"http://cran.us.r-project.org\", type=\"binary\")", READMEfile, append=TRUE)
write("", READMEfile, append=TRUE)
write("# Install pelfoss from github using the devtools package:", READMEfile, append=TRUE)
write("devtools::install_github(\"Sea2Data/pelfoss\")", READMEfile, append=TRUE)
write("# Alternatively install the latest develop version: devtools::install_github(\"Sea2Data/pelfoss\", ref=\"develop\")", READMEfile, append=TRUE)
write("", READMEfile, append=TRUE)
# Write release notes:
write("", READMEfile, append=TRUE)
write(paste0("# Release notes pelfoss_", version, ":"), READMEfile, append=TRUE)
# Read the changes:
l <- readLines(NEWSfile)
# Split into vesions:
atversion <- which(substr(l, 1, 1) == "#")
# Strip off "#", and extract the version string:
versionStringInChanges <- l[atversion]
startversion <- regexpr("Version ", versionStringInChanges)
startversion <- startversion + attributes(startversion)$match.length
versionStringInChanges <- substring(versionStringInChanges, startversion)
endversion <- regexpr(" ", versionStringInChanges) - 1
versionStringInChanges <- substr(versionStringInChanges, 1, endversion)
# Split into versions and format to insert into the README file:
l <- split(l, findInterval(seq_along(l), c(atversion, length(l)+1)))
names(l) <- versionStringInChanges
# Remove the version line:
l <- lapply(l, function(xx) xx[substr(xx, 1, 1) != "#"])
thisl <- l[[version]]
hasText <- which(nchar(thisl)>1)
thisl[hasText] <- paste0("# ", seq_along(hasText), ". ", thisl[hasText])
write(thisl, READMEfile, append=TRUE)
if(official){
NEWSlink <- "https://github.com/Sea2Data/pelfoss/blob/master/NEWS"
}
else{
NEWSlink <- "https://github.com/Sea2Data/pelfoss/blob/alpha/NEWS"
}
write("", READMEfile, append=TRUE)
write(paste0("# For historical release notes see ", NEWSlink), READMEfile, append=TRUE)
}
# Functions used for extracting the imports in Rstox, in order to inform about these in the README file. This will not be needed once the package is on CRAN:
discardBasePackages <- function(x){
inst <- installed.packages()
Base <- inst[, "Package"][inst[,"Priority"] %in% c("base", "recommended")]
sort(setdiff(x, Base))
}
getImports <- function(buildDir, version=list()){
# Read the NAMESPACE file and get the package dependencies:
buildDirList <- list.files(buildDir, recursive=TRUE, full.names=TRUE)
imports <- NULL
if(length(buildDirList)){
print(buildDirList[basename(buildDirList) == "NAMESPACE"])
NAMESPACE <- readLines(buildDirList[basename(buildDirList) == "NAMESPACE"])
atImports <- grep("import", NAMESPACE)
imports <- NAMESPACE[atImports]
imports <- sapply(strsplit(imports, "(", fixed=TRUE), "[", 2)
imports <- sapply(strsplit(imports, ")", fixed=TRUE), "[", 1)
imports <- unique(sapply(strsplit(imports, ",", fixed=TRUE), "[", 1))
#inst <- installed.packages()
#Base <- inst[, "Package"][inst[,"Priority"] %in% c("base", "recommended")]
#imports <- sort(setdiff(imports, Base))
imports <- discardBasePackages(imports)
#notBase <- inst[, "Package"][!(inst[,"Priority"]) %in% "base"]
#imports <- sort(imports[!imports %in% notBase])
}
# Add required version for packages:
if(length(version)){
# Remove version information for packages that are not present in the imports:
if(!all(names(version) %in% imports)){
warning("Not all package versions specified in 'version' are present as imports.")
}
version <- version[names(version) %in% imports]
atversion <- match(names(version), imports)
for(i in seq_along(version)){
imports[atversion[i]] <- paste0(imports[atversion[i]], " (>= ", version[i], ")")
}
}
return(imports)
}
########## End of functions ##########
# Clear the installed package:
try(lapply(.libPaths(), function(xx) remove.packages(pkgName, xx)), silent=TRUE)
if(length(exportDir)==0){
exportDir <- file.path(dirname(buildDir), "builds")
}
if(length(grep(exportDir, buildDir))>0){
stop("The 'exportDir' cannot be contained in the 'buildDir', since the exports are build from the 'buildDir'")
}
#exportDir <- file.path(buildDir, "bundle")
manDir <- file.path(buildDir, "man")
DESCRIPTIONfile <- file.path(buildDir, "DESCRIPTION")
NAMESPACEfile <- file.path(buildDir, "NAMESPACE")
unlink(NAMESPACEfile, recursive=TRUE, force=TRUE)
onLoadFile = file.path(buildDir, "R", "onLoad.R")
onAttachFile = file.path(buildDir, "R", "onAttach.R")
# Changed added to make the package name identical to the name of the GitHub release:
thisExportDir <- file.path(exportDir, paste(pkgName, version, sep="_"))
suppressWarnings(dir.create(thisExportDir))
READMEfile <- file.path(buildDir, "README")
READMEfileExport <- file.path(thisExportDir, "README")
NEWSfile <- file.path(buildDir, "NEWS")
##### Save the following content to the onLoad.R file in the "R" directory: #####
onLoadText = paste(
".onLoad <- function(libname, pkgname){}", sep="\n")
write(onLoadText, onLoadFile)
##########
##### Save a Java memory message to the onAttach.R file in the "R" directory: #####
onAttachText = paste(
".onAttach <- function(libname, pkgname){}", sep="\n")
write(onAttachText, onAttachFile)
##########
##### Add required fields to the DESCRIPTION file (below is the full content of the DESCRIPTION file): #####
# Depends is replaced by @import specified by functions"
DESCRIPTIONtext = paste(
paste0("Package: ", pkgName),
"Title: Simulate acosutic-trawl surveys and produce survey estimated using Rstox",
paste0("Version: ", version),
"Authors@R: c(",
" person(\"Arne Johannes\", \"Holmin\", role = c(\"aut\",\"cre\"), email = \"[email protected]\"))",
"Author: Arne Johannes Holmin [aut, cre]",
"Maintainer: Arne Johannes Holmin <[email protected]>",
paste0("Depends: R (>= ", Rversion, ")"),
"Description: The package pelfoss contains code to simulate acoustic-trawl surveys based on biomass fields from population dynamic models, and produces survey estimates using the Rstox package.",
"BugReports: https://github.com/Sea2Data/pelfoss/issues",
"License: LGPL-3",
"LazyData: true\n", sep="\n")
write(DESCRIPTIONtext, DESCRIPTIONfile)
##########
##### Create documentation: #####
# Remove current documentation first:
unlink(manDir, recursive=TRUE, force=TRUE)
document(buildDir)
# Alter the DESCRIPTION file to contain the imports listed in the NAMESPACE file:
imports <- getImports(buildDir, version=pckversion)
if(length(imports)){
cat("Imports:\n ", file=DESCRIPTIONfile, append=TRUE)
cat(paste(imports, collapse=",\n "), file=DESCRIPTIONfile, append=TRUE)
cat("", file=DESCRIPTIONfile, append=TRUE)
}
# Add also the suggests:
if(length(suggests)){
lapply(suggests, devtools::use_package, type="suggests", pkg=buildDir)
}
##########
##### Run R cmd check with devtools: #####
if(check){
devtools::check(pkg=buildDir)
}
##########
### Generate the README file: ###
betaAlpha <- length(gregexpr(".", version, fixed=TRUE)[[1]]) + 1
betaAlphaString <- c("", "beta", "alpha")[betaAlpha]
# Read the NAMESPACE file and get the package dependencies. This is needed since we are not on CRAN:
writePelfossREADME(READMEfile, NEWSfile, version, Rversion, betaAlpha, betaAlphaString, imports=getImports(buildDir), official=official)
file.copy(READMEfile, READMEfileExport, overwrite=TRUE)
##########
##### Create platform independent bundle of source package: #####
dir.create(thisExportDir, recursive=TRUE)
pkgFileVer <- build(buildDir, path=thisExportDir)
# To comply with GitHub, rename to using hyphen (whereas build() hardcodes using "_"):
versionString <- paste0("pelfoss_", version, ".tar.gz")
pkgFileVerHyphen <- file.path(thisExportDir, versionString)
file.rename(pkgFileVer, pkgFileVerHyphen)
##### Unload the package: #####
unload(pkgName)
##########
##### Install local source package by utils (independent of dev-tools), and check that it loads: #####
install.packages(pkgFileVerHyphen, repos=NULL, type="source", lib=.libPaths()[1])
library(pelfoss)
##########
}
########## Functions ##########
# Function used for writing the README file automatically, including package dependencies, R and Rstox version and release notes:
writeRstoxREADME <- function(READMEfile, NEWSfile, version, Rversion, betaAlpha, betaAlphaString, imports, official=FALSE){
# Write Rstox and R version in the first two lines. THIS SHOULD NEVER BE CHANGED, SINCE STOX READS THESE TWO LINES TO CHECK VERSIONS:
write(paste0("# Rstox version: ", version, " (latest ", betaAlphaString, ", ", format(Sys.time(), "%Y-%m-%d"), ")"), READMEfile)
write(paste0("# R version: ", Rversion), READMEfile, append=TRUE)
write("", READMEfile, append=TRUE)
# Package description and installation code:
write("# The package Rstox contains most of the functionality of the stock assesment utility StoX, which is an open source approach to acoustic and swept area survey calculations. Download Rstox from ftp://ftp.imr.no/StoX/Download/Rstox or install by running the following commands in R:", READMEfile, append=TRUE)
write("", READMEfile, append=TRUE)
write("# Install the packages that Rstox depends on. Note that this updates all the specified packages to the latest (binary) version:", READMEfile, append=TRUE)
write(paste0("dep.pck <- c(\"", paste0(imports, collapse="\", \""), "\")"), READMEfile, append=TRUE)
# WARNING: IT IS CRUSIAL TO ENCLUDE THE repos IN THIS CALL, FOR STOX TO SOURCE THE README FILE PROPERLY (RESULTS IN AN ERROR IF ABSENT) IT SEEMS "R CMD BATCH source(TheReadMeFile)" RETURNS AN ERROR WHEN repos IS NOT SET (2016-12-16):
write("install.packages(dep.pck, repos=\"http://cran.us.r-project.org\", type=\"binary\")", READMEfile, append=TRUE)
#write("install.packages(dep.pck, type=\"binary\")", READMEfile, append=TRUE)
write("", READMEfile, append=TRUE)
write("# Install Rstox:", READMEfile, append=TRUE)
# Get the version string, the name of the Rstox tar file, the ftp root and, finally, the ftp directory and full path to the Rstox tar file:
# Changed added to make the package name identical to the name of the GitHub release:
#versionString <- paste0("Rstox_", version)
versionString <- paste("Rstox", version, sep="_")
tarName <- paste0(versionString, ".tar.gz")
ftpRoot <- "ftp://ftp.imr.no/StoX/Download/Rstox"
if(betaAlpha==3){
ftpDir <- file.path(ftpRoot, "Versions", "Alpha", versionString)
}
else{
if(official){
ftpDir <- ftpRoot
}
else{
ftpDir <- file.path(ftpRoot, "Versions", versionString)
}
}
tarFile <- file.path(ftpDir, tarName)
# Write the Rstox install command:
write(paste0("install.packages(\"", tarFile, "\", repos=NULL)"), READMEfile, append=TRUE)
write("", READMEfile, append=TRUE)
write("# Alternatively, install the latest development version from GitHub.", READMEfile, append=TRUE)
write(paste0("# Note that this does not guarantee a stable version."), READMEfile, append=TRUE)
write(paste0("# For official versions of Rstox, refer to the ftp server ", ftpDir, " as described above."), READMEfile, append=TRUE)
write("# Install from github using the devtools package:", READMEfile, append=TRUE)
write("# devtools::install_github(\"Sea2Data/Rstox\", ref=\"develop\")", READMEfile, append=TRUE)
write("", READMEfile, append=TRUE)
write("# R should be installed as the 64 bit version. On Windows 10, ONLY the 64 bit version should be used.", READMEfile, append=TRUE)
write("# To do this, uncheck the box \"32-bit Files\" when selecting components to install.", READMEfile, append=TRUE)
write("# If you are re-installing an R that has both 32 and 64 bit, you will need to uninstall R first.", READMEfile, append=TRUE)
write("", READMEfile, append=TRUE)
write("# On Windows systems with adminstrator requirements, it is recommended to install R in C:/users/<user>/documents/R.", READMEfile, append=TRUE)
write("# Also if you are using Rstudio, please make sure that you are using the correct R version (in case you have", READMEfile, append=TRUE)
write("# multiple versions installed). The R version can be selected in Tools > Global Options.", READMEfile, append=TRUE)
write("", READMEfile, append=TRUE)
write("# Note that 64 bit Java is required to run Rstox", READMEfile, append=TRUE)
write("", READMEfile, append=TRUE)
write("# On Windows, install Java from this webpage: https://www.java.com/en/download/windows-64bit.jsp,", READMEfile, append=TRUE)
write("# or follow the instructions found on ftp://ftp.imr.no/StoX/Tutorials/", READMEfile, append=TRUE)
write("", READMEfile, append=TRUE)
write("# On Mac, getting Java and Rstox to communicate can be challenging.", READMEfile, append=TRUE)
write("# If you run into problems such as \"Unsupported major.minor version ...\", try the following:", READMEfile, append=TRUE)
write("# Update java, on", READMEfile, append=TRUE)
write("# \thttp://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html", READMEfile, append=TRUE)
write("# If this does not work install first the JDK and then the JRE:", READMEfile, append=TRUE)
write("# \thttp://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html", READMEfile, append=TRUE)
write("# \thttp://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html", READMEfile, append=TRUE)
write("# Rstox sohuld also work with Java 11, presently available only as Development Kit:", READMEfile, append=TRUE)
write("# \thttps://www.oracle.com/technetwork/java/javase/downloads/jdk11-downloads-5066655.html", READMEfile, append=TRUE)
write("# You may want to check that the downloaded version is first in the list by running the following in the Terminal:", READMEfile, append=TRUE)
write("# \t/usr/libexec/java_home -V", READMEfile, append=TRUE)
write("# \tjava -version", READMEfile, append=TRUE)
write("# Then run this in the Terminal.app (you will be asked for password, but the password will not show as you type.", READMEfile, append=TRUE)
write("# It is possible to type the password in a text editor first and then paste it into the Terminal.):", READMEfile, append=TRUE)
write("# \tsudo ln -s $(/usr/libexec/java_home)/jre/lib/server/libjvm.dylib /usr/local/lib", READMEfile, append=TRUE)
write("# \tsudo R CMD javareconf", READMEfile, append=TRUE)
write("# Open R (close and then open if already open) and install rJava:", READMEfile, append=TRUE)
#write("# \tinstall.packages('rJava', type='source')", READMEfile, append=TRUE)
write("# \tinstall.packages('rJava', type=\"binary\")", READMEfile, append=TRUE)
write("# If this fails, try installing from source instead using install.packages('rJava', type='source')", READMEfile, append=TRUE)
write("# Then the installed Rstox should work.", READMEfile, append=TRUE)
# Write release notes:
write("", READMEfile, append=TRUE)
write("", READMEfile, append=TRUE)
write(paste0("# Release notes Rstox_", version, ":"), READMEfile, append=TRUE)
# Read the changes:
l <- readLines(NEWSfile)
# Split into vesions:
atversion <- which(substr(l, 1, 1) == "#")
# Strip off "#", and extract the version string:
versionStringInChanges <- l[atversion]
startversion <- regexpr("Version ", versionStringInChanges)
startversion <- startversion + attributes(startversion)$match.length
versionStringInChanges <- substring(versionStringInChanges, startversion)
endversion <- regexpr(" ", versionStringInChanges) - 1
versionStringInChanges <- substr(versionStringInChanges, 1, endversion)
# Split into versions and format to insert into the README file:
l <- split(l, findInterval(seq_along(l), c(atversion, length(l)+1)))
names(l) <- versionStringInChanges
# Remove the version line:
l <- lapply(l, function(xx) xx[substr(xx, 1, 1) != "#"])
thisl <- l[[version]]
hasText <- which(nchar(thisl)>1)
thisl[hasText] <- paste0("# ", seq_along(hasText), ". ", thisl[hasText])
write(thisl, READMEfile, append=TRUE)
if(official){
NEWSlink <- "https://github.com/Sea2Data/Rstox/blob/master/NEWS"
}
else{
NEWSlink <- "https://github.com/Sea2Data/Rstox/blob/alpha/NEWS"
}
write("", READMEfile, append=TRUE)
write(paste0("# For historical release notes see ", NEWSlink), READMEfile, append=TRUE)
}
# Functions used for extracting the imports in Rstox, in order to inform about these in the README file. This will not be needed once the package is on CRAN:
discardBasePackages <- function(x){
inst <- installed.packages()
Base <- inst[, "Package"][inst[,"Priority"] %in% c("base", "recommended")]
sort(setdiff(x, Base))
}
getImports <- function(buildDir, version=list()){
# Read the NAMESPACE file and get the package dependencies:
buildDirList <- list.files(buildDir, recursive=TRUE, full.names=TRUE)
imports <- NULL
if(length(buildDirList)){
print(buildDirList[basename(buildDirList) == "NAMESPACE"])
NAMESPACE <- readLines(buildDirList[basename(buildDirList) == "NAMESPACE"])
atImports <- grep("import", NAMESPACE)
imports <- NAMESPACE[atImports]
imports <- sapply(strsplit(imports, "(", fixed=TRUE), "[", 2)
imports <- sapply(strsplit(imports, ")", fixed=TRUE), "[", 1)
imports <- unique(sapply(strsplit(imports, ",", fixed=TRUE), "[", 1))
#inst <- installed.packages()
#Base <- inst[, "Package"][inst[,"Priority"] %in% c("base", "recommended")]
#imports <- sort(setdiff(imports, Base))
imports <- discardBasePackages(imports)
#notBase <- inst[, "Package"][!(inst[,"Priority"]) %in% "base"]
#imports <- sort(imports[!imports %in% notBase])
}
# Add required version for packages:
if(length(version)){
# Remove version information for packages that are not present in the imports:
if(!all(names(version) %in% imports)){
warning("Not all package versions specified in 'version' are present as imports.")
}
version <- version[names(version) %in% imports]
atversion <- match(names(version), imports)
for(i in seq_along(version)){
imports[atversion[i]] <- paste0(imports[atversion[i]], " (>= ", version[i], ")")
}
}
return(imports)
}
########## End of functions ##########
# Function used for building and testing the Rstox package.
# Use this in the continous development of Rstox.
# Rstox can also be built from the develop brach of Sea2Data/Rstox, but the function build_Rstox() generates the README and DESCRIPTION file, treats dependencies and tests the package and examples if check=TRUE:
build_Rstox <- function(buildDir, pkgName="Rstox", version="1.0", Rversion="3.3.1", pckversion=list(), official=FALSE, check=FALSE, exportDir=NULL, suggests=NULL) {
# Clear the installed package:
try(lapply(.libPaths(), function(xx) remove.packages(pkgName, xx)), silent=TRUE)
if(length(exportDir)==0){
exportDir <- file.path(dirname(buildDir), "builds")
}
if(length(grep(exportDir, buildDir))>0){
stop("The 'exportDir' cannot be contained in the 'buildDir', since the exports are build from the 'buildDir'")
}
#exportDir <- file.path(buildDir, "bundle")
manDir <- file.path(buildDir, "man")
DESCRIPTIONfile <- file.path(buildDir, "DESCRIPTION")
NAMESPACEfile <- file.path(buildDir, "NAMESPACE")
unlink(NAMESPACEfile, recursive=TRUE, force=TRUE)
onLoadFile = file.path(buildDir, "R", "onLoad.R")
onAttachFile = file.path(buildDir, "R", "onAttach.R")
# Changed added to make the package name identical to the name of the GitHub release:
thisExportDir <- file.path(exportDir, paste(pkgName, version, sep="_"))
suppressWarnings(dir.create(thisExportDir))
READMEfile <- file.path(buildDir, "README")
READMEfileExport <- file.path(thisExportDir, "README")
NEWSfile <- file.path(buildDir, "NEWS")
##### Save the following content to the onLoad.R file in the "R" directory: #####
onLoadText = paste(
".onLoad <- function(libname, pkgname){",
" ",
" if(Sys.getenv(\"JAVA_HOME\")!=\"\") Sys.setenv(JAVA_HOME=\"\")",
" # options(java.parameters=\"-Xmx2g\")",
" # Initiate the Rstox envitonment:",
" Definitions <- initiateRstoxEnv()",
" # Set the Java memory:",
" setJavaMemory(Definitions$JavaMem)",
"}",
sep="\n"
)
write(onLoadText, onLoadFile)
##########
##########
# Define the onAttach funciton for the Rstox package:
if(official){
onAttachText = paste(
".onAttach <- function(libname, pkgname){",
" ",
paste0(" packageStartupMessage(\"", pkgName, "_", version, "\n**********\nIf problems with Java Memory such as java.lang.OutOfMemoryError occurs, see ?setJavaMemory.\n**********\n\", appendLF=FALSE)"),
"}",
sep="\n"
)
}
else{
onAttachText = paste(
".onAttach <- function(libname, pkgname){",
" ",
paste0(" packageStartupMessage(\"", pkgName, "_", version, "\n**********\nWARNING: This version of Rstox is an unofficial/developer version and bugs should be expected.\nIf problems with Java Memory such as java.lang.OutOfMemoryError occurs, see ?setJavaMemory.\n**********\n\", appendLF=FALSE)"),
"}",
sep="\n"
)
}
write(onAttachText, onAttachFile)
##########
##### Add required fields to the DESCRIPTION file (below is the full content of the DESCRIPTION file): #####
# Depends is replaced by @import specified by functions"
DESCRIPTIONtext = paste(
paste0("Package: ", pkgName),
"Title: Running Stox functionality independently in R",
paste0("Version: ", version),
"Authors@R: c(",
" person(\"Arne Johannes\", \"Holmin\", role = c(\"aut\",\"cre\"), email = \"[email protected]\"),",
" person(\"Edvin\", \"Fuglebakk\", role = \"ctb\"),",
" person(\"Gjert Endre\", \"Dingsoer\", role = \"ctb\"),",
" person(\"Aasmund\", \"Skaalevik\", role = \"ctb\"),",
" person(\"Espen\", \"Johnsen\", role = \"ctb\"))",
"Author: Arne Johannes Holmin [aut, cre],",
" Edvin Fuglebakk [ctr],",
" Gjert Endre Dingsoer [ctr],",
" Aasmund Skaalevik [ctr],",
" Espen Johnsen [ctr]",
"Maintainer: Arne Johannes Holmin <[email protected]>",
paste0("Depends: R (>= ", Rversion, ")"),
"Description: This package contains most of the functionality of the StoX software, which is used for assessment of fish and other marine resources based on biotic and acoustic survey and landings data, among other uses. Rstox is intended for further analyses of such data, facilitating iterations over an arbitrary number of parameter values and data sets.",
"BugReports: https://github.com/Sea2Data/Rstox/issues",
"License: LGPL-3",
"LazyData: true", sep="\n")
write(DESCRIPTIONtext, DESCRIPTIONfile)
##########
##### Create documentation: #####
# Remove current documentation first:
unlink(manDir, recursive=TRUE, force=TRUE)
document(buildDir)
# Alter the DESCRIPTION file to contain the imports listed in the NAMESPACE file:
imports <- getImports(buildDir, version=pckversion)
if(length(imports)){
cat("Imports:\n ", file=DESCRIPTIONfile, append=TRUE)
cat(paste(imports, collapse=",\n "), file=DESCRIPTIONfile, append=TRUE)
cat("", file=DESCRIPTIONfile, append=TRUE)
}
# Add also the suggests:
if(length(suggests)){
lapply(suggests, devtools::use_package, type="suggests", pkg=buildDir)
}
##########
##### Run R cmd check with devtools: #####
if(check){
devtools::check(pkg=buildDir)
# args = "--no-examples"
}
##########
### Generate the README file: ###
betaAlpha <- length(gregexpr(".", version, fixed=TRUE)[[1]]) + 1
betaAlphaString <- c("", "beta", "alpha")[betaAlpha]
# Read the NAMESPACE file and get the package dependencies. This is needed since we are not on CRAN:
writeRstoxREADME(READMEfile, NEWSfile, version, Rversion, betaAlpha, betaAlphaString, imports=getImports(buildDir, version=pckversion), official=official)
file.copy(READMEfile, READMEfileExport, overwrite=TRUE)
##########
##### Create platform independent bundle of source package: #####
dir.create(thisExportDir, recursive=TRUE)
pkgFileVer <- build(buildDir, path=thisExportDir)
# To comply with GitHub, rename to using hyphen (whereas build() hardcodes using "_"):
versionString <- paste0("Rstox_", version, ".tar.gz")
pkgFileVerHyphen <- file.path(thisExportDir, versionString)
file.rename(pkgFileVer, pkgFileVerHyphen)
##### Unload the package: #####
unload(pkgName)
##########
##### Install local source package by utils (independent of dev-tools), and check that it loads: #####
install.packages(pkgFileVerHyphen, repos=NULL, type="source", lib=.libPaths()[1])
# Build documentation pdf:
lib <- file.path(.libPaths()[1], pkgName)
devtools::build_manual(pkg=lib, path=lib)
##########
# Load the package:
library(pkgName, character.only=TRUE)
}
#*********************************************
#*********************************************
#' Get the platform ID of an operating system
#'
#' @param var The element of Sys.info() used as identifyer of the platform.
#'
#' @export
#' @keywords internal
#'
getPlatformID <- function(){
#getPlatformID <- function(var="release"){
# 2019-02-05: Removed the 'release' to make file paths shorter:
paste(.Platform$OS.type, paste(strsplit(Sys.info()["release"], " ", fixed=TRUE)[[1]], collapse="_"), sep="_")
}
#*********************************************
#*********************************************
#' Small funciton to get a list of the file paths to the sub folders of the test directory (ProjOrig, Proj, Output, Diff)
#'
#' @param x The test directory
#'
#' @export
#' @keywords internal
#'
getTestFolderStructure <- function(x){
# Accept the platform specific directory:
if("ProjOrig" %in% list.dirs(x, recursive=FALSE, full.names=FALSE)){
x <- dirname(x)
}
platformFolderName <- getPlatformID()
list(
StagedProjOrig = file.path(x, "StagedProjOrig"),
#Notes = file.path(x, platformFolderName, "Notes"),
ProjOrig = file.path(x, platformFolderName, "ProjOrig"),
ProjOrig1 = file.path(x, platformFolderName, "ProjOrig", "Rstox_1.0_StoXLib_1.0"),
Proj = file.path(x, platformFolderName, "Proj"),
Output = file.path(x, platformFolderName, "Output"),
Diff = file.path(x, platformFolderName, "Diff"))
}
#*********************************************
#*********************************************
#' Get the latest directory of
#'
#' @param dir The directory of subdirectories named with the Rstox and stox-lib versions.
#' @param op The operator used to get the latest. Do not mess with this unless you know what you are doing.
#' @param n The number of directories to return, as used in utils::tail().
#'
#' @export
#' @keywords internal
#'
getLatestDir <- function(dir, op="<", n=1){
if(length(dir)==0){
return(NULL)
}
# Get the Rstox and stox-lib versions:
current <- sapply(getRstoxVersion(), as.character)
current <- data.frame(package=names(current), version=unlist(current), stringsAsFactors=FALSE)
currentString <- paste(current$version, sep="_", collapse="_")
currentNumeric <- version2numeric(current)
current <- versionScaled(currentNumeric)
# List all directories:
All <- list.dirs(dir, recursive=FALSE)
All <- All[grep("Rstox", All)]
if(length(All)==0){
warning(paste0("No projects in the test folder '", dir, "'"))
}
# Get the Rstox and stox-lib versions encoded in the folder names:
versions <- strsplit(basename(All), "_")
# Pick out every other element, which are the version strings:
versionStrings <- lapply(versions, extractVersionstrings)
versionStrings <- lapply(versionStrings, version2numeric)
versions <- sapply(versionStrings, versionScaled)
# Order All and versions in increasing order by the scale:
o <- order(versions)
versions <- versions[o]
All <- All[o]
# There has to be at least one previous version:
latest <- do.call(op, list(versions, current))
if(!any(is.na(latest)) && any(latest)){
#return(All[max(which(latest))])
# Allow for specifying e.g. the third latest:
if(is.integer(n)){
atlatest <- sort(which(latest))
out <- All[atlatest[length(atlatest) - n + 1]]
}
else{
out <- All[tail(sort(which(latest)), n)]
}
return(out)
}
else{
warning(paste0("No directories with Rstox version before Rstox_StoXLib version \"", currentString, "\" in the directory \"", dir, "\""))
return(NULL)
}
}
# Function for converting the Rstox version to a numeric value suitable for sorting, by multiplying each digit in the version number by scaling factor which are largest for the first digits (e.g., Rstox_1.10.3 gives 1 * 1e4 + 10 * 1e2 + 3 = 11003):
extractVersionstrings <- function(x){
# Remove duplicated, since the diff paths have e.g. Rstox twice in the folder name:
packageAndVersion <- data.frame(
package = x[seq(1, length(x), by=2)],
version = x[seq(2, length(x), by=2)],
stringsAsFactors = FALSE
)
dup <- duplicated(packageAndVersion$package)
packageAndVersion <- packageAndVersion[!dup, ]
# packageAndVersion$version
packageAndVersion
}
version2numeric <- function(x){
if(is.data.frame(x)){
temp <- lapply(strsplit(x$version, ".", fixed=TRUE), as.numeric)
x$version <- sapply(temp, function(y) sum(y * 10^(6 - 2 * seq_along(y))))
}
else{
temp <- lapply(strsplit(x, ".", fixed=TRUE), as.numeric)
x <- sapply(temp, function(y) sum(y * 10^(6 - 2 * seq_along(y))))
}
x
}
versionScaled <- function(x){
power <- list(
Rstox = 3,
StoXLib = 2,
eca = 1
)
scale <- unlist(power[x$package])
scale <- 10^(7 * scale)
sum(x$version * scale)
}
#*********************************************
#*********************************************
#' Copy the 'n' latest directories of the folders 'toCopy' from the local 'from' to the central 'to' directory.
#'
#' @param from The local directory holding the version testing.
#' @param to The central directory holding the version testing.
#' @param toCopy The sub folders to copy files from.
#' @param overwrite Logical: If TRUE, overwrite the files on the central directory.
#' @param msg Logical: If TRUE, print progress to the console.
#' @param op,n See \code{\link{getLatestDir}}.
#'
#' @export
#' @keywords internal
#'
copyLatestToServer <- function(local, server, toCopy=c("Diff", "Output", "ProjOrig"), overwrite=TRUE, msg=FALSE, op="<", n=1){
# Function for copying from one subdirectory:
copyLatestOne <- function(folder, local, server, overwrite=TRUE, msg=FALSE, op="<", n=1){
local <- getLatestDir(local[[folder]], op=op, n=n)
if(length(local)){
# Check for the existence of the folder (as opposed to using 'overwrite' in file.copy(), which copies all files which do not exist in the destination).
if(file.exists(server[[folder]]) && !overwrite){
warning(paste0("The folder ", server[[folder]], " already exists and was not overwritten. Use overwrite=TRUE to overwrite from ", local))
}
else{
temp <- file.copy(local, server[[folder]], recursive=TRUE, overwrite=overwrite)
if(msg){
cat("Copied", local, "to", server[[folder]], "\n")
}
}
}
}
# Get the folder structure of the local and central directory:
local <- getTestFolderStructure(path.expand(local))
#server <- getTestFolderStructure(path.expand(server))
# Quick fix of duplicated consecutive platform ID:
server <- getTestFolderStructure(path.expand(dirname(server)))
lapply(server, dir.create, recursive=TRUE, showWarnings=FALSE)
# Copy for all specified subdirectories:
invisible(lapply(toCopy, copyLatestOne, local, server, overwrite=overwrite, msg=msg, op=op, n=n))
}
copyStaged_Projects_original <- function(server, local, overwrite=TRUE, op="<", n=1){
local <- getTestFolderStructure(path.expand(local))$StagedProjOrig
server <- getTestFolderStructure(path.expand(server))$StagedProjOrig
# Get the latest local folder, to which staged projects on the server will be copied:
#localLatest <- getLatestDir(local, op="<", n=1)
localLatest <- file.path(local, getRstoxVersionString())
# Look for the corresponding folder on the server:
serverLatest <- file.path(server, getRstoxVersionString())
# Copy if 'serverLatest' exists and is not empty:
serverLatestDirs <- list.dirs(serverLatest, recursive=FALSE)
if(length(serverLatestDirs)){
# Delete the local StagedProjOrig:
unlink(localLatest, recursive=TRUE, force=TRUE)
message("Copying the following projects from the server to the local system:\n\t", paste(serverLatestDirs, collapse="\n\t"))
file.copy(serverLatest, local, recursive=TRUE, overwrite=overwrite)
}
else{
message("No staged original projects copied from the server to the local system")
}
}
#*********************************************
#*********************************************
#' Get the path to the server, depending on the local platform (Mac, Windows).
#'
#' @param root A list of specifyers for the root directory to the central server.
#' @param path The relative path from the root.
#'
#' @export
#' @keywords internal
#'
getServerPath <- function(root=list(windows="\\\\delphi", unix="/Volumes"), path="pc_prog/S2D/stox/StoXVerTest"){
root <- root[[.Platform$OS.type]]
if(length(root)==0){
stop(paste0("The OS.type ", .Platform$OS.type, " does not match any of the names of 'root' (", paste(names(root), collapse=", "), ")"))
}
# There should be one directory per system, named by the output of getPlatformID():
server <- file.path(root, path, getPlatformID())
if(!file.exists(server)){
warning(paste0("The server location ", server, " does not exist. Please create it manually for the given platform ID (obtained by getPlatformID()): ", getPlatformID()))
}
server
}
#*********************************************
#*********************************************
#' Copy the test run to the central srever.
#'
#' @param root A list of specifyers for the root directory to the central server.
#' @param path The relative path from the root.
#' @param toCopy The sub folders to copy files from.
#' @param overwrite Logical: If TRUE, overwrite the files on the central directory.
#' @param msg Logical: If TRUE, print progress to the console.
#' @param n The number of runs (one runfor each version tested) to copy.
#'
#' @export
#' @keywords internal
#'
copyCurrentToServer <- function(root=list(windows="\\\\delphi", unix="/Volumes"), path="pc_prog/S2D/stox/StoXVerTest", toCopy=c("Diff", "Output", "ProjOrig"), overwrite=FALSE, msg=FALSE, n=1){
server <- getServerPath(root=root, path=path)
dir <- getProjectPaths()$projectRoot
dir <- file.path(dir, "StoXVerTest")
copyLatestToServer(dir, server, toCopy=toCopy, overwrite=overwrite, msg=msg, op="<=", n=n)
}
#*********************************************
#*********************************************
#' Function for running the r scripts of a project and copying the relevant output files to the "Output" directory:
#'
#' @param projectName The path to the project.
#' @param progressFile The paht to the progress file.
#' @param outputDir The path to the directory in which to put the output files to be compared for the project (everything in "output" except trash files, baseline and baseline report output, and the project.xml file).
#'
#' @export
#' @keywords internal
#'
runProject <- function(projectName, progressFile, outputDir, ind=NULL){
RstoxVersion <- getRstoxVersion()
# Run the scripts and print info to the progress file:
write(paste0(now(TRUE), "Starting project", paste0(" ", ind), ": ", projectName), progressFile, append=TRUE)
cat(paste0("\n\n------------------------------------------------------------\nRunning project", paste0(" ", ind), ": ", projectName, ":\n"))
# Run the baseline and baseline report (the latter with input=NULL):
# The parameter 'modelType', enabling reading Baseline Report, was introduced in 1.8.1:
# 2018-04-19 Added saveProject() since we wish to pick up changes in the project.xml files:
#if(RstoxVersion$Rstox > "1.8"){
if(version2numeric(getRstoxVersion()$Rstox) > version2numeric("1.8")){
write(paste0(now(TRUE), "Running Baseline and Baseline Report"), progressFile, append=TRUE)
baselineOutput <- getBaseline(projectName, exportCSV=TRUE, modelType="baseline", input=c("par", "proc"), drop=FALSE)
saveProject(projectName)
baselineReportOutput <- getBaseline(projectName, exportCSV=TRUE, modelType="report", input=c("par", "proc"), drop=FALSE)
saveProject(projectName)
}
else{
write(paste0(now(TRUE), "Running Baseline"), progressFile, append=TRUE)
baselineOutput <- getBaseline(projectName, exportCSV=TRUE, input=c("par", "proc"), drop=FALSE)
saveProject(projectName)
}
# Get the path to the scripts to run:
r_script <- file.path(projectName, "output", "R", "r.R")
rreport_script <- file.path(projectName, "output", "R", "r-report.R")
# Generate the r scripts:
generateRScripts(projectName)
write(paste0(now(TRUE), "Running r.R"), progressFile, append=TRUE)
if(file.exists(r_script)){
source(r_script)
}
write(paste0(now(TRUE), "Running r-report.R"), progressFile, append=TRUE)
if(file.exists(rreport_script)){
source(rreport_script)
}
write(paste0(now(TRUE), "Ending project", paste0(" ", ind), ": ", projectName), progressFile, append=TRUE)
write("", progressFile, append=TRUE)
closeProject(projectName)
# Copy output files to the output directory:
unlink(outputDir, recursive=TRUE, force=TRUE)
suppressWarnings(dir.create(outputDir, recursive=TRUE))
output <- file.path(projectName, "output")
file.copy(output, outputDir, recursive=TRUE)
# Delete trash:
trash <- list.dirs(outputDir)
trash <- trash[grep("trash", trash)]
unlink(trash, recursive=TRUE, force=TRUE)
# Save also the output from baseline and baseline report to an RData file:
save(baselineOutput, file=file.path(outputDir, "baselineOutput.RData"))
#if(RstoxVersion$Rstox > "1.8"){
if(version2numeric(getRstoxVersion()$Rstox) > version2numeric("1.8")){
save(baselineReportOutput, file=file.path(outputDir, "baselineReportOutput.RData"))
}
# Copy the project.xml file:
from <- getProjectPaths(projectName)$projectXML
to <- file.path(outputDir, "project.xml")
file.copy(from=from, to=to, overwrite=TRUE)
cat("\n")
}
# Convenience function for getting the Rstox version string, which is a possible output from getRstoxVersion() as of approximately Rstox_1.9:
getRstoxVersionString <- function(){
#if(getRstoxVersion()$Rstox < "1.8.1"){
if(version2numeric(getRstoxVersion()$Rstox) < version2numeric("1.8.1")){
RstoxVersionString <- getRstoxVersion()
RstoxVersionString <- paste(names(RstoxVersionString), unlist(lapply(RstoxVersionString, as.character)), sep="_", collapse="_")
}
else{
RstoxVersionString <- getRstoxVersion("string")
}
RstoxVersionString
}
# On Windows 10 the file.path() using .Platform$file.sep is "/", but cmd fc only accepts "\\". Thus we hach the file.path funciton to accommodate this:
file.path_Windwos10 <- function(...){
release <- Sys.info()["release"]
if(tolower(.Platform$OS.type) == "windows" && startsWith(release, "10")){
paste(..., sep="\\")
}
else{
file.path(...)
}
}
# Function for deleting all output files of a project:
deleteOutput <- function(x){
if(length(x)==1 && !isProject(x[1])){
x <- list.dirs(x, recursive=FALSE)
}
output <- file.path(x, "output")
files <- list.files(output, recursive=TRUE, full.names=TRUE)
unlink(files)
invisible(files)
}
all.equal2 <- function(target, current){
out <- all.equal(target, current)
if(!isTRUE(out)){
out <- gsub("“|”", "\"", out)
}
out
}
#*********************************************
#*********************************************
#' Function for running all test projects and comparing outputs with previous outputs.
#'
#' @param root A list of specifyers for the root directory to the central server.
#' @param path The relative path from the root.
#' @param copyFromServer Logical: If TRUE, copy the latest original projects, outputs and diffs in the server to the local directory.
#' @param process Which steps to run in the testing used mostly to reduce processing time for development and bug fixing.
#' @param diffs Which diffs to include, also used to reduce processing time.
#' @param nlines The number of lines to display for diffs between text files.
#'
#' @export
#' @keywords internal
#'
automatedRstoxTest <- function(root=list(windows="\\\\delphi", unix="/Volumes"), path="pc_prog/S2D/stox/StoXVerTest", copyFromServer=TRUE, process=c("run", "diff"), diffs=c("Rdata", "images", "text", "baseline"), projectInd=NULL, nlines=50, mem.size=16e9, nwarnings=10000, n=1L, skipError=FALSE){
#automatedRstoxTest <- function(dir, copyFromServer=TRUE, process=c("run", "diff"), nlines=-1L, root=list(windows="\\\\delphi", unix="/Volumes"), path="pc_prog/S2D/stox/StoXAutoTest"){
# Load image packages:
library(png)
library(jpeg)
library(tiff)
# Load utilities packages:
library(tools)
library(R.utils)
setJavaMemory(mem.size)
oldnwarnings <- options()$nwarnings
options(nwarnings=nwarnings)
# The function readBaselineFiles() was introduced in Rstox 1.8.1:
#if(getRstoxVersion()$Rstox <= "1.8"){
if(version2numeric(getRstoxVersion()$Rstox) <= version2numeric("1.8")){
readBaselineFiles <- function(x){
# Return NULL if no files are given:
if(length(x)==0){
return(NULL)
}
# Function for converting string to logical:
string2logical <- function(y){
string2logicalOne <- function(z){
if(length(z)>0 && any(z %in% c("true", "false"))){
z <- as.logical(z)
}
z
}
as.data.frame(lapply(y, string2logicalOne), stringsAsFactors=FALSE)
}
# Read one text connection:
if("textConnection" %in% class(x)){
out <- read.csv(x, sep="\t", stringsAsFactors=FALSE, na.strings="-", encoding="UTF-8", quote=NULL)
out <- string2logical(out)
}
# Read the files:
else{
out <- lapply(x, function(y) read.csv(y, sep="\t", stringsAsFactors=FALSE, na.strings="-", encoding="UTF-8", quote=NULL))
for(i in seq_along(out)){
out[[i]] <- string2logical(out[[i]])
}
# Get the names of the processes and data frames:
x_split <- strsplit(basename(x), "_")
#dataFrameNames <- sapply(lapply(x_split, "[", -1), paste, collapse="_")
#processNames <- sapply(x_split, "[", 2)
dataFrameNames <- sapply(lapply(x_split, "[", -1), paste, collapse="_")
processNames <- sapply(x_split, function(y) paste(y[seq(2, length(y)-2)], sep="_"))
# Set the names of the data frames:
names(out) <- dataFrameNames