Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parametrize safe/unsafe inserts #42

Merged
merged 2 commits into from
Jun 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/SparseVariables.jl
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export SparseArray
export IndexedVarArray
export insertvar!
export unsafe_insertvar!
export SafeInsert, UnsafeInsert

@setup_workload begin
# Putting some things in `setup` can reduce the size of the
Expand Down
22 changes: 19 additions & 3 deletions src/indexedarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ struct IndexedVarArray{V<:AbstractVariableRef,N,T} <: AbstractSparseArray{V,N}
index_cache::Vector{Dictionary}
end

struct SafeInsert end
struct UnsafeInsert end

_data(sa::IndexedVarArray) = sa.data

already_defined(var, index) = haskey(_data(var), index)
Expand Down Expand Up @@ -37,23 +40,36 @@ end
Insert a new variable with the given index only after checking if keys are valid and not already defined.
"""
function insertvar!(var::IndexedVarArray{V,N,T}, index...) where {V,N,T}
return insertvar!(var, SafeInsert(), index...)
end
function insertvar!(
var::IndexedVarArray{V,N,T},
::SafeInsert = SafeInsert(),
index...,
) where {V,N,T}
!valid_index(var, index) && throw(BoundsError(var, index))# "Not a valid index for $(var.name): $index"g
already_defined(var, index) && error("$index already defined for array")

var[index] = var.f(index...)

clear_cache!(var)
return var[index]
end

function insertvar!(
var::IndexedVarArray{V,N,T},
::UnsafeInsert,
index...,
) where {V,N,T}
return var[index] = var.f(index...)
end

"""
unsafe_insertvar!(var::indexedVarArray{V,N,T}, index...)

Insert a new variable with the given index withouth checking if the index is valid or
already assigned.
"""
function unsafe_insertvar!(var::IndexedVarArray{V,N,T}, index...) where {V,N,T}
return var[index] = var.f(index...)
return insertvar!(var, UnsafeInsert(), index...)
end

joinex(ex1, ex2) = :($ex1..., $ex2...)
Expand Down
3 changes: 3 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,9 @@ end
unsafe_insertvar!(x, 2, 102)
@test length(x) == 2

insertvar!(x, UnsafeInsert(), 2, 103)
@test length(x) == 3

# When no names are provided
@variable(m, y[1:3, 100:102] >= 0, container = IndexedVarArray)
@test length(y) == 0
Expand Down