# Example sum of two quadratic functions.importnumpyasnpimportmatplotlib.pyplotaspltfromscipy.ioimportsavematfrommiscimportgnuplotsavefrommiscimportellipseimportos# def ellipse(A, level, npts, center):# """Generate points on an ellipse"""# theta = np.linspace(0, 2*np.pi, npts)# eigvals, eigvecs = np.linalg.eig(A)# # Get points on unit circle# circle_pts = np.vstack([np.cos(theta), np.sin(theta)])# # Transform circle to ellipse# scale = np.sqrt(level/eigvals)[:, np.newaxis]# transform = eigvecs @ np.diag(scale.flatten())# ellipse_pts = transform @ circle_pts# # Shift by center point# x = ellipse_pts[0,:] + center[0]# y = ellipse_pts[1,:] + center[1]# return x, y# Example sum of two quadratic functionsa=np.array([-1,0]).reshape(-1,1)b=np.array([1,1]).reshape(-1,1)A=np.array([[1.25000,0.75000],[0.75000,1.25000]])B=np.array([[1.50000,-0.50000],[-0.50000,1.50000]])# add the two quadraticsH=A+Bh=np.linalg.solve(H,A@a+B@b)d=-(A@a+B@b).T@h+a.T@A@a+b.T@B@b# plot resulting ellipse for combining two ellipses# V(x) = V_1(x) + V_2(x)level=0.5npts=50xA,yA,*_=ellipse(A,level,npts,a.flatten())xB,yB,*_=ellipse(B,level,npts,b.flatten())level=(2-d/2)*2xH,yH,*_=ellipse(H,level,npts,h.flatten())ifnotos.getenv('OMIT_PLOTS')=='true':plt.plot(xA,yA,'-r',a[0],a[1],'or',xB,yB,'-g',b[0],b[1],'og',xH,yH,'-b',h[0],h[1],'ob')plt.legend(['A','a','B','b','H = A + B','h'],loc='upper left')# Save datadata={}data['contours']=np.column_stack([xA,yA,xB,yB,xH,yH])data['centers']=np.column_stack([a.T,b.T,h.T])# Save to dat filegnuplotsave('nestedV.dat',data);