@@ -164,3 +164,33 @@ variable_by_name(model, "x") === nothing
164
164
# For more information on the difference between string names, symbolic
165
165
# names, and bindings, see
166
166
# [String names, symbolic names, and bindings](@ref variable_names_and_bindings).
167
+
168
+ # ## Sparsity
169
+
170
+ # JuMP executes the code that you write without trying to be clever about
171
+ # multiplication by `0.0`. For example, consider this model:
172
+
173
+ d = 100_000
174
+ a = zeros (d);
175
+ a[3 ] = 1.0
176
+ model = Model ();
177
+ @variable (model, x[1 : d]);
178
+ complicated_expression (x, i) = x[i]^ 2
179
+ @expression (model, sum (a[i] * complicated_expression (x, i) for i in 1 : d))
180
+
181
+ # Although the final expression consists of a single element, the sum is over
182
+ # 100,000 elements, all but one of which are then multiplied by `0.0`. The
183
+ # `@expression` line is equivalent to:
184
+
185
+ expr = zero (QuadExpr)
186
+ for i in 1 : d
187
+ tmp = complicated_expression (x, i)
188
+ global expr = add_to_expression! (expr, a[i], tmp)
189
+ end
190
+
191
+ # Notice how we compute `complicated_expression` in every iteration, even though
192
+ # most results will be discarded. You can improve the performance of model
193
+ # construction by pre-computing the set of non-zero indices:
194
+
195
+ indices = [i for i in 1 : d if ! iszero (a[i])]
196
+ @expression (model, sum (a[i] * complicated_expression (x, i) for i in indices))
0 commit comments