how can i convert my sympy code to symengine in python - python

This code I wrote in Sympy is running slow. I want to write this with symengine. How can I translate? I had some difficulty with the Solve commands. Can you help me ?
Edit: Here is my code:
import sympy as sy
import time
#import numpy as np
import math as mat
from sympy import Eq
testere_capi=197
dis_sayisi=78
ic_acisi = 16
sirt_acisi = 8
derinlik_carpani = 0.4
kucuk_daire_carpani = 0.25
buyuk_daire_carpani = 0.8
son_dogrunun_carpani = 0.06
tas_kalinligi = 2.0
T = ((testere_capi * mat.pi) / dis_sayisi) # hatve
H = T * derinlik_carpani # derinlik
x = sy.symbols("x")
y = sy.symbols("y")
D2 = sy.Eq(y, H)
a8 = 0
b8 = 0
m_d1 = mat.tan(mat.radians(90 - ic_acisi))
D1 = sy.Eq(y - b8, m_d1 * (x - a8))
S1 = sy.solve((D2, D1), (x, y))
a1 = S1[x]
b1 = S1[y]
b2 = T * kucuk_daire_carpani
a2 = b2 / mat.tan(mat.radians(90 - ic_acisi) / 2)
r1 = T * kucuk_daire_carpani
D3 = sy.Eq((x - a2) ** 2 + (y - b2) ** 2, r1 ** 2)
D1 = sy.expand(D1)
D3 = sy.expand(D3)
S7 = sy.solve((D1,D3),(x,y))
a7 = S7[0][0]
b7 = S7[0][1]

Related

My output seems to be wrong in comparison to symbolab

Getting wrong output for this equation. Can someone review my code?
from math import cos
from math import sin
from math import pi
a0 = int(input("a0:"))
b0 = int(input("b0:"))
N = int(input("N:"))
L = int(input("L:"))
X = int(input("X:"))
n = 0
an = a0
bn = b0
y=0
for i in range(N):
an = an + 10 # since our first value would An = A0 +10 , we could just loop the values by adding 10 to it
bn = bn * 10
y= an * cos((n*pi*X/(L))) + bn*(sin(n*pi*X/(L)))
print(y)
y= an * cos((n*pi*X/(L))) + bn*(sin(n*pi*X/(L)))
There's never any change in the n variable! Given that n starts (and remains) at 0, you always calculate
an * cos(0) + bn * sin(0) == an * 1 + bn * 0 == an
Furthermore you need to add the result to the y variable, not just assign it. And you need to prime the y variable with a0.
an = a0
bn = b0
c = 0
d = pi * X / L # precalculating for efficiency
y = a0
for i in range(N):
an = an + 10
bn = bn * 10
c = c + d
y = y + an * cos(c) + bn * sin(c)
print(y)

How to store values found within loops?

