1D Example#

[ ]:
import numpy as np
import cbx
import matplotlib.pyplot as plt

#%% define the objective function and solve
def f(x):
    return np.abs(np.sin(x)) + np.abs(x)**(3/4) * (np.sin(x)+1) - 0.5*(np.abs(x)>1)
dyn = cbx.dynamics.CBO(f, d=1, verbosity=0, max_it=10)
x = dyn.optimize()

#%% visualize
plt.close('all')
s = np.linspace(-4,4,1000)
plt.plot(s, f(s), linewidth=3, color='xkcd:sky', label='Objective', zorder=-1)
plt.scatter(x, f(x), label='Solution', c='green', s=50, marker='x')
plt.scatter(dyn.x, f(dyn.x), label='Solution', c='xkcd:red', s=30, marker='.')
plt.xlim([-4,4])
plt.legend()
plt.tight_layout()
plt.savefig('1D')