Skip to content

Commit db840a2

Browse files
Simplify GDXFile constructor and add setters (#5)
1 parent 20d5e69 commit db840a2

2 files changed

Lines changed: 28 additions & 0 deletions

File tree

src/GDXFile.jl

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,10 @@ function GDXFile(path::String, symbols::Dict{Symbol, <:GDXSymbol})
145145
return gdx
146146
end
147147

148+
function GDXFile(path::String)
149+
return GDXFile(path, Dict{Symbol, GDXSymbol}(), Symbol[])
150+
end
151+
148152
function _insert!(gdx::GDXFile, key::Symbol, sym::GDXSymbol)
149153
lk = _symkey(key)
150154
if !haskey(gdx._symbols, lk)
@@ -200,6 +204,10 @@ Base.haskey(gdx::GDXFile, sym::Symbol) = haskey(gdx._symbols, _symkey(sym))
200204
Base.keys(gdx::GDXFile) = Symbol[Symbol(gdx._symbols[k].name) for k in gdx._order]
201205
Base.length(gdx::GDXFile) = length(gdx._order)
202206

207+
# Dictionary-like setting (inserts or updates symbols)
208+
Base.setindex!(gdx::GDXFile, sym::GDXSymbol, key::Symbol) = _insert!(gdx, key, sym)
209+
Base.setindex!(gdx::GDXFile, sym::GDXSymbol, key::String) = _insert!(gdx, Symbol(key), sym)
210+
203211
function Base.iterate(gdx::GDXFile)
204212
isempty(gdx._order) && return nothing
205213
k = gdx._order[1]

test/test_gdxfile.jl

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -522,4 +522,24 @@ execute_unload "gams_gdx_test.gdx", i, p, x, y;
522522

523523
rm(outfile, force=true)
524524
end
525+
526+
527+
@testset "Setting symbols via indexing" begin
528+
gdxfile = GDXFile("")
529+
530+
df = DataFrame(i = ["a", "b"], value = [1.0, 2.0])
531+
p = GDXParameter("p", "test param", ["i"], df)
532+
gdxfile[:p] = p
533+
534+
@test :p in list_parameters(gdxfile)
535+
@test gdxfile[:p].value == [1.0, 2.0]
536+
537+
# String keys should also work
538+
df2 = DataFrame(j = ["x", "y"], value = [3.0, 4.0])
539+
p2 = GDXParameter("q", "another param", ["j"], df2)
540+
gdxfile["q"] = p2
541+
542+
@test :q in list_parameters(gdxfile)
543+
@test gdxfile[:q].value == [3.0, 4.0]
544+
end
525545
end

0 commit comments

Comments
 (0)