-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathRDBES_Functions.R
2802 lines (2208 loc) · 114 KB
/
RDBES_Functions.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
library(RODBC)
library(dplyr)
library(data.table)
library(XML)
library(icesVocab)
library(RCurl)
library(httr)
library(readxl)
library(compare)
# Location for our output files
outputFolder <- "./output/"
print(paste("The default output folder for exchange files is '",outputFolder,"' Change the value of 'outputFolder' if you want to save them to a different place.",sep = ""))
statRects <- readRDS("referenceData/ICESRectAreas.RDS")
#' loadRDBESData
#' This function loads data that is already in the RDBES format from a relational database.
#'
#' @param connectionString A string specifying the connection string to the database in a formt that odbcDriverConnect can use e.g. 'driver=SQL Server;server=mysqlhost;database=mydbname;trusted_connection=true'
#'
#' @return A named list containing the different RDBES tables
#' @export
#'
#' @examples
#' myRDBESData <- loadRDBESData(readRDS('connectionString.RDS'))
loadRDBESData <- function(connectionString){
# Connect to the database
channel <- odbcDriverConnect(connectionString)
# Run queries to fetch the data
myCE <- sqlQuery(channel,"select * from dbo.CE", stringsAsFactors = FALSE)
myCL <- sqlQuery(channel,"select * from dbo.CL", stringsAsFactors = FALSE)
myDE <- sqlQuery(channel,"select * from dbo.Design", stringsAsFactors = FALSE)
mySD <- sqlQuery(channel,"select * from dbo.SamplingDetails", stringsAsFactors = FALSE)
myOS <- sqlQuery(channel,"select * from dbo.OnshoreEvent", stringsAsFactors = FALSE)
myLE <- sqlQuery(channel,"select * from dbo.LandingEvent", stringsAsFactors = FALSE)
myVS <- sqlQuery(channel,"select * from dbo.VesselSelection", stringsAsFactors = FALSE)
myFT <- sqlQuery(channel,"select * from dbo.FishingTrip", stringsAsFactors = FALSE)
myFO <- sqlQuery(channel,"select * from dbo.FishingOperation", stringsAsFactors = FALSE)
mySS <- sqlQuery(channel,"select * from dbo.SpeciesSelection", stringsAsFactors = FALSE)
mySA <- sqlQuery(channel,"select * from dbo.Sample", stringsAsFactors = FALSE)
myFM <- sqlQuery(channel,"select * from dbo.FrequencyMeasure", stringsAsFactors = FALSE)
myBV <- sqlQuery(channel,"select * from dbo.BiologicalVariable", stringsAsFactors = FALSE)
mySL <- sqlQuery(channel,"select * from dbo.SpeciesListDetails", stringsAsFactors = FALSE)
myVD <- sqlQuery(channel,"select * from dbo.VesselDetails", stringsAsFactors = FALSE)
#myLocodes <- sqlQuery(channel,"select * from dbo.PortLocodes", stringsAsFactors = FALSE)
#myAphiaIds <- sqlQuery(channel,"select * from dbo.SpeciesAphiaIDs", stringsAsFactors = FALSE)
# Close the connection
close(channel)
# Create a named list to return our data
myRDBESData <- list( CE = myCE
,CL = myCL
,DE = myDE
,SD = mySD
,OS = myOS
,LE = myLE
,VS = myVS
,FT = myFT
,FO = myFO
,SS = mySS
,SA = mySA
,FM = myFM
,BV = myBV
,SL = mySL
,VD = myVD
)
return(myRDBESData)
}
#' Generate an exchange format file for the RDBES
#'
#' @param typeOfFile The file we want to create - allowed values are CL, CE, VD, SL, H1 - H13
#' @param outputFileName (Optional) The name we wish to give the file we produce - if not supplied a standard pattern will be used
#' @param yearToUse The year we want to generate the file for
#' @param country The country to extract data for
#' @param RDBESdata A named list containing our RDBES data
#' @param numberOfRows (Optional) Limit the output to this number of rows (just used for testing CL,CE,VD,SL files)
#' @param numberOfSamples (Optional) Limit the output to this number of samples (just used for testing H1 - H13 files)
#' @param cleanData (Optional) if TRUE then remove any invalid rows from the data before generating the upload files - warning data will potentially be lost from your upload file if you do this!
#' @param RDBESvalidationdata (Optional) If you have selected to cleanData then you need to supply validation data (derived from BaseTypes.xsd)
#' @param RDBEScodeLists (Optional) If you have selected to cleanData then you need to supply reference data (derived from ICES vocabulary server)
#' @param RequiredTables (Optional) A list of the tables required for each hierachy - required for H1 - H13 files
#'
#' @return
#' @export
#'
#' @examples
#' generateExchangeFile(typeOfFile = 'CL', yearToUse = 2017, country = 'IE', RDBESdata = myRDBESData, numberOfRows=50,cleanData = TRUE, RDBESvalidationdata = validationData, RDBEScodeLists = allowedValues)
generateExchangeFile <- function(typeOfFile, outputFileName = "", yearToUse, country, RDBESdata, numberOfRows = NULL, numberOfSamples = NULL, cleanData = FALSE, RDBESvalidationdata = NULL, RDBEScodeLists = NULL, RequiredTables = NULL){
simpleFiles <- c("CL","CE","VD","SL")
complexfiles <- c("H1","H2","H3","H4","H5","H6","H7","H8","H9","H10","H11","H12","H13")
if(typeOfFile %in% simpleFiles) {
generateSimpleExchangeFile(typeOfFile = typeOfFile
,outputFileName = outputFileName
,yearToUse = yearToUse
,country = country
,RDBESdata = RDBESdata
,numberOfRows = numberOfRows
,cleanData = cleanData
,RDBESvalidationdata = RDBESvalidationdata
,RDBEScodeLists = RDBEScodeLists)
} else if(typeOfFile %in% complexfiles) {
generateComplexExchangeFile(typeOfFile = typeOfFile
,outputFileName = outputFileName
,yearToUse = yearToUse
,country = country
,RDBESdata = RDBESdata
,numberOfSamples = numberOfSamples
,cleanData = cleanData
,RDBESvalidationdata = RDBESvalidationdata
,RDBEScodeLists = RDBEScodeLists
,RequiredTables = RequiredTables)
} else {
stop(paste0("typeOfFile not recognised: ",typeOfFile))
}
}
#' generateSimpleExchangeFile Generate either a CE, CL, VD, or SL exchange format file for the RDBES
#'
#' @param typeOfFile The file we want to create - allowed values are CL, CE, VD, or SL
#' @param outputFileName (Optional) The name we wish to give the file we produce - if not supplied a standard pattern will be used
#' @param yearToUse The year we want to generate the file for
#' @param country The country to extract data for
#' @param RDBESdata A named list containing our RDBES data
#' @param numberOfRows (Optional) Limit the output to this number of rows (just used for testing)
#' @param cleanData (Optional) if TRUE then remove any invalid rows from the data before generating the upload files - warning data will potentially be lost from your upload file if you do this!
#' @param RDBESvalidationdata (Optional) If you have selected to cleanData then you need to supply validation data (derived from BaseTypes.xsd)
#' @param RDBEScodeLists (Optional) If you have selected to cleanData then you need to supply reference data (derived from ICES vocabulary server)
#'
#' @return
#' @export
#'
#' @examples generateSimpleExchangeFile(typeOfFile = 'CL', yearToUse = 2017, country = 'IE', RDBESdata = myRDBESData, numberOfRows=50,cleanData = TRUE, RDBESvalidationdata = validationData, RDBEScodeLists = allowedValues)
generateSimpleExchangeFile <- function(typeOfFile, outputFileName = "", yearToUse, country, RDBESdata,numberOfRows = NULL, cleanData = FALSE, RDBESvalidationdata = NULL, RDBEScodeLists = NULL){
# We only need a 2 letter name for the file/table to use
if (length(typeOfFile)>2){
typeOfFile <- substr(typeOfFile,1,2)
}
# Stop if we don't have a valid file type
if (!typeOfFile %in% c("CL","CE","VD","SL")){
stop(paste("Invalid value for 'typeOfFile': ",typeOfFile))
}
## Step 0 - Generate a file name if we need to
if (outputFileName == ""){
fileName <- paste("H",typeOfFile,".csv", sep ="")
outputFileName <- paste(country,yearToUse,fileName, sep ="_")
}
# Create the output directory if we need do
ifelse(!dir.exists(file.path(outputFolder)), dir.create(file.path(outputFolder)), FALSE)
## Step 1 - Filter the data and write it out
RDBESdataForFile <- list(CE=RDBESdata[['CE']], CL=RDBESdata[['CL']], VD=RDBESdata[['VD']], SL=RDBESdata[['SL']])
myData <- RDBESdataForFile[[typeOfFile]]
# Filter the data by our input parameters
if (typeOfFile == 'CE'){
myDataForFile <- myData[myData$CEyear == yearToUse & myData$CEvesselFlagCountry == country,]
} else if (typeOfFile == 'CL'){
myDataForFile <- myData[myData$CLyear == yearToUse & myData$CLvesselFlagCountry == country,]
} else if (typeOfFile == 'VD') {
myDataForFile <- myData[myData$VDyear == yearToUse & myData$VDcountry == country,]
} else if (typeOfFile == 'SL') {
myDataForFile <- myData[myData$SLyear == yearToUse & myData$SLcountry == country,]
}
RDBESdataForFile[[typeOfFile]]<-myDataForFile
# If we want to remove any invalid data before generating the upload files do this now
if(cleanData){
rowsBefore <- 0
if (!is.null(myDataForFile)){
rowsBefore <- nrow(myDataForFile)
}
print(paste(rowsBefore, ' rows before removing invalid data', sep =""))
# Validate
myErrors <- validateTables(RDBESdata = RDBESdataForFile, RDBESvalidationdata = RDBESvalidationdata, RDBEScodeLists = RDBEScodeLists, shortOutput = FALSE,framestoValidate = c(typeOfFile))
# Remove any invalid rows
myDataForFile <- removeInvalidRows(tableName = typeOfFile,dataToClean = myDataForFile,errorList = myErrors)
rowsAfter <- 0
if (!is.null(myDataForFile)){
rowsAfter <- nrow(myDataForFile)
}
print(paste(rowsAfter, ' rows after removing invalid data', sep =""))
if (rowsAfter < rowsBefore){
missingRows <- rowsBefore - rowsAfter
warning(paste(missingRows,' invalid rows removed before trying to generate output files', sep = ""))
}
}
# If we only want a certain number of rows we'll subset the data (normally just used during testing)
if (!is.null(numberOfRows)){
if (nrow(myDataForFile) > numberOfRows)
{
myDataForFile <- myDataForFile[1:numberOfRows,]
print(paste("File truncated to ",numberOfRows, " rows",sep=""))
}
}
# If myDataForFile is NULL at this point just stop
if (is.null(myDataForFile)){
print("Error - the data to generate the exchange file is is NULL")
stop("Could not generate an exchange file - please validate your data to identify any problems")
}
# We now write out the data frame with ids and column names included to make debugging easier
fwrite(myDataForFile, paste(outputFolder, "debug_", outputFileName,sep="") ,row.names=F,col.names=T,quote=F)
# Get rid of the XXid fields from our data - not included in the final output file
colstoRemove <- names(myDataForFile)[grepl("^..id$",names(myDataForFile))]
myDataForFile <- select(myDataForFile,-all_of(colstoRemove))
# Replace any NAs with ''
myDataForFile[is.na(myDataForFile)] <- ''
# Get all the values and list them out
myFinalData <- do.call('paste',c(myDataForFile,sep=','))
# replace NA with blanks
# 20/8/20 - if we get rid of NAs liek this it also removes NAs from the middle of words :-S - we'll get rid of NAs from the data frame instead earlier
#myFinalData <- gsub('NA','',myFinalData)
# Write out the file
fwrite(list(myFinalData), paste(outputFolder,outputFileName, sep = "") ,row.names=F,col.names=F,quote=F)
print(paste("Output file written to ",outputFileName,sep=""))
}
#' generateComplexExchangeFile This function creates an RDBES exchange file for CS data
#'
#' @param typeOfFile The hierarchy we want to generate a CS file for e.g. 'H1'
#' @param yearToUse The year we want to generate the CS H5 file for
#' @param country The country to extract data for
#' @param RDBESdata A named list containing our RDBES data
#' @param outputFileName (Optional) The name we wish to give the file we produce - if not supplied a standard pattern will be used
#' @param numberOfSamples (Optional) Limit the output to this number of samples (just used for testing)
#' @param cleanData (Optional) if TRUE then remove any invalid rows from the data before generating the upload files - warning data will potentially be lost from your upload file if you do this!
#' @param RDBESvalidationdata (Optional) If you have selected to cleanData then you need to supply validation data (derived from BaseTypes.xsd)
#' @param RDBEScodeLists (Optional) If you have selected to cleanData then you need to supply reference data (derived from ICES vocabulary server)
#' @param RequiredTables A list of the tables required for each hierachy
#'
#' @return
#' @export
#'
#' @examples generateComplexExchangeFile(typeOfFile = 'H1', yearToUse = 2016, country = 'IE', RDBESdata = myRDBESData)
generateComplexExchangeFile <- function(typeOfFile, yearToUse, country, RDBESdata, outputFileName="", numberOfSamples = NULL, cleanData = FALSE, RDBESvalidationdata = NULL, RDBEScodeLists = NULL, RequiredTables){
# For testing
# typeOfFile <- 'H1'
# RDBESdata<-myRDBESData
# yearToUse <- 2019
# country <- 'IE'
# outputFileName <- ""
# numberOfSamples <- 10
# cleanData <- TRUE
# RDBESvalidationdata <- validationData
# RDBEScodeLists <- allowedValues
# RequiredTables <- allRequiredTables
## Step 0 - Check typeOfFile and generate a file name if we need to
testedCSfileTypes <- c('H1','H5')
if (!typeOfFile %in% testedCSfileTypes){
warning(paste("Method not tested for ",typeOfFile, " yet", sep =""))
}
if (outputFileName == ""){
outputFileName <- paste(country,yearToUse,paste(typeOfFile,".csv", sep = ""), sep ="_")
}
# Create the output directory if we need do
ifelse(!dir.exists(file.path(outputFolder)), dir.create(file.path(outputFolder)), FALSE)
# Find which tables we need for this file type
upperHierarchy <- substr(typeOfFile,2,nchar(typeOfFile))
requiredTables <- RequiredTables[[typeOfFile]]
## Step 1 - Filter the data
myCSData <- filterCSData(RDBESdata = RDBESdata , RequiredTables = requiredTables, YearToFilterBy = yearToUse, CountryToFilterBy = country, UpperHierarchyToFilterBy = upperHierarchy)
# If we want to remove any invalid data before generating the upload files do this now
if(cleanData){
myCSData <- cleanCSData(DataToClean = myCSData, RDBESvalidationdata = RDBESvalidationdata, RDBEScodeLists = RDBEScodeLists, RequiredTables = requiredTables, YearToFilterBy = yearToUse, CountryToFilterBy = country, UpperHierarchyToFilterBy = upperHierarchy)
}
# If required, limit the number of samples we will output (normally just used during testing)
if (!is.null(numberOfSamples)){
myCSData <- limitSamplesInCSData(DataToFilter = myCSData, NumberOfSamples = numberOfSamples, RequiredTables = requiredTables)
}
# If myCSData is empty at this point just stop
if (length(myCSData)==0){
print("Error - the data to generate the exchange file is empty")
stop("Could not generate an exchange file - please validate your data to identify any problems")
}
## Step 2 - I now add a SortOrder field to each of our fitlered data frames
## this will allow me to generate the CS file in the correct row order without needing a slow for-loop
myCSData <- generateSortOrder(RDBESdataToSort = myCSData, RequiredTables = requiredTables)
# Combine our SortOrder values
# TODO Need to double-check this works correctly
for (myRequiredTable in requiredTables){
if (myRequiredTable == 'DE'){
FileSortOrder <- myCSData[[myRequiredTable]]$SortOrder
} else {
FileSortOrder <-c(FileSortOrder,myCSData[[myRequiredTable]]$SortOrder)
}
}
## STEP 3) Create a version of the output data for debugging
# Here we create a version of the output data with all the ids and sorting columns in so I can check things are correct
csForChecking <- NULL
for (myRequiredTable in requiredTables){
if (!is.null(myCSData[[myRequiredTable]])){
if (myRequiredTable == 'DE'){
csForChecking <- do.call('paste',c(myCSData[[myRequiredTable]],sep=','))
} else {
csForChecking <- c(csForChecking,do.call('paste',c(myCSData[[myRequiredTable]],sep=',')))
}
}
}
# Sort the output into the correct order
csForCheckingOrdered <- csForChecking[order(FileSortOrder)]
# Write out a file with the row ids left in - used for debugging and checking the output
fwrite(list(csForCheckingOrdered), paste(outputFolder,"debug_", outputFileName,sep="") ,row.names=F,col.names=F,quote=F)
## STEP 4) Create the real version of the output data
# Create the CS data with the sort columns and ids removed - this will then be used to generate the exchange file
cs <- NULL
for (myRequiredTable in requiredTables){
if (!is.null(myCSData[[myRequiredTable]])){
# First remove the columns we don't want in the final output (SortOrder and any XXid columns)
colstoRemove <- c("SortOrder", names(myCSData[[myRequiredTable]])[grepl("^..id$",names(myCSData[[myRequiredTable]]))])
myData <- select(myCSData[[myRequiredTable]],-all_of(colstoRemove))
# Replace any NAs with ''
myData[is.na(myData)] <- ''
# Now stick all the lines from each table together with commas seperating the values
if (myRequiredTable == 'DE'){
cs <- do.call('paste',c(myData,sep=','))
} else {
cs <- c(cs,do.call('paste',c(myData,sep=',')))
}
}
}
# Sort the output into the correct order
csOrdered <- cs[order(FileSortOrder)]
# replace NA with blanks
# 20/8/20 - if we get rid of NAs like this it also removes NAs from the middle of words :-S - we'll get rid of NAs from the data frame instead earlier
#csOrdered <- gsub('NA','',csOrdered)
fwrite(list(csOrdered), paste(outputFolder,outputFileName, sep = "") ,row.names=F,col.names=F,quote=F)
print(paste("Output file written to ",outputFileName,sep=""))
}
#' limitSamplesInCSData
#'
#' @param DataToFilter
#' @param NumberOfSamples
#' @param RequiredTables
#'
#' @return
#' @export
#'
#' @examples
limitSamplesInCSData <- function(DataToFilter, NumberOfSamples, RequiredTables){
# Get our samples (not including sub-samples)
NotSubSamples <- DataToFilter[['SA']][is.na(DataToFilter[['SA']]$SAparentSequenceNumber),]
#if (nrow(myCSData[['SA']])>numberOfSamples ) {
if (!is.null(NotSubSamples)){
if (nrow(NotSubSamples)>NumberOfSamples ) {
#Subset the data to get the SAid values we are interested it
#SAidsToUse <- myCSData[['SA']][1:numberOfSamples,"SAid"]
SAidsToUse <- NotSubSamples[1:NumberOfSamples,"SAid"]
# Need Sort out SA and FM first, then we'll deal with the other tables
allSAData <- DataToFilter[['SA']]
# SA : Top level samples not including sub-samplea
DataToFilter[['SA']]<- DataToFilter[['SA']][DataToFilter[['SA']]$SAid %in% SAidsToUse,]
# Now handle any sub-samples
mySubSampleData <- DataToFilter[['SA']][!is.na(DataToFilter[['SA']]$SAparentSequenceNumber),]
# If we have any sub-samples see if we need to include them
if (nrow(mySubSampleData) > 0){
# Use a recursive function to fetch the top level sequence number of our sub-samples
#mySubSampleData$topLevelSequenceNumber <- sapply(mySubSampleData$SAsequenceNumber,getTopLevelSequenceNumber,SAdata = mySubSampleData)
mySubSampleData$topLevelSequenceNumber <- sapply(mySubSampleData$SAsequenceNumber,getTopLevelSequenceNumber,SAdata = allSAData)
# Only include sub-samples if their top level sequence numebr is in our filtered sample data
mySubSampleData <- mySubSampleData[mySubSampleData$topLevelSequenceNumber %in% DataToFilter[['SA']]$SAsequenceNumber,]
# Remove the column we added
mySubSampleData$topLevelSequenceNumber <- NULL
# Combine our samples and sub-samples together
DataToFilter[['SA']] <- rbind(DataToFilter[['SA']],mySubSampleData)
}
# FM
DataToFilter[['FM']]<- DataToFilter[['FM']][DataToFilter[['FM']]$SAid %in% DataToFilter[['SA']]$SAid,]
# Now deal with all the other tables
myData <- NULL
previousRequiredTable <- NULL
# Iterate through the required tables in reverse order and remove any records not assoicated with our selected samples
for (myRequiredTable in rev(RequiredTables)){
if (myRequiredTable %in% c('SA','FM')){
# Do nothing - already handled above
}
# Need to check if the BV records are in either the FM or SA tables
else if (myRequiredTable == 'BV'){
# don't assume FMid and SAid always exist
myData <- DataToFilter[['BV']][DataToFilter[['BV']]$FMid %in% DataToFilter[['FM']]$FMid | DataToFilter[['BV']]$SAid %in% DataToFilter[['SA']]$SAid,]
if ('FMid' %in% names(DataToFilter[['BV']])){
data1 <- DataToFilter[['BV']][DataToFilter[['BV']]$FMid %in% DataToFilter[['FM']]$FMid,]
} else {
data1 <- NULL
}
if ('SAid' %in% names(DataToFilter[['BV']])){
data2 <- DataToFilter[['BV']][DataToFilter[['BV']]$SAid %in% DataToFilter[['SA']]$SAid,]
} else {
data2 <- NULL
}
#DataToFilter[['BV']] <- myData
DataToFilter[['BV']] <- rbind(data1,data2)
}
# Other tables can follow a general pattern
else {
previousHierarchyTable <- DataToFilter[[previousRequiredTable]]
## Assume the primary key is the first field
currentPrimaryKey <- names(DataToFilter[[myRequiredTable]])[1]
myData <- DataToFilter[[myRequiredTable]][DataToFilter[[myRequiredTable]][,currentPrimaryKey] %in% previousHierarchyTable[,currentPrimaryKey],]
DataToFilter[[myRequiredTable]] = myData
}
previousRequiredTable <- myRequiredTable
}
print(paste("File truncated to data relating to ",NumberOfSamples, " samples",sep=""))
}
}
DataToFilter
}
#' cleanCSData
#'
#' @param DataToClean
#' @param RDBESvalidationdata
#' @param RDBEScodeLists
#' @param RequiredTables
#' @param YearToFilterBy
#' @param CountryToFilterBy
#' @param UpperHierarchyToFilterBy
#'
#' @return
#' @export
#'
#' @examples
cleanCSData <- function(DataToClean,RDBESvalidationdata, RDBEScodeLists, RequiredTables, YearToFilterBy, CountryToFilterBy,UpperHierarchyToFilterBy ){
# For testing
# typeOfFile <- 'H1'
# UpperHierarchyToFilterBy <- substr(typeOfFile,2,nchar(typeOfFile))
# YearToFilterBy <- 2019
# CountryToFilterBy <- 'IE'
# outputFileName <- ""
# RDBESvalidationdata <- validationData
# RDBEScodeLists <- allowedValues
# #RequiredTables <- requiredTables
# requiredTables <- allRequiredTables[[typeOfFile]]
# DataToClean <- filterCSData(RDBESdata = RDBESdata , RequiredTables = requiredTables, YearToFilterBy = YearToFilterBy, CountryToFilterBy = CountryToFilterBy, UpperHierarchyToFilterBy = UpperHierarchyToFilterBy)
rowsBefore <- 0
for (myRequiredTable in RequiredTables){
if (!is.null(DataToClean[[myRequiredTable]])){
rowsBefore <- rowsBefore + nrow(DataToClean[[myRequiredTable]])
}
}
print(paste(rowsBefore, ' rows before removing invalid data', sep =""))
# Validate
myErrors <- validateTables(RDBESdata = DataToClean
,RDBESvalidationdata = RDBESvalidationdata
,RDBEScodeLists = RDBEScodeLists
,shortOutput = FALSE
,framestoValidate = RequiredTables
)
# Remove any invalid rows
for (myRequiredTable in RequiredTables){
DataToClean[[myRequiredTable]]<- removeInvalidRows(tableName = myRequiredTable,dataToClean = DataToClean[[myRequiredTable]],errorList = myErrors)
}
# Filter the data again to ensure we don't have any orphan rows in our output
DataToClean <- filterCSData(RDBESdata = DataToClean , RequiredTables = RequiredTables, YearToFilterBy = YearToFilterBy, CountryToFilterBy = CountryToFilterBy, UpperHierarchyToFilterBy = UpperHierarchyToFilterBy)
rowsAfter <- 0
for (myRequiredTable in RequiredTables){
if (!is.null(DataToClean[[myRequiredTable]])){
rowsAfter <- rowsAfter + nrow(DataToClean[[myRequiredTable]])
}
}
print(paste(rowsAfter, ' rows after removing invalid data', sep =""))
if (rowsAfter < rowsBefore){
missingRows <- rowsBefore - rowsAfter
warning(paste(missingRows,' invalid rows removed before trying to generate output files', sep = ""))
}
DataToClean
}
#' filterCSData Filter the CS data to sub-set by year, country, and hierarchy
#'
#' @param RDBESdata
#' @param RequiredTables
#' @param YearToFilterBy
#' @param CountryToFilterBy
#' @param UpperHierarchyToFilterBy
#'
#' @return
#' @export
#'
#' @examples
filterCSData <- function(RDBESdata, RequiredTables, YearToFilterBy, CountryToFilterBy, UpperHierarchyToFilterBy){
# For testing
# RDBESdata <- myRDBESData
# RequiredTables <- requiredTables
# YearToFilterBy <- 2017
# CountryToFilterBy <- 'IE'
# UpperHierarchyToFilterBy <- 1
myCSData <- list()
myData <- NULL
previousRequiredTable <- NULL
# Get the data for each required table - filter by year, country, and upper hierarchy
for (myRequiredTable in RequiredTables){
myData <- RDBESdata[[myRequiredTable]]
# Don't worry about tables we don't have data for
if (!is.null(myData)){
# Need to filter DE by year and upper hieararchy
if (myRequiredTable == 'DE'){
myData <- myData[myData$DEyear == YearToFilterBy & myData$DEhierarchy == UpperHierarchyToFilterBy,]
myCSData[[myRequiredTable]] = myData
}
# Need to filter SD by country
else if (myRequiredTable == 'SD'){
myData <- myData[myData$DEid %in% myCSData[[previousRequiredTable]]$DEid & myData$SDcountry == CountryToFilterBy,]
myCSData[[myRequiredTable]] = myData
}
# Need to handle samples and sub-samples for SA
else if (myRequiredTable == 'SA'){
#Lets deal with Samples first
previousHierarchyTable <- myCSData[[previousRequiredTable]]
## Assume the primary key is the first field
previousPrimaryKey <- names(previousHierarchyTable)[1]
mySampleData <- myData[myData[,previousPrimaryKey] %in% previousHierarchyTable[,previousPrimaryKey],]
# Samples which don't have a parent
myTopLevelSampleData <- mySampleData[is.na(mySampleData$SAparentSequenceNumber),]
# Now handle any sub-samples
mySubSampleData <- myData[!is.na(myData$SAparentSequenceNumber),]
# Use a recursive function to fetch the top level sequence number of our sub-samples
#mySubSampleData$topLevelSequenceNumber <- sapply(mySubSampleData$SAsequenceNumber,getTopLevelSequenceNumber,SAdata = mySubSampleData)
mySubSampleData$topLevelSequenceNumber <- sapply(mySubSampleData$SAsequenceNumber,getTopLevelSequenceNumber,SAdata = mySampleData)
# Only include sub-samples if their top level sequence numebr is in our filtered sample data
#mySubSampleData <- mySubSampleData[mySubSampleData$topLevelSequenceNumber %in% mySampleData$SAsequenceNumber,]
mySubSampleData <- mySubSampleData[mySubSampleData$topLevelSequenceNumber %in% myTopLevelSampleData$SAsequenceNumber,]
# Get rid of the column we added earlier
mySubSampleData$topLevelSequenceNumber <- NULL
# Stick our samples and sub-samples together
#myData <- rbind(mySampleData, mySubSampleData)
myData <- rbind(myTopLevelSampleData, mySubSampleData)
myCSData[[myRequiredTable]] = myData
}
# BVid can either be in FM or SA
else if (myRequiredTable == 'BV'){
#myData <- myData[myData$FMid %in% myCSData[['FM']]$FMid | myData$SAid %in% myCSData[['SA']]$SAid,]
# Don't just assume the FMid or SAid columns are present - check first
if ('FMid' %in% names(myData)){
myData1 <- myData[myData$FMid %in% myCSData[['FM']]$FMid,]
} else {
myData1 <- NULL
}
if ('SAid' %in% names(myData)){
myData2 <- myData[myData$SAid %in% myCSData[['SA']]$SAid,]
} else {
myData2 <- NULL
}
#myCSData[[myRequiredTable]] = myData
myCSData[[myRequiredTable]] = rbind(myData1,myData2)
}
# all other tables can follow a general pattern of matching
else {
#previousHierarchyTable <- RDBESdata[[myRequiredTable]]
previousHierarchyTable <- myCSData[[previousRequiredTable]]
## Assume the primary key is the first field
previousPrimaryKey <- names(previousHierarchyTable)[1]
myData <- myData[myData[,previousPrimaryKey] %in% previousHierarchyTable[,previousPrimaryKey],]
myCSData[[myRequiredTable]] = myData
}
}
previousRequiredTable <- myRequiredTable
}
myCSData
}
#' getTopLevelSequenceNumber Recursive function to get the top level SAsequenceNumber of a series of sameples and sub-samples
#'
#' @param SAdata
#' @param SAsequenceNumber
#'
#' @return
#' @export
#'
#' @examples
getTopLevelSequenceNumber <- function(SAdata,SAsequenceNumber ){
#print(SAsequenceNumber)
# Check if the sequence numbers are both numeric
if(!(is.numeric(SAdata$SAsequenceNumber) &
is.numeric(SAdata$SAparentSequenceNumber))){
warning("SAsequenceNumber and SAparentSequenceNumber should both be numeric")
}
dataToCheck <- SAdata[SAdata$SAsequenceNumber == SAsequenceNumber,]
# If we have mutiple matches we probably don't have unique SAsequenceNumber values
if (nrow(dataToCheck) > 1){
warning("There is a problem with non-unique SAsequenceNumber values- check your data")
# Just use the first match
dataToCheck <- dataToCheck[1,]
}
if (nrow(dataToCheck) == 0) {
return (NA)
} else if (is.na(dataToCheck$SAparentSequenceNumber)) {
return (SAsequenceNumber)
} else {
return (getTopLevelSequenceNumber(SAdata = SAdata,SAsequenceNumber = dataToCheck$SAparentSequenceNumber))
}
}
#' generateSortOrder Adds a SortOrder field to each frame in our list of data frames. When the data is sorted by this column it shoudl be in the correct order to generate a CS exchange file. Even if the data frame is empty I add in a blank SortOrder column - that way I can guarantee it exists
#'
#' @param RDBESdataToSort
#' @param RequiredTables
#'
#' @return
#' @export
#'
#' @examples
generateSortOrder <- function(RDBESdataToSort, RequiredTables){
# For testing
#RDBESdataToSort <- myCSData
#RequiredTables <- requiredTables
# IMPORTANT - I'm using inner_join from dply so we can maintain the ordering of the first data frame in the join
# if the ordering isn't maintained then the exchange file will be output in the wrong order
# TODO For our data BV only follows SA not FM - need to check that the sort order will work if there is a mix of lower hierarchies
previousRequiredTable <- NULL
for (myRequiredTable in RequiredTables){
# If the table actually exists
if(!is.null(RDBESdataToSort[[myRequiredTable]])){
# Check if there are any rows in this table
if(nrow(RDBESdataToSort[[myRequiredTable]])>0) {
# Need to handle DE differently because the SortOrder doesn't just use the primary key
if (myRequiredTable == 'DE'){
RDBESdataToSort[[myRequiredTable]]$SortOrder <- paste(RDBESdataToSort[[myRequiredTable]]$DEhierarchy,RDBESdataToSort[[myRequiredTable]]$DEyear,RDBESdataToSort[[myRequiredTable]]$DEsamplingScheme,RDBESdataToSort[[myRequiredTable]]$DEstratum,sep="-")
}
# Need to handle SA differently because there can be sub-samples
else if (myRequiredTable == 'SA'){
# We will use SAsequenceNumber in the SortOrder - this shoudl ensure all samples and sub-samples end-up in the correct order
# TODO this needs checking
previousHierarchyTable <- RDBESdataToSort[[previousRequiredTable]]
## Assume the primary key is the first field
previousPrimaryKey <- names(previousHierarchyTable)[1]
currentPrimaryKey <- names(RDBESdataToSort[[myRequiredTable]])[1]
# Create the value for SortOrder based on the value of SortOrder from the previous table, and the current primary key
RDBESdataToSort[[myRequiredTable]]$SortOrder <- paste( inner_join(RDBESdataToSort[[myRequiredTable]],previousHierarchyTable, by =previousPrimaryKey)[,c("SortOrder")], RDBESdataToSort[[myRequiredTable]][,"SAsequenceNumber"], sep = "-")
}
# Need to handle BV differently because it can be linked to from either FM or SA
else if (myRequiredTable == 'BV') {
# Add the SortOrder field first
# Bit ugly but we'll call it SortOrder_BV to start with to avoid some issues - we'll name it propery in a minute
RDBESdataToSort[[myRequiredTable]]$SortOrder_BV <- character(nrow(RDBESdataToSort[[myRequiredTable]]))
currentPrimaryKey <- names(RDBESdataToSort[[myRequiredTable]])[1]
# Add SortOrder where there is a link to FM (rows where FMid is not NA)
if (nrow( RDBESdataToSort[[myRequiredTable]][!is.na(RDBESdataToSort[[myRequiredTable]]$FMid),] )>0){
previousHierarchyTable <- RDBESdataToSort[['FM']]
previousPrimaryKey <- names(previousHierarchyTable)[1]
# Create the value for SortOrder based on the value of SortOrder from the previous table, and the current primary key (just for the BV rows that have an FMid)
RDBESdataToSort[[myRequiredTable]][!is.na(RDBESdataToSort[[myRequiredTable]]$FMid),"SortOrder_BV"] <- paste( inner_join(RDBESdataToSort[[myRequiredTable]][!is.na(RDBESdataToSort[[myRequiredTable]]$FMid),],previousHierarchyTable, by =previousPrimaryKey)[,c("SortOrder")], RDBESdataToSort[[myRequiredTable]][!is.na(RDBESdataToSort[[myRequiredTable]]$FMid),currentPrimaryKey], sep = "-")
}
# Add SortOrder where there is a link to SA (rows where SAid is not NA)
if (nrow( RDBESdataToSort[[myRequiredTable]][!is.na(RDBESdataToSort[[myRequiredTable]]$SAid),] )>0){
previousHierarchyTable <- RDBESdataToSort[['SA']]
previousPrimaryKey <- names(previousHierarchyTable)[1]
# Create the value for SortOrder based on the value of SortOrder from the previous table, and the current primary key (just for BV rows that have an SAid)
RDBESdataToSort[[myRequiredTable]][!is.na(RDBESdataToSort[[myRequiredTable]]$SAid),"SortOrder_BV"] <- paste( inner_join(RDBESdataToSort[[myRequiredTable]][!is.na(RDBESdataToSort[[myRequiredTable]]$SAid),],previousHierarchyTable, by =previousPrimaryKey)[,c("SortOrder")], RDBESdataToSort[[myRequiredTable]][!is.na(RDBESdataToSort[[myRequiredTable]]$SAid),currentPrimaryKey], sep = "-")
}
# Rename SortOrder_BV field to SortOrder
names(RDBESdataToSort[[myRequiredTable]])[names(RDBESdataToSort[[myRequiredTable]]) == "SortOrder_BV"] <- "SortOrder"
}
# Else follow the general pattern
else {
previousHierarchyTable <- RDBESdataToSort[[previousRequiredTable]]
## Assume the primary key is the first field
previousPrimaryKey <- names(previousHierarchyTable)[1]
currentPrimaryKey <- names(RDBESdataToSort[[myRequiredTable]])[1]
# Create the value for SortOrder based on the value of SortOrder from the previous table, and the current primary key
RDBESdataToSort[[myRequiredTable]]$SortOrder <- paste( inner_join(RDBESdataToSort[[myRequiredTable]],previousHierarchyTable, by =previousPrimaryKey)[,c("SortOrder")], RDBESdataToSort[[myRequiredTable]][,currentPrimaryKey], sep = "-")
}
# If there's no rows in the table we'll add an emtpy SortOrder column so it definitely exists
} else {
RDBESdataToSort[[myRequiredTable]]$SortOrder <- character(0)
}
}
previousRequiredTable <- myRequiredTable
}
RDBESdataToSort
}
#' saveRDataFilesForCS Saves RData files containing the relevent data frames for a CS upper hierarchy. Each data frame is stored in a seperate RData file. Data is filtered by country and year
#'
#' @param typeOfFile
#' @param yearToUse
#' @param country
#' @param RDBESdata
#' @param RequiredTables
#'
#' @return
#' @export
#'
#' @examples
saveRDataFilesForCS <- function(typeOfFile, yearToUse, country, RDBESdata, RequiredTables){
# Find which tables we need for this file type
upperHierarchy <- substr(typeOfFile,2,nchar(typeOfFile))
requiredTables <- RequiredTables[[typeOfFile]]
## Step 0
# Create the output directory if we need do
ifelse(!dir.exists(file.path(paste0(outputFolder,typeOfFile))), dir.create(file.path(paste0(outputFolder,typeOfFile))), FALSE)
## Step 1 - Filter the data
myCSData <- filterCSData(RDBESdata = RDBESdata , RequiredTables = requiredTables, YearToFilterBy = yearToUse, CountryToFilterBy = country, UpperHierarchyToFilterBy = upperHierarchy)
## Step 2 Save the data
for (myRequiredTable in requiredTables){
frameToSave <- RDBESdata[[myRequiredTable]]
save(frameToSave, file = paste0(outputFolder,typeOfFile,"/",myRequiredTable, ".RData"))
}
}
#' getFieldNameMapping Get a data frame that maps between database names and the shorter R names
#'
#' @param downloadFromGitHub TRUE if you want to download the latest data model spreadsheets from GitHub
#' @param gitHubDirectory (Optional) Default value is "https://api.github.com/repos/ices-tools-dev/RDBES/contents/Documents"
#' @param fileLocation The location you want to save and read the data model spredsheet from
#'
#' @return
#' @export
#'
#' @examples
getFieldNameMapping <- function(downloadFromGitHub= TRUE, gitHubDirectory = "https://api.github.com/repos/ices-tools-dev/RDBES/contents/Documents", fileLocation){
# For testing
#downloadFromGitHub = TRUE
#fileLocation <- './tableDefs/'
#gitHubDirectory <- "https://api.github.com/repos/ices-tools-dev/RDBES/contents/Documents"
if (downloadFromGitHub){
myDataModelFiles <- NULL
myResponse <- GET(gitHubDirectory)
filesOnGitHub <- content(myResponse)
for (myFile in filesOnGitHub){
myGitHubFile <- data.frame(fileName = myFile$name, downloadURL = myFile$download_url)
if (is.null(myDataModelFiles)){
myDataModelFiles <- myGitHubFile
} else {
myDataModelFiles <- rbind(myDataModelFiles,myGitHubFile)
}
}
# Sub-set to the files we are interested in
myDataModelFiles <- myDataModelFiles[grepl('^.*Data Model.*xlsx$',myDataModelFiles$fileName),]
print(paste("Downloading ",nrow(myDataModelFiles), " files from GitHub", sep =""))
# Download our files
for (i in 1:nrow(myDataModelFiles)){
aDataModelFile <- getBinaryURL(myDataModelFiles[i,'downloadURL'])
# save the file locally
myFileConnection = file(paste(fileLocation,myDataModelFiles[i,'fileName'], sep = ""), "wb")
writeBin(aDataModelFile, myFileConnection)
aDataModelFile <- NA
close(myFileConnection)
}
print("Finished downloading")
}
# Now we'll read the spreadsheets
# (Need to find the names of the files again in case we haven't dowloaded them in this function call)
filesToRead <- list.files(path = fileLocation, pattern = "*.xlsx", recursive = FALSE, full.names = FALSE)
dataModel <- list()
# get the contents of each relevent worksheet in our spreadsheets
for (myfile in filesToRead){
myFileLocation <- paste(fileLocation,myfile, sep = "")
myFileSheets <- excel_sheets(myFileLocation)
# CE CL
if (grepl('^.*CL CE.*xlsx$',myfile)){
print("Loading CL CE names")
# Add the sheets to the dataModel list
dataModel[['CE']] <- read_excel(myFileLocation,sheet = myFileSheets[grepl(".*CE.*",myFileSheets)])
dataModel[['CL']] <- read_excel(myFileLocation,sheet = myFileSheets[grepl(".*CL.*",myFileSheets)])
}
# VD SL
else if (grepl('^.*VD SL.*xlsx$',myfile)){
print("Loading VD SL names")
# Add the sheets to the dataModel list
dataModel[['VD']] <- read_excel(myFileLocation,sheet = myFileSheets[grepl(".*Vessel.*",myFileSheets)])
dataModel[['SL']] <- read_excel(myFileLocation,sheet = myFileSheets[grepl(".*Species.*",myFileSheets)])
}
# CS
else if (grepl('^.*CS.xlsx$',myfile)){
#else if (myfile == "RDBES Data Model.xlsx"){
for (aFileSheet in myFileSheets) {
if (!grepl(".*Model.*",aFileSheet)){
print(paste("Loading ", aFileSheet, " names", sep = ""))
myDataModel <- read_excel(myFileLocation,sheet = aFileSheet)
dataModel[[aFileSheet]] <- myDataModel
}
}
}
}
# Put the field names and R names from each entry in the list into a single data frame
myNameMappings <- NULL
for (i in 1:length(dataModel)){
myDataModelEntry <- dataModel[[i]]
validColumnNames <- names(myDataModelEntry)[names(myDataModelEntry) %in% c("Field Name","R Name")]
if (length(validColumnNames == 2)) {
aNameMapping <- myDataModelEntry[,c("Field Name","R Name")]
# Add in the Table Name - based on the first 2 letters of the first entry
if (nrow(aNameMapping)>0) {
tableName <- substr(aNameMapping[1,1],1,2)
} else {
tableName <- NA
}
aNameMapping$TableName <- tableName
myNameMappings <- rbind(myNameMappings,aNameMapping)
} else {
print(paste("Not including ",names(dataModel)[i], " in mapping due to invalid column names",sep=""))
}
}
# Remove any NAs
if (!is.null(myNameMappings)){
myNameMappings <- myNameMappings[!is.na(myNameMappings[,"Field Name"]) & !is.na(myNameMappings[,"R Name"]),]
}
myNameMappings
}