using import dataStructures.jl - dictionary

I am using the dataStructures.jl package. The documentation online states that once created a dictionaries
dict = DataStructures.SortedDict{Int64, Int64}
I should be able to insert key-value pairs into the data structure by the function, for example
insert!(dict, 10, 100)
but I keep getting the error
ERROR: MethodError: `insert!` has no method matching insert!(
::Type{DataStructures.SortedDict{Int64,Int64,Ord<:Base.Order.Ordering}}, ::Int64, ::Int64)
Closest candidates are:
insert!{T}(::Array{T,1}, ::Integer, ::Any)
insert!(::BitArray{1}, ::Integer, ::Any)
insert!(::PyCall.PyVector{T}, ::Integer, ::Any)
Why is this? Thanks.

I think you've created a datatype, not a dictionary:
julia> using DataStructures
julia> dict = DataStructures.SortedDict{Int64, Int64}
DataStructures.SortedDict{Int64,Int64,Ord<:Base.Order.Ordering}
julia> typeof(dict)
DataType
—the error message is saying "Don't call this function with a type as the first argument, there's no method for that."
I think this is what you want:
julia> dict = SortedDict(["a" => 1, "b" => 2])
DataStructures.SortedDict{String,Int64,Base.Order.ForwardOrdering} with 2 entries:
"a" => 1
"b" => 2
julia> typeof(dict)
DataStructures.SortedDict{String,Int64,Base.Order.ForwardOrdering}

Related

Array of structs with generic function members?

