forked from lawaFreshwater/WQualityStateTrend
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlawa_state_functions.R
1890 lines (1638 loc) · 76.9 KB
/
lawa_state_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
#===================================================================================================
# LAWA STATE ANALYSIS
# FUNCTION LIBRARY
# Horizons Regional Council
#
# 2-December-2013
#
# Purpose: Water Quality State Analysis Service Definition
#
# Processing of council water quality monitoring data for the LAWNZ website
# has been completed by Horizons council staff between 2011 and 2013. To
# reduce the dependancy on council staff and to increase transparency to
# all participants, this script file has been prepared to automate the STATE
# assessment portion of LAWA's State and Trend Analysis.
#
# To make the data collation component of this script as flexible as possible,
# proprietary file formats or RDBMS systems are not used. Instead, data is
# accessed using standards-based requests to Council time series servers that
# deliver WaterML 2.0 XML files. WaterML 2.0 is an Open Geospatial Consortium
# standard that encodes water data time series into an XML file. These data
# can be accessed using standard XML libraries provided by many programming
# languages.
#
# Maree Clark
# Sean Hodges
# Horizons Regional Council
#===================================================================================================
#/* -===Load required libraries=== */
#
# These libraries will need to be installed within R first, otherwise
# the script will error and stop. The first couple of lines do the install
# if the libraries are not detected.
# */
pkgs <- c('XML', 'RCurl','ggplot2','gridExtra','plyr','reshape2','RODBC','doBy','NADA','gdata','survival','lubridate','tidyr','dplyr','EnvStats')
if(!all(pkgs %in% installed.packages()[, 'Package']))
install.packages(pkgs, dep = T)
require(XML) # XML library
require(RCurl) # managing, parsing URL calls and responses
require(reshape2) # melt, cast, ...
require(ggplot2) # pretty plots ...
require(gridExtra)
require(plyr)
require(RODBC) # Database connectivity
require(doBy)
require(NADA)
require(gdata)
require(survival)
require(lubridate)
require(tidyr)
require(dplyr)
require(EnvStats) # Library from EPA with seasonal kendall
#===================================================================================================
#/* -===Pseudo-Function prototypes===-
# A list of the required functions for this routine
# Rather than taking a linear approach to scripting, a number of
# functions will be defined to do key tasks with the STATE analysis
# script
#*/
#// SiteTable <- function(){}
#// requestData <- function(vendor,tss_url,request){}
#// SiteList <- function(xmlsdata){}
#// MeasurementList <- function(xmlmdata,requestType){}
#// StateAnalysis <- function(df,type,level){}
#// StateScore <- function(df,scope,altitude,landuse,wqparam,comparison)
#// calcScore <- function(df1,df2,wqparam)
#===================================================================================================
#/* -===Function definitions===- */
# dataCleanse <- function(df,args){}
# Create yearMon variable to order data yyyy-mm
# Count results by Site and parameter for each date
# Count less thans for each Site and parameter
# Count each less than value for each site and parameter combo
# Remove greater thans for each site and parameter
# Review results
SiteTable <- function(databasePathFileName,sqlID){
# Creating connection to hilltop database containing lawa site table
# Creates a lockfile on the access mdb
# conn <- odbcConnectAccess("g:/projects/LAWNZ/RC_DATA/LAWNZ_WQ.mdb")
#databasePathFileName<-"//ares/waterquality/LAWA/2013/hilltop.mdb"
# If you run a 64bit Windows env, you may need to install the
# Access Database engine in order to get this to work
if(Sys.getenv("R_ARCH")=="/i386"){ #32bit Environment R_ARCH=="/i386"
conn <- odbcConnectAccess(databasePathFileName)
} else if(Sys.getenv("R_ARCH")=="/x64"){ #64bit Environment R_ARCH=="/x64"
dbtxt <- paste("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=",databasePathFileName,sep="")
conn <- odbcDriverConnect(dbtxt,readOnlyOptimize = FALSE)
}
sql <- c("SELECT Lawnz-Sites].* FROM [Lawnz-Sites]",
"SELECT [NationalSiteTable].* FROM [NationalSiteTable]",
"SELECT [NationalSiteView].* FROM [NationalSiteView] WHERE [NationalSiteView].[UsedInLAWA] = TRUE AND [NationalSiteView].[Site_Type] like '%SoE%'")
#sqlID=3
# ' // Creating query and extracting dataset to LAWNZ data.frame
LAWASites <- sqlQuery(conn, sql[sqlID])
names(LAWASites) <- make.names(names(LAWASites))
# ' // Closing connnection to hilltop database containing lawa site table
# ' // Removes lock file on Access mdb
close(conn)
# removing variable "conn"
rm(conn)
return(LAWASites)
}
readUrl <- function(vendor,tss_url,request){
out <- tryCatch(
{
# Just to highlight: if you want to use more than one
# R expression in the "try" part then you'll have to
# use curly brackets.
# 'tryCatch()' will return the last evaluated expression
# in case the "try" part was completed successfully
message("Attempting data retrieval")
if(vendor=="HILLTOP"){
url <- paste(tss_url,request,sep="")
#cat(url,'\n')
}
xmlInternalTreeParse(url)
#readLines(con=url, warn=FALSE)
# The return value of `readLines()` is the actual value
# that will be returned in case there is no condition
# (e.g. warning or error).
# You don't need to state the return value via `return()` as code
# in the "try" part is not wrapped insided a function (unlike that
# for the condition handlers for warnings and error below)
},
error=function(cond) {
message(paste("URL returning empty document:", url))
message("Trying again ...")
xmldata <- xmlInternalTreeParse(url)
#message("Here's the original error message:")
#message(cond)
# Choose a return value in case of error
return(xmldata)
},
warning=function(cond) {
message(paste("URL caused a warning:", url))
message("Here's the original warning message:")
message(cond)
# Choose a return value in case of warning
},
finally={
# NOTE:
# Here goes everything that should be executed at the end,
# regardless of success or error.
# If you want more than one expression to be executed, then you
# need to wrap them in curly brackets ({...}); otherwise you could
# just have written 'finally=<expression>'
message(paste("Processed URL:", url))
#message("Some other message at the end")
}
)
return(out)
}
requestData <- function(vendor,tss_url,request){
if(vendor=="HILLTOP"){
url <- paste(tss_url,request,sep="")
cat(url,'\n')
xmldata <- xmlInternalTreeParse(url)
} else if(vendor=="KISTERS"){
} else if(vendor=="52NORTH"){
}
return(xmldata)
}
SiteList <- function(xmlsdata){
# GETTING SITES WITH LOCATION DATA ONLY
#site.attr<-getNodeSet(xmlsdata,"//Latitude/../@Name")
#site.list<-sapply(site.attr, as.character)
#data.lat <- sapply(getNodeSet(getSites.xml, "//HilltopServer/Site/Latitude"), xmlValue)
#data.lon <- sapply(getNodeSet(getSites.xml, "//HilltopServer/Site/Longitude"), xmlValue)
#ds<-data.frame(site.list,data.lat,data.lon, stringsAsFactors=FALSE)
# GETTING ALL SITES WITHOUT LOCATION DATA
sites<-sapply(getNodeSet(xmlsdata,"//Site/@Name"),as.character)
sites <- gsub("''","'",sites) # replacing the double apostrophe's generated by parsing the XML with single '.
return(sites)
}
MeasurementList <- function(xmlmdata,requestType){
if(requestType=="SOS"){
DateTime <- sapply(getNodeSet(doc=xmlmdata, path="//wml2:point/wml2:MeasurementTVP/wml2:time"), xmlValue)
value <- as.numeric(sapply(getNodeSet(doc=xmlmdata, path="//wml2:point/wml2:MeasurementTVP/wml2:value"), xmlValue))
} else if(requestType=="Hilltop"){
#DateTime <- sapply(getNodeSet(doc=xmlmdata, path="//Data/E/T"), xmlValue)
#value <- as.numeric(sapply(getNodeSet(doc=xmlmdata, path="//Data/E/Value"), xmlValue))
#site.attr<-getNodeSet(doc=xmlmdata,path="//T/ancestor::Measurement/@SiteName")
#site.list<-sapply(site.attr, as.character)
a<-getNodeSet(xmlmdata, path="//Measurement")
for(i in 1:length(a)){
myPath<-paste("//Measurement[",i,"]",sep="")
c<-getNodeSet(xmlmdata, path=myPath)
s<-sapply(c,function(el) xmlGetAttr(el, "SiteName"))
c<-getNodeSet(xmlmdata, path=paste(myPath,"/Data/E/T"))
d<-xmlSApply(c, xmlValue)
c<-getNodeSet(xmlmdata, path=paste(myPath,"/Data/E/Value"))
# need to represent this data as a character vector before converting to a numeric vector
# in order to account for '<' and other value qualifiers. Will deal with these in another
# function call
v<-xmlSApply(c, xmlValue)
#v<-as.numeric(xmlSApply(c, xmlValue))
s <- rep(s,length(v))
# Get method description
myPath<-paste("//Measurement[",i,"]/Data/E/Parameter[@Name='Method']",sep="")
f<-getNodeSet(xmlmdata, path=myPath)
g<-sapply(f,function(el) xmlGetAttr(el, "Value"))
if(length(f)==0){
g <- rep("",length(v))
tmp <- data.frame(as.POSIXct(strptime(d,format="%Y-%m-%dT%H:%M:%S")), g,stringsAsFactors=FALSE)
names(tmp)<-c("Date","Method")
} else {
# Get dates related to method description
myPath<-paste("//Measurement[",i,"]/Data/E/Parameter[@Name='Method']/../T",sep="")
h<-getNodeSet(xmlmdata, path=myPath)
k<-xmlSApply(h, xmlValue)
tmp <- data.frame(as.POSIXct(strptime(k,format="%Y-%m-%dT%H:%M:%S")), g,stringsAsFactors=FALSE)
names(tmp)<-c("Date","Method")
}
if(i==1){
df<-data.frame(s,as.POSIXct(strptime(d,format="%Y-%m-%dT%H:%M:%S")),v, stringsAsFactors=TRUE)
names(df) <- c("Site","Date","Value")
df <- merge(df, tmp,by.x="Date",by.y="Date", all.x=TRUE)
} else {
df1<-data.frame(s,as.POSIXct(strptime(d,format="%Y-%m-%dT%H:%M:%S")),v, stringsAsFactors=TRUE)
names(df1) <- c("Site","Date","Value")
df1 <- merge(df1, tmp,by.x="Date",by.y="Date", all.x=TRUE)
df<-rbind(df,df1)
}
}
}
#df <- data.frame(as.POSIXct(strptime(DateTime,format="%Y-%m-%dT%H:%M:%S")),value,stringsAsFactors=FALSE)
names(df) <- c("Date","SiteName","Value","Method")
df$SiteName <- gsub("''","'",df$SiteName) # replacing the double apostrophe's generated by parsing the XML with single '.
df<-df[,c(2,1,3,4)]
return(df)
}
qualifiedValues <- function(df){
df$qualifier <- substr(df$Value,start=1,stop=1)
df$v <-ifelse(df$qualifier=="<",as.numeric(as.character(substr(df$Value,2,length(df$Value)-1)))/2,as.numeric(as.character(df$Value)))
df$value <- df$Value
df$Value <- df$v
df$v <- NULL
df$qualifier <- NULL
df$value <- NULL
return(df)
}
qualifiedValues2 <- function(df){
df$ROS <- df$Value # If no reason to apply ROS, just return values
df$i1Values <- df$Value # If no reason to apply ROS, just return values
df$i1Values[df$CenType=="Left"] <- (df$Value[df$CenType=="Left"])/2
return(df)
}
StateAnalysis <- function(df,type,level){
# df = dataframe
# type = Site, Catchment, Region, NZ
# level = LandUseAltitude,Landuse,Altitude,None
# ' // =================================================================
# ' // =================================================================
# ' // summaryBy .... Calculating medians for all sites.
# ' // =================================================================
# ' // The summaryBy command allows selected summary statistics to be generated
# ' // for selected variables across various factors
# ' // The output of summaryBy is a data.frame with site medians,
# ' // with the grouping variables of landuse, altitude, catchment and local
# ' // local authority name. This data.frame forms the basis for calculating
# ' // State for each site, based on the median of the last sampled values
# ' // s = sitemedians
dfs <- summaryBy(Value~SiteName+LAWAID+parameter,
id=~LanduseGroup+AltitudeGroup+Catchment+Region+Frequency,
data=df,
FUN=c(quantile), probs=c(0.5), type=5, na.rm=TRUE, keep.name=TRUE)
# ==============================================================
# Test number of samples by Site/parameter
# ==============================================================
# Added 8-Oct-2015
#
# Exclusion criteria
# - less than 30 samples for monthly
# - less than 80 percent of samples for bimonthly/quarterly
# ========================
# Add Sample Counts to dfs
# ========================
# This summaryBy call is identical to the one above, except that it asks for the number of
# samples by group, instead of the median.
# Both function calls return data.frames of the same length with records in the same order.
# As a consequence, the Count field can be joined directly to the data.frame with medians
# with bothering with a merge().
dfs_count <- summaryBy(Value~SiteName+LAWAID+parameter,
id=~LanduseGroup+AltitudeGroup+Catchment+Region+Frequency,
data=wqdata,
FUN=c(length))
# Renaming Value.Length field
c<-names(dfs_count)
c[4]<-"Count"
names(dfs_count) <- c
dfs$Count <- dfs_count$Count
rm(dfs_count)
# ========================
# Identifying rows meeting exclusion criteria
dfs$Exclude<-FALSE
dfs$Exclude[dfs$Frequency=="Monthly" & dfs$Count<30] <- TRUE
dfs$Exclude[dfs$Frequency=="Bimonthly" & dfs$Count<(0.8*6*5)] <- TRUE
dfs$Exclude[dfs$Frequency=="Quarterly" & dfs$Count<(0.8*4*5)] <- TRUE
# ========================
# Filtering data.frame to remove rows meeting exclusion criteria
dfs<-dfs[dfs$Exclude==FALSE,1:9]
# ==============================================================
if(type=="Site"){
if(level=="LandUseAltitude"){
s <- summaryBy(Value~AltitudeGroup+LanduseGroup+Region+Catchment+SiteName+LAWAID+parameter,
data=dfs,
FUN=c(quantile), type=5, na.rm=TRUE, keep.name=TRUE)
t <- summaryBy(Value~AltitudeGroup+LanduseGroup+Region+Catchment+SiteName+LAWAID+parameter,
data=dfs,
FUN=c(length), keep.name=TRUE)
s$Value<-t$Value
}
s$scope <- type
} else if(type=="Catchment"){
if(level=="LandUseAltitude"){
s <- summaryBy(Value~AltitudeGroup+LanduseGroup+Region+Catchment+parameter,
id=~SiteName+LAWAID,
data=dfs,
FUN=c(quantile),na.rm=TRUE, keep.name=TRUE)
t <- summaryBy(Value~AltitudeGroup+LanduseGroup+Region+Catchment+parameter,
id=~SiteName+LAWAID,
data=dfs,
FUN=c(length), keep.name=TRUE)
s$Value<-t$Value
s$SiteName <- "All"
s$LAWAID <- "All"
} else if(level=="LandUse"){
s <- summaryBy(Value~LanduseGroup+Region+Catchment+parameter,
id=~SiteName+LAWAID+AltitudeGroup,
data=dfs,
FUN=c(quantile),na.rm=TRUE, keep.name=TRUE)
t <- summaryBy(Value~LanduseGroup+Region+Catchment+parameter,
id=~SiteName+LAWAID+AltitudeGroup,
data=dfs,
FUN=c(length), keep.name=TRUE)
s$Value<-t$Value
s$AltitudeGroup <- "All"
s$SiteName <- "All"
s$LAWAID <- "All"
} else if(level=="Altitude"){
s <- summaryBy(Value~AltitudeGroup+Region+Catchment+parameter,
id=~SiteName+LAWAID+LanduseGroup,
data=dfs,
FUN=c(quantile),na.rm=TRUE, keep.name=TRUE)
t <- summaryBy(Value~AltitudeGroup+Region+Catchment+parameter,
id=~SiteName+LAWAID+LanduseGroup,
data=dfs,
FUN=c(length), keep.name=TRUE)
s$Value<-t$Value
s$LanduseGroup <- "All"
s$SiteName <- "All"
s$LAWAID <- "All"
} else if(level=="None"){
s <- summaryBy(Value~Region+Catchment+parameter,
id=~SiteName+LAWAID+AltitudeGroup+LanduseGroup,
data=dfs,
FUN=c(quantile),na.rm=TRUE, keep.name=TRUE)
t <- summaryBy(Value~Region+Catchment+parameter,
id=~SiteName+LAWAID+AltitudeGroup+LanduseGroup,
data=dfs,
FUN=c(length), keep.name=TRUE)
s$Value<-t$Value
s$LanduseGroup <- "All"
s$AltitudeGroup <- "All"
s$SiteName <- "All"
s$LAWAID <- "All"
}
s$scope <- type
} else if(type=="Region"){
if(level=="LandUseAltitude"){
s <- summaryBy(Value~AltitudeGroup+LanduseGroup+Region+parameter,
id=~Catchment+SiteName+LAWAID,
data=dfs,
FUN=c(quantile),na.rm=TRUE, keep.name=TRUE)
t <- summaryBy(Value~AltitudeGroup+LanduseGroup+Region+parameter,
id=~Catchment+SiteName+LAWAID,
data=dfs,
FUN=c(length), keep.name=TRUE)
s$Value<-t$Value
s$SiteName <- "All"
s$LAWAID <- "All"
s$Catchment <- "All"
} else if(level=="LandUse"){
s <- summaryBy(Value~LanduseGroup+Region+parameter,
id=~Catchment+SiteName+LAWAID+AltitudeGroup,
data=dfs,
FUN=c(quantile), type=5, na.rm=TRUE, keep.name=TRUE)
t <- summaryBy(Value~LanduseGroup+Region+parameter,
id=~Catchment+SiteName+LAWAID+AltitudeGroup,
data=dfs,
FUN=c(length), keep.name=TRUE)
s$Value<-t$Value
s$AltitudeGroup <- "All"
s$SiteName <- "All"
s$LAWAID <- "All"
s$Catchment <- "All"
} else if(level=="Altitude"){
s <- summaryBy(Value~AltitudeGroup+Region+parameter,
id=~Catchment+SiteName+LAWAID+LanduseGroup,
data=dfs,
FUN=c(quantile),na.rm=TRUE, keep.name=TRUE)
t <- summaryBy(Value~AltitudeGroup+Region+parameter,
id=~Catchment+SiteName+LAWAID+LanduseGroup,
data=dfs,
FUN=c(length), keep.name=TRUE)
s$Value<-t$Value
s$LanduseGroup <- "All"
s$SiteName <- "All"
s$LAWAID <- "All"
s$Catchment <- "All"
} else if(level=="None"){
s <- summaryBy(Value~Region+parameter,
id=~Catchment+SiteName+LAWAID+LanduseGroup,
data=dfs,
FUN=c(quantile), type=5, na.rm=TRUE, keep.name=TRUE)
t <- summaryBy(Value~Region+parameter,
id=~Catchment+SiteName+LAWAID+LanduseGroup,
data=dfs,
FUN=c(length), keep.name=TRUE)
s$Value<-t$Value
s$AltitudeGroup <- "All"
s$LanduseGroup <- "All"
s$SiteName <- "All"
s$LAWAID <- "All"
s$Catchment <- "All"
}
s$scope <- type
} else if(type=="NZ"){
if(level=="LandUseAltitude"){
s <- summaryBy(Value~AltitudeGroup+LanduseGroup+parameter,
id=~Region+Catchment+SiteName+LAWAID,
data=dfs,
FUN=c(quantile),na.rm=TRUE, keep.name=TRUE)
t <- summaryBy(Value~AltitudeGroup+LanduseGroup+parameter,
id=~Region+Catchment+SiteName+LAWAID,
data=dfs,
FUN=c(length), keep.name=TRUE)
s$Value<-t$Value
s$SiteName <- "All"
s$LAWAID <- "All"
s$Catchment <- "All"
s$Region <-"All"
} else if(level=="LandUse"){
s <- summaryBy(Value~LanduseGroup+parameter,
id=~Region+Catchment+SiteName+LAWAID+AltitudeGroup,
data=dfs,
FUN=c(quantile),na.rm=TRUE, keep.name=TRUE)
t <- summaryBy(Value~LanduseGroup+parameter,
id=~Region+Catchment+SiteName+LAWAID+AltitudeGroup,
data=dfs,
FUN=c(length), keep.name=TRUE)
s$Value<-t$Value
s$AltitudeGroup <- "All"
s$SiteName <- "All"
s$LAWAID <- "All"
s$Catchment <- "All"
s$Region <-"All"
} else if(level=="Altitude"){
s <- summaryBy(Value~AltitudeGroup+parameter,
id=~Region+Catchment+SiteName+LAWAID+LanduseGroup,
data=dfs,
FUN=c(quantile),na.rm=TRUE, keep.name=TRUE)
t <- summaryBy(Value~AltitudeGroup+parameter,
id=~Region+Catchment+SiteName+LAWAID+LanduseGroup,
data=dfs,
FUN=c(length), keep.name=TRUE)
s$Value<-t$Value
s$LanduseGroup <- "All"
s$SiteName <- "All"
s$LAWAID <- "All"
s$Catchment <- "All"
s$Region <-"All"
} else if(level=="None"){
s <- summaryBy(Value~parameter,
id=~Region+Catchment+SiteName+LAWAID+LanduseGroup+AltitudeGroup,
data=dfs,
FUN=c(quantile),na.rm=TRUE, keep.name=TRUE)
t <- summaryBy(Value~parameter,
id=~Region+Catchment+SiteName+LAWAID+LanduseGroup+AltitudeGroup,
data=dfs,
FUN=c(length), keep.name=TRUE)
s$Value<-t$Value
s$LanduseGroup <- "All"
s$AltitudeGroup <- "All"
s$SiteName <- "All"
s$LAWAID <- "All"
s$Catchment <- "All"
s$Region <-"All"
}
s$scope <- type
}
return(s)
}
StateScore <- function(df,scope,altitude,landuse,wqparam,comparison){
# df <- sa
# scope <- scope[i]
# altitude <- ""
# landuse <- ""
# wqparam
# comparison <- 1
# ' // In assigning state scores, the routine needs to process each combination of altitude
# ' // and landuse and compare to the National levels for the same combinations.
# ' // These combinations are:
# ' // NZ scale data set - no factors
# ' // Each site (all altitude and landuses) compared to overall National medians
# ' // Single factor comparisons
# ' // Each upland site (all landuses) compared to upland National medians
# ' // Each lowland site (all landuses) compared to lowland National medians
# ' // Each rural site (all altitudes) compared to rural National medians
# ' // Each forest site (all altitudes) compared to forest National medians
# ' // Each urban site (all altitudes) compared to urban National medians
# ' // Multiple factor comparisons
# ' // For each Landuse
# ' // Each upland site compared to upland National medians
# ' // Each lowland site compared to lowland National medians
# ' // For each Altitude
# ' // Each rural site compared to rural National medians
# ' // Each forest site compared to forest National medians
# ' // Each urban site compared to urban National medians
# ' // Then repeat for catchment and region.
# scope = "NZ", "Region", "Catchment", "Site"
# scope = "NZ" is used for comparison, so only Region, Catchment and Site feed through.
# comparision = 1,2,3,4
# 1 = All - AltitudeGroup=="All" & LanduseGroup=="All" & Scope=="NZ"
# 2 = Altitude - AltitudeGroup==altitude & LanduseGroup=="All" & Scope=="NZ"
# 3 = Land use - AltitudeGroup=="All" & LanduseGroup==landuse & Scope=="NZ"
# 4 = Altitude & Land use - AltitudeGroup==altitude & LanduseGroup==landuse & Scope=="NZ"
# -=== WQ PARAMETERS ===-
for(i in 1:length(wqparam)){
# set a comparison enum_type 1,2,3,4 - make this a function argument to specify which
# comparison to undertake.
# Region|All, Catchment|All, Site|All
if(comparison==1){
# df_scope represents the results for a specific scope : Site, Catchment, Region
df_scope <- subset(df, Scope==scope & Parameter==wqparam[i])
df_scope$StateGroup<- paste(scope,"All",sep="|")
# df_baseline represents the dataset against which site results will be compared and
# assigned a state score
df_baseline <- subset(df, AltitudeGroup=="All" & LanduseGroup=="All" & Scope=="NZ" & Parameter==wqparam[i])
# Region|Upland, Catchment|Upland, Site|Upland Region|Lowland, Catchment|Lowland, Site|Lowland
} else if(comparison==2){
df_scope <- subset(df, Scope==scope & AltitudeGroup==altitude & Parameter==wqparam[i])
df_scope$StateGroup<- paste(scope,altitude,sep="|")
# df_baseline represents the dataset against which site results will be compared and
# assigned a state score
df_baseline <- subset(df, AltitudeGroup==altitude & LanduseGroup=="All" & Scope=="NZ" & Parameter==wqparam[i])
# Region|Forest, Catchment|Forest, Site|Forest Region|Rural, Catchment|Rural, Site|Rural Region|Urban, Catchment|Urban, Site|Urban
} else if(comparison==3){
df_scope <- subset(df, Scope==scope & LanduseGroup==landuse & Parameter==wqparam[i])
df_scope$StateGroup<- paste(scope,landuse,sep="|")
# df_baseline represents the dataset against which site results will be compared and
# assigned a state score
df_baseline <- subset(df, AltitudeGroup=="All" & LanduseGroup==landuse & Scope=="NZ" & Parameter==wqparam[i])
}
# Region|Upland|Forest, Catchment|Upland|Forest, Site|Upland|Forest Region|Upland|Rural, Catchment|Upland|Rural, Site|Upland|Rural Region|Upland|Urban, Catchment|Upland|Urban, Site|Upland|Urban
# Region|Lowland|Forest, Catchment|Lowland|Forest, Site|Lowland|Forest Region|Lowland|Rural, Catchment|Lowland|Rural, Site|Lowland|Rural Region|Lowland|Urban, Catchment|Lowland|Urban, Site|Lowland|Urban
else if(comparison==4){
df_scope <- subset(df, Scope==scope & AltitudeGroup==altitude & LanduseGroup==landuse & Parameter==wqparam[i])
if(length(df_scope[,1])!=0){ # Testing for zero records returned - allows for zero Upland - Urban combination during testing.
df_scope$StateGroup<- paste(scope,altitude,landuse,sep="|")
# df_baseline represents the dataset against which site results will be compared and
# assigned a state score
df_baseline <- subset(df, AltitudeGroup==altitude & LanduseGroup==landuse & Scope=="NZ" & Parameter==wqparam[i])
}
}
if(i==1){
state<-calcScore(df_scope,df_baseline,wqparam[i])
} else {
state<-rbind(state, calcScore(df_scope,df_baseline,wqparam[i]))
}
}
return(state)
}
calcScore <- function(df1,df2,wqparam){
df1 <- na.omit(df1)
df2 <- na.omit(df2)
for(i in 1:length(df1[,1]))
if(wqparam=="BDISC"){
if(df1$Q50[i]<=df2$Q25){
df1$LAWAState[i] <- 4
} else if(df1$Q50[i]>df2$Q25 & df1$Q50[i]<df2$Q50){
df1$LAWAState[i] <- 3
} else if(df1$Q50[i]>=df2$Q50 & df1$Q50[i]<df2$Q75){
df1$LAWAState[i] <- 2
} else if(df1$Q50[i]>=df2$Q75){
df1$LAWAState[i] <- 1
}
} else if(wqparam=="PH"){
if(df1$Q50[i]<=df2$Q25){
df1$LAWAState[i] <- 2
} else if(df1$Q50[i]>df2$Q25 & df1$Q50[i]<df2$Q50){
df1$LAWAState[i] <- 1
} else if(df1$Q50[i]>=df2$Q50 & df1$Q50[i]<df2$Q75){
df1$LAWAState[i] <- 1
} else if(df1$Q50[i]>=df2$Q75){
df1$LAWAState[i] <- 2
}
} else {
if(df1$Q50[i]<=df2$Q25){
df1$LAWAState[i] <- 1
} else if(df1$Q50[i]>df2$Q25 & df1$Q50[i]<df2$Q50){
df1$LAWAState[i] <- 2
} else if(df1$Q50[i]>=df2$Q50 & df1$Q50[i]<df2$Q75){
df1$LAWAState[i] <- 3
} else if(df1$Q50[i]>=df2$Q75){
df1$LAWAState[i] <- 4
}
}
return(df1)
}
calcTrendScore <- function(df1,trendMethod="ci"){
if(trendMethod=="sig"){
x<-calcTrendScore.sig(df1)
} else if(trendMethod=="ci"){
x<-calcTrendScore.ci(df1)
}
return(x)
}
calcTrendScore.sig <- function(df1){
#names(seasonalkendall) <- c("LAWAID","Parameter","Sen.Pct","Sen.Slope","p.value")
#trendscores <- calcTrendScore(seasonalkendall)
df1 <- na.omit(df1)
for(i in 1:length(df1[,1])){
if(df1$Parameter[i]=="BDISC"){
if(df1$p.value[i]<0.05){
if(df1$Sen.Pct[i]<=-1){
df1$TrendScore[i] <- -2
} else if(df1$Sen.Pct[i]>=1){
df1$TrendScore[i] <- 2
} else {
df1$TrendScore[i] <- sign(df1$Sen.Pct[i])*1
}
} else{
df1$TrendScore[i] <- 0
}
} else {
if(df1$p.value[i]<0.05){
if(df1$Sen.Pct[i]<=-1){
df1$TrendScore[i] <- 2
} else if(df1$Sen.Pct[i]>=1){
df1$TrendScore[i] <- -2
} else {
df1$TrendScore[i] <- sign(df1$Sen.Pct[i])*-1
}
} else{
df1$TrendScore[i] <- 0
}
}
}
return(df1)
}
calcTrendScore.ci <- function(df1){
#names(seasonalkendall) <- c("LAWAID","Parameter","Sen.Pct","Sen.Slope","p.value")
#trendscores <- calcTrendScore(seasonalkendall)
df1 <- na.omit(df1)
# Step 1
# Start by setting trend score to 0
df1$TrendScore <- 0
# Step 2
# Assessment of existance of slope based on Confidence limits
df1$zeroLocationCL90 <- FALSE ## Set initial state for zero outside 90pct CI bounds
df1$zeroLocationCL90[df1$Sen.Slope.LCL90<0&seasonalkendall$Sen.Slope.UCL90>0] <- TRUE
df1$TrendScore[!df1$zeroLocationCL90] <- 1
# Step 3
# Applying direction of slope to TrendScore
df1$TrendScore[df1$Parameter=="BDISC"&df1$Sen.Slope<0] <- df1$TrendScore[df1$Parameter=="BDISC"&df1$Sen.Slope<0]*-1
df1$TrendScore[df1$Parameter!="BDISC"&df1$Sen.Slope>0] <- df1$TrendScore[df1$Parameter!="BDISC"&df1$Sen.Slope>0]*-1
return(df1)
}
calcTrendScoreAggregate <- function(df1,trendMethod="ci"){
if(trendMethod=="sig"){
x<-calcTrendScoreAggregate.sig(df1)
} else if(trendMethod=="ci"){
x<-calcTrendScoreAggregate.ci(df1)
}
return(x)
}
calcTrendScoreAggregate.sig <- function(df1){
#names(seasonalkendall) <- c("LAWAID","Parameter","Sen.Pct","Sen.Slope","p.value")
#trendscores <- calcTrendScore(seasonalkendall)
for(i in 1:length(df1[,1])){
if(df1$Parameter[i]=="BDISC"){
if(df1$p.flag[i]>=0.5){
if(df1$Sen.Pct[i]<=-1){
df1$TrendScore[i] <- -2
} else if(df1$Sen.Pct[i]>=1){
df1$TrendScore[i] <- 2
} else {
df1$TrendScore[i] <- sign(df1$Sen.Pct[i])*1
}
} else{
df1$TrendScore[i] <- 0
}
} else {
if(df1$p.flag[i]>=0.5){
if(df1$Sen.Pct[i]<=-1){
df1$TrendScore[i] <- 2
} else if(df1$Sen.Pct[i]>=1){
df1$TrendScore[i] <- -2
} else {
df1$TrendScore[i] <- sign(df1$Sen.Pct[i])*-1
}
} else{
df1$TrendScore[i] <- 0
}
}
}
return(df1)
}
calcTrendScoreAggregate.ci <- function(df1){
df1$TrendScoreAgg <- 0
df1$TrendScoreAgg[df1$Direction>0] <- 1
df1$TrendScoreAgg[df1$Direction<0] <- -1
return(df1)
}
PlotSites1 <- function(df,label){
pdf("test.pdf", width=21, height=27.8)
n <- 1
plot = list()
for(i in unique(df$LAWAID)){
#
dfSite<-subset(df, df$LAWAID==i)
print(i)
# par() # view current settings
# opar <- par() # make a copy of current settings
# par(mfrow=c(1,1)) # Specifying 1 graphs to plot on one page
# par(oma=c(2,2,2,2)) # outer margin area = 2 lines all the way around
# par(mar=c(4,4,0.5,0.5)) # reducing whitespace between multiple graphs
# ' // Plotting a graph
# plot(df$Date, df$Value,
# xlab="",
# ylab=label,
# pch=20, col="black"
# )
# lines(df$Date, df$Value,
# type="l",
# col="black"
# )
# dev.off()
# par(opar) # restore original settings
plot[[n]] <- ggplot(dfSite, aes(Date,Value)) + geom_bar(stat="identity")
if(n %% 8 == 0) {
print (do.call(grid.arrange, plot))
plot<-list()
n<-0
}
# Create a simple timeseries plot for given time period
h <- ggplot(dfSite, aes(Date,Value))
p <- h + geom_bar(stat="identity")
n <- n + 1
}
if(length(plot) != 0){
print(do.call(grid.arrange, plot))
}
dev.off()
return()
}
PlotSites <- function(df,label){
# Create a simple timeseries plot for given time period
p <- ggplot(df, aes(Date,Value)) + geom_bar(stat="identity")
plots <- dlply(df, "LAWAID", '%+%', el=p)
ml <- do.call(marrangeGrob, c(plots, list(nrow=8, ncol=1)))
ggsave("multipage.pdf",ml)
return()
}
sk <- function(lawa_ids,freqNum,freqText,df,rate,years,months){
k <- 1 # counter for sites/parameters meeting minimum N
for(i in 1:length(lawa_ids)){
months<-freqNum
l <- lawa_ids[i]
df1 <- subset(df, LAWAID==l)
parameters <- as.character(unique(df1$parameter))
# this step is to double check output with TimeTrends
#Uncomment if needed
#write.csv(df_value_monthly1,file=paste("c:/data/MWR_2013/2013/ES-00022.csv",sep=""))
lawa <- wqData(data=df1,locus=c(3,5,15),c(2,4),site.order=TRUE,time.format="%Y-%m-%d",type="long")
x <- tsMake(object=lawa,focus=gsub("-",".",l))
cat("length(parameters)",length(parameters),"\n")
cat(parameters,"\n")
# calculating seasonal Kendall statistics for individual parameters for an individual site
for(j in 1:length(parameters)){
# exclude sites/parameters where period of record is insufficient
if(length(subset(df1,parameter==parameters[j])[,1])>=rate*(years*months)){
s<-seaKen(x[,j])
#s$sen.slope.pct # <---- required for LAWA
#s$sen.slope # <----
#s$p.value # <---- required for LAWA
m <-matrix(data=c(l,parameters[j],s$sen.slope.pct,s$sen.slope,s$p.value),nrow=1,ncol=5,byrow=TRUE)
if(k==1){ # removed i==i condition - causing errors where first site doesn't meet criteria for trend analysis
seasonalkendall <-as.data.frame(m,stringsAsFactors=FALSE)
cat("seasonalkendal dataframe created\n")
} else {
seasonalkendall <- rbind(seasonalkendall, as.data.frame(m,stringsAsFactors=FALSE))
cat("Appending to seasonalkendall dataframe\n")
}
k <- k + 1
}
}
}
names(seasonalkendall) <- c("LAWAID","Parameter","Sen.Pct","Sen.Slope","p.value")
seasonalkendall$Sen.Pct <-as.numeric(as.character(seasonalkendall$Sen.Pct))
seasonalkendall$Sen.Slope <-as.numeric(as.character(seasonalkendall$Sen.Slope))
seasonalkendall$p.value <-as.numeric(as.character(seasonalkendall$p.value))
seasonalkendall$freq<- freqText
return(seasonalkendall)
}
seaKenLAWA <- function (x,stat) {
if (!is(x, "ts"))
stop("x must be a 'ts'")
fr <- frequency(x)
S <- 0
varS <- 0
miss <- NULL
slopes <- NULL
for (m in 1:fr) {
xm <- x[cycle(x) == m]
tm <- time(x)[cycle(x) == m]
ken <- mannKen(ts(xm, start = start(x)[1], frequency = 1))
S <- S + ken$S
varS <- varS + ken$varS
miss <- c(miss, ken$miss)
outr <- outer(xm, xm, "-")/outer(tm, tm, "-")
slopes.m <- outr[lower.tri(outr)]
slopes <- c(slopes, slopes.m)
}
sen.slope <- median(slopes, na.rm = TRUE)
if(stat=="mean"){
sen.slope.pct <- 100 * sen.slope/abs(mean(x, na.rm = TRUE))
} else if (stat=="median"){
sen.slope.pct <- 100 * sen.slope/abs(median(x, na.rm = TRUE))
}
Z <- (S - sign(S))/sqrt(varS)
p.value <- 2 * pnorm(-abs(Z))
names(miss) <- as.character(1:m)
list(sen.slope = sen.slope, sen.slope.pct = sen.slope.pct,
p.value = p.value, miss = round(miss, 3))
}
seaKenEPA <- function(x,stat="median"){