Python -- Matplotlib for elliptic curve with sympy solve()
Asked Answered
D

2

5

I have an elliptic curve plotted. I want to draw a line along a P,Q,R (where P and Q will be determined independent of this question). The main problem with the P is that sympy solve() returns another equation and it needs to instead return a value so it can be used to plot the x-value for P. As I understood it, solve() should return a value, so I'm clearly doing something wrong here that I'm just totally not seeing. For reference, here's how P+Q=R should look:

enter image description here

I've been going over the docs and other material and this is as far as I've been able to get myself into trouble:

from mpl_toolkits.axes_grid.axislines import SubplotZero
from pylab import *
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
from matplotlib import rc
import random
from sympy.solvers import solve
from sympy import *


def plotGraph():
    fig = plt.figure(1)
    #ax = SubplotZero(fig, 111)
    #fig.add_subplot(ax)
    #for direction in ["xzero", "yzero"]:
        #ax.axis[direction].set_axisline_style("-|>")
        #ax.axis[direction].set_visible(True)
    #ax.axis([-10,10,-10,10])
    a = -2; b = 1
    y, x = np.ogrid[-10:10:100j, -10:10:100j]
    xlist = x.ravel(); ylist = y.ravel()
    elliptic_curve = pow(y, 2) - pow(x, 3) - x * a - b
    plt.contour(xlist, ylist, elliptic_curve, [0])
    #rand = random.uniform(-5,5)
    randmid = random.randint(30,70)
    #y = ylist[randmid]; x = xlist[randmid]
    xsym, ysym = symbols('x ylist[randmid]')
    x_result = solve(pow(ysym, 2) - pow(xsym, 3) - xsym * a - b, xsym) # 11/5/13 needs to return a value
    plt.plot([-1.5,5], [-1,8], color = "c", linewidth=1) # plot([x1,x2,x3,...],[y1,y2,y3,...])
    plt.plot([xlist[randmid],5], [ylist[randmid],8], color = "m", linewidth=1)
    #rc('text', usetex=True)
    text(-9,6,' size of xlist: %s \n size of ylist: %s \n x_coord: %s \n random_y: %s'
        %(len(xlist),len(ylist),x_result,ylist[randmid]),
        fontsize=10, color = 'blue',bbox=dict(facecolor='tan', alpha=0.5))
    plt.annotate('$P+Q=R$', xy=(2, 1), xytext=(3, 1.5),arrowprops=dict(facecolor='black', shrink=0.05))

##    verts = [(-5, -10),(5, 10)] # [(x,y)startpoint,(x,y)endpoint] #,(0, 0)]
##    codes = [Path.MOVETO,Path.LINETO] # related to verts[] #,Path.STOP]
##    path = Path(verts, codes)
##    patch = patches.PathPatch(path, facecolor='none', lw=2)
##    ax.add_patch(patch)

    plt.grid(True)
    plt.show()


def main():
    plotGraph()


if __name__ == '__main__':
    main()

Ultimately, I'd like to draw a line to show P+Q=R, so if someone also has something to add on how to code to get the Q that would be greatly appreciated. I'm teaching myself about Python and elliptic curves so I'm sure that any entry-level programmer can figure out in 2 minutes what I've been on for some time already.

Diphthongize answered 5/11, 2013 at 22:41 Comment(2)
Creating a Symbol called ylist[randmid] doesn't in any way link it to the Python variables ylist and randmid.Shovel
Hi. Do you have full solution?Iverson
L
9

I don't know what are you calculating, but here is the code that can plot the graph:

import numpy as np
import pylab as pl

Y, X = np.mgrid[-10:10:100j, -10:10:100j]

def f(x):
    return x**3 -3*x + 5

px = -2.0
py = -np.sqrt(f(px))

qx = 0.5
qy = np.sqrt(f(qx))

k = (qy - py)/(qx - px)
b = -px*k + py 

poly = np.poly1d([-1, k**2, 2*k*b+3, b**2-5])

x = np.roots(poly)
y = np.sqrt(f(x))

pl.contour(X, Y, Y**2 - f(X), levels=[0])
pl.plot(x, y, "o")
pl.plot(x, -y, "o")

x = np.linspace(-5, 5)
pl.plot(x, k*x+b)

graph:

enter image description here

Lop answered 6/11, 2013 at 12:49 Comment(3)
Yes thanks that's helpful and also a good learning example for my future coding, +1 and accepted.Diphthongize
Is there a way to draw the coordinates, too?Donohue
This answer provides a way to draw the coordinates by using plot.figure ; How can I draw axis lines inside a plot in Matplotlib?Donohue
N
0

based on HYRY's answer, I just update some details to make it better:

import numpy as np
import pylab as pl

Y, X = np.mgrid[-10:10:100j, -10:10:100j]

def f(x, a, b):
    return x**3 + a*x + b

a = -2
b = 4
# the 1st point: 0, -2
x1 = 0
y1 = -np.sqrt(f(x1, a, b))
print(x1, y1)

# the second point
x2 = 3 
y2 = np.sqrt(f(x2, a, b))
print(x2, y2)

# line: y=kl*x+bl
kl = (y2 - y1)/(x2 - x1)
bl = -x1*kl + y1 # bl = -x2*kl + y2

# y^2=x^3+ax+b , y=kl*x+bl => [-1, kl^2, 2*kl*bl, bl^2-b]
poly = np.poly1d([-1, kl**2, 2*kl*bl-a, bl**2-b])

# the roots of the poly
x = np.roots(poly)
y = np.sqrt(f(x, a, b))
print(x, y)

pl.contour(X, Y, Y**2 - f(X, a, b), levels=[0])
pl.plot(x, y, "o")
pl.plot(x, -y, "o")

x = np.linspace(-5, 5)
pl.plot(x, kl*x+bl)

And we got the roots of this poly: [3. 2.44444444 0. ] [5. 3.7037037 2. ]

Negrete answered 1/12, 2022 at 10:26 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.