I'm trying construct an array of structs where each instance contains a different function. I want to add these to an array in a loop.
Here's an example:
struct mystruc{F}
σ::F
end
a = [mystruc(relu)]
for i in 1:3
append!(a, [mystruc(identity), ])
end
As a side note, I have the option to preallocate the array I just couldn't figure out how to do with this type of struct.
Each function has a type, which is exclusive to that function:
julia> typeof(x -> x) == typeof(x -> x)
false
Here we created the function x -> x twice, they are two different functions, so their types are not the same.
In your construction of a, you create an Array of that specific type:
julia> a = [mystruc(relu)]
1-element Array{mystruc{typeof(relu)},1}:
mystruc{typeof(relu)}(relu)
julia> typeof(a)
Array{mystruc{typeof(relu)},1}
So when you push another function, we get an error, because this array can only contain objects of the type mystruc{typeof(relu)}.
julia> push!(a, mystruc(x -> 2x))
ERROR: MethodError: Cannot `convert` an object of type
mystruc{var"#3#4"} to an object of type
mystruc{typeof(relu)}
Closest candidates are:
convert(::Type{T}, ::T) where T at essentials.jl:171
mystruc{typeof(relu)}(::Any) where F at REPL[2]:2
Solution
When you construct a, tell Julia that the array will contain mystruc with any function:
julia> a = mystruc{<:Function}[mystruc(relu)]
and now it works!
julia> push!(a, mystruc(x -> 2x))
2-element Array{mystruc{#s1} where #s1<:Function,1}:
mystruc{typeof(relu)}(relu)
mystruc{var"#5#6"}(var"#5#6"())

error generator in Julia JuMP optimization error

I am converting a code in julia 0.6 to 1.2.
Here is the old version:
#variable(model, use[i=eachindex(n), j=1:m], Bin)
Used = [indmax(getvalue(use[i,j])
for j=1:m) for i=eachindex(n)]
I converted to the following,
#variable(model, use[i=eachindex(n), j=1:m], Bin)
JuMP.optimize!(model)
Used = [argmax(JuMP.value(use[i,j])
for j=1:m) for i=eachindex(n)]
but with error:
MethodError: no method matching keys(::Base.Generator{UnitRange{Int64},getfield(Main, Symbol("##261#266")){Int64,JuMP.Containers.SparseAxisArray{VariableRef,2,Tuple{Any,Any}}}})
Closest candidates are:
keys(!Matched::Core.SimpleVector) at essentials.jl:606
keys(!Matched::Cmd) at process.jl:963
keys(!Matched::BenchmarkTools.BenchmarkGroup) at /Users/shuaiwang/.julia/packages/BenchmarkTools/7aqwe/src/groups.jl:31
...
pairs(::Base.Generator{UnitRange{Int64},getfield(Main, Symbol("##261#266")){Int64,JuMP.Containers.SparseAxisArray{VariableRef,2,Tuple{Any,Any}}}}) at abstractdict.jl:132
_findmax(::Base.Generator{UnitRange{Int64},getfield(Main, Symbol("##261#266")){Int64,JuMP.Containers.SparseAxisArray{VariableRef,2,Tuple{Any,Any}}}}, ::Colon) at array.jl:2068
findmax(::Base.Generator{UnitRange{Int64},getfield(Main, Symbol("##261#266")){Int64,JuMP.Containers.SparseAxisArray{VariableRef,2,Tuple{Any,Any}}}}) at array.jl:2065
argmax(::Base.Generator{UnitRange{Int64},getfield(Main, Symbol("##261#266")){Int64,JuMP.Containers.SparseAxisArray{VariableRef,2,Tuple{Any,Any}}}}) at array.jl:2153
(::getfield(Main, Symbol("##260#265")){ScenarioGraph,JuMP.Containers.SparseAxisArray{VariableRef,2,Tuple{Any,Any}}})(::Int64) at none:0
iterate at generator.jl:47 [inlined]
collect at array.jl:606 [inlined]
The problem seems to be unrelated to JuMP. The fix to your code is:
Used = [argmax([JuMP.value(use[i,j]) for j=1:m]) for i=eachindex(n)]
(I have not tested the whole code as it was not complete)
And the core of the issue is that you are not allowed to use argmax on generators, you have to pass a collection that supports pairs to it, e.g.:
julia> argmax(i for i in 1:3)
ERROR: MethodError: no method matching keys(::Base.Generator{UnitRange{Int64},getfield(Main, Symbol("##15#16"))})
fails, but
julia> argmax([i for i in 1:3])
3
julia> argmax((1,2,3))
3
julia> argmax((a=1,b=2,c=3))
:c
julia> argmax(Dict(:a=>1,:b=>2,:c=>3))
:c
work

How do I parse a string to a float or int in Julia?

I am trying to take a string a = "99.99" and then convert it to be of type float. On top of that, I want to be able to convert a to an int as well. How can I do that? The built-in int() and float() functions don't appear to take strings.
julia> a = "99.99"
"99.99"
julia> float(a)
ERROR: MethodError: no method matching AbstractFloat(::String)
Closest candidates are:
AbstractFloat(::Bool) at float.jl:252
AbstractFloat(::Int8) at float.jl:253
AbstractFloat(::Int16) at float.jl:254
...
Stacktrace:
[1] float(::String) at ./float.jl:271
[2] top-level scope at REPL[2]:1
julia> Int(a)
ERROR: MethodError: no method matching Int64(::String)
Closest candidates are:
Int64(::Union{Bool, Int32, Int64, UInt32, UInt64, UInt8, Int128, Int16, Int8, UInt128, UInt16}) at boot.jl:710
Int64(::Ptr) at boot.jl:720
Int64(::Float32) at float.jl:700
...
Stacktrace:
[1] top-level scope at REPL[3]:1
Inspired by this post.
You can use the parse(::Type{T}, ::AbstractString) function, like so:
julia> parse(Float64, "1")
1.0

TypeError typeassert for custom typealias

I fail to understand the following behaviour
a = [1,2,3]
a::Vector # works
d = Dict(0=>a)
typealias DictVector{K,V} Dict{K, Vector{V}}
d::DictVector # fails
the error is the following
TypeError: typeassert: expected Dict{K,Array{V,1}}, got
Dict{Int64,Array{Int64,1}}
in include_string(::String, ::String) at loading.jl:441
in eval(::Module, ::Any) at boot.jl:234
in (::Atom.##65#68)() at eval.jl:40
in withpath(::Atom.##65#68, ::Void) at utils.jl:30
in withpath(::Function, ::Void) at eval.jl:46
in macro expansion at eval.jl:109 [inlined]
in (::Atom.##64#67{Dict{String,Any}})() at task.jl:60
however Vector is itself as typealias Vector{T} Array{T,1} so what is the decisive difference between the two cases?
Any clarification is highly appriciated
You're right that should work. It looks like this was a bug in the old type system in 0.5. It's fixed in the upcoming 0.6 release.
Here's a possible workaround for 0.5:
julia> typealias DictVector{K,V<:Vector} Dict{K,V}
Dict{K,V<:Array{T,1}}
julia> d::DictVector
Dict{Int64,Array{Int64,1}} with 1 entry:
0 => [1,2,3]
julia> isa(d, DictVector)
true

How to initialize a dictionary in Julia?

When I tried to do:
d = {1:2, 3:10, 6:300, 2:1, 4:5}
I get the error:
syntax: { } vector syntax is discontinued
How to initialize a dictionary in Julia?
The {} syntax has been deprecated in julia for a while now. The way to construct a dict now is:
Given a single iterable argument, constructs a Dict whose key-value pairs are taken from 2-tuples (key,value) generated by the argument.
julia> Dict([("A", 1), ("B", 2)])
Dict{String,Int64} with 2 entries:
"B" => 2
"A" => 1
Alternatively, a sequence of pair arguments may be passed.
julia> Dict("A"=>1, "B"=>2)
Dict{String,Int64} with 2 entries:
"B" => 2
"A" => 1
(as quoted from the documentation, which can be obtained by pressing ? in the terminal to access the "help" mode, and then type Dict)

Resources