-
Notifications
You must be signed in to change notification settings - Fork 3
/
pumpingtest.R
1936 lines (1934 loc) · 72.5 KB
/
pumpingtest.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
#' pumpingtest: A package for the analysis and evaluation of aquifer tests
#'
#' The pumpingtest package provides functions to analyze and evaluate aquifer tests.
#'
#' The package includes the solution to the most common
#' pumping tests applied in aquifers such as:
#' \itemize{
#' \item Theis and Cooper-Jacob solutions (confined aquifer)
#' \item Hantush-Jacob solution (leaky aquifer)
#' \item Jacob-Lohman solution (artesian confined aquifer)
#' \item Boulton solution (phreatic aquifer)
#' \item Cooper solution (slug tests)
#' \item Agarwal solution (recovery tests)
#' \item Agarwal solution (tests with skin effects)
#' \item General Radial Flow (fractured aquifer)
#' \item Neuzil solution (pulse tests)
#' \item Papadopoulous-Cooper solution (large diameter wells)
#' \item Warren and Root solution (dual porosity aquifer)
#' \item Gringarten solution (single fracture)
#' \item Hvorslev solution (slug tests)
#' \item Bower-Rice solution (slug tests)
#' }
#'
#' The estimation of the hydraulic parameter is achieved by different optimization algorithms
#' including
#' \itemize{
#' \item Nonlinear least squares with the Levenberg-Marquart algorithm (package minpack.lm)
#' \item L-BFGS-B (package optim)
#' \item Simulated Annealing (package GenSA)
#' \item Genetic Algorithms(package GA)
#' \item Particle Swarm Optimization (package PSO)
#' \item Differential Evolution (package DEoptim)
#' \item Estimation of Distribution Algorithm using Copulas (package copulaedas)
#' }
#' with four possible objective functions:
#' \itemize{
#' \item Sum of Squares Residuals
#' \item Mean Absolute Deviation
#' \item Maximum Absolute Deviation
#' \item Maximum Likelihood (under the assumption that the residuals follow a normal distribution).
#' }
#'
#' @section Base functions:
#' The base function includes the contructor of the S3 class pumping_test and associated functions
#' to display summaries, print on the console, create diagnostic and estimation plots with
#' the information from a pumping test, estimate the hydraulic parameters, and predict.
#'
#' The functions in this section are:
#'
#' pumping_test, summary, print, plot, fit, evaluate, simulate, confint
#'
#' @docType package
#' @name pumpingtest
NULL
#' @title
#' pumping_test
#' @description
#' Function to create a pumping_test object
#' @param id a character string defining the Pumping test ID
#' @param Q rate measured at pumping well (m3/s)
#' @param r distance to observation well (m)
#' @param t Numeric vector with the times at which measurements were taken (s)
#' @param s Numeric vector with the measured drawdown (m)
#' @return A pumping_test object
#' @usage pumping_test(id = character(0), Q = 0.0, r = 0.0, t = NULL, s = NULL)
#' @author
#' Oscar Garcia-Cabrejo \email{khaors@gmail.com}
#' @export
#' @family base functions
#' @examples
#' # Define a pumping test
#' tt <- logseq(0, 5, 30)
#' Tr <- 1e-3
#' Ss <- 0.0001
#' r <- 1e3
#' Q <- 1e-3
#' s <- Q/(4*pi*Tr)*theis_well_function(tt)
#' ptest <- pumping_test("Test", Q = Q, r = r, t = tt, s = s)
#' ptest
#' plot(ptest)
pumping_test <- function(id = character(0), Q = 0.0, r = 0.0, t = NULL, s = NULL){
coeffs <- stehfest_coefficients_cpp(8)
nt <- length(t)
ns <- length(s)
nq <- length(Q)
if(nt != ns & nt!=nq){
stop('The t and s/q vectors are not of the same size')
}
if(nt == 1){
stop('t is a vector of a single element')
}
if(ns == 1){
warning('WARNING: s is a vector of a single element. Constant.drawdown test assumed.')
}
#
pos_valid <- t > 1e-12
if(sum(pos_valid) != nt){
warning('WARNING: some t values are less than 1e-12. Removing times and drawdown.')
t <- t[pos_valid]
if(ns > 1){
s <- s[pos_valid]
}
if(nq > 1){
Q <- Q[pos_valid]
}
}
# Define aquifer test type
current.type <- "constant.rate"
if(class(Q) == "data.frame"){
current.type <- "variable.rate"
}
if(class(Q) != "data.frame" & abs(Q) < 1e-12){
current.type <- "slug"
}
if(class(Q) == "numeric" & length(s) == 0){
current.type <- "constant.drawdown"
}
#
test <- list(id = id, Q = Q, r = r, t = t, s = s,
additional_parameters = NULL,
hydraulic_parameters = NULL,
parameters = NULL,
coeffs = coeffs,
model = character(0),
estimated = FALSE,
hydraulic_parameters_names = NULL,
test.type = current.type)
class(test) <- "pumping_test"
invisible(test)
}
#' @title
#' hydraulic.parameters<-
#' @description
#' Function to assign the hydraulic parameters to a pumping_test object
#' @param x A pumping_test object
#' @param value A list or matrix with the hydraulic parameters.
#' @return
#' The pumping_test object with the hydraulic parameters
#' @family base functions
#' @author
#' Oscar Garcia-Cabrejo \email{khaors@gmail.com}
#' @export
#' @examples
#' data(theis)
#' ptest.theis <- pumping_test('Well1', Q = 1.38e-2, r = 250, t = theis$t, s = theis$s)
#' ptest.theis.fit <- fit(ptest.theis, 'theis')
#' hydraulic.parameters(ptest.theis) <- ptest.theis.fit$hydraulic_parameters
`hydraulic.parameters<-` <- function(x, value) {
x$hydraulic_parameters <- value
return(x)
}
#' @title
#' additional.parameters<-
#' @description
#' Function to assign the additional parameters (well radius, aquifer thickness, ) to a
#' pumping_test object
#' @param x A pumping_test object
#' @param value A list with the additional parameters
#' @return
#' The pumping_test object with the additional parameters
#' @author
#' Oscar Garcia-Cabrejo \email{khaors@gmail.com}
#' @family base functions
#' @export
#' @examples
#' data(theis)
`additional.parameters<-` <- function(x, value) {
x$additional_parameters <- value
return(x)
}
#' @title
#' fit.parameters<-
#' @description
#' Function to assign the fit parameters (a, t0 and others depending on the model) to a
#' pumping_test object
#' @param x A pumping_test object
#' @param value A list with the parameters obtained by the fit procedure
#' @return
#' The pumping_test object with the fit parameters
#' @author
#' Oscar Garcia-Cabrejo \email{khaors@gmail.com}
#' @family base functions
#' @export
#' @examples
#' data(theis)
#' ptest.theis <- pumping_test('Well1', Q = 1.38e-2, r = 250, t = theis$t, s = theis$s)
#' ptest.theis.fit <- fit(ptest.theis, 'theis')
#' hydraulic.parameters(ptest.theis) <- ptest.theis.fit$hydraulic_parameters
#' fit.parameters(ptest.theis) <- ptest.theis.fit$parameters
`fit.parameters<-` <- function(x, value) {
x$parameters <- value
return(x)
}
#' @title
#' model<-
#' @description
#' Function to assign the model for estimation to a pumping_test object
#' @param x A pumping_test object
#' @param value Character sting wit the model used in the intepretation
#' @return
#' The pumping_test object with the model assigned
#' @author
#' Oscar Garcia-Cabrejo \email{khaors@gmail.com}
#' @family base functions
#' @export
#' @examples
#' data(theis)
#' ptest.theis <- pumping_test('Well1', Q = 1.38e-2, r = 250, t = theis$t, s = theis$s)
#' ptest.theis.fit <- fit(ptest.theis, 'theis')
#' hydraulic.parameters(ptest.theis) <- ptest.theis.fit$hydraulic_parameters
#' model(ptest.theis) <- 'theis'
`model<-` <- function(x, value) {
x$model <- value
return(x)
}
#' @title
#' estimated<-
#' @description
#' Function to define an intepreted pumping_test object
#' @param x A pumping_test object
#' @param value Logical value
#' @return
#' The pumping_test object with estimated variable set to TRUE
#' @author
#' Oscar Garcia-Cabrejo \email{khaors@gmail.com}
#' @family base functions
#' @export
#' @examples
#' data(theis)
#' ptest.theis <- pumping_test('Well1', Q = 1.38e-2, r = 250, t = theis$t, s = theis$s)
#' ptest.theis.fit <- fit(ptest.theis, 'theis')
#' hydraulic.parameters(ptest.theis) <- ptest.theis.fit$hydraulic_parameters
#' model(ptest.theis) <- 'theis'
#' estimated(ptest.theis) <- TRUE
`estimated<-` <- function(x, value) {
x$estimated <- value
return(x)
}
#' @title
#' hydraulic.parameter.names <-
#' @description
#' Function to assign name of the hydraulic parameters to a pumping_test object. This is
#' useful in plotting results
#' @param x A pumping_test object
#' @param value A list with the names of the hydraulic parameters
#' @return
#' The pumping_test object with the names of the hydraulic parameters
#' @family base functions
#' @author
#' Oscar Garcia-Cabrejo \email{khaors@gmail.com}
#' @export
`hydraulic.parameter.names<-` <- function(x, value) {
x$hydraulic_parameters_names <- value
return(x)
}
#' @title
#' summary.pumping_test
#' @description
#' Function to display a short summary of the drawdown data
#' @param object A pumping_test object
#' @param ... additional parameters for the data.frame summary function
#' @return
#' This function displays on the console a summary of the drawdown data
#' @author
#' Oscar Garcia-Cabrejo \email{khaors@gmail.com}
#' @family base functions
#' @import stringi
#' @export
#' @examples
#' # Define a pumping test
#' tt <- logseq(0, 5, 30)
#' Tr <- 1e-3
#' Ss <- 0.0001
#' r <- 1e3
#' Q <- 1e-3
#' s <- Q/(4*pi*Tr)*theis_well_function(tt)
#' ptest <- pumping_test("Test", Q = Q, r = r, t = tt, s = s)
#' summary(ptest)
summary.pumping_test <- function(object, ...){
ptest <- object
cat('Pumping Test: '%s+%ptest$id%s+%'\n')
cat('Test Type: '%s+%ptest$test.type%s+%'\n')
pdata <- as.data.frame(cbind(ptest$t, ptest$s))
names(pdata) <- c("time","drawdown")
summary(pdata, ...)
}
#' @title
#' print
#' @description
#' Function to print on the screen a pumping_test object
#' @param x A pumping_test object
#' @param ... Additional parameters to the data.frame print function
#' @return
#' This function prints the information from the pumping test on the screen
#' @usage \\method{print}{pumping_test}(x, ...)
#' @author
#' Oscar Garcia-Cabrejo \email{khaors@gmail.com}
#' @family base functions
#' @export
#' @examples
#' # Define a pumping test
#' tt <- logseq(0, 5, 30)
#' Tr <- 1e-3
#' Ss <- 0.0001
#' r <- 1e3
#' Q <- 1e-3
#' s <- Q/(4*pi*Tr)*theis_well_function(tt)
#' ptest <- pumping_test("Test", Q = Q, r = r, t = tt, s = s)
#' print(ptest)
print.pumping_test <- function(x, ...){
ptest <- x
cat('Pumping Test: '%s+%ptest$id%s+%'\n')
cat('Test Type: '%s+%ptest$test.type%s+%'\n')
if(ptest$test.type != "slug"){
if(ptest$test.type == "constant.rate"){
cat('Q = '%s+%ptest$Q%s+%'\n')
}
else if(ptest$test.type == "variable.rate"){
cat("Pumping history\n")
print(ptest$Q)
}
}
cat('r= '%s+%ptest$r%s+%'\n')
pdata <- as.data.frame(cbind(ptest$t, ptest$s))
names(pdata) <- c("time","drawdown")
print(pdata, ...)
}
#' @title
#' plot.pumping_test
#' @description
#' Function to plot the pumping test data. This function can create two different
#' types of plots: diagnostic and estimation. The diagnostic plot includes the
#' drawdown vs time plot and the derivative of drawdown with respect to the log of
#' time. This derivative can help in the identification of the flow regime that
#' occurred when the data was acquired.
#' @param x A pumping_test object
#' @param type Type of plot. Current options include
#' \itemize{
#' \item diagnostic
#' \item estimation
#' \item model.diagnostic
#' \item uncertainty
#' \item mcmc.trace
#' \item mcmc.run_mean
#' \item mcmc.compare
#' \item mcmc.autocorr
#' \item sample.influence
#' }
#' @param d Derivative parameter. If method is bourdet then d is a parameter to specify
#' the number of lags in the derivative. If method is spline then d is the number of points
#' used to calculate the derivative.
#' @param dmethod Method to calculate the derivative (central, horner, bourdet, spline)
#' @param scale Option to define a loglog or semilog diagnostic plot
#' @param y.intersp Numeric value to define the interspacing between lines in the legend
#' @param slug Logical flag to indicate a slug test
#' @param legend Logical flag to indicate if legend is included (only for estimation plot)
#' @param results Logical flag to indicate if the estimation results are going to be included in the estimation plot
#' @param cex character expansion factor relative to current par("cex"). This is a parameter of the plot functions.
#' @param ... Additional parameters for the plot, points and lines functions.
#' @author
#' Oscar Garcia-Cabrejo \email{khaors@gmail.com}
#' @importFrom ggplot2 ggplot geom_point geom_line labs xlab ylab ggtitle aes theme_bw
#' @importFrom ggplot2 scale_x_log10 scale_y_log10 scale_shape_manual scale_color_manual
#' @importFrom dplyr full_join
#' @importFrom stringr str_to_upper str_pad str_length str_c
#' @family base functions
#' @export
#' @examples
#' # Define a pumping test
#' data(theis)
#' ptest <- pumping_test("Test", Q = 1.388e-2, r = 250, t = theis$t, s = theis$s)
#' # Diagnostic plot using default parameters
#' plot(ptest)
#' # Diagnostic plot with Horner derivative
#' plot(ptest, dmethod = 'horner')
#' # Diagnostic plot with Bourdet derivative d = 3
#' plot(ptest, dmethod = 'bourdet', d = 3)
#' # Diagnostic plot with Spline derivative
#' plot(ptest, dmethod = 'spline', d = 20)
#' # Diagnostic plot with semilog scale
#' plot(ptest, scale = 'slog')
#' #estimation Plot
#' ptest.fit <- fit(ptest, "theis")
#' hydraulic.parameters(ptest) <- ptest.fit$hydraulic_parameters
#' fit.parameters(ptest) <- ptest.fit$parameters
#' model(ptest) <- "theis"
#' estimated(ptest) <- TRUE
#' plot(ptest, type = 'estimation', dmethod = "spline", d = 30, results = FALSE)
#' # Model Diagnostic plot
#' plot(ptest, type = 'model.diagnostic')
#' # Uncertainty plot (bootstrap)
#' ptest.confint <- confint(ptest, level = c(0.025, 0.975), method = 'bootstrap', n = 30, neval = 100)
#' hydraulic.parameters(ptest) <- ptest.confint$hydraulic.parameters
#' hydraulic.parameter.names(ptest) <- ptest.confint$hydraulic.parameters.names
#' plot(ptest, type = 'uncertainty')
plot.pumping_test <- function(x, type = c('diagnostic','estimation',
'model.diagnostic', 'uncert',
'mcmc.trace', 'mcmc.run_mean',
'mcmc.compare', 'mcmc.autocorr',
'sample.influence'),
dmethod = 'central', d = 2, scale = 'loglog',
y.intersp = 0.5, slug = FALSE, legend = TRUE,
results = FALSE, cex = 1, ...){
if(class(x) != "pumping_test"){
stop('ERROR: a pumpingtest object is required as input')
}
ptest <- x
size <- cex*2.5
variable <- NULL
shape <- NULL
colors <- NULL
title <- NULL
# create dataframe with all information
t <- ptest$t
s <- ptest$s
ndat <- length(t)
variable1 <- vector('character', length = ndat)
variable1[1:ndat] <- 'Drawdown'
df.drawdown <- data.frame(t= t, s = s, variable = variable1)
# create dataframe with derivative
if(slug){
ds <- log_derivative(t, -s, d = d, method = dmethod)
}
else {
ds <- log_derivative(t, s, d = d, method = dmethod)
}
dt <- ds$x
ds <- ds$y
nder <- length(dt)
variable2 <- vector('character', length = nder)
variable2[1:nder] <- str_c('Derivative(',dmethod,')')
df.derivative <- data.frame(t = dt, s = ds, variable = variable2)
# Join data.frames
suppressWarnings(
ptest.def <- full_join(df.drawdown, df.derivative)
)
#
#print(ptest.def)
# Define title
type <- type[1]
if(type == 'diagnostic'){
if(is.null(title)){
ctitle <- str_c("Diagnostic Plot: ", ptest$id)
}
else {
ctitle <- title
}
}
else if(type == 'estimation'){
if(is.null(title)){
ctitle <- str_c("Estimation Plot: ", ptest$id)
}
else {
ctitle <- title
}
}
#
if(is.null(colors)){
colors <- c('#00BFC4', '#F8766D')
}
#
if(is.null(shape)){
shape <- c(17, 16)
}
#
# Create diagnostic plot
p1 <- NULL
if(type == 'diagnostic'){
p1 <- ggplot(data = ptest.def) + geom_point(aes(x = t, y = s, group = variable,
color = variable,
shape = variable), size = size) +
scale_x_log10()+
labs(title = ctitle) +
xlab("Time(s)") +
ylab("Drawdown(m)") +
scale_shape_manual(values = rev(shape)) +
scale_color_manual(values = rev(colors))
if(scale == 'loglog'){
p1 <- p1 + scale_y_log10()
}
p1 <- p1 + theme_bw()
}
# Create Estimation plot
if(type == 'estimation'){
# Calculate drawdown from hydraulic parameters
if(ptest$estimated){
#tpred <- logseq(from = 0.99*log10(min(ptest$t)), to = 1.01*log10(max(ptest$t)), 100)
ptest.pred <- evaluate(ptest, ptest$model, FALSE, n = 200)
ptest.pred.df <- data.frame(t = ptest.pred$t[1:199],
s = ptest.pred$s[1:199],
variable = "estimation")
dptest.pred.df <- data.frame(t = ptest.pred$t[1:199],
s = ptest.pred$dsdlnt[1:199])
}
else {
stop('ERROR: A estimated hydraulic parameters are required for estimation plot')
}
#
p1 <- ggplot(data = ptest.def) + geom_point(aes(x = t, y = s, group = variable,
color = variable,
shape = variable), size = size) +
scale_x_log10() +
labs(title = ctitle) +
xlab("Time(s)") +
ylab("Drawdown(m)") +
geom_line(aes(x = t, y = s), ptest.pred.df, color = colors[1]) +
geom_line(aes(x = t, y = s), dptest.pred.df, color = colors[2]) +
scale_shape_manual(values = rev(shape)) +
scale_color_manual(values = rev(colors)) +
theme_bw()
if(scale == 'loglog'){
p1 <- p1 + scale_y_log10()
}
p1 <- p1 + theme_bw()
}#Estimation
else if(type == 'model.diagnostic'){
p1 <- plot_model_diagnostic(ptest, cex = cex, ...)
}
else if(type == 'uncertainty'){
p1 <- plot_uncert(ptest)
}
#
return(p1)
}
#' @title
#' plot_model_diagnostic
#' @description
#' Function to plot the residuals of an estimated pumping test
#' @param ptest A pumping_test object. It must be estimated.
#' @param ... Additional parameters to the plot function used in scatter.smooth
#' @author
#' Oscar Garcia-Cabrejo \email{khaors@gmail.com}
#' @family base functions
#' @importFrom stats sd
#' @importFrom ggplot2 ggplot geom_point coord_equal ggtitle geom_smooth geom_qq
#' @importFrom gridExtra arrangeGrob grid.arrange
#' @export
#' @examples
#' data(theis)
#' ptest <- pumping_test("Test", Q = 1.388e-2, r = 250, t = theis$t, s = theis$s)
#' ptest.fit <- fit(ptest, "theis")
#' hydraulic.parameters(ptest) <- ptest.fit$hydraulic_parameters
#' fit.parameters(ptest) <- ptest.fit$parameters
#' model(ptest) <- "theis"
#' estimated(ptest) <- TRUE
#' plot(ptest, type = 'estimation', dmethod = "spline", d = 30)
#' plot_model_diagnostic(ptest)
plot_model_diagnostic <- function(ptest, ...){
if(class(ptest) != 'pumping_test'){
stop('A pumping_test object is required as input')
}
if(!ptest$estimated){
stop('An estimated pumping_test object is required as input')
}
res <- evaluate(ptest, ptest$model)
s.pred <- res$sd
s.residuals <- s.pred - ptest$s
s.std.residuals <- s.residuals/sd(s.residuals)
s.std.residuals1 <- abs(s.residuals) #sqrt(abs(s.std.residuals))
# Define global variables
measured <- NULL
calculated <- NULL
residuals <- NULL
abs.residuals <- NULL
# Plot measured rho vs calculated rho
df1 <- data.frame(measured = ptest$s, calculated = s.pred,
residuals = s.residuals,
abs.residuals = s.std.residuals1)
p1 <- ggplot() + geom_point(aes(x = measured, y = calculated), data = df1,
color = "red") +
coord_equal() +
ggtitle("a) Measured vs Calculated") +
theme_bw()
#
p2 <- ggplot(data = df1, aes(x = calculated, y = residuals)) +
geom_point(color = "red") +
geom_smooth() +
ggtitle("b) Residuals") +
theme_bw()
#
p3 <- ggplot(data = df1, aes(x = calculated, y = abs.residuals)) +
geom_point(color = "red") +
geom_smooth() +
ggtitle("c) Absolute Residuals") +
theme_bw()
#
p4 <- ggplot(data = df1, aes(sample = residuals)) + geom_qq(color = "red") +
ggtitle("d) QQ plot") +
theme_bw()
#
#ptot <- arrangeGrob(p1, p2, p3, p4, ncol = 2)
ptot <- grid.arrange(p1, p2, p3, p4, ncol = 2)
return(ptot)
}
#' @title
#' plot_sample_influence
#' @description
#' Function to create a plot with an influence measure for each sample of the pumping test.
#' This plot is helpful in the identification of the samples that are influential in the
#' estimation of the hydraulic parameters.
#' @param res A list with the results of the jackniffe CI estimation.
#' @param ... Additional parameters to the plot function
#' @return
#' A plot with the influence measure of each sample
#' @author
#' Oscar Garcia-Cabrejo \email{khaors@gmail.com}
#' @family base functions
#' @importFrom grDevices colors
#' @importFrom graphics plot abline lines points legend title text par mtext
#' @export
plot_sample_influence <- function(res, ...){
if(res$method != 'jackniffe'){
stop('ERROR the results of confint_jackniffe are required to create this plot.')
}
par.label.names <- list(Tr = 'Transmissivity(m2/s)',
Ss = 'Storage Coefficient',
radius_influence = 'Radius Influence(m)',
r = 'Distance to well(m)',
Q = 'Discharge(m3/s)',
omegad = 'Drainage Porosity',
cd = 'Wellbore storage',
rho = 'Dimensionless radius',
Ka = 'K aquitard (m/s)',
B = 'Aquitard Thickness(m)',
rw = 'Well radius(m)',
rc = 'Casing radius(m)',
rd = 'Dimensionless radius',
Sxf2 = 'Sxf2',
n = 'n (Flow Dimension)')
label <- c('a', 'b', 'c', 'd', 'e', 'f')
dfbeta <- res$dfbeta
npar <- ncol(dfbeta)
ndat <- nrow(dfbeta)
nrowp <- ceiling(npar/2)
hydr.par.names <- colnames(dfbeta)
#
par0 <- par(no.readonly = TRUE)
par(mfrow=c(nrowp, 2))
pos <- seq(1, nrow(dfbeta), by = 1)
for(ipar in 1:npar){
mx <- max(max(dfbeta[,ipar]), 2.5)
plot(dfbeta[,ipar], type = "p", xlab = "Sample", ylab = "DFBETA",
main = paste0(label[ipar],') ', par.label.names[[hydr.par.names[ipar]]]),
ylim = c(0, mx), ...)
lines(c(1,nrow(dfbeta)),c(2.,2.), lty = 3, col = "red", ...)
pos_influential <- dfbeta[,ipar] > 2
if(sum(pos_influential) > 0){
points(pos[pos_influential], dfbeta[pos_influential,ipar], col = "red",
pch = 7, ...)
}
for(i in 1:ndat){
lines(c(i,i),c(0,dfbeta[i,ipar]), col = "black")
}
}
par(par0)
}
#' @title
#' plot_uncert
#' @description
#' Function to plot the distributions of the confidence intervals estimated using bootstrapp
#' from a model fitted using nonlinear regression.
#' @param ptest A pumping_test object.
#' @param cex Character expansion
#' @param ... Additional parameters for the plot function
#' @importFrom GGally ggpairs
#' @importFrom ggplot2 theme_bw
#' @author
#' Oscar Garcia-Cabrejo \email{khaors@gmail.com}
#' @family base functions
#' @export
plot_uncert <- function(ptest, cex =1, ...){
if(class(ptest) != 'pumping_test'){
stop('A pumping_test object is required as input')
}
#
if(!ptest$estimated){
stop('An estimated pumping_test object is required')
}
#
if(class(ptest$hydraulic_parameters) != 'matrix'){
stop('The values of the hydraulic parameters must be stored in a matrix')
}
#
if(nrow(ptest$hydraulic_parameters) < 30){
stop('There are not enough values of the hydraulic parameters')
}
#
if(is.null(ptest$hydraulic_parameters_names)){
stop('ERROR the names of the hydraulic parameters have not been assigned')
}
#
par.label.names <- list(Tr = 'Transmissivity(m2/s)',
Ss = 'Storage Coefficient',
radius_influence = 'Radius Influence(m)',
r = 'Distance to well(m)',
Q = 'Discharge(m3/s)',
omegad = 'Drainage Porosity',
cd = 'Wellbore storage',
rho = 'Dimensionless radius',
Ka = 'K aquitard (m/s)',
B = 'Aquitard Thickness(m)',
rw = 'Well radius(m)',
rc = 'Casing radius(m)',
rd = 'Dimensionless radius',
Sxf2 = 'Sxf2',
n = 'n (Flow Dimension)')
#
hydr.parameters.names <- ptest$hydraulic_parameters_names
hydr.parameters.names1 <- vector('character', length(hydr.parameters.names))
for(ipar in 1:length(hydr.parameters.names)){
current_par <- hydr.parameters.names[[ipar]]
hydr.parameters.names1[ipar] <- par.label.names[[current_par]]
}
#
hydraulic_parameters.df <- as.data.frame(ptest$hydraulic_parameters)
names(hydraulic_parameters.df) <- hydr.parameters.names1
p1 <- ggpairs(hydraulic_parameters.df,
columnLabels = hydr.parameters.names1) +
theme_bw()
return(p1)
}
#' @title
#' fit
#' @description
#' Generic function to estimate the aquifer parameters from a pumping test. This function uses
#' nonlinear least squares to estimate these parameters.
#' @param ptest A pumping_test object
#' @param model Character string specifying the model used in the estimation
#' @param control.par A list with parameters of the parameter estimation using nonlinear
#' regression
#' @param trace A logical flag indicating if the results of the nonlinear regression are
#' printed on the screen
#' @return
#' A list with the following entries:
#' \itemize{
#' \item hydraulic_parameters: hydraulic parameters of the model (includes transmissivity, storage
#' coefficient and radius of influence)
#' \item paraemters: fitted parameters (includes a and t0)
#' \item resfit: List with the results of the nonlinear regression
#' \item value: Value of the residual sum of squares
#' }
#' @author
#' Oscar Garcia-Cabrejo \email{khaors@gmail.com}
#' @import minpack.lm
#' @importFrom stats as.formula
#' @family base functions
#' @export
#' @examples
#' #Fit test from confined aquifer
#' data(theis)
#' ptest <- pumping_test('Well1', Q = 1.388e-2, r = 250, t = theis$t, s = theis$s)
#' res_th <- fit(ptest, 'theis')
#' print(res_th)
#' #Fit test from confined aquifer
#' res_cj <- fit(ptest, 'cooper_jacob')
fit <- function(ptest, model, control.par, trace = F){
drawdown_curve <- as.data.frame(cbind(ptest$t,ptest$s))
names(drawdown_curve) <- c('t','s')
#print(names(drawdown_curve))
initial_solution_fn <- model%s+%'_solution_initial'
initial_solution <- do.call(initial_solution_fn,list(ptest))
parameters <- names(initial_solution)
#npar <- length(parameters)
#lower <- rep(1e-3, npar)
current_formula <- 's ~ '%s+%model%s+%'_solution(ptest,'
for(ipar in parameters){
current_formula <- current_formula%s+%ipar%s+%','
}
current_formula <- current_formula%s+%'t'%s+%')'
current_formula <- as.formula(current_formula)
#print(current_formula)
Q <- ptest$Q
r <- ptest$r
t <- ptest$t
nprint <- 10
if(missing(control.par)){
if(!trace){
nprint <- 0
}
control.par <- nls.lm.control(ftol = 1e-10,
ptol = 1e-10,
maxiter = 200,
nprint = nprint,
maxfev = 1000)
}
resfit <- nlsLM(current_formula, data = drawdown_curve,
start = initial_solution, trace = trace,
control = control.par) #, lower = lower, upper = rep(Inf,npar)
pars <- resfit$m$getAllPars()
pars <- as.list(pars)
fn <- model%s+%'_calculate_parameters'
args <- list('ptest' = ptest, 'par' = pars)
res <- do.call(fn, args = args)
res1 <- list(hydraulic_parameters = res, parameters = pars, resfit = resfit,
value = resfit$m$deviance())
return(res1)
}
#' @title
#' fit.optimization
#' @description
#' Function to estimate the aquifer parameters from a pumping test using several optimization
#' functions.
#' @param ptest A pumping_test object.
#' @param model A character string specifying the model used in the parameter estimation.
#' @param obj.fn A character string specifying the objective function used in the parameter estimation.
#' Currently the following objective functions are included:
#' \itemize{
#' \item 'rss': Residual sum of squares
#' \item 'mnad': Mean absolute deviation
#' \item 'mxad': Maximum absolute deviation
#' \item 'loglik': Loglikelihood function
#' }
#' @param opt.method A character string specifying the optimization method used in the parameter estimation.
#' Currently the following methologies are included:
#' \itemize{
#' \item 'nls': Nonlinear regression
#' \item 'sa': Simulated Annealing (GenSA package)
#' \item 'ga': Genetic Algorithms (GA package)
#' \item 'l-bfgs-b': using optim function (stats package)
#' \item 'pso': Particle Swarm Optimization (pso package)
#' \item 'copulaedas': Estimation of Distribution Algorithms Based on Copulas (copulaedas package)
#' \item 'de': Differential Evolution (DEoptim package)
#' }
#' @param lower A numeric vector with the lower values of the search region
#' @param upper A numeric vector with the upper values of the search region
#' @param control.par A list with the parameters of the optimization method
#' @param seed A random seed
#' @return
#' A list with the following entries:
#' \itemize{
#' \item hydraulic_parameters: hydraulic parameters of the model (includes transmissivity, storage
#' coefficient and radius of influence, or others)
#' \item parameters: fitted parameters (including a and t0 and other depending on the model)
#' \item resfit: The list or object returned by the optimization driver of each method.
#' \item value: The value of the objective function reached at the end of the optimization run.
#' }
#' @importFrom stats optim
#' @importFrom GenSA GenSA
#' @importFrom GA ga
#' @importFrom pso psoptim
#' @importFrom copulaedas edaRun edaTerminateMaxGen edaReportSimple VEDA
#' @importFrom DEoptim DEoptim DEoptim.control
#' @importFrom methods setMethod
#' @author
#' Oscar Garcia-Cabrejo \email{khaors@gmail.com}
#' @family base functions
#' @export
#' @examples
#' \dontrun{
#' # Define pumping_test object
#' data("boulton")
#' ptest.boulton <- pumping_test("Well1", Q = 0.03, r = 20,
#' t = boulton$t, s = boulton$s)
#' # Parameter estimation using L-BFGS-B
#' ptest.boulton.bfgs.rss <- fit.optimization(ptest.boulton,
#' "boulton", obj.fn = "rss", opt.method = "l-bfgs-b",
#' seed = 54321)
#' # Parameter estimation using Simulated Annealing
#' ptest.boulton.sa.rss <- fit.optimization(ptest.boulton,
#' "boulton", obj.fn = "rss", opt.method = "sa", seed = 54321)
#' # Parameter estimation using Genetic Algorithms
#' ptest.boulton.ga.rss <- fit.optimization(ptest.boulton,
#' "boulton", obj.fn = "rss", opt.method = "ga", seed = 54321)
#' # Parameter estimation using Differential Evolution
#' ptest.boulton.de.rss <- fit.optimization(ptest.boulton,
#' "boulton", obj.fn = "rss", opt.method = "de", seed = 54321)
#' # Parameter estimation using Particle Swarm Optimization
#' ptest.boulton.pso.rss <- fit.optimization(ptest.boulton,
#' "boulton", obj.fn = "rss", opt.method = "pso", seed = 54321)
#' }
fit.optimization <- function(ptest, model, obj.fn = 'rss', opt.method = 'nls',
lower = 1e-9, upper = Inf, control.par, seed = 12345){
if(class(ptest) != 'pumping_test'){
stop('A pumping_test object is required as input')
}
drawdown_curve <- as.data.frame(cbind(ptest$t,ptest$s))
names(drawdown_curve) <- c('t','s')
# Determine initial solution using the corresponding function for each model
initial_solution_fn <- paste(model, '_solution_initial', sep = '')
initial_solution <- do.call(initial_solution_fn,list(ptest))
parameters <- names(initial_solution)
par <- as.numeric(initial_solution)
# Initialize results list
res1 <- list()
# Set Random seed
set.seed(seed)
# Add the sigma parameter for loglikelihood estimation
if(obj.fn == 'loglik' | obj.fn == 'loglik-bc'){
par[(length(par)+1)] <- 0.1
}
# Define lower and upper limits of the search region
if(missing(lower)){
lower <- 1e-3*par
}
if(missing(upper)){
upper <- 20.0*par
}
#print(c(obj.fn, opt.method))
#res1 <- list()
# Check optimization methods for loglikelihood estimation
if(opt.method == 'nls' & obj.fn == 'loglik' |
opt.method == 'nls' & obj.fn == 'loglik-bc'){
stop('LogLikelihood function cannot be minimized with nls')
}
# Define the corresponding objective functions
par.obj.fn <- NULL
if(obj.fn == 'rss'){
if(opt.method == 'ga'){
par.obj.fn <- function(par, ptest, model){-1*residual_sum_squares(par, ptest, model) }
}
else if(opt.method == 'copulaedas'){
par.obj.fn1 <- function(par){
residual_sum_squares(par, ptest, model)
}
}
else{
par.obj.fn = residual_sum_squares
}
}
else if(obj.fn == 'loglik'){
if(opt.method == 'ga' ){
par.obj.fn <- loglikelihood
}
else if(opt.method == 'copulaedas'){
par.obj.fn1 <- function(par){
-1*loglikelihood(par, ptest, model)
}
}
else{
par.obj.fn <- function(par, ptest, model){ -1* loglikelihood(par, ptest, model)}
}
}
else if(obj.fn == 'loglik-bc'){
if(opt.method == 'ga'){
par.obj.fn <- loglikelihood_bc
}
else if(opt.method == 'copulaedas'){
par.obj.fn1 <- function(par){
-1*loglikelihood_bc(par, ptest, model)
}
}
else{
par.obj.fn <- function(par, ptest, model){ -1* loglikelihood_bc(par, ptest, model)}
}
}
else if(obj.fn == 'mnad'){
if(opt.method == 'ga'){
par.obj.fn <- function(par, ptest, model){-1*mean_absolute_deviation(par, ptest, model)}
}
else if(opt.method == 'copulaedas'){
par.obj.fn1 <- function(par){
mean_absolute_deviation(par, ptest, model)
}
}
else{
par.obj.fn <- mean_absolute_deviation
}
}
else if(obj.fn == 'mxad'){
if(opt.method == 'ga'){
par.obj.fn <- function(par, ptest, model){-1*max_absolute_deviation(par, ptest, model)}
}
else if(opt.method == 'copulaedas'){
par.obj.fn1 <- function(par){
max_absolute_deviation(par, ptest, model)
}
}
else{
par.obj.fn <- max_absolute_deviation
}
}
#
if(opt.method == 'nls' & obj.fn == 'rss'){
current_formula <- paste('s ~ ', model, '_solution(ptest,', sep = '')
for(ipar in parameters){
current_formula <- paste(current_formula, ipar, ',', sep = '')
}
current_formula <- paste(current_formula, 't', ')', sep = '')
current_formula <- as.formula(current_formula)
#print(current_formula)
Q <- ptest$Q
r <- ptest$r
t <- ptest$t
if(missing(control.par)){
control.par <- nls.lm.control(ftol = 1e-10,
ptol = 1e-10,
maxiter = 200,
nprint = 0,
maxfev = 1000)
}
resfit <- nlsLM(current_formula, data = drawdown_curve,
start = initial_solution, trace = F,
control = control.par )
pars <- resfit$m$getAllPars()
pars <- as.list(pars)
fn <- paste(model, '_calculate_parameters', sep = '')
args <- list('ptest' = ptest, 'par' = pars)
res <- do.call(fn, args = args)
current_par <- pars