I am trying to run multiple nested loops and then retrieve an array of values based on a condition within the loop. I have 14 alpha values I need to test, and each on needs to be tested for an epoch of 1, 2, 3, 4, 5, 6. As I test each alpha value for all 6 epochs I want to record the number of times the error is less then 0.05. At the end I want a 2D array where the rows represent the 14 different alpha values and each column is a different epoch value.
I want to know if there is a better way of doing this then using a tensor with numpy. Using this method gives me a lot of issues when I try to scale this project.
For people who are interested this is just a 2 input, single hidden layer, output neural network to teach myself about back propagation. The code i submitted is for 2 neurons but I am trying to scale this to 4 right now and eventually n neurons. And storing the error values and calculating the success to output in a 2D array where I could see what alpha and epoch pair produce the best results would be very helpful.
I have already completed this task before using this code:
import numpy as np
for l in range(0,14):
alpha = [0.001, 0.002, 0.003, 0.004, 0.005, 0.006, 0.007, 0.008, 0.009, 0.01, 0.02, 0.03, 0.04, 0.05]
nEpoch=1
for n in range(0,6):
nSuccess = 0
w11f = np.zeros(nEpoch*nTrain)
w12f = np.zeros(nEpoch*nTrain)
for j in range(0,50):
w11 = 0.5 - np.random.rand();
w12 = 0.5 - np.random.rand();
w21 = 0.5 - np.random.rand();
w22 = 0.5 - np.random.rand();
w31 = 0.5 - np.random.rand();
w32 = 0.5 - np.random.rand();
w41 = 0.5 - np.random.rand();
w42 = 0.5 - np.random.rand();
b4 = 0.5 - np.random.rand();
b3 = 0.5 - np.random.rand();
b2 = 0.5 - np.random.rand();
b1 = 0.5 - np.random.rand();
ww1 = 0.5 - np.random.rand();
ww2 = 0.5 - np.random.rand();
ww3 = 0.5 - np.random.rand();
ww4 = 0.5 - np.random.rand();
bb = 0.5 - np.random.rand();
sp = random.sample(a,nTrain + nTest)
p = 0
for epoch in range(0,nEpoch):
for i in range(0,nTrain):
y1 = b1 + w11*x[sp[i],0] + w12*x[sp[i],1]
y2 = b2 + w21*x[sp[i],0] + w22*x[sp[i],1]
y3 = b3 + w31*x[sp[i],0] + w32*x[sp[i],1]
y4 = b4 + w41*x[sp[i],0] + w42*x[sp[i],1]
dxx1 = y1 > 0
xx1 = y1*dxx1
dxx2 = y2 > 0
xx2 = y2*dxx2
dxx3 = y3 > 0
xx3 = y3*dxx3
dxx4 = y4 > 0
xx4 = y4*dxx4
yy = bb + ww1*xx1 + ww2*xx2 + ww3*xx3 + ww4*xx4
yy = yy > 0
e = t[sp[i]] - yy
#Updating parameters
ww1 = ww1 + alpha[l]*e*xx1
ww2 = ww2 + alpha[l]*e*xx2
ww3 = ww3 + alpha[l]*e*xx3
ww4 = ww4 + alpha[l]*e*xx4
bb = bb + alpha[l]*e
w11 = w11 + alpha[l]*e*ww1*dxx1*x[sp[i],0]
w12 = w12 + alpha[l]*e*ww1*dxx1*x[sp[i],1]
w21 = w21 + alpha[l]*e*ww2*dxx2*x[sp[i],0]
w22 = w22 + alpha[l]*e*ww2*dxx2*x[sp[i],1]
w31 = w31 + alpha[l]*e*ww3*dxx3*x[sp[i],0]
w32 = w32 + alpha[l]*e*ww3*dxx3*x[sp[i],1]
w41 = w41 + alpha[l]*e*ww4*dxx4*x[sp[i],0]
w42 = w42 + alpha[l]*e*ww4*dxx4*x[sp[i],1]
b1 = b1 + alpha[l]*e*ww1*dxx1
b2 = b2 + alpha[l]*e*ww2*dxx2
b3 = b3 + alpha[l]*e*ww3*dxx3
b4 = b4 + alpha[l]*e*ww4*dxx4
w11f[p] = w11
w12f[p] = w12
p = p + 1
er = 0
for k in range(nTrain,nTrain + nTest):
y1 = b1 + w11*x[sp[i],0] + w12*x[sp[i],1]
y2 = b2 + w21*x[sp[i],0] + w22*x[sp[i],1]
y3 = b3 + w31*x[sp[i],0] + w32*x[sp[i],1]
y4 = b4 + w41*x[sp[i],0] + w42*x[sp[i],1]
dxx1 = y1 > 0
xx1 = y1*dxx1
dxx2 = y2 > 0
xx2 = y2*dxx2
dxx3 = y3 > 0
xx3 = y3*dxx3
dxx4 = y4 > 0
xx4 = y4*dxx4
yy = bb + ww1*xx1 + ww2*xx2 + ww3*xx3 + ww4*xx4
yy = yy > 0
e = abs(t[sp[k]] - yy)
er = er + e #Accumulates error
er = er/nTest #Calculates average error
er_List[l,j,n] = er
if er_List[l,j,n] < 0.05:
nSuccess = nSuccess + 1
#Part C - Creating an Array that contains the success values of each
#alpha and epoch value pair
nSuccess_Array[l,n] = nSuccess #Array that contains the success
if nEpoch < 6:
nEpoch += 1

Dtype error in function using norm pdf over a pandas dataframe

