Skip to content

Add option to pass a callback function to optimize()#79

Merged
HarrisonKramer merged 2 commits intomasterfrom
feat/optimization_callback
Feb 22, 2025
Merged

Add option to pass a callback function to optimize()#79
HarrisonKramer merged 2 commits intomasterfrom
feat/optimization_callback

Conversation

@drpaprika
Copy link
Collaborator

@drpaprika drpaprika commented Feb 22, 2025

This simple PR allows to pass a callback function to scipy's optimize().
This allows the user to add anything he likes to vizualize the optimization progress, for example (tested in a notebook):

import matplotlib.pyplot as plt
from IPython.display import clear_output

optimizer = optimization.OptimizerGeneric(problem)

history = []
def callback(_):
    # Plot the lens at each merit function call
    clear_output(wait=True)
    lens.draw()
    
    # Plot merit function evolution
    f_val = optimizer.problem.sum_squared()
    history.append(f_val)
    plt.figure(figsize=(6, 4))
    plt.plot(history, color='black')
    plt.yscale('log')
    plt.title("Merit function value")
    plt.xlabel("Iteration")
    plt.ylabel("Merit function value")
    plt.grid(alpha=0.25)
    plt.show()

res = optimizer.optimize(tol=1e-9, callback=callback)

plot_during_optimization

Only LeastSquares doesn't seem to accept a callback function.

I also included a fix to update the lens at the end of the optimization with the best paramerters (result.x), as the last merit function call is not necessarily the lowest one.

Of course plotting during the optimization slows it significantly, but that's up to the user.
drpaprika

@codecov
Copy link

codecov bot commented Feb 22, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Impacted file tree graph

@@            Coverage Diff             @@
##           master      #79      +/-   ##
==========================================
- Coverage   96.57%   96.56%   -0.02%     
==========================================
  Files         105      105              
  Lines        6340     6348       +8     
==========================================
+ Hits         6123     6130       +7     
- Misses        217      218       +1     
Files with missing lines Coverage Δ
optiland/optimization/optimization.py 98.17% <100.00%> (+0.03%) ⬆️

... and 1 file with indirect coverage changes

@HarrisonKramer
Copy link
Owner

Looks good. Thanks for the contribution!

And nice catch on updating to the best parameters after the optimization completes. I'll merge now.

Regards,
Kramer

@HarrisonKramer HarrisonKramer merged commit 440b21d into master Feb 22, 2025
6 checks passed
@HarrisonKramer HarrisonKramer deleted the feat/optimization_callback branch February 22, 2025 12:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants