When I change the location of J = 0 (I showed in the code below), I am having the error.
Well yes. That makes sense, since you define another variable with the name J
four lines further down:
J = 0 # it does not work if I move it here
a_d, b_d, c_d, d_d = poly(desired_response_x, desired_response_y)
for i in np.linspace(0, max_disp, N):
disp.assign(Constant([0.0, i, 0.0]))
Ic, J, F, C, I, E = kinematics(u)
Also, I expect my optimized coefficients to change but they still the same after the optimization.
What initial values are you using? Did you already try using a different set of initial values to see whether those are changed in any way by the optimization process?