The following python code uses the nlopt library to train a qonn (quantum optical neural net) to learn the fuctionality of a CNOT gate:
import numpy as np
import bosonic as b
import nlopt
global psi_in, psi_out, system
system, info = b.qonn.build_system_function(2, 4, 2, phi=3.141592653589793, method='clements', lossy=False) #phi is strength nonlinearity
#CNOT dataset
K=4 #aantal input-output pairs
psi_in = np.array([
[[0], [0], [1], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [1], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [1], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [1], [0], [0], [0]]], dtype=complex)
psi_out = np.array([
[[0], [0], [1], [0], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [1], [0], [0], [0], [0], [0], [0]],
[[0], [0], [0], [0], [0], [0], [1], [0], [0], [0]],
[[0], [0], [0], [0], [0], [1], [0], [0], [0], [0]]], dtype=complex)
#cost function
def costfunc(theta):
S = system(theta)
K = psi_in.shape[0]
res = 1
for i in range(K):
temp = np.dot(S,psi_in[i])
temp2 = np.dot(np.transpose(psi_out[i]),temp)
res -= (1/K) * ((np.absolute(temp2)) ** 2)
return res
#nlopt
opt = nlopt.opt(nlopt.LN_BOBYQA, info['numPhases'])
opt.set_min_objective(costfunc)
opt.set_lower_bounds([0]*info['numPhases'])
opt.set_upper_bounds([2*np.pi]*info['numPhases'])
opt.set_maxtime(3)
theta = np.random.rand(info['numPhases'])*2*np.pi
theta_opt = opt.optimize([1]*info['numPhases'])
minf = opt.last_optimum_value()
print("minimum value = ", minf)
but I get the following error:
File ".../BOBYQA.py", line 43, in <module>
theta_opt = opt.optimize([1]*info['numPhases'])
File "User\Anaconda3\lib\site-packages\nlopt.py", line 334, in optimize
return _nlopt.opt_optimize(self, *args)
TypeError: costfunc() takes 1 positional argument but 2 were given
What am I doing wrong? I am not a python expert. Thanks in advance
Optimization objective function signature is incorrect. Please change your objective function to be of the form
f(x, grad)
.NLOPT doc reference, go to Objective Function: https://nlopt.readthedocs.io/en/latest/NLopt_Python_Reference/