The formula for half vector is (Hv) = (Lv + Vv) / |Lv+Vv|, where Lv is light vector, and Vv is view vector.
Am I doing this right in Python code?
Vvx = 0-xi # view vector (calculating it from surface points)
Vvy = 0-yi
Vvz = 0-zi
Vv = math.sqrt((Vvx * Vvx) + (Vvy * Vvy) + (Vvz * Vvz)) # normalizing
Vvx = Vvx / Vv
Vvy = Vvy / Vv
Vvz = Vvz / Vv
Lv = (1,1,1) # light vector
Hn = math.sqrt(((1 + Vvx) * (1 + Vvx)) + ((1 + Vvy) * (1 + Vvy)) +
((1 + Vvz) * (1 + Vvz)))
Hv = ((1 + Vvx) / Hn, (1 + Vvy) / Hn, (1 + Vvz) / Hn) # half-way vector
This is misnamed. What you've written is simple vector addition of two vectors, with the result being a normalized unit vector.
Here's how I'd do it:
import math
def magnitude(v):
return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))
def add(u, v):
return [ u[i]+v[i] for i in range(len(u)) ]
def sub(u, v):
return [ u[i]-v[i] for i in range(len(u)) ]
def dot(u, v):
return sum(u[i]*v[i] for i in range(len(u)))
def normalize(v):
vmag = magnitude(v)
return [ v[i]/vmag for i in range(len(v)) ]
if __name__ == '__main__':
l = [1, 1, 1]
v = [0, 0, 0]
h = normalize(add(l, v))
print h
Related
I am trying to replicate the below R code to estimate parameters using Maximum Likelihood method in Python.
I want to obtain the same results using both the codes, but my estimated values are different, I am not sure if both the codes are optimising the same parameters.
R-Code:
ll <- function (prop, numerator, denominator) {
return(
lgamma(denominator + 1) -
lgamma( numerator + 1) -
lgamma(denominator - numerator + 1) +
numerator * log(prop) + (denominator - numerator) * log(1 - prop)
)
}
compLogLike <- function(pvec){
return(sum(ll(pvec, dat$C, dat$N)))
}
fct_p_ll <- function(a, c0, c1){
xa_ <- exp(c0 + c1*c(20, a))
return(1 - exp((xa_[1]-xa_[2])/c1))
}
fct_ll <- function(x){
pv <- sapply(22.5+5*(0:8), FUN = fct_p_ll, c0 = x[1], c1 = x[2])
return(compLogLike(pv))
}
opt.res <- optim(par = c(-9.2, 0.07), fn = fct_ll, control = list(fnscale = -1.0), hessian = TRUE)
fisherInfo <- solve(-opt.res$hessian)
propSigma <- sqrt(diag(fisherInfo))
upper <- opt.res$par+1.96*propSigma
lower <- opt.res$par-1.96*propSigma
interval <- data.frame(val = opt.res$par, ci.low=lower, ci.up = upper)
Python Code:
def ll(prop, numerator, denominator):
print(prop, numerator, denominator)
if prop > 0:
value = (math.lgamma(denominator + 1) -
math.lgamma( numerator + 1) -
math.lgamma(denominator - numerator + 1) +
numerator * math.log(prop) + (denominator - numerator) * math.log(1 - prop))
return value
return 0
def compLogLike(pvec):
p = list(pvec)
c = list(df["C"])
n = list(df["N"])
compLog = 0
for idx, val in enumerate(p):
compLog += ll(p[idx],c[idx],n[idx])
print(compLog)
return compLog
def fct_p_ll(a,c0,c1):
val_list = [c1 * val for val in [20, a]]
xa_ = np.exp([c0 + val for val in val_list])
return 1 - np.exp((xa_[0] -xa_[1])/c1)
def fct_ll(x):
ages_1 = np.arange(22.5, 67.5 , 5)
pv = [fct_p_ll(a=val,c0=x[0],c1=x[1]) for val in ages_1]
return compLogLike(pv)
opt = minimize(fct_ll, [-9.2, 0.07], method='Nelder-Mead', hess=Hessian(lambda x: fct_ll(x,a)))
Any inputs would be really helpful.
I am trying to make several plots for a project of mine using the following code:
import pprint
import scipy
import scipy.linalg # SciPy Linear Algebra Library
import numpy as np
from scipy.linalg import lu , lu_factor, lu_solve
from scipy.integrate import quad
import matplotlib.pyplot as plt
#Solving the equations for the Prandtl case
K = 100
alpha = 0.1
visc = 5
diff = 5
N = 0.01
L = 5000
height = 250
subdivisions = 100
tick = 10
points = np.arange(0,L/2+tick,tick)
def H(y):
return ( height * (1 + np.cos(2 * np.pi * y/L)) )
def Bsfc(y):
return 0.1
final_system = []
b=[]
for q in range(-K,K+1):
equation1 = []
equation2 = []
equation3 = []
Aki = []
Cki = []
Dki = []
for k in range(-K,K+1):
R = 2 * N**2 * np.cos(alpha)**2 / (visc * diff) * (k * np.pi / L)**2
Q = N**2 * np.sin(alpha)**2 / (3 * visc * diff)
S1 = abs(R + np.sqrt(Q**3 + R**2) )**(1/3)
S2 = - abs( np.sqrt(Q**3 + R**2) -R )**(1/3)
phi = np.sqrt(S1**2 + S2**2 - S1*S2)
Lk = np.arccos(- (S1 + S2)/ (2 * phi) )
m1 = - np.sqrt(S1 + S2)
m2 = - np.sqrt(phi) * np.exp(1j * Lk/2)
m3 = m2.conjugate()
def f1r(y):
return (np.exp(m1 * H(y)) * np.cos(2 * (q - k) * np.pi * y / L) ).real
def f1i(y):
return (np.exp(m1 * H(y)) * np.cos(2 * (q - k) * np.pi * y / L) ).imag
gamma1 = 2/L * (quad(f1r,0,L/2,limit=subdivisions)[0] + quad(f1i,0,L/2,limit=subdivisions)[0]*1j)
def f2r(y):
return (np.exp(m2 * H(y)) * np.cos(2 * (q - k) * np.pi * y / L) ).real
def f2i(y):
return (np.exp(m2 * H(y)) * np.cos(2 * (q - k) * np.pi * y / L) ).imag
gamma2 = 2/L * (quad(f2r,0,L/2,limit=subdivisions)[0] + quad(f2i,0,L/2,limit=subdivisions)[0]*1j)
if k == 0:
equation1.append(2 * gamma2.real)
Cki.append(k)
equation1.append(-2 * gamma2.imag)
Dki.append(k)
else:
equation1.append(gamma1)
Aki.append(k)
equation1.append(2 * gamma2.real)
Cki.append(k)
equation1.append(-2 * gamma2.imag)
Dki.append(k)
if q != 0:
if k == 0:
equation2.append(0)
equation2.append(0)
else:
equation2.append(k * gamma1 / (m1**3) )
equation2.append(2 * k * (gamma2 / (m2**3) ).real)
equation2.append(-2 * k * (gamma2 / (m2**3) ).imag)
if k == 0:
equation3.append(2 * (m2**2 * gamma2).real)
equation3.append(-2 * (m2**2 * gamma2).imag)
else:
equation3.append(m1**2 * gamma1)
equation3.append(2 * (m2**2 * gamma2).real)
equation3.append(-2 * (m2**2 * gamma2).imag)
final_system.append(equation1)
def f4r(y):
return (Bsfc(y) * np.cos(2 * q * np.pi * y / L) ).real
def f4i(y):
return (Bsfc(y) * np.cos(2 * q * np.pi * y / L) ).imag
b.append(2/L * (quad(f4r,0,L/2,limit=subdivisions)[0] + quad(f4i,0,L/2,limit=subdivisions)[0]*1j))
if q != 0:
final_system.append(equation2)
b.append(0)
final_system.append(equation3)
b.append(0)
final_system = np.array(final_system)
b=np.array(b)
#LU solver
P, Ls, U = scipy.linalg.lu(final_system)
Bl = np.linalg.inv(P) # b
Z = np.linalg.solve(Ls,Bl)
X = np.linalg.solve(U,Z)
print (np.allclose(final_system # X, b))
#Getting the values for Ak, Ck and Dk
strings = []
for k in range(-K,K+1):
if k != 0:
strings.append('A')
strings.append('R')
strings.append('I')
Ak = []
Rk = []
Ik = []
for k in range(0,len(X)):
if 'A' in strings[k]:
Ak.append(X[k])
if 'R' in strings[k]:
Rk.append(X[k])
if 'I' in strings[k]:
Ik.append(X[k])
Ck=[]
for k in range(0,len(Rk)):
Ck.append(Rk[k] + Ik[k] * 1j)
Ck = np.array(Ck)
Dk = Ck.conjugate()
Ak = np.array(Ak)
#Getting the Buoyancy value
z = np.arange(0,2010,10)
y = np.arange(-L,L+10,10)
Y,Z = np.meshgrid(y,z)
B = np.ones_like(Y)*[0]
for k in range(-K,K+1):
R = 2 * N**2 * np.cos(alpha)**2 / (visc * diff) * (k * np.pi / L)**2
Q = N**2 * np.sin(alpha)**2 / (3 * visc * diff)
S1 = abs(R + np.sqrt(Q**3 + R**2) )**(1/3)
S2 = - abs( np.sqrt(Q**3 + R**2) -R )**(1/3)
phi = np.sqrt(S1**2 + S2**2 - S1*S2)
Lk = np.arccos(- (S1 + S2)/ (2 * phi) )
m1 = - np.sqrt(S1 + S2)
m2 = -np.sqrt(phi) * np.exp(1j * Lk/2)
m3 = m2.conjugate()
if k != 0:
B = B + ( Ak[Aki.index(k)] * np.exp(m1 * Z) * np.exp(2j * (k) * np.pi * Y / L) )
B = B + ( ( Ck[Cki.index(k)] * np.exp(m2 * Z) + Dk[Dki.index(k)] * np.exp(m3 * Z) ) * np.exp(2j * (k) * np.pi * Y / L) )
for k in range(0,B.shape[0]):
for t in range(0,B.shape[1]):
if Z[k][t] < H(Y[k][t]):
B[k][t] = np.nan
if Z[k][t] == H(Y[k][t]):
print (B[k][t], "B value at the ground")
if abs(Z[k][t] - H(Y[k][t])) < 0.1:
if B[k][t] > 0.101:
print (B[k][t],'error -------------------------------------------------')
# print (B[k][t], Z[k][t], H(Y[k][t]), Y[k][t], '-----------------------------------------------------------------------------' )
Bp = Bsfc(Y) * np.exp(-Z * np.sqrt(N * np.sin(alpha) ) / (4*visc*diff)**(1/4) ) * np.cos(np.sqrt(N*np.sin(alpha)) /((4*visc*diff)**(1/4))*Z )
##Plotting the buoyancy
fig = plt.figure(figsize=(10,10)) # create a figure
plt.rcParams.update({'font.size':16})
plt.title('Buoyancy')
plt.contourf(Y,Z,B,np.arange(-0.2,0.201,0.001),cmap='seismic')
#plt.contourf(Y,Z,B,cmap='seismic')
plt.colorbar(label='1/s')
plt.xlabel("Y axis")
plt.ylabel("Height")
plt.xlim([-L,L])
plt.ylim([0,1500])
plt.show()
The following plot shows a run that yielded a good result:
Buoyancy
However, when I increase the "height" parameter, I start getting unstable results, which I suspect occurs because of numerical instabilities:
Buoyancy unstable
Is there a way to increase numerical precision in python? I have experimented a bit with numpy.double, but with unsuccessful results so far.
Thanks
I guess you'll find your answer here on Stackoverflow
In the standard library, the decimal module may be what you're looking
for. Also, I have found mpmath to be quite helpful...
import re
import math
from random
import randint
import hashlib
P = (-0.15, 2.645)
Q = (0.7, 2.71)
max_mod = 1.158 * 10 ** 77
def SHA256_INT(text):
return int(f'0x{hashlib.sha256(text.encode("ascii")).hexdigest()}', 0)
def ecc_double_slope(P):
slope = (3 * P[0] ** 2) / (2 * P[1])
return slope
def ecc_add(P, Q, slope):
xr = slope ** 2 - P[0] - Q[0]
yr = slope * (P[0] - xr) - P[1]
return (xr, yr)
def ecc_double(P):
slope = ecc_double_slope(P)
sum0 = ecc_add(P, P, slope)
return sum0
def ecc_double_for(P, limit):
lis = []
for i in range(limit):
b = ecc_double(P)
P = b
lis.append((2 ** i, b))
return lis
def greedy2(number):
x = 0
dub_lis = []
add_lis = []
while 2 ** x < number:
dub_lis.append(2 ** x)
x += 1
x -= 1
n = 2 ** x
while n != number:
y = x
while n + (2 ** y) > number:
y -= 1
n += (2 ** y)
x += 1
add_lis.append(2 ** y)
return len(dub_lis), add_lis
def ecc_main_add(P, Q):
x1 = P[0]
y1 = P[1]
x2 = Q[0]
y2 = Q[1]
slope = (y2 - y1) / (x2 - y1)
xr = slope ** 2 - x1 - x2
yr = slope * (x1 - xr) - y1
return xr, yr
def gen_points(gen, points):
if gen == 1:
return points
elif gen > 1:
if type(points) == int:
point_curve = (points, math.sqrt(points ** 3 + 7))
elif type(points) == tuple:
point_curve = points
point_steps = greedy2(gen)
point_dub = point_steps[0]
point_add = point_steps[1]
dub_list = ecc_double_for(point_curve, point_dub)
for i in point_add:
b = ecc_main_add(dub_list[int(math.log(i, 2))][1], dub_list[-1][1])
return b, gen
elif gen == 0:
return 0
def sign(messsage, private_key, public_key, G):
global max_mod
msg_hash = SHA256_INT(messsage)
randnum = randint(2, max_mod)
r = gen_points(randnum, G)[0]
r_x = r[0]
msg_hash = SHA256_INT(messsage)
s = (r_x * private_key + msg_hash) / randnum
p1 = gen_points(msg_hash/s, G)
p2 = gen_points(r_x/s, public_key)
p3 = ecc_main_add(p1, p2)
return p3
pub, priv = gen_points(9756, P)
print(sign('hello', priv, pub, P))
Hello, I'm trying to implement a way to sign messages using this tutorial:
https://learnmeabitcoin.com/beginners/digital_signatures_signing_verifying
I've tried to follow the tutorial before, but it's either my key generation is wrong, I didn't follow the tutorial correctly, or both.
My current code generates an error, I've already debugged it and it generates the error: TypeError: 'NoneType' object is not subscriptable.
Does anyone know how to solve this?
def rainflow(pr, dt, ci, k, tabo):
phi = tabo/dt
qsim = pd.Series(data=None, index=pr.index)
qsim.iloc[0] = ci
for i in range(1, len(qsim) + 1):
qsim.iloc[i] = k * (pr.iloc[i] - (phi * (qsim.iloc[i-1] / pr.iloc[i-1])))
return qsim.iloc
def irmse(dif, obs):
rmse = np.sqrt(np.mean(dif ** 2) / len(obs))
delta = obs - obs.shift(1)
delta_prom = np.mean(delta)
sigma_obs = (np.sqrt((np.sum((delta - delta_prom) ** 2) / (len(delta)) - 1)))
irmse = rmse / sigma_obs
return irmse
def obj_fun(par, arg):
sim = rainflow(arg[1], arg[2], par[0], par[1])
dif = arg[0] - sim
return irmse(dif, arg[0])
df_data = pd.ExcelFile('Taller_opt.xlsx').parse(sheetname='caudal', index_col='Fecha')
sr_pr_cal = df_data['PT'].iloc[0:int(len(df_data['PT']) * 0.7)]
sr_pr_val = df_data['PT'].iloc[int(len(df_data['PT']) * 0.7):]
sr_qobs_cal = df_data['Qobs'].iloc[0:int(len(df_data['Qobs']) * 0.7)]
sr_qobs_val = df_data['Qobs'].iloc[int(len(df_data['Qobs']) * 0.7):]
dt = 1.
ci = sr_qobs_cal.iloc[0]
met_opt = 'minimize'
par_ini = [0.5, 10]
min_results = so.minimize(fun=obj_fun, x0=par_ini, args=[sr_pr_cal, sr_qobs_cal], method='Nelder-Mead')
I'm trying to optimize my equation but it's give:
File "C:/Users/yeni/PycharmProjects/untitled/new.py", line 23, in obj_fun
sim = rainflow(arg[1], arg[2], par[0], par[1])
IndexError: list index out of range
"IndexError: list index out of range" Why is this happening?
How can ir fix it?
I've been working on a computational physics project (plotting related rates of chemical reactants with respect to eachother to show oscillatory behavior) with a fair amount of success. However, one of my simulations involves more than two active oscillating agents (five, in fact) which would obviously be unsuitable for any single visual plot...
My scheme was hence to have the user select which two reactants they wanted plotted on the x-axis and y-axis respectively. I tried (foolishly) to convert string input values into the respective variable names, but I guess I need a radically different approach if any exist?
If it helps clarify any, here is part of my code:
def coupledBrusselator(A, B, t_trial,display_x,display_y):
t = 0
t_step = .01
X = 0
Y = 0
E = 0
U = 0
V = 0
dX = (A) - (B+1)*(X) + (X**2)*(Y)
dY = (B)*(X) - (X**2)*(Y)
dE = -(E)*(U) - (X)
dU = (U**2)*(V) -(E+1)*(U) - (B)*(X)
dV = (E)*(U) - (U**2)*(V)
array_t = [0]
array_X = [0]
array_Y = [0]
array_U = [0]
array_V = [0]
while t <= t_trial:
X_1 = X + (dX)*(t_step/2)
Y_1 = Y + (dY)*(t_step/2)
E_1 = E + (dE)*(t_step/2)
U_1 = U + (dU)*(t_step/2)
V_1 = V + (dV)*(t_step/2)
dX_1 = (A) - (B+1)*(X_1) + (X_1**2)*(Y_1)
dY_1 = (B)*(X_1) - (X_1**2)*(Y_1)
dE_1 = -(E_1)*(U_1) - (X_1)
dU_1 = (U_1**2)*(V_1) -(E_1+1)*(U_1) - (B)*(X_1)
dV_1 = (E_1)*(U_1) - (U_1**2)*(V_1)
X_2 = X + (dX_1)*(t_step/2)
Y_2 = Y + (dY_1)*(t_step/2)
E_2 = E + (dE_1)*(t_step/2)
U_2 = U + (dU_1)*(t_step/2)
V_2 = V + (dV_1)*(t_step/2)
dX_2 = (A) - (B+1)*(X_2) + (X_2**2)*(Y_2)
dY_2 = (B)*(X_2) - (X_2**2)*(Y_2)
dE_2 = -(E_2)*(U_2) - (X_2)
dU_2 = (U_2**2)*(V_2) -(E_2+1)*(U_2) - (B)*(X_2)
dV_2 = (E_2)*(U_2) - (U_2**2)*(V_2)
X_3 = X + (dX_2)*(t_step)
Y_3 = Y + (dY_2)*(t_step)
E_3 = E + (dE_2)*(t_step)
U_3 = U + (dU_2)*(t_step)
V_3 = V + (dV_2)*(t_step)
dX_3 = (A) - (B+1)*(X_3) + (X_3**2)*(Y_3)
dY_3 = (B)*(X_3) - (X_3**2)*(Y_3)
dE_3 = -(E_3)*(U_3) - (X_3)
dU_3 = (U_3**2)*(V_3) -(E_3+1)*(U_3) - (B)*(X_3)
dV_3 = (E_3)*(U_3) - (U_3**2)*(V_3)
X = X + ((dX + 2*dX_1 + 2*dX_2 + dX_3)/6) * t_step
Y = Y + ((dX + 2*dY_1 + 2*dY_2 + dY_3)/6) * t_step
E = E + ((dE + 2*dE_1 + 2*dE_2 + dE_3)/6) * t_step
U = U + ((dU + 2*dU_1 + 2*dY_2 + dE_3)/6) * t_step
V = V + ((dV + 2*dV_1 + 2*dV_2 + dE_3)/6) * t_step
dX = (A) - (B+1)*(X) + (X**2)*(Y)
dY = (B)*(X) - (X**2)*(Y)
t_step = .01 / (1 + dX**2 + dY**2) ** .5
t = t + t_step
array_X.append(X)
array_Y.append(Y)
array_E.append(E)
array_U.append(U)
array_V.append(V)
array_t.append(t)
where previously
display_x = raw_input("Choose catalyst you wish to analyze in the phase/field diagrams (X, Y, E, U, or V) ")
display_y = raw_input("Choose one other catalyst from list you wish to include in phase/field diagrams ")
coupledBrusselator(A, B, t_trial, display_x, display_y)
Thanks!
Once you have calculated the different arrays, you could add them to a dict that maps names to arrays. This can then be used to look up the correct arrays for display_x and display_y:
named_arrays = {
"X": array_X,
"Y": array_Y,
"E": array_E,
...
}
return (named_arrays[display_x], named_arrays[display_y])