I am having issues calculating a function, while the function itself is pretty straightforward.
I have the following dataframe:
import pandas as pd
import numpy as np
import math as m
from scipy.stats import norm
dff = pd.DataFrame({'SKU': ['001', '002', '003','004','005'],
'revenue_contribution_in_percentage': [0.2, 0.2, 0.3,0.1,0.2],
'BuyPrice' : [7.78,9.96,38.87,6.91,14.04],
'SellPrice' : [7.9725,12.25,43,7.1,19.6],
'margin' : [0.9725,2.2908,5.8305,0.2764,5.1948],
'Avg_per_week' : [71.95,75.65,105.7,85.95,66.1],
'StockOnHand' : [260,180,260,205,180],
'StockOnOrder': [0,0,0,0,0],
'Supplier' : ['ABC', 'ABC', 'ABC','ABC','ABC'],
'SupplierLeadTime': [12,12,12,12,12],
'cumul_value':[0.20,0.4,0.6,0.8,1],
'class_mention':['A','A','B','D','C'],
'std_week':[21.585,26.4775,21.14,31.802, 26.44],
'review_time' : [5,5,5,5,5],
'holding_cost': [0.35, 0.35, 0.35,0.35,0.35],
'aggregate_order_placement_cost': [1000, 1000,1000,1000,1000],
'periods' : [7,7,7,7,7]})
dff['holding_cost'] = 0.35
dff1 = dff.sort_values(['Supplier'])
df2 = pd.DataFrame(dff1)
df2['forecast_dts'] = 5
df2['sigma_rtlt'] = 0.5
i need passing some of this parameters into the function:
#
a0 = -5.3925569
a1 = 5.6211054
a2 = -3.883683
a3 = 1.0897299
b0 = 1
b1 = -0.72496485
b2 = 0.507326622
b3 = 0.0669136868
b4 = -0.00329129114
z = np.sqrt(np.log(25
/
(norm.pdf((df2['forecast_dts'])*(1-0.98)/df2['sigma_rtlt']) -
((df2['forecast_dts']*(1-0.98)/df2['sigma_rtlt']))* (1-norm.cdf(df2['forecast_dts']*(1-0.98)/df2['sigma_rtlt']))) ^ 2))
num = (a0 + a1 * z + a2 * z ^ 2 + a3 * z ^ 3)
den = (b0 + b1 * z + b2 * z ^ 2 + b3 * z ^ 3 + b4 * z ^ 4)
k = num / den
return k
but then calculating
calc = calc_invUnitNormalLossApprox()*df2['sigma_rtlt']
returns the error:
File "/usr/local/lib/python3.7/site-packages/pandas/core/ops/__init__.py", line 1280, in na_op
dtype=x.dtype, typ=type(y).__name__
TypeError: cannot compare a dtyped [float64] array with a scalar of type [bool]
At this point I am not sure what is going on there, especially because i know the formula itself is correct, I am assuming there is something wrong with my use of norm pdf and cdf but I couldnt figure it out.
Any help would be really appreciated.
I think with the ^ operator you are trying to do a bitwise XOR
I think you need to use the ** operator.
This code works
def calc():
a0 = -5.3925569
a1 = 5.6211054
a2 = -3.883683
a3 = 1.0897299
b0 = 1
b1 = -0.72496485
b2 = 0.507326622
b3 = 0.0669136868
b4 = -0.00329129114
z = np.sqrt(np.log(25
/
(norm.pdf((df2['forecast_dts'])*(1-0.98)/df2['sigma_rtlt']) -
((df2['forecast_dts']*(1-0.98)/df2['sigma_rtlt']))* (1-norm.cdf(df2['forecast_dts']*(1-0.98)/df2['sigma_rtlt']))) ** 2))
num = (a0 + a1 * z + a2 * z ** 2 + a3 * z ** 3)
den = (b0 + b1 * z + b2 * z ** 2 + b3 * z ** 3 + b4 * z ** 4)
k = num / den
return k
Not : I have change the ^ operator to **

Exponential distribution of values between a given range in Python

I have three variables Min=0.29, Max=6.52 and center = 2.10. I wish to create a table that distributes this data into 100 values in a table format in the following fashion:
Here, this image can be split into two parts 0 to 50 and 50 to 100.
In the first part, the increase in x vs y for subsequent value is higher between 1-10 vs 10-20 and higher in 10-20 vs 20-30 and so on.
In the second part, the increase in x vs y for subsequent value is lower between 50-60 vs 60-70 and lower between 60-70 vs 70-80 and so on.
Now, I don't have high proficiency in statistics hence was unable to figure out how to provide min, max and centre value to an exponential distribution and how to implement it in python.
I tried using solution given in link, but couldn't get it to work for my case. Any help will be appreciated.
Each of the two exponential functions is defined by 3 parameters, but you only have 2 points belonging to each. One possibility is to provide the asymptotic value for both functions. I'll paste my code here, including the derivation of all formulae, for lack of time – sorry:
from math import exp, log
from matplotlib import pyplot as plt
X_MIN, X_CTR, X_MAX = 1, 50, 100
Y_MIN, Y_CTR, Y_MAX = 0.29, 2.10, 6.52
c1 = float(input(f"c1 (> {Y_CTR}): "))
c2 = float(input(f"c2 (< {Y_CTR}): "))
plot = input("plot? (y|n): ")[:1] in "yY"
# c1 - a1 * exp(-b1 * X_MIN) == Y_MIN # with a1 > 0, b1 > 0, c1 > Y_CTR
# c1 - a1 * exp(-b1 * X_CTR) == Y_CTR
# c2 + a2 * exp( b2 * X_CTR) == Y_CTR # with a2 > 0, b2 > 0, c2 < Y_CTR
# c2 + a2 * exp( b2 * X_MAX) == Y_MAX
# a1 * exp(-b1 * X_MIN) == c1 - Y_MIN
# a1 * exp(-b1 * X_CTR) == c1 - Y_CTR
# a2 * exp( b2 * X_CTR) == Y_CTR - c2
# a2 * exp( b2 * X_MAX) == Y_MAX - c2
# log(a1) - b1 * X_MIN == log(c1 - Y_MIN)
# log(a1) - b1 * X_CTR == log(c1 - Y_CTR)
# log(a2) + b2 * X_CTR == log(Y_CTR - c2)
# log(a2) + b2 * X_MAX == log(Y_MAX - c2)
# b1 * (X_CTR - X_MIN) == log(c1 - Y_MIN) - log(c1 - Y_CTR)
# b2 * (X_MAX - X_CTR) == log(Y_MAX - c2) - log(Y_CTR - c2)
b1 = (log(c1 - Y_MIN) - log(c1 - Y_CTR)) / (X_CTR - X_MIN)
b2 = (log(Y_MAX - c2) - log(Y_CTR - c2)) / (X_MAX - X_CTR)
# log(a1) == log(c1 - Y_MIN) + b1 * X_MIN
# log(a2) == log(Y_MAX - c2) - b2 * X_MAX
a1 = exp(log(c1 - Y_MIN) + b1 * X_MIN)
a2 = exp(log(Y_MAX - c2) - b2 * X_MAX)
x_lst = list(range(X_MIN, X_MAX+1))
y_lst = [c1 - a1 * exp(-b1 * x) if x < X_CTR else
c2 + a2 * exp( b2 * x) for x in x_lst]
if plot:
plt.plot(x_lst, y_lst)
plt.grid(True)
plt.show()
else:
for x, y in zip(x_lst, y_lst):
print(f"{x},{y:.14}")
E.g., with this input:
c1 (> 2.1): 2.13
c2 (< 2.1): 2.08
plot? (y|n): y
the output is:

EOF error python 3?

I keep getting an EOF error in python 3. Here is my code
num = float(input()) #servings
p = float(input()) #people
a2 = float(input())
b2 = float(input())
c2 = float(input())
d2 = float(input())
e2 = float(input())
f2 = float(input())
g2 = float(input())
h2 = float(input())
i2 = float(input())
a1 = a2 / num
b1 = b2 / num
c1 = c2 / num
d1 = d2 / num
e1 = e2 / num
f1 = f2 / num
g1 = g2 / num
h1 = h2 / num
i1 = i2 / num
a = a1 * p
b = b1 * p
c = c1 * p
d = d1 * p
e = e1 * p
f = f1 * p
g = g1 * p
h = h1 * p
i = i1 * p
lis = str(a)+ str(b)+ str(c)+ str(d)+ str(e)+ str(f)+ str(g)+ str(h)+ str(i)
print (lis) #8 14 1 1 6 2 1 2 .5 2
and the error is on line 11. If I delete line 11 and all code that goes with it, it gives me the error on line 10, then 9, then 8, etc.
The code works fine until you give 11 input values since there are 11 input statements. The EOF error occurs when you don't provide sufficient inputs. I assume the comment on the last line is your input and it has only 10 values. I think that's the reason for the EOF error.

Categories