I have the following SageMath code, which works perfectly in CoCalc:
def mean_x(factor, values):
return sum([cos(2*pi*v/factor) for v in values])/len(values)
def mean_y(factor, values):
return sum([sin(2*pi*v/factor) for v in values])/len(values)
def calculatePeriodAppeal(factor, values):
mx = mean_x(factor, values)
my = mean_y(factor, values)
appeal = sqrt(mx^2+my^2)
return appeal
def calculateBestLinear(factor, values):
mx = mean_x(factor, values).n()
my = mean_y(factor, values).n()
y0 = factor*atan2(my,mx)/(2*pi).n()
err = 1-sqrt(mx^2+my^2).n()
return [factor*x + y0, err]
def calculateGCDAppeal(factor, values):
mx = mean_x(factor, values)
my = mean_y(factor, values)
appeal = 1 - sqrt((mx-1)^2+my^2)/2
return appeal
testSeq = [0,125,211,287,408,520,650,735,816,942,1060]
gcd = calculateGCDAppeal(x, testSeq)
agcd = find_local_maximum(gcd,2,100)
print(agcd)
plot(gcd,(x, 2, 100))
The output is the best approximate greatest common divisor of the numbers from testSeq
, along with a plot.
How can I use this code in Python?
Here is the current Python version, which does not yet work:
import numpy as np
import sage as sm
def mean_x(factor, values):
return sum([np.cos(2*np.pi*v/factor) for v in values])/len(values)
def mean_y(factor, values):
return sum([np.sin(2*np.pi*v/factor) for v in values])/len(values)
def calculatePeriodAppeal(factor, values):
mx = mean_x(factor, values)
my = mean_y(factor, values)
appeal = np.sqrt(mx**2+my**2)
return appeal
def calculateBestLinear(factor, values):
mx = mean_x(factor, values).n()
my = mean_y(factor, values).n()
y0 = factor*np.atan2(my,mx)/(2*np.pi).n()
err = 1-np.sqrt(mx**2+my**2).n()
return [factor*x + y0, err]
def calculateGCDAppeal(factor, values):
mx = mean_x(factor, values)
my = mean_y(factor, values)
appeal = 1 - np.sqrt((mx-1)**2+my**2)/2
return appeal
testSeq = [0,125,211,287,408,520,650,735,816,942,1060]
gcd = calculateGCDAppeal(x, testSeq)
agcd = sm.find_local_maximum(gcd,2,100)
print(agcd)
The errors I get are:
Traceback (most recent call last):
File "<ipython-input-805-d2a8b405fd43>", line 30, in <module>
gcd = calculateGCDAppeal(x, testSeq)
NameError: name 'x' is not defined
I don't understand this because because this code works in CoCalc.
Traceback (most recent call last):
File "<ipython-input-803-80cdeb0485a5>", line 33, in <module>
agcd = sm.find_local_maximum(gcd,2,100)
AttributeError: module 'sage' has no attribute 'find_local_maximum'
...but I know that SageMath has the function find_local_maximum.
If I use numerical.optimize.find_local_maximum
instead, I get:
Traceback (most recent call last):
File "<ipython-input-842-949de8b03df5>", line 34, in <module>
agcd = sm.numerical.optimize.find_local_maximum(gcd,2,100)
AttributeError: module 'sage' has no attribute 'numerical'
I don't know how to add the "numerical" attribute.