@@ -146,7 +146,6 @@ def solve(self, problem: QuadraticProgram) -> OptimizationResult:
146
146
x_j = problem_ .variables [j ].name
147
147
if correlations [i , j ] > 0 :
148
148
# set x_i = x_j
149
- problem_ .substitute_variables ()
150
149
problem_ = problem_ .substitute_variables (variables = {i : (j , 1 )})
151
150
if problem_ .status == QuadraticProgram .Status .INFEASIBLE :
152
151
raise QiskitOptimizationError ('Infeasible due to variable substitution' )
@@ -158,16 +157,23 @@ def solve(self, problem: QuadraticProgram) -> OptimizationResult:
158
157
159
158
# 1a. get additional offset
160
159
constant = problem_ .objective .constant
161
- constant += problem_ .objective .quadratic [i , i ]
162
160
constant += problem_ .objective .linear [i ]
161
+ constant += problem_ .objective .quadratic [i , i ]
163
162
problem_ .objective .constant = constant
164
163
165
164
# 1b. get additional linear part
166
165
for k in range (problem_ .get_num_vars ()):
167
- coeff = problem_ .objective .quadratic [i , k ]
166
+ coeff = problem_ .objective .linear [k ]
167
+ if k == i :
168
+ coeff += 2 * problem_ .objective .quadratic [i , k ]
169
+ else :
170
+ coeff += problem_ .objective .quadratic [i , k ]
171
+
172
+ # set new coefficient if not too small
168
173
if np .abs (coeff ) > 1e-10 :
169
- coeff += problem_ .objective .linear [k ]
170
174
problem_ .objective .linear [k ] = coeff
175
+ else :
176
+ problem_ .objective .linear [k ] = 0
171
177
172
178
# 2. replace x_i by -x_j
173
179
problem_ = problem_ .substitute_variables (variables = {i : (j , - 1 )})
@@ -211,7 +217,16 @@ def find_value(x, replacements, var_values):
211
217
return results
212
218
213
219
def _find_strongest_correlation (self , correlations ):
214
- m_max = np .argmax (np .abs (correlations .flatten ()))
220
+
221
+ # get absolute values and set diagonal to -1 to make sure maximum is always on off-diagonal
222
+ abs_correlations = np .abs (correlations )
223
+ for i in range (len (correlations )):
224
+ abs_correlations [i , i ] = - 1
225
+
226
+ # get index of maximum (by construction on off-diagonal)
227
+ m_max = np .argmax (abs_correlations .flatten ())
228
+
229
+ # translate back to indices
215
230
i = int (m_max // len (correlations ))
216
231
j = int (m_max - i * len (correlations ))
217
232
return (i , j )
0 commit comments