Skip to content

Commit

Permalink
BUG: manually call the iteration callback instead of relying on the d…
Browse files Browse the repository at this point in the history
…efunct Knitro callback
  • Loading branch information
jeffgortmaker committed May 6, 2018
1 parent a8c6e2a commit ec19f74
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions pyblp/utilities/optimization.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,10 +303,17 @@ def knitro_optimizer(initial_values, bounds, objective_function, iteration_callb
"file."
)

# define a function that handles requests to compute either the objective or its gradient, which are cached
# define a function that handles requests to compute either the objective or its gradient (which are cached for
# when the next request is for the same values) and calls the iteration callback when there's a new iteration
def combined_callback(*args):
request_code, values, objective_store, gradient_store = (args[i] for i in [0, 5, 7, 9])

# call the iteration callback if this is a new iteration
iterations = knitro.KTR_get_number_iters(knitro_context)
while combined_callback.iterations < iterations:
iteration_callback()
combined_callback.iterations += 1

# compute the objective or used cached values
if combined_callback.cache is not None and np.array_equal(values, combined_callback.cache[0]):
combined = combined_callback.cache[1]
Expand All @@ -326,12 +333,12 @@ def combined_callback(*args):
return knitro.KTR_RC_BEGINEND
return knitro.KTR_RC_CALLBACK_ERR

# initialize an empty cache
# initialize an empty cache and the counter
combined_callback.cache = None
combined_callback.iterations = 0

# configure Knitro callbacks
callback_mapping = {
knitro.KTR_set_newpt_callback: lambda *_: iteration_callback(),
knitro.KTR_set_func_callback: combined_callback,
knitro.KTR_set_grad_callback: combined_callback
}
Expand Down

0 comments on commit ec19f74

Please sign in to comment.