forked from lawaFreshwater/WQualityStateTrend
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlawa_trend_only_x_yrs.R
338 lines (251 loc) · 12.9 KB
/
lawa_trend_only_x_yrs.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
#===================================================================================================
# LAWA TREND ANALYSIS
# Horizons Regional Council
#
# 27 March 2018
#
# Sean Hodges
# Horizons Regional Council
#===================================================================================================
rm(list = ls())
TRENDPERIOD <- 5 # years
# Clearing workspace
ANALYSIS<-"TREND"
# Set working directory
od <- getwd()
wd <- "//file/herman/R/OA/08/02/2017/Water Quality/R/lawa_state"
setwd(wd)
x <- Sys.time()
#Reference Dates
EndYear <- 2016
StartYear <- EndYear - TRENDPERIOD + 1
#/* -===Include required function libraries===- */
source("scripts/WQualityStateTrend/lawa_state_functions.R")
# DATA CLEANSE #
#Calculating the Long term LAWA Trends in water quality.
#Reference Dates
#StartYear <- Set at start of script
#EndYear <- Set at start of script
years <- EndYear - StartYear + 1
StartMonth <- 1
EndMonth <- 12
if(years==5){
rate<-1
} else{
rate<-0.9
}
load(file=paste("//file/herman/R/OA/08/02/2017/Water Quality/ROutput/trenddata",StartYear,"-",EndYear,".RData",sep=""))
###################################################################################
#Step 0 Data Summary
###################################################################################
#a " Ensure one value per sampling interval
#b " Calculate the number of samples per sampling interval and select/calculate/
# determine representative values
lawadata <- samplesByInterval(StartYear,EndYear,StartMonth,EndMonth,lawadata)
#drop sites with no LAWA ID
lawadata <- lawadata[!is.na(lawadata$LAWAID),]
df_count <- summaryBy(Value~SiteName+parameter+yearMon,data=lawadata, FUN=c(length), keep.name=TRUE)
multipleResultsByMonth <- subset(df_count,Value>1)
# ---- DOCUMENTATION ----
# Values are now derived for the three sampling frequencies.
# Medians are derived, rather than nearest values. The original
# justification was the number of samples that Councils would
# deliver in their data for a month - SOE samples were not
# necessarily separated out from other project data. A decision
# was made early on to simply take a median. That decision has
# not been reviewed, but should have been, in the light of
# of the progressive improvements in data supply.
## Default median calculation
df_value_monthly <- subset(summaryBy(Value~SiteName+parameter+yearMon,data=lawadata,
id=~LAWAID+LanduseGroup+AltitudeGroup+Catchment+Region+Frequency+year+mon+bimon+Qtr+depth,
FUN=c(quantile), prob=c(0.5), type=5, keep.name=TRUE),Frequency=="Monthly")
## A slightly less fraught method is to use Aggregate() to return first value in each group
df_value_quarterly <- aggregate(lawadata, list(lawadata$SiteName,
lawadata$parameter,
lawadata$yearQtr), FUN=head, 1)
df_value_quarterly <- df_value_quarterly[,c(4,8,40,6,16,20,19,29,23,22,34,35,37,39,33)] # matching columns to what's generated by summaryBy above.
###################################################################################
#require(wq)
#======================================================
#SEASONAL KENDALL ANALYSIS
#======================================================
t <- Sys.time()
######################################################################################################
# Seasonal Kendall for Monthly Sampling for each site, by each parameter
# Returning unique LAWAIDs for processing data subsets
#lawa_ids <- as.character(unique(df_value_monthly$LAWAID))
uLAWAID <- unique(df_value_monthly$LAWAID)
months<-12 # Monthly data
monthLbl <- "Monthly"
k <- 1 # counter for sites/parameters meeting minimum N
rbindTrendCheck<-FALSE # Flagging condition for rbinding dataframe that keeps track of sites, measurements and checks for trend inclusion
for(i in 1:length(uLAWAID)){
# Store current LAWAID
l <- uLAWAID[i]
# Store vector of unique parameters for current LAWAID
uWQParam <- unique(df_value_monthly$parameter[df_value_monthly$LAWAID==l])
# calculating seasonal Kendall statistics for individual parameters for an individual site
for(j in 1:length(uWQParam)){
# subsetting dataframe based on lawaid and parameter
x <- df_value_monthly[df_value_monthly$LAWAID==l&df_value_monthly$parameter==uWQParam[j],]
### TREND INCLUSION CRITERIA
# 1. Count samples in the first or last 12 month periods to compare to entry criteria for trend
first_year<-length(x$year[x$year==StartYear])
last__year<-length(x$year[x$year==EndYear])
# 2. Count samples in order to compare to entry criteria for trend
num_samples <- length(x[,1])
# building dataframe to report out data to assess pass-fails for trend inclusion
v <- matrix(data=c(l,uWQParam[j],first_year,last__year,num_samples),nrow=1,ncol=5,byrow=TRUE)
if(!rbindTrendCheck){
validDataForTrend <-as.data.frame(v,stringsAsFactors=FALSE)
rbindTrendCheck<-TRUE
} else {
validDataForTrend <- rbind(validDataForTrend, as.data.frame(v,stringsAsFactors=FALSE))
}
# Check Trend Criteria - Assess pass-fail for trends analysis
PassTrendCriteria <- TrendCriteria(first_year, last__year, num_samples, rate, years, months, monthMultiplier = 1)
# Processing Trends for sites/parameters pass trend criteria
if(PassTrendCriteria){
s <- seaKenEPA(x)
m <-data.frame(l,
uWQParam[j],
s$sen.slope.pct,
s$sen.slope,
s$p.value,
s$sen.z,
s$sen.z.prob,
s$slope.lcl90,
s$slope.ucl90,
stringsAsFactors = FALSE)
if(k==1){
seasonalkendall <- m
#cat("seasonalkendal dataframe created\n")
} else {
seasonalkendall <- rbind(seasonalkendall, m)
#cat("Appending to seasonalkendall dataframe\n")
}
rm(s,m)
k <- k + 1
}
}
}
names(seasonalkendall) <- c("LAWAID",
"Parameter",
"Sen.Pct",
"Sen.Slope",
"p.value",
"sen.z",
"sen.z.prob",
"Sen.Slope.LCL90",
"Sen.Slope.UCL90")
seasonalkendall$freq<- monthLbl
trendscores <- calcTrendScore(seasonalkendall)
names(validDataForTrend) <- c("LAWAID","Parameter","N.Months.StartYear","N.Months.EndYear","Num.Samples")
validDataForTrend$freq<- monthLbl
load(file="//file/herman/R/OA/08/02/2017/Water Quality/ROutput/lawa_sitetable.RData")
# Fields have been renamed from WFS feed to match what the code is
# expecting, as code originally written expecting data from Hilltop Site Table.
newFieldNames <- c("X","LAWAID","ID", "CouncilSiteID", "UsedInLAWA","AltitudeGroup","LanduseGroup","FrequencyAll","Frequency",
"Region","Agency","ISLAND","CatchID","CatchType",
"NZREACH","Catchment","Comments","LawaCatchm")
names(l) <- newFieldNames
trends <- merge(trendscores, l, by.x="LAWAID",by.y="LAWAID",all.x=TRUE) # Using LAWAIDs to join tables
rm(seasonalkendall)
write.csv(trends,file=paste("//file/herman/R/OA/08/02/2017/Water Quality/ROutput/trend_monthly_",StartYear,"-",EndYear,".csv",sep=""))
write.csv(validDataForTrend,file=paste("//file/herman/R/OA/08/02/2017/Water Quality/ROutput/validDataForTrend_monthly_",StartYear,"-",EndYear,".csv",sep=""))
cat("LAWA Water QUality Trend Analysis\nCompleted assigning Trend Results for Monthly Data\n")
cat(paste(k,"Sites/Parameter combinations meet 90 percent sampling occasion requirements\n"))
rm(trends,validDataForTrend)
######################################################################################################
# Seasonal Kendall for Quarterly Sampling for each site, by each parameter
# Returning unique LAWAIDs for processing data subsets
#lawa_ids <- as.character(unique(df_value_monthly$LAWAID))
uLAWAID <- unique(df_value_quarterly$LAWAID)
months<-4 # Quarterly data
monthLbl <- "Quarterly"
k <- 1 # counter for sites/parameters meeting minimum N
rbindTrendCheck<-FALSE # Flagging condition for rbinding dataframe that keeps track of sites, measurements and checks for trend inclusion
for(i in 1:length(uLAWAID)){
# Store current LAWAID
l <- uLAWAID[i]
# Store vector of unique parameters for current LAWAID
uWQParam <- unique(df_value_quarterly$parameter[df_value_quarterly$LAWAID==l])
# calculating seasonal Kendall statistics for individual parameters for an individual site
for(j in 1:length(uWQParam)){
# subsetting dataframe based on lawaid and parameter
x <- df_value_quarterly[df_value_quarterly$LAWAID==l&df_value_quarterly$parameter==uWQParam[j],]
### TREND INCLUSION CRITERIA
# 1. Count samples in the first or last 12 month periods to compare to entry criteria for trend
first_year<-length(x$year[x$year==StartYear])
last__year<-length(x$year[x$year==EndYear])
# 2. Count samples in order to compare to entry criteria for trend
num_samples <- length(x[,1])
# building dataframe to report out data to assess pass-fails for trend inclusion
v <- matrix(data=c(l,uWQParam[j],first_year,last__year,num_samples),nrow=1,ncol=5,byrow=TRUE)
if(!rbindTrendCheck){
validDataForTrend <-as.data.frame(v,stringsAsFactors=FALSE)
rbindTrendCheck<-TRUE
} else {
validDataForTrend <- rbind(validDataForTrend, as.data.frame(v,stringsAsFactors=FALSE))
}
# Check Trend Criteria - Assess pass-fail for trends analysis
PassTrendCriteria <- TrendCriteria(first_year, last__year, num_samples, rate, years, months, monthMultiplier = 1)
# Processing Trends for sites/parameters pass trend criteria
if(PassTrendCriteria){
s <- seaKenEPA(x)
m <-data.frame(l,
uWQParam[j],
s$sen.slope.pct,
s$sen.slope,
s$p.value,
s$sen.z,
s$sen.z.prob,
s$slope.lcl90,
s$slope.ucl90,
stringsAsFactors = FALSE)
if(k==1){
seasonalkendall <- m
#cat("seasonalkendal dataframe created\n")
} else {
seasonalkendall <- rbind(seasonalkendall, m)
#cat("Appending to seasonalkendall dataframe\n")
}
rm(s,m)
k <- k + 1
}
}
}
names(seasonalkendall) <- c("LAWAID",
"Parameter",
"Sen.Pct",
"Sen.Slope",
"p.value",
"sen.z",
"sen.z.prob",
"Sen.Slope.LCL90",
"Sen.Slope.UCL90")
seasonalkendall$freq<- monthLbl
trendscores <- calcTrendScore(seasonalkendall)
names(validDataForTrend) <- c("LAWAID","Parameter","N.Months.StartYear","N.Months.EndYear","Num.Samples")
validDataForTrend$freq<- monthLbl
rm(m)
load(file="//file/herman/R/OA/08/02/2017/Water Quality/ROutput/lawa_sitetable.RData")
# Fields have been renamed from WFS feed to match what the code is
# expecting, as code originally written expecting data from Hilltop Site Table.
#newFieldNames <- c("X","LAWAID","ID", "UsedInLAWA","AltitudeGroup","LanduseGroupAll","LanduseGroup","FrequencyAll","Frequency",
# "Region","Agency","ISLAND","CatchID","CatchType",
# "NZREACH","Catchment","Comments","LawaCatchm")
newFieldNames <- c("X","LAWAID","ID", "CouncilSiteID", "UsedInLAWA","AltitudeGroup","LanduseGroup","FrequencyAll","Frequency",
"Region","Agency","ISLAND","CatchID","CatchType",
"NZREACH","Catchment","Comments","LawaCatchm")
names(l) <- newFieldNames
trends <- merge(trendscores, l, by.x="LAWAID",by.y="LAWAID",all.x=TRUE) # Using LAWAIDs to join tables
rm(seasonalkendall)
write.csv(trends,file=paste("//file/herman/R/OA/08/02/2017/Water Quality/ROutput/trend_quarterly_",StartYear,"-",EndYear,".csv",sep=""))
write.csv(validDataForTrend,file=paste("//file/herman/R/OA/08/02/2017/Water Quality/ROutput/validDataForTrend_quarterly_",StartYear,"-",EndYear,".csv",sep=""))
cat("LAWA Water QUality Trend Analysis\nCompleted assigning Trend Results for Quarterly Data\n")
cat(paste(k,"Sites/Parameter combinations meet 90 percent sampling occasion requirements\n"))
rm(trends,validDataForTrend)
######################################################################################################
print(Sys.time()-t)
setwd(od)