-
Notifications
You must be signed in to change notification settings - Fork 0
/
macrounchained.r
4906 lines (3791 loc) · 165 KB
/
macrounchained.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
# +--------------------------------------------------------+
# | Package: See 'Package' in file ../DESCRIPTION |
# | Author: Julien MOEYS |
# | Language: R |
# | Contact: See 'Maintainer' in file ../DESCRIPTION |
# | License: See 'License' in file ../DESCRIPTION |
# | and file ../LICENSE |
# +--------------------------------------------------------+
# .onAttach ================================================
#'@importFrom utils packageVersion
NULL
.onAttach <- function(# Internal. Message displayed when loading the package.
libname,
pkgname
){
# .rml_testDateFormat()
# .rml_testDecimalSymbol()
# Welcome message
if( interactive() ){
gitRevision <- system.file( "REVISION", package = pkgname )
if( gitRevision != "" ){
gitRevision <- readLines( con = gitRevision )[ 1L ]
gitRevision <- strsplit( x = gitRevision, split = " ",
fixed = TRUE )[[ 1L ]][ 1L ]
gitRevision <- sprintf( "(git revision: %s)", gitRevision )
}else{
gitRevision <- "(git revision: ?)"
}
msg <- sprintf(
"%s %s %s. For help type: help(pack='%s')",
pkgname,
as.character( utils::packageVersion( pkgname ) ),
gitRevision,
pkgname )
packageStartupMessage( msg )
}
}
# .muc_internals ===========================================
# Environment that will be used to pass information from
# generic functions to methods or from higher level functions
# to lower level functions.
.muc_internals <- new.env()
# .muc_logMessage ==========================================
.muc_justify_text <- function(
txt,
log_width = 60L,
indent = " "
){
txt <- strsplit( x = txt, split = " " )[[ 1L ]]
txt[ txt == "" ] <- " "
txt_nchar <- nchar( txt )
output <- vector( length = length(txt), mode = "list" )
current_row <- 1L
for( i in 1:length(txt) ){
if( is.null( output[[ current_row ]] ) ){
output[[ current_row ]] <- txt[ i ]
}else{
tmp <- paste( output[[ current_row ]], txt[ i ],
sep = ifelse( test = txt[ i ] == " ",
yes = "", no = " " ) )
if( nchar( tmp ) < log_width ){
output[[ current_row ]] <- tmp
}else{
current_row <- current_row + 1L
output[[ current_row ]] <- paste(
indent, txt[ i ], sep = "" )
}
}
}
row_not_null <- !unlist( lapply( X = output,
FUN = is.null ) )
output <- output[ row_not_null ]
output <- paste( unlist( output ), collapse = "\n" )
return( output )
}
# test_txt <- c(
# "<1905-01-01_23:13:59> alpha beta gamma delta epsilon zeta eta theta.",
# "theta eta zeta epsilon delta gamma beta alpha.",
# "alpha beta gamma delta epsilon zeta eta theta.",
# "theta eta zeta epsilon delta gamma beta alpha.",
# "alpha beta gamma delta epsilon zeta eta theta." )
# test_txt <- paste( test_txt, collapse = " " )
# message( .muc_justify_text( txt = test_txt, log_width = 30L ) )
.muc_text_to_files <- function(text,logfiles,append){
n_logfiles <- length( logfiles )
if( n_logfiles != 0 ){
if( (length( append ) == 1L) & (n_logfiles > 1L) ){
append <- rep( append, times = n_logfiles )
}
silence <- lapply(
X = 1:n_logfiles,
FUN = function(i){
con <- file(
description = logfiles[ i ],
open = ifelse(
test = append[ i ],
yes = "at",
no = "wt" ),
encoding = "UTF-8" )
on.exit( close( con ) )
writeLines( text = text, con = con,
sep = "\n" )
} )
}
}
#'@importFrom utils flush.console
NULL
## # Send one or several information message(s) about work progresses
## #
## # Send one or several information message(s) about work progresses.
## # Wrapper around \code{message(sprintf())}, with an additional
## # information about message time and date.
## #
## #
## # @param m
## # See \code{fmt} in \code{\link[base]{sprintf}}. Message
## # to be displayed whenever \code{verbose} is >= 1.
## #
## # @param verbose
## # See \code{verbose} in \code{\link[rrmacrolite]{rmlPar}}.
## #
## # @param \dots
## # See \code{\link[base]{sprintf}}.
## #
## # @return
## # Does not return anything. Output messages
## #
## #
## # @rdname .muc_logMessage
## #
#'@importFrom rmacrolite getRmlPar
.muc_logMessage <- function(
m,
# fmt2 = NULL,
verbose = 1L,
fun = message,
# infix = "",
frame = NULL,
log_width = getRmlPar("log_width"),
values = NULL, # a list
logfiles = NULL,
append = rep(FALSE,length(logfiles))
){
if( verbose >= 1L ){
frame_not_null <- !is.null(frame)
if( frame_not_null ){
frame0 <- rep( x = substr( frame, 1L, 1L ),
times = log_width )
frame0 <- paste( frame0, collapse = "" )
.muc_text_to_files( text = frame0, logfiles = logfiles,
append = append )
fun( frame0 )
}
if( !is.null( values ) ){
m <- do.call( what = "sprintf",
args = c( list( "fmt" = paste( "<%s>", m, sep = " " ),
format( Sys.time(), "%Y-%m-%d|%H:%M:%S" ) ),
values ) )
}else{
m <- sprintf( paste( "<%s>", m, sep = " " ), format(
Sys.time(), "%Y-%m-%d|%H:%M:%S" ) )
}
# fun( sprintf( paste( "<%s>", m ), Sys.time(), ... ) )
m <- .muc_justify_text( txt = m, log_width = log_width )
.muc_text_to_files( text = m, logfiles = logfiles,
append = append )
fun( m )
if( frame_not_null ){
.muc_text_to_files( text = frame0, logfiles = logfiles,
append = append )
fun( frame0 )
}
utils::flush.console()
}
}
# .muc_logMessage( m = "Hello" )
# .muc_logMessage( m = "Hello %s", values = list( "you" ) )
# .muc_logMessage( m = "Hello %s", values = list( "you" ), infix = " " )
# .muc_logMessage( m = "Hello %s", values = list( "you" ), frame = "*+" )
# .muc_print ===============================================
#'@importFrom utils capture.output
.muc_print_to_files <- function(x,logfiles,append,...){
n_logfiles <- length( logfiles )
if( n_logfiles != 0 ){
if( (length( append ) == 1L) & (n_logfiles > 1L) ){
append <- rep( append, times = n_logfiles )
}
dotdotdot <- list(...)
silence <- lapply(
X = 1:n_logfiles,
FUN = function(i){
con <- file(
description = logfiles[ i ],
open = ifelse(
test = append[ i ],
yes = "at",
no = "wt" ),
encoding = "UTF-8" )
on.exit( close( con ) )
capture.output(
# do.call( what = "print", args = c( list( x = x, dotdotdot ) ) ),
print( x = x, ... ),
file = con,
type = "output",
split = FALSE )
} )
}
}
#'@importFrom utils flush.console
#'@importFrom rmacrolite getRmlPar
.muc_print <- function(
x,
verbose = 1L,
log_width = getRmlPar("log_width"),
logfiles = NULL,
append = rep(FALSE,length(logfiles)),
...
){
if( verbose >= 1L ){
old_width <- options( "width" )[[1L]]
on.exit( options( "width" = old_width ) )
options( "width" = log_width )
# Print to console
print( x = x, ... )
# Print to logfiles
.muc_print_to_files( x = x, logfiles = logfiles,
append = append )
options( "width" = old_width )
on.exit( NULL )
utils::flush.console()
}
}
# .muc_justify_path ========================================
.muc_justify_path <- function(
txt,
split = "/",
log_width = 60L,
sep = " "
){
txt <- strsplit( x = txt, split = split, fixed = TRUE )[[ 1L ]]
txt_nchar <- nchar( txt )
output <- vector( length = length(txt), mode = "list" )
current_row <- 1L
for( i in 1:length(txt) ){
if( is.null( output[[ current_row ]] ) ){
output[[ current_row ]] <- txt[ i ]
}else{
tmp <- paste( output[[ current_row ]], txt[ i ],
sep = split )
if( nchar( tmp ) < log_width ){
output[[ current_row ]] <- tmp
}else{
current_row <- current_row + 1L
output[[ current_row ]] <- paste(
sep, txt[ i ], sep = "" )
}
}
}
row_not_null <- !unlist( lapply( X = output,
FUN = is.null ) )
output <- output[ row_not_null ]
output <- paste( unlist( output ),
collapse = sprintf( "%s", split ) )
return( output )
}
# .muc_anonymisePath =======================================
### remove user name and user profile from a path,
### in order to preserve the user anonymity.
### To be used together with .muc_logMessage(),
### or with sprintf( output )
.muc_anonymisePath <- function(
path,
anonymise = TRUE,
x2 = FALSE,
winslash = "/",
log_width = 60L,
sep = " "
){
# Normalise the path
path <- unlist( lapply(
X = path,
FUN = function(p){
if( !is.na( p ) ){
p <- normalizePath( path = p, mustWork = FALSE,
winslash = winslash )
}
if( anonymise ){
# Fetch user name, profile and home path
user_profile <- Sys.getenv( "USERPROFILE",
unset = NA_character_ )
home_path <- Sys.getenv( "HOMEPATH",
unset = NA_character_ )
user_name <- Sys.getenv( "USERNAME",
unset = NA_character_ )
if( !is.na( user_profile ) ){
user_profile <- normalizePath(
path = user_profile,
mustWork = FALSE,
winslash = winslash )
p <- gsub(
pattern = user_profile,
replacement = ifelse( x2, "%%USERPROFILE%%",
"%USERPROFILE%" ),
x = p,
# ignore.case = TRUE,
fixed = TRUE )
}
if( !is.na( home_path ) ){
home_path <- normalizePath(
path = home_path,
mustWork = FALSE,
winslash = winslash )
p <- gsub(
pattern = home_path,
replacement = ifelse( x2, "%%HOMEPATH%%",
"%HOMEPATH%" ),
x = p,
# ignore.case = TRUE,
fixed = TRUE )
}
if( !is.na( user_name ) ){
user_name <- normalizePath(
path = user_name,
mustWork = FALSE,
winslash = winslash )
p <- gsub(
pattern = user_name,
replacement = ifelse( x2, "%%USERNAME%%",
"%USERNAME%" ),
x = p,
# ignore.case = TRUE,
fixed = TRUE )
}
}
p <- .muc_justify_path(
txt = p,
split = winslash,
log_width = log_width,
sep = sep )
return( p )
}
) )
return( path )
}
# .muc_vbar_to_numeric =====================================
.muc_vbar_to_numeric <- function( x ){
if( any( c( "list", "AsIs" ) %in% class( x ) ) ){
test_x <- unlist( lapply( X = x, FUN = is.character ) )
if( !all( test_x ) ){
stop( "Some items in 'x' are not character-class" )
}
x <- lapply(
X = x,
FUN = function(y){
out0 <- strsplit(
x = y,
split = "|",
fixed = TRUE )[[ 1L ]]
return( as.numeric( out0 ) )
}
)
x <- I( x )
}else if( all( is.character( x ) ) ){
x <- lapply(
X = x,
FUN = function(y){
out0 <- strsplit(
x = y,
split = "|",
fixed = TRUE )[[ 1L ]]
return( as.numeric( out0 ) )
}
)
x_length <- unlist( lapply( X = x, FUN = length ) )
if( all( x_length <= 1L ) ){
x <- unlist( x )
}else{
x <- I( x )
}
}else if( !any( c( "numeric", "integer" ) %in% class( x ) ) ){
stop( sprintf(
"'x' should be of class 'list', 'AsIs', 'character' or 'numeric'. Now class %s",
paste( class( x ), collapse = " " )
) )
}
return( x )
}
# .muc_vbar_to_numeric( x = "1000|900" )
# # [[1]]
# # [1] 1000 900
# .muc_vbar_to_numeric( x = c( 1000, "900|800" ) )
# # [[1]]
# # [1] 1000
# # [[2]]
# # [1] 900 800
# .muc_vbar_to_numeric( x = list( "1000", "900|800" ) )
# # [[1]]
# # [1] 1000
# # [[2]]
# # [1] 900 800
# .muc_vbar_to_numeric( x = data.frame( a = I(list( "1000", "900|800" )), b = 1:2 )[,1L] )
# # [[1]]
# # [1] 1000
# # [[2]]
# # [1] 900 800
# .muc_vbar_to_numeric( x = c( "1000", "800" ) )
# # [1] 1000 800
# .muc_vbar_to_numeric( x = c( 1000, 900 ) )
# # [1] 1000 900
# .muc_tar =================================================
#'@importFrom utils tar
.muc_tar <- function( tarfile, files ){
where_tar <- Sys.getenv( "tar", unset = NA_character_ )
if( is.na( where_tar ) ){
suppressWarnings( where_tar <- tryCatch( system2(
command = "where",
args = "tar.exe",
stdout = TRUE ) ) )
if( is.null( attr( where_tar, "status" ) ) ){
utils::tar(
tarfile = tarfile,
files = files,
compression = "gzip",
tar = "tar.exe" )
out <- TRUE
}else{
out <- FALSE
}
}else{
utils::tar(
tarfile = tarfile,
files = files,
compression = "gzip",
tar = where_tar )
out <- TRUE
}
return( out )
}
# macrounchained ===========================================
#' Batch run MACRO simulations with different substance properties and application patterns
#'
#' Batch run MACRO simulations with different substance
#' properties and application patterns, starting from a
#' template imported MACRO par-file, including metabolites.
#'
#'
#'@param s
#' A \code{\link[base]{data.frame}} containing different sets
#' of substance properties and application patterns to be
#' simulated. Each row is a substance. The order of the
#' column has no importance, but the order of the row
#' will steer the simulation order. Substances deriving
#' from the same applied substance will nonetheless be
#' simulated together. The following columns
#' must or can be provided
#' \itemize{
#' \item{"soil"}{(optional) Name of the FOCUS-scenario (soil/ site)
#' to be used for the parameter set. Can only be
#' used when the argument \code{focus_mode} is set
#' to \code{"gw"}. When the column \code{"soil"} is
#' provided, the column
#' \code{"crop"} should be provided too (see below),
#' but the argument \code{parfile} should not be
#' used, and neither the optional column
#' \code{"parfile"}, as the template
#' par-file is determined internally.
#' \code{\link[base:pmatch]{Partial matching}} and
#' \code{\link[base:iconv]{transliteration}} are
#' used, and casing is ignored, and so that input
#' like \code{"Ch\^{a}teaudun"}, \code{"chateaudun"} or
#' \code{"chat"} will all refer to the same
#' \code{"Ch\^{a}teaudun"} FOCUS-scenario. An
#' \code{\link[base:stop]{error}} will be raised in
#' case of multiple matches or no match.}
#' \item{"crop"}{(optional) Name of the FOCUS-crop
#' to be used for the parameter set. Can only be
#' used when the argument \code{focus_mode} is set
#' to \code{"gw"}. When the column \code{"crop"} is
#' provided, the column
#' \code{"soil"} should be provided too (see above).
#' \code{\link[base:pmatch]{Partial matching}} and
#' \code{\link[base:iconv]{transliteration}} are
#' used, and casing is ignored. Important qualifiers
#' such as \code{"winter"} and \code{"spring"} (for
#' cereals and oil seed rape), or \code{"bulb"},
#' \code{"fruiting"}, \code{"leafy"} and \code{"root"}
#' (for vegetables), should be separated from the
#' crop name by a comma (as in MACRO In FOCUS user
#' interface), but the can come either before or
#' after the crop name. Spaces are otherwise ignored.
#' Input like \code{"Cereals, Winter"},
#' \code{"cereals, winter"}, \code{"cer, win"} or
#' even \code{"win, cer"} will all refer to the same
#' Winter cereals FOCUS-crop. \code{"Sugar beets"}
#' is equivalent to \code{"sugarbeets"}.
#' An \code{\link[base:stop]{error}} will be raised in
#' case of multiple matches or no match.}
#' \item{"id"}{Integer-value, between 1 and 998. Unique
#' identifier of the substance. Will also be used as
#' a Run ID.}
#' \item{"name"}{Character-string. Name of the substance.
#' Names don't need to be unique, but it may be a
#' good idea if they are.}
#' \item{"kfoc"}{Numeric-value. [L/kg]. Freundlich
#' adsorption coefficient of the substance.}
#' \item{"nf"}{Numeric-value. [-]. Freundlich exponent
#' of the substance.}
#' \item{"dt50"}{Numeric-value. [days]. Half-life of
#' the substance in soil.}
#' \item{"dt50_ref_temp"}{Numeric-value. [Degrees Celsius].
#' Reference temperature at which the half-life was
#' measured.}
#' \item{"dt50_pf"}{Integer-value. [log10(cm)]. pF at
#' which the DT50 was measured.}
#' \item{"exp_temp_resp"}{Numeric-value. [-]. Exponent
#' of the temperature response (effect of temperature
#' on degradation).}
#' \item{"exp_moist_resp"}{Numeric-value. [-]. Exponent
#' of the moisture response (effect of soil water
#' content on degradation).}
#' \item{"crop_upt_f"}{Numeric-value. [-]. Crop uptake
#' factor. Between 0 (no root uptake of the substance)
#' and 1 (passive uptake of the substance with root
#' water uptake).}
#' \item{"diff_coef"}{Numeric-value. [m2/s]. Substance
#' diffusion coefficient (in water).}
#' \item{"parent_id"}{Integer-value. Only for metabolites.
#' Leave empty (\code{NA_integer_}) for substances
#' that are not the degradation product of another
#' substance. \code{id} of the parent substance, i.e.
#' the substance that degrades into the metabolite
#' described in this row. For secondary metabolites
#' (and further), the "parent" will also be a
#' metabolite.}
#' \item{"g_per_mol"}{Numeric-value. [g/mol]. Molar mass
#' of the substance. Only needed when the substance
#' is degrading into a degradation product or is
#' the degradation product of another substance.
#' Leave empty (\code{NA_integer_}) otherwise.}
#' \item{"g_as_per_ha"}{Numeric-value or, in case of
#' multiple applications, character string. [g/ha].
#' Application
#' rate (in g substance per hectare) of the substance.
#' Set to 0 g/ha if the substance is a degradation
#' product. In case of several applications per year,
#' give the values separated with a vertical bar
#' (see https://en.wikipedia.org/wiki/Vertical_bar).
#' Do quote the values. For example, for two
#' applications of 1000g/ha and 90g/ha, respectively,
#' type \code{"1000|900"}.}
#' \item{"app_j_day"}{Integer-value or, in case of
#' multiple applications, character string. Between
#' 1 and 365.
#' [Julian day]. Application date of the substance.
#' Use the application date of the applied substance
#' (the top parent) if the substance is a
#' degradation product. In case of several
#' applications per year, give the values separated
#' with a vertical bar (see https://en.wikipedia.org/wiki/Vertical_bar).
#' Do quote the values. For example, for two
#' applications on Julian days 298 and 305,
#' respectively, type \code{"298|305"}}
#' \item{"f_int"}{Numeric-value. [-]. Fraction of the
#' applied product that is intercepted by the crop
#' canopy.}
#' }
#' The columns \code{"parent_id"} and \code{"g_per_mol"} can
#' be entirely skipped (missing), and should at least be
#' only \code{NA} when no metabolite is to be simulated.
#'
#'@param parfile
#' A \code{macroParFile}, as imported with
#' \code{\link[rmacrolite]{rmacroliteImportParFile-methods}}
#'
#'@param verbose
#' Single integer value. If set to a value \code{< 1},
#' the program is silent (except on errors or warnings). If
#' set to \code{1}, the program outputs messages. Values
#' \code{> 1} may also activate messages from lower level
#' functions (for debugging purpose).
#'
#'@param indump
#' Single logical value. If \code{TRUE} (the default),
#' the so called \code{indump.tmp} parameter file is produced.
#' Must be \code{TRUE} when \code{run} is \code{TRUE}.
#'
#'@param run
#' Single logical value. If \code{TRUE} (the default),
#' the parametrised simulations are run.
#'
#'@param overwrite
#' Single logical value. If \code{FALSE} (the default),
#' the function will check that the files to be created
#' do not exist yet, and will \code{\link[base]{stop}} if
#' some of the files already exist. Set to \code{TRUE} to
#' silently overwrite existing files.
#'
#'@param analyse
#' Single R \code{\link[base]{function}}. Function to be
#' used by \code{macrounchained} to analyse the results of
#' MACRO simulations. An example of such function is
#' \code{\link[macroutils2:macroutilsFocusGWConc-methods]{macroutilsFocusGWConc}}.
#' Notice that the appropriate function depends on what
#' output needs to be analysed and what parameters are
#' exported from MACRO, as defined in \code{parfile}, so
#' there is no generic all purpose function to be used here.
#' When \code{analyse} is \code{NULL} (the default), MACRO
#' output is not analysed.
#'
#'@param analyse_args
#' A \code{\link[base]{list}} containing named-items to
#' be passed as arguments to \code{analyse}. An example
#' of use is \code{analyse_args =} \code{list( "quiet" = TRUE )}.
#'
#'@param analyse_summary
#' Single R \code{\link[base]{function}}. Function to be
#' used by \code{macrounchained} to summarise all the results
#' of MACRO simulations, as output by \code{analyse}.
#' An example of such function is
#' \code{\link[macrounchained:macroutilsFocusGWConc_summary-methods]{macroutilsFocusGWConc_summary}}.
#' Notice that the appropriate function depends on what
#' output needs to be summarised and what output \code{analyse}
#' is returning, so there is no generic all purpose function
#' to be used here.
#'
#'@param dt50_depth_f
#' See \code{\link[rmacrolite:rmacroliteDegradation-methods]{rmacroliteDegradation}}.
#'
#'@param anonymise
#' Single boolean value. If \code{TRUE}, the function
#' tries to replace USERNAME, HOMEPATH and USERPROFILE
#' (i.e Windows environment variables) in paths displayed
#' in messages by their environment variables, in order
#' to preserve the user anonymity in the logs produced.
#'
#'@param archive
#' Single boolean value. If \code{TRUE}, all the files
#' generated are archived in a \code{.tar.gz}-file when
#' all other operations are finished. Default to
#' \code{FALSE}.
#'
#'@param keep0conc
#' See \code{\link[rmacrolite:rmacroliteApplications-methods]{rmacroliteApplications}}.
#'
#'@param focus_mode
#' See \code{\link[rmacrolite:rmacroliteApplications-methods]{rmacroliteApplications}}.
#'
#'@param \dots
#' Additional parameters passed to specific methods.
#' Currently not used.
#'
#'
#'@return
#' TO BE WRITTEN.
#'
#'
#'@rdname macrounchained-methods
#'@aliases macrounchained
#'
#'@export
#'
#'@docType methods
#'
#'@importFrom utils packageName
macrounchained <- function(
s,
...
# .internal = list()
){
if( is.null( .muc_internals[[ "match_call" ]] ) ){
.muc_internals[[ "match_call" ]] <- match.call()
}
if( is.null( .muc_internals[[ "package" ]] ) ){
.muc_internals[[ "package" ]] <- utils::packageName()
}
if( is.null( .muc_internals[[ "timeStart" ]] ) ){
.muc_internals[[ "timeStart" ]] <- Sys.time()
}
UseMethod( generic = "macrounchained" )
}
#'@rdname macrounchained-methods
#'
#'@method macrounchained data.frame
#'
#'@export
#'
#'@importFrom stats na.omit
#'@importFrom utils read.csv
#'@importFrom utils write.csv
#'@importFrom utils write.table
#'@importFrom rmacrolite getRmlPar
#'@importFrom rmacrolite rmlPar
#'@importFrom rmacrolite rmacroliteImportParFile
#'@importFrom rmacrolite rmacroliteGetModelVar
#'@importFrom rmacrolite rmacroliteExportParFile
#'@importFrom rmacrolite rmacroliteRunId<-
#'@importFrom rmacrolite rmacroliteSimType<-
#'@importFrom rmacrolite rmacroliteSorption<-
#'@importFrom rmacrolite rmacroliteDegradation<-
#'@importFrom rmacrolite rmacroliteCropUptF<-
#'@importFrom rmacrolite rmacroliteDiffCoef<-
#'@importFrom rmacrolite rmacroliteApplications
#'@importFrom rmacrolite rmacroliteApplications<-
#'@importFrom rmacrolite rmacroliteInfo<-
#'@importFrom rmacrolite rmacroliteRun
#'@importFrom rmacrolite rmacroliteMacroVersion
#'@importFrom codeinfo codeinfo
macrounchained.data.frame <- function(
s,
parfile,
verbose = 1L,
indump = TRUE,
run = TRUE,
overwrite = FALSE,
analyse = NULL,
analyse_args = NULL,
analyse_summary = NULL,
dt50_depth_f = NULL,
keep0conc = TRUE,
focus_mode = "no",
anonymise = TRUE,
archive = TRUE,
...
# .internal = list()
){
log_width <- getRmlPar( "log_width" )
# Create a temporary log-file
temp_log <- tempfile( pattern = "rml_log_", fileext = ".txt" )
.muc_logMessage( m = "Temporary log-file %s",
verbose = verbose, log_width = log_width,
values = list( .muc_anonymisePath( path = temp_log,
anonymise = anonymise, winslash = "/",
log_width = log_width ) ),
logfiles = temp_log, append = FALSE )
if( run ){
.muc_logMessage( m = "Parametrise and run MACRO simulations",
verbose = verbose, log_width = log_width,
frame = "*", logfiles = temp_log, append = TRUE )
if( !indump ){
stop( "Argument 'indump' must be TRUE when 'run' is TRUE." )
}
}else{
.muc_logMessage( m = "Parametrise MACRO simulations",
verbose = verbose, log_width = log_width,
frame = "*", logfiles = temp_log, append = TRUE )
}
# ======================================================
# Traceability
# ======================================================
if( is.null( .muc_internals[[ "match_call" ]] ) ){
.muc_internals[[ "match_call" ]] <- match.call()
}
if( is.null( .muc_internals[[ "package" ]] ) ){
.muc_internals[[ "package" ]] <- utils::packageName()
}
if( is.null( .muc_internals[[ "timeStart" ]] ) ){
.muc_internals[[ "timeStart" ]] <- Sys.time()
}
.muc_logMessage(
m = "Fetch MACRO executables names and location",
verbose = verbose, log_width = log_width,
logfiles = temp_log, append = TRUE )
modelVar <- rmacroliteGetModelVar()
.muc_logMessage(
m = "Fetch MACRO version",
verbose = verbose, log_width = log_width,
logfiles = temp_log, append = TRUE )
macro_version <- rmacroliteMacroVersion(
path = modelVar[[ "path" ]] )
# ======================================================
# Check parameter table 's'
# ======================================================
.muc_logMessage( m = "Check input parameter-table ('s')",
verbose = verbose, log_width = log_width,
logfiles = temp_log, append = TRUE )
s0 <- .muc_check_s(
s = s,
focus_mode = focus_mode,
macro_version = macro_version,
parfile = parfile )
metabolites <- s0[[ "metabolites" ]]
scenario_provided <- s0[[ "scenario_provided" ]]
parfile_in_s <- s0[[ "parfile_in_s" ]]
if( nrow( s0[[ "parfile_table" ]] ) > 0 ){
parfile_table <- s0[[ "parfile_table" ]]
}
macroinfocus_version <- s0[[ "macroinfocus_version" ]]
id_range <- s0[[ "id_range" ]]
names_provided <- s0[[ "names_provided" ]]
s <- s0[[ "s" ]]
rm( s0 )
# ======================================================
# Check other parameters
# ======================================================
dotdotdot <- list( ... )
if( length( list(...) ) > 0L ){
warning( sprintf(
"Additional arguments passed via '...', while '...' currently not in use (%s)",
paste( names( dotdotdot ), collapse = ", " )
) )
}
# ======================================================
# Find out the FOCUS-scenario, if needed
# ======================================================
if( scenario_provided ){
s0 <- .muc_scenario_parameters(
s = s,
verbose = verbose,
log_width = log_width,
logfiles = temp_log,
append = TRUE,
modelVar = modelVar,
focus_mode = focus_mode,
macroinfocus_version = macroinfocus_version
)
s <- s0[[ "s" ]]
crop_params <- s0[[ "crop_params" ]]
crop_param_map <- s0[[ "crop_param_map" ]]
parfile_table <- s0[[ "parfile_table" ]]
rm( s0 )
}