I have a complete working code that uses scipy.optimize.minimize
but always returns the initial value as the optimized scalar parameter. Here is the complete code:
import sysimport randomimport numpy as npimport matplotlib.pyplot as pltimport scipy.optimize as opt# Define the real shiftshift = 50.5data1_x = []data1_y = []data2_x = []data2_y = []for index in range(int(shift)): data2_x.append(index) data2_y.append(0)for index in range(500): x = index if index<100: y = 0 elif index<200: y = (index-100) elif index<300: y = 100 elif index<400: y = 400 - index else: y = 0 data1_x.append(x) data1_y.append(y) data2_x.append(x + shift) data2_y.append(y)index_range = range(len(data2_x))# The function to minimize, returning a floatdef overlap(shift, data1_x, data1_y, data2_x, data2_y): sum_ = 0 for index1 in range(len(data1_x)): x1 = data1_x[index1] + shift[0] index2 = min(index_range, key=lambda i: abs(data2_x[i]-x1)) x2 = data2_x[index2] y1 = data1_y[index1] y2 = data2_y[index2] # Ignore x values outside of common range if abs(x2-x1)>5: continue sum_ += abs(y2 - y1) return sum_# Here chose some other initial value instead of '40'.result = opt.minimize(overlap, 40, args=(data1_x, data1_y, data2_x, data2_y))# Print message indicating why the process terminatedprint(result.message)# Print the minimum value of the functionprint(result.fun)# Print the x-value resulting in the minimum valueprint(result.x)calculated_shift = result.x[0]# Plot the original and shifted signals along with cross-correlationplt.subplot(2, 1, 1)plt.scatter(data1_x, data1_y, s=20, marker="o", c="b", label="Data1")plt.scatter(data2_x, data2_y, s=5, marker="o", c="g", label="Data2")plt.legend()plt.subplot(2, 1, 2)plt.scatter(data1_x, data1_y, s=20, marker="o", c="b", label="Data1")plt.scatter([x-calculated_shift for x in data2_x], data2_y, s=5, marker="o", c="g", label="Data2")plt.legend()plt.tight_layout()plt.show()
Why does optimize
not optimize?