-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathMadsIO.jl
2043 lines (1876 loc) · 56.7 KB
/
MadsIO.jl
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
import OrderedCollections
import JLD
import JLD2
import XLSX
import CSV
import SHA
import Dates
import DataFrames
import LightXML
mutable struct DATA
filename::String
filehash::String
end
function createhash!(DATA::DATA)
println("File: $(DATA.filename)")
open(DATA.filename) do f
hash = SHA.bytes2hex(SHA.sha2_256(f))
@info("Hash: $(hash)")
if DATA.filehash == hash
@info("Hash did not change!")
else
@warn("Hash changed!")
DATA.filehash = hash
end
end
end
function checkhash(input_file::AbstractString, target_hash::AbstractString, throw_error::Bool=false)::Bool
local hash
open(input_file) do f
hash = SHA.bytes2hex(SHA.sha2_256(f))
end
check = hash == target_hash
if !check
@info("Current hash: $(hash)")
@info("Expected hash: $(target_hash)")
if throw_error
@error "File hash for $(input_file) does not match!"
throw("Error")
end
else
@info "File hash for $(input_file) matches!"
end
return check
end
function checkhash(DATA::DATA, throw_error::Bool=true)::Bool
checkhash(DATA.filename, DATA.filehash, throw_error)
end
@doc """
Check hash of a file
$(DocumentFunction.documentfunction(checkhash))
""" checkhash
function get_datasets(filename::AbstractString)
if !isfile(filename)
@error("File $(filename) does not exist!")
return []
end
datasets = [""]
e = lowercase(last(splitext(filename)))
if ((e == ".jld") || (e == ".jld2"))
if e == ".jld"
ds = JLD.load(filename)
else
ds = JLD2.load(filename)
end
datasets = collect(keys(ds))
@info("File $(filename) datasets: $(datasets)")
elseif e == ".xlsx"
xb = XLSX.readxlsx(filename)
datasets = collect(XLSX.sheetnames(xb))
@info("File $(filename) sheets: $(datasets)")
end
return datasets
end
"""
Get data from an EXCEL file
$(DocumentFunction.documentfunction(get_excel_data))
"""
function get_excel_data(excel_file::AbstractString, sheet_name::AbstractString=""; header::Union{Int, Vector{Int}, UnitRange{Int}}=1, rows::Union{Int, Vector{Int}, UnitRange{Int}}=0, cols::Union{Int, Vector{Int}, Vector{String}, UnitRange{Int}}=0, keytype::DataType=String, numbertype::DataType=Float64, mapping::Dict=Dict(), usenans::Bool=true, dataframe::Bool=true)::Union{OrderedCollections.OrderedDict, DataFrames.DataFrame}
@assert numbertype <: Real
if dataframe
df = DataFrames.DataFrame()
else
df = OrderedCollections.OrderedDict{keytype, Vector{Any}}()
end
if !isfile(excel_file)
@error("File $(excel_file) does not exist!")
return df
end
if rows != 0 && minimum(rows) <= maximum(header)
@error("Header rows and data rows overlap!")
return df
end
XLSX.openxlsx(excel_file, mode="r") do xf
if sheet_name == ""
sheet_name = xf[1].name
@warn("Sheet name is not provided! Using the first sheet: $(sheet_name)")
end
if cols == 0 # all columns
col_range = xf[sheet_name].dimension.start.column_number:xf[sheet_name].dimension.stop.column_number
col_vector = collect(col_range)
elseif eltype(cols) <: Integer # Vector{Int} or UnitRange{Int}
col_vector = collect(cols)
col_range = minimum(cols):maximum(cols)
else # Vector{String}
xlsx_col_range = convert(XLSX.ColumnRange, "$(cols[1]):$(cols[end])")
col_range = xlsx_col_range.start:xlsx_col_range.stop
col_vector = collect(col_range)
end
if header != 0
header_vector = collect(header)
header_range = minimum(header):maximum(header)
end
row_vector = collect(rows)
row_range = minimum(rows):maximum(rows)
if length(header) > 1 # multiple header rows
params = Vector{String}()
for c in col_vector
v = xf[sheet_name][header_range,c][header_vector .- minimum(header_range) .+ 1]
v[ismissing.(v) .| isnothing.(v)] .= ""
p = strip(.*((string.(v) .* " ")...))
p = p == "" ? "Column $c" : p
push!(params, p)
end
ni = Mads.nonunique_indices(params)
for i in ni
params[i] = "$(params[i]) C$(i)"
end
if rows == 0
row_range = (maximum(header) + 1):xf[sheet_name].dimension.stop.row_number
row_vector = collect(row_range)
end
elseif length(header) == 1 && maximum(header) > 0 # single header row
params = xf[sheet_name][header, col_range][col_vector .- minimum(col_range) .+ 1]
for (i, c) in enumerate(col_vector) # replace missing values with column number
p = params[i]
if ismissing(p) || isnothing(p) || p == "" || occursin(r"^-*$", p)
params[i] = "Column $(c)"
end
end
if rows == 0
row_range = (maximum(header) + 1):xf[sheet_name].dimension.stop.row_number
row_vector = collect(row_range)
end
elseif header == 0 # no header row
params = ["Column $i" for i in col_vector]
if rows == 0
row_range = xf[sheet_name].dimension.start.row_number:xf[sheet_name].dimension.stop.row_number
row_vector = collect(row_range)
end
else
@error("Invalid header row ranges!")
return df
end
# NOTE: xf[sheet_name][row_vector, col_vector] is not working; that is why we use the following
data = xf[sheet_name][row_range, col_range][row_vector .- minimum(row_range) .+ 1,col_vector .- minimum(col_range) .+ 1]
data = data[.!all.(ismissing, eachrow(data)), :] # skip rows with all missing values
for (i, param) in enumerate(params)
param_name = ""
if length(mapping) > 0
for key in keys(mapping)
if param == mapping[key]
param_name = key
if keytype <: AbstractString
param_name = string(param_name)
elseif keytype <: Symbol
param_name = Symbol(param_name)
end
break
end
end
if param_name == ""
@warn("Parameter named `$(param)` is not found in the mapping!")
end
end
if param_name == ""
if keytype <: AbstractString
param_name = convert(keytype, param)
elseif keytype <: Symbol
param_name = Symbol(replace(strip(lowercase(param)), r"\s+"=> "_", "-" => "_"))
end
end
v = data[:,i]
if !all(ismissing.(v))
if all(typeof.(v) .<: Union{Missing,Number})
mask_missing = isnull.(v)
if usenans
v[mask_missing] .= numbertype(NaN)
v = convert(Vector{numbertype}, v)
else
v[mask_missing] .= missing
v = convert(Vector{Union{Missing,numbertype}}, v)
end
elseif all(typeof.(v) .<: Union{Missing,AbstractString})
v[ismissing.(v)] .= ""
v = convert(Vector{String}, v)
else
v = convert(Vector{Union{unique(typeof.(v))...}}, v)
end
if dataframe
df[!, param_name] = v
else
df[param_name] = v
end
else
@warn("All values for parameter/column \"$(param)\" are missing!")
end
end
end
return df
end
function load_data(filename::AbstractString; dataset="", kw...)::Union{DataFrames.DataFrame,AbstractArray}
if !isfile(filename)
@warn("File $(filename) does not exist!")
return DataFrames.DataFrame()
else
@info("Load input data: $(filename)")
end
e = lowercase(last(splitext(filename)))
if e == ".csv"
try
c = CSV.read(filename, DataFrames.DataFrame)
catch
@error("CSV error reading $(filename)!")
c = DataFrames.DataFrame()
end
elseif e == ".xlsx"
c = Mads.get_excel_data(filename, dataset; dataframe=true, kw...)
elseif ((e == ".jld") || (e == ".jld2"))
try
if e == ".jld"
ds = JLD.load(filename)
else
ds = JLD2.load(filename)
end
datasets = collect(keys(ds))
@info("File $(filename) datasets: $(datasets)")
if dataset in datasets
@info("Dataset $(dataset) loaded from $(filename) ...")
c = ds[dataset]
else
@info("Dataset $(datasets[1]) loaded from $(filename) ...")
c = ds[datasets[1]]
end
if typeof(c) <: DataFrames.DataFrame
c = c
elseif length(size(c)) == 2
c = DataFrames.DataFrame(c, :auto)
else
c = c
end
catch
@error("Data from File $(filename) cannot be opened!")
c = DataFrames.DataFrame()
end
else
@error("Unknown file type with extension $(e)!")
c = DataFrames.DataFrame()
end
return c
end
function save_data(df::DataFrames.DataFrame, filename::AbstractString)::Nothing
if isfile(filename)
madsinfo("File $(filename) does exist! It will be overwritten!")
else
madsinfo("Save output data: $(filename)")
end
e = lowercase(last(splitext(filename)))
if e == ".csv"
CSV.write(filename, df)
elseif e == ".xlsx"
XLSX.writetable(filename, collect(eachcol(df)), names(df); overwrite=true)
elseif e == ".jld"
JLD.save(filename, "data", df)
elseif e == ".jld2"
JLD2.save(filename, "data", df)
else
@error("Unknown file type with extension $(e)!")
end
return nothing
end
function save_data(d::AbstractDict, filename::AbstractString)::Nothing
df = DataFrames.DataFrame()
for k in keys(d)
df[!, Symbol(k)] = d[k]
end
save_data(df, filename)
return nothing
end
"""
Get file names by expanding wildcards
$(DocumentFunction.documentfunction(getfilenames))
"""
function getfilenames(cmdstring::AbstractString)
readlines(runcmd("ls " * cmdstring; quiet=true, pipe=true)[2])
end
"""
Change the current directory to the Mads source dictionary
$(DocumentFunction.documentfunction(madsdir))
"""
function madsdir()
Base.cd(Mads.dir)
return pwd()
end
function splitdirdot(d)
r, f = splitdir(d)
r = r == "" ? "." : r
return r, f
end
"""
Load MADS input file defining a MADS problem dictionary
$(DocumentFunction.documentfunction(loadmadsfile;
argtext=Dict("filename"=>"input file name (e.g. `input_file_name.mads`)"),
keytext=Dict("julia"=>"if `true`, force using `julia` parsing functions; if `false` (default), use `python` parsing functions",
"format"=>"acceptable formats are `yaml` and `json` [default=`yaml`]")))
Returns:
- MADS problem dictionary
Example:
```julia
md = Mads.loadmadsfile("input_file_name.mads")
```
"""
function loadmadsfile(filename::AbstractString; bigfile::Bool=false, format::AbstractString="yaml", quiet::Bool=Mads.quiet, dicttype=OrderedCollections.OrderedDict{Any,Any})
if bigfile
madsdata = loadbigyamlfile(filename)
end
if !bigfile || isnothing(madsdata)
if format == "yaml"
madsdata = loadyamlfile(filename; dicttype=dicttype)
elseif format == "json"
madsdata = loadjsonfile(filename)
end
end
while typeof(madsdata) <: AbstractString # Windows links fix
filename = joinpath(splitdir(filename)[1], madsdata)
if format == "yaml"
madsdata = loadyamlfile(filename; dicttype=dicttype)
elseif format == "json"
madsdata = loadjsonfile(filename)
end
end
madsdata["Filename"] = filename
parsemadsdata!(madsdata)
if haskey(madsdata, "Observations")
t = getobstarget(madsdata)
isn = isnan.(t)
if any(isn) && !quiet
l = length(isn[isn.==true])
if l == 1
Mads.madswarn("There is 1 observation with a missing target!")
else
Mads.madswarn("There are $(l) observations with missing targets!")
end
end
end
if haskey(madsdata, "Julia function")
fn = Symbol(madsdata["Julia function"])
if isdefined(Main, fn)
@info("Main version of $(fn) will be used ...")
elseif isdefined(Mads, fn)
@info("Mads version of $(fn) will be used ...")
elseif isdefined(Mads, fn)
@info("Mads version of $(fn) will be used ...")
else
madswarn("Julia function $(fn) is not defined!")
end
end
return convert(Dict{String,Any}, madsdata)
end
"""
Load BIG YAML input file
$(DocumentFunction.documentfunction(loadmadsfile;
argtext=Dict("filename"=>"input file name (e.g. `input_file_name.mads`)")))
Returns:
- MADS problem dictionary
"""
function loadbigyamlfile(filename::AbstractString)
lines = readlines(filename)
nlines = length(lines)
keyln = findall((in)(true), map(i->(match(r"^[A-Z]", lines[i]) !== nothing), 1:nlines))
if length(keyln) == 0
return nothing
end
obsia = indexin(["Observations:"], strip.(lines[keyln]))
if length(obsia) == 0
return nothing
else
obsi = obsia[1]
obsln = keyln[obsi]
end
readflag = true
yamlflag = true
if obsln != 1 && obsln != nlines && obsi < length(keyln)
parseindeces = vcat(collect(1:obsln-1), collect(keyln[obsi+1]:nlines))
readindeces = obsln+1:keyln[obsi+1]-1
elseif obsln == 1 && obsi < length(keyln)
parseindeces = keyln[obsi+1]:nlines
readindeces = 2:keyln[obsi+1]-1
elseif obsln == nlines
parseindeces = 1:obsln-1
readindeces = obsln+1:nlines
elseif length(keyln) == 1
parseindeces = 0:0
yamlflag = false
readindeces = 1:nlines
else
parseindeces = 1:nlines
readindeces = 0:0
readflag = false
end
if readflag
obsdict = OrderedCollections.OrderedDict{String,Any}()
t = []
badlines = Array{Int}(undef, 0)
for i in readindeces
mc = match(r"^- (\S*):.*", lines[i])
if !isnothing(mc)
kw = mc.captures[1]
else
push!(badlines, i)
continue
end
if occursin("filename", kw)
readflag = false
yamlflag = true
parseindeces = 1:nlines
break
end
obsdict[kw] = OrderedCollections.OrderedDict{String,Any}()
mc = match(r"^.*target[\"]?:[\s]*?([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?).*", lines[i])
if !isnothing(mc)
obsdict[kw]["target"] = parse(Float64, mc.captures[1])
end
mc = match(r"^.*weight[\"]?:[\s]*?([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?).*", lines[i])
if !isnothing(mc)
obsdict[kw]["weight"] = parse(Float64, mc.captures[1])
end
mc = match(r"^.*min[\"]?:[\s]*?([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?).*", lines[i])
if !isnothing(mc)
obsdict[kw]["min"] = parse(Float64, mc.captures[1])
end
mc = match(r"^.*max[\"]?:[\s]*?([-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?).*", lines[i])
if !isnothing(mc)
obsdict[kw]["max"] = parse(Float64, mc.captures[1])
end
end
end
if yamlflag
io = IOBuffer(join(lines[parseindeces], '\n'))
madsdata = YAML.load(io; dicttype=OrderedCollections.OrderedDict{String,Any})
else
madsdata = OrderedCollections.OrderedDict{String,Any}()
end
if readflag
madsdata["Observations"] = obsdict
end
return madsdata
end
"""
Parse loaded MADS problem dictionary
$(DocumentFunction.documentfunction(parsemadsdata!;
argtext=Dict("madsdata"=>"MADS problem dictionary")))
"""
function parsemadsdata!(madsdata::AbstractDict)
madsproblemdir = Mads.getmadsproblemdir(madsdata)
if haskey(madsdata, "Parameters")
parameters = OrderedCollections.OrderedDict{String,OrderedCollections.OrderedDict}()
for dict in madsdata["Parameters"]
for key in keys(dict)
if !haskey(dict[key], "exp") # it is a real parameter, not an expression
parameters[key] = OrderedCollections.OrderedDict{String,Any}()
for pf in keys(dict[key])
parameters[key][pf] = dict[key][pf]
end
else
if !haskey(madsdata, "Expressions")
madsdata["Expressions"] = OrderedCollections.OrderedDict{String,OrderedCollections.OrderedDict}()
end
madsdata["Expressions"][key] = OrderedCollections.OrderedDict{String,Any}()
for pf in keys(dict[key])
madsdata["Expressions"][key][pf] = dict[key][pf]
end
end
end
end
madsdata["Parameters"] = parameters
end
addsourceparameters!(madsdata)
if haskey(madsdata, "Parameters")
parameters = madsdata["Parameters"]
for key in keys(parameters)
if !haskey(parameters[key], "init") && !haskey(parameters[key], "exp")
Mads.madserror("""Parameter `$key` does not have initial value; add "init" value!""")
end
for v in ["init", "init_max", "init_min", "max", "min", "step"]
if haskey(parameters[key], v)
if typeof(parameters[key][v]) <: AbstractString
parameters[key][v] = parse(Float64, parameters[key][v])
elseif typeof(parameters[key][v]) <: Number
parameters[key][v] = float(parameters[key][v])
end
end
end
if haskey(parameters[key], "log")
flag = parameters[key]["log"]
if flag == "yes" || flag == true
parameters[key]["log"] = true
for v in ["init", "init_max", "init_min", "max", "min", "step"]
if haskey(parameters[key], v)
if parameters[key][v] < 0
Mads.madserror("""The value $v for Parameter $key cannot be log-transformed; it is negative!""")
end
end
end
else
parameters[key]["log"] = false
end
end
end
end
checkparameterranges(madsdata)
if haskey(madsdata, "Wells")
wells = OrderedCollections.OrderedDict{String,Any}()
for dict in madsdata["Wells"]
if collect(keys(dict))[1] == "filename"
dictnew = loadmadsfile(joinpath(madsproblemdir, collect(values(dict))[1]), bigfile=true)["Wells"]
elseif collect(keys(dict))[1] == "script"
dictnew = include(collect(values(dict))[1])
else
dictnew = dict
end
for key in keys(dictnew)
wells[key] = dict[key]
wells[key]["on"] = true
if haskey(wells[key], "obs") && !isnothing(wells[key]["obs"])
for i = eachindex(wells[key]["obs"])
for k in keys(wells[key]["obs"][i])
wells[key]["obs"][i] = wells[key]["obs"][i][k]
end
end
end
end
end
madsdata["Wells"] = wells
Mads.wells2observations!(madsdata)
elseif haskey(madsdata, "Observations") # TODO drop zero weight observations
if typeof(madsdata["Observations"]) <: Array
observations = OrderedCollections.OrderedDict{String,OrderedCollections.OrderedDict}()
for dict in madsdata["Observations"]
if collect(keys(dict))[1] == "filename"
dictnew = loadmadsfile(joinpath(madsproblemdir, collect(values(dict))[1]), bigfile=true)["Observations"]
elseif collect(keys(dict))[1] == "script"
dictnew = include(collect(values(dict))[1])
else
dictnew = dict
end
for key in keys(dictnew)
observations[key] = OrderedCollections.OrderedDict{String,Any}()
for of in keys(dictnew[key])
observations[key][of] = dictnew[key][of]
end
end
end
madsdata["Observations"] = observations
end
end
if haskey(madsdata, "Templates")
templates = Array{AbstractDict}(undef, length(madsdata["Templates"]))
i = 1
for dict in madsdata["Templates"]
for key in keys(dict)
templates[i] = dict[key]
filename = joinpath(madsproblemdir, templates[i]["tpl"])
if isfile(filename)
tplfile = open(filename)
line = readline(tplfile)
if length(line) >= 10 && line[1:9] == "template "
separator = line[10]
if separator == '$'
Mads.madserror("Template file $filename separator cannot be \$!")
end
end
close(tplfile)
else
Mads.madswarn("Template file $filename is missing!")
end
end
i += 1
end
madsdata["Templates"] = templates
end
if haskey(madsdata, "Instructions")
instructions = Array{AbstractDict}(undef, length(madsdata["Instructions"]))
i = 1
for dict in madsdata["Instructions"]
for key in keys(dict)
instructions[i] = dict[key]
end
i += 1
end
madsdata["Instructions"] = instructions
end
if haskey(madsdata, "Setup")
include(values(madsdata["Setup"]))
end
end
function savemadsfile(madsdata::AbstractDict, filename::AbstractString=""; observations_separate::Bool=false, filenameobs=getrootname(filename; version=true) * "_observations.yaml")
if filename == ""
filename = setnewmadsfilename(madsdata)
end
if observations_separate
madsdata2 = deepcopy(madsdata)
if !isfile(filenameobs)
printobservations(madsdata, filenameobs)
else
Mads.madswarn("External observation file already exist ($(filenameobs)); delete if needed!")
end
madsdata2["Observations"] = Dict{String,String}("filename"=>filenameobs)
else
madsdata2 = madsdata
end
dumpyamlmadsfile(madsdata2, filename)
end
function savemadsfile(madsdata::AbstractDict, parameters::AbstractDict, filename::AbstractString=""; explicit::Bool=false, observations_separate::Bool=false)
if filename == ""
filename = setnewmadsfilename(madsdata)
end
if explicit
madsdata2 = loadyamlfile(madsdata["Filename"])
for i = eachindex(madsdata2["Parameters"])
pdict = madsdata2["Parameters"][i]
paramname = collect(keys(pdict))[1]
realparam = pdict[paramname]
if haskey(realparam, "type") && realparam["type"] == "opt"
oldinit = realparam["init"]
realparam["init"] = parameters[paramname]
newinit = realparam["init"]
end
end
if observations_separate
filenameobs = getrootname(filename; version=true) * "_observations.yaml"
printobservations(madsdata, filenameobs)
madsdata2["Observations"] = Dict{String,String}("filename"=>filenameobs)
end
dumpyamlfile(filename, madsdata2)
else
madsdata2 = deepcopy(madsdata)
setparamsinit!(madsdata2, parameters)
if observations_separate
filenameobs = getrootname(filename; version=true) * "_observations.yaml"
printobservations(madsdata, filenameobs)
madsdata2["Observations"] = Dict{String,String}("filename"=>filenameobs)
end
dumpyamlmadsfile(madsdata2, filename)
end
end
@doc """
Save MADS problem dictionary `madsdata` in MADS input file `filename`
$(DocumentFunction.documentfunction(savemadsfile;
argtext=Dict("madsdata"=>"MADS problem dictionary",
"parameters"=>"Dictionary with parameters (optional)",
"filename"=>"input file name (e.g. `input_file_name.mads`)"),
keytext=Dict("julia"=>"if `true` use Julia JSON module to save [default=`false`]",
"explicit"=>"if `true` ignores MADS YAML file modifications and rereads the original input file [default=`false`]")))
Example:
```julia
Mads.savemadsfile(madsdata)
Mads.savemadsfile(madsdata, "test.mads")
Mads.savemadsfile(madsdata, parameters, "test.mads")
Mads.savemadsfile(madsdata, parameters, "test.mads", explicit=true)
```
""" savemadsfile
"""
Set a default MADS input file
$(DocumentFunction.documentfunction(setmadsinputfile;
argtext=Dict("filename"=>"input file name (e.g. `input_file_name.mads`)")))
"""
function setmadsinputfile(filename::AbstractString)
global madsinputfile = filename
end
"""
Get the default MADS input file set as a MADS global variable using `setmadsinputfile(filename)`
$(DocumentFunction.documentfunction(getmadsinputfile))
Returns:
- input file name (e.g. `input_file_name.mads`)
"""
function getmadsinputfile()
return madsinputfile
end
"""
Get the MADS problem root name
$(DocumentFunction.documentfunction(getmadsrootname;
argtext=Dict("madsdata"=>"MADS problem dictionary"),
keytext=Dict("first"=>"use the first . in filename as the seperator between root name and extention [default=`true`]",
"version"=>"delete version information from filename for the returned rootname [default=`false`]")))
Example:
```julia
madsrootname = Mads.getmadsrootname(madsdata)
```
Returns:
- root of file name
"""
function getmadsrootname(madsdata::AbstractDict; first=true, version=false)
if haskey(madsdata, "Filename")
madsrootname = getrootname(madsdata["Filename"]; first=first, version=version)
else
madsrootname = ""
end
return madsrootname
end
"""
Get directory
$(DocumentFunction.documentfunction(getdir;
argtext=Dict("filename"=>"file name")))
Returns:
- directory in file name
Example:
```julia
d = Mads.getdir("a.mads") # d = "."
d = Mads.getdir("test/a.mads") # d = "test"
```
"""
function getdir(filename::AbstractString)
d = dirname(filename)
if d == ""
d = "."
end
return d
end
"""
Get the directory where the Mads data file is located
$(DocumentFunction.documentfunction(getmadsproblemdir;
argtext=Dict("madsdata"=>"MADS problem dictionary")))
Example:
```julia
madsdata = Mads.loadmadsfile("../../a.mads")
madsproblemdir = Mads.getmadsproblemdir(madsdata)
```
where `madsproblemdir` = `"../../"`
"""
function getmadsproblemdir(madsdata::AbstractDict)
if haskey(madsdata, "Filename")
getdir(madsdata["Filename"])
else
return "."
end
end
"""
Get the directory where currently Mads is running
$(DocumentFunction.documentfunction(getproblemdir))
Example:
```julia
problemdir = Mads.getproblemdir()
```
Returns:
- Mads problem directory
"""
function getproblemdir()
source_path = Base.source_path()
if isnothing(source_path)
problemdir = "."
elseif source_path == ""
problemdir = Base.pkgdir(Mads)
else
problemdir = first(splitdir(source_path))
end
madsinfo("Problem directory: $(problemdir)")
return problemdir
end
"""
Get the filename root
$(DocumentFunction.documentfunction(getrootname;
argtext=Dict("filename"=>"file name"),
keytext=Dict("first"=>"use the first . in filename as the seperator between root name and extention [default=`true`]",
"version"=>"delete version information from filename for the returned rootname [default=`false`]")))
Returns:
- root of file name
Example:
```julia
r = Mads.getrootname("a.rnd.dat") # r = "a"
r = Mads.getrootname("a.rnd.dat", first=false) # r = "a.rnd"
```
"""
function getrootname(filename::AbstractString; first::Bool=true, version::Bool=false)
d = splitdir(filename)
s = split(d[2], ".")
if !first && length(s) > 1
r = join(s[1:end-1], ".")
else
r = s[1]
end
if version
if occursin(r"-v[0-9].$", r)
rm = match(r"-v[0-9].$", r)
r = r[1:rm.offset-1]
elseif occursin(r"-rerun$", r)
rm = match(r"-rerun$", r)
r = r[1:rm.offset-1]
end
end
if length(d) > 1
r = joinpath(d[1], r)
end
return r
end
function setnewmadsfilename(madsdata::AbstractDict)
setnewmadsfilename(madsdata["Filename"])
end
function setnewmadsfilename(filename::AbstractString)
dir = getdir(filename)
root = splitdir(getrootname(filename))[end]
if occursin(r"-v[0-9]*$", root)
rm = match(r"-v([0-9]*)$", root)
v = Base.parse(Int, rm.captures[1]) + 1
l = length(rm.captures[1])
f = "%0" * string(l) * "d"
filename = "$(root[1:rm.offset-1])-v$(sprintf(f, v)).mads"
else
filename = "$(root)-rerun.mads"
end
return joinpath(dir, filename)
end
@doc """
Set new mads file name
$(DocumentFunction.documentfunction(setnewmadsfilename;
argtext=Dict("madsdata"=>"MADS problem dictionary",
"filename"=>"file name")))
Returns:
- new file name
""" setnewmadsfilename
"""
Get next mads file name
$(DocumentFunction.documentfunction(getnextmadsfilename;
argtext=Dict("filename"=>"file name")))
Returns:
- next mads file name
"""
function getnextmadsfilename(filename::AbstractString)
t0 = 0
filename_old = filename
while isfile(filename)
t = mtime(filename)
if t < t0
filename = filename_old
break
else
t0 = t
filename_old = filename
filename = setnewmadsfilename(filename_old)
if !isfile(filename)
filename = filename_old
break
end
end
end
return filename
end
"""
Get file name extension
$(DocumentFunction.documentfunction(getextension;
argtext=Dict("filename"=>"file name")))
Returns:
- file name extension
Example:
```julia
ext = Mads.getextension("a.mads") # ext = "mads"
```
"""
function getextension(filename::AbstractString)
d = splitdir(filename)
s = split(d[2], ".")
if length(s) > 1
return s[end]
else
return ""
end
end
"""
Check the directories where model outputs should be saved for MADS
$(DocumentFunction.documentfunction(checkmodeloutputdirs;
argtext=Dict("madsdata"=>"MADS problem dictionary")))
Returns:
- true or false
"""
function checkmodeloutputdirs(madsdata::AbstractDict)
directories = Array{String}(undef, 0)
if haskey(madsdata, "Instructions")
for instruction in madsdata["Instructions"]
filename = instruction["read"]
push!(directories, getdir(filename))
end
end
if haskey(madsdata, "JLDPredictions")
for filename in vcat(madsdata["JLDPredictions"])
push!(directories, getdir(filename))
end
end
if haskey(madsdata, "JLD2Predictions")
for filename in vcat(madsdata["JLD2Predictions"])
push!(directories, getdir(filename))
end
end
if haskey(madsdata, "JSONPredictions")
for filename in vcat(madsdata["JSONPredictions"])
push!(directories, getdir(filename))
end
end
if haskey(madsdata, "YAMLPredictions")
for filename in vcat(madsdata["YAMLPredictions"])
push!(directories, getdir(filename))
end
end
if haskey(madsdata, "ASCIIPredictions")
for filename in vcat(madsdata["ASCIIPredictions"])
push!(directories, getdir(filename))