# Optimize slow constraint generation

**URL:** <https://discourse.julialang.org/t/optimize-slow-constraint-generation/21996>\
**Category:** Optimization (Mathematical)\
**Created:** [March 18, 2019, 10:56am UTC](https://discourse.julialang.org/t/optimize-slow-constraint-generation/21996 "2019-03-18T10:56:48Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Di11on](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/di11on/32/6352_2.png) [@Di11on](https://discourse.julialang.org/u/Di11on)\
**Post date:** [March 18, 2019, 10:56am UTC](https://discourse.julialang.org/t/optimize-slow-constraint-generation/21996/1 "2019-03-18T10:56:48Z")

</div>

This is somewhat related to my other post ([Deleting containerized constraints](https://discourse.julialang.org/t/deleting-containerized-constraints/21971)) but here, I want to see if there is a way to formulate my constraint differently.

Following advice in [this thread](https://discourse.julialang.org/t/slow-generation-of-a-large-lp-model-in-jump/3034), I put all my variable and constraint creation statements inside individual functions. This improved model generation time significantly. However, the following constraint is taking 30 seconds to formulate with 369 nodes and 548 branches:

```julia
function gen_q_baseflow(v_baseflow,v_net_injection,ptdf_b_n)
    @constraint(m,
        q_baseflow[b in branch(), (t,s) in T_S],
        + v_baseflow[b,t,s]
        ==
        + sum( ptdf_b_n[b,n] * v_net_injection[n,t,s] for n in injection_nodes if abs(ptdf_b_n[b,n]) > tx_pdtf_tolerance(settings=:TRANSMISSION))
    )
end

```

here `ptdf_b_n[b,n]` is `AxisArray{Float64,2,Array{Float64,2},Tuple{Axis{:branch,Array{Symbol,1}},Axis{:node,Array{Symbol,1}}}}`

What can I do to improve the creation time of this?

---

<div class="post-metadata">

**Author:** ![Di11on](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/di11on/32/6352_2.png) [@Di11on](https://discourse.julialang.org/u/Di11on)\
**Post date:** [March 18, 2019, 12:55pm UTC](https://discourse.julialang.org/t/optimize-slow-constraint-generation/21996/2 "2019-03-18T12:55:25Z")

</div>

Ok, so I’ve got the constraint generation time down to \< 2 seconds by constructing a Dict which holds for every b only the nodes where abs(ptdf\_b\_n[b,n] ) \> tolerance
