# Dynamically adding constraints with @constraintref

**URL:** https://discourse.julialang.org/t/dynamically-adding-constraints-with-constraintref/13830
**Category:** Optimization (Mathematical)
**Created:** [August 21, 2018, 1:13pm UTC](https://discourse.julialang.org/t/dynamically-adding-constraints-with-constraintref/13830 "2018-08-21T13:13:45Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![mm0063](https://avatars.discourse-cdn.com/v4/letter/m/74df32/32.png) [@mm0063](https://discourse.julialang.org/u/mm0063)
#### Post date: [August 21, 2018, 1:13pm UTC](https://discourse.julialang.org/t/dynamically-adding-constraints-with-constraintref/13830/1 "2018-08-21T13:13:45Z")

</div>

Dear all,

I am trying to dynamically add constraints to my model as in the example below. However, this formulation results in the error stated below the formulation. I believe that the problem occurs due to the [t in t\_a] in the @constraint command. Does anyone have an idea how this can be solved?

Z = @variable(m, [t in ts, cg in cgs, lt in lts2], Bin)  
@constraintref limit\_activation2[cgs, lts2]  
for cg in cgs  
for lt in lts2  
t\_a = [t for t in ts if t \< L[t][cg][lt][“t\_k”]]

```
           limit_activation2[cg,lt] = @constraint(m, [t in t_a], Z[t,cg,lt] == 0 )
    end

```

end

Error: MethodError: Cannot `convert` an object of type JuMP.JuMPArray{JuMP.ConstraintRef,  
1,Tuple{Array{Int64,1}}} to an object of type JuMP.ConstraintRef  
This may have arisen from a call to the constructor JuMP.ConstraintRef(…),  
since type constructors fall back to convert methods.

---

<div class="post-metadata">

### Author: ![blegat](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/blegat/32/217090_2.png) [@blegat](https://discourse.julialang.org/u/blegat)
#### Post date: [August 21, 2018, 1:24pm UTC](https://discourse.julialang.org/t/dynamically-adding-constraints-with-constraintref/13830/2 "2018-08-21T13:24:38Z")

</div>

`@constraintref` creates a container for holding `ConstraintRef` elements but there the elements have type `JuMP.JuMPArray{JuMP.ConstraintRef, 1,Tuple{Array{Int64,1}}}`.  
The easiest way to solve this would be to do

```julia
limit_activation2 = Dict{Tuple{eltype(cgs), eltype(lts2)}, JuMP.JuMPArray{JuMP.ConstraintRef,
1,Tuple{Array{Int64,1}}}}()
...
for ...
    ...
    limite_activation[(cg, lt)] = ...
end

```

If you prefer using an array instead of a dictionary, you can use [AxisArrays](https://github.com/JuliaArrays/AxisArrays.jl)
