Hi I am trying to write a trust-region algorithm using the dogleg method with python for a class I have. I have a Newton's Method algorithm and Broyden's Method algorthm that agree with each other but I can't seem to get this Dogleg method to work.
Here is the function I am trying to find the solution to:
def test_function(x):
x1 = float(x[0])
x2 = float(x[1])
r = np.array([[x2**2 - 1],
[np.sin(x1) - x2]])
return r
and here is the jacobian I wrote
def Test_Jacobian(x, size):
e = create_ID_vec(size)
#print(e[0])
epsilon = 10e-8
J = np.zeros([size,size])
#print (J)
for i in range(0, size):
for j in range(0, size):
J[i][j] = ((test_function(x[i]*e[j] + epsilon*e[j])[i] - test_function(x[i]*e[j])[i])/epsilon)
return J
and here is my Trust-Region algorithm:
def Trust_Region(x):
trust_radius = 1
max_trust = 300
eta = rand.uniform(0,.25)
r = test_function(x) # change to correspond with the function you want
J = Test_Jacobian(r, r.size) # change to correspond with function
i = 0
iteration_table = [i]
function_table = [vector_norm(r, r.size)]
while vector_norm(r, r.size) > 10e-10:
print(x, 'at iteration', i, "norm of r is", vector_norm(r, r.size))
p = dogleg(x, r, J, trust_radius)
rho = ratio(x, J, p)
if rho < 0.25:
print('first')
trust_radius = 0.25*vector_norm(p,p.size)
elif rho > 0.75 and vector_norm(p,p.size) == trust_radius:
print('second')
trust_radius = min(2*trust_radius, max_trust)
else:
print('third')
trust_radius = trust_radius
if rho > eta:
print('x changed')
x = x + p
#r = test_function(x)
#J = Test_Jacobian(r, r.size)
else:
print('x did not change')
x = x
r = test_function(x) # change to correspond with the function you want
J = Test_Jacobian(r, r.size) # change to correspond with function
i = i + 1
#print(r)
#print(J)
#print(vector_norm(p,p.size))
print(rho)
#print(trust_radius)
iteration_table.append(i)
function_table.append(vector_norm(r,r.size))
print ('The solution to the non-linear equation is: ', x)
print ('This solution was obtained in ', i, 'iteratations')
plt.figure(figsize=(10,10))
plt.plot(iteration_table, np.log10(function_table))
plt.xlabel('iteration number')
plt.ylabel('function value')
plt.title('Semi-Log Plot for Convergence')
return x, iteration_table, function_table
def dogleg(x, r, J, trust_radius):
tau_k = min(1, vector_norm(J.transpose().dot(r), r.size)**3/(trust_radius*r.transpose().dot(J).dot(J.transpose().dot(J)).dot(J.transpose()).dot(r)))
p_c = -tau_k*(trust_radius/vector_norm(J.transpose().dot(r), r.size))*J.transpose().dot(r)
if vector_norm(p_c, p_c.size) == trust_radius:
print('using p_c')
p_k = p_c
else:
p_j = -np.linalg.inv(J.transpose().dot(J)).dot(J.transpose().dot(r))
print ('using p_j')
tau = tau_finder(x, p_c, p_j, trust_radius, r.size)
p_k = p_c + tau*(p_j-p_c)
return p_k
def ratio(x, J, p):
r = test_function(x)
r_p = test_function(x + p)
print (vector_norm(r, r.size)**2)
print (vector_norm(r_p, r_p.size)**2)
print (vector_norm(r + J.dot(p), r.size)**2)
rho_k =(vector_norm(r, r.size)**2 - vector_norm(r_p, r_p.size)**2)/(vector_norm(r, r.size)**2 - vector_norm(r + J.dot(p), r.size)**2)
return rho_k
def tau_finder(x, p_c, p_j, trust_radius, size):
a = 0
b = 0
c = 0
for i in range(0, size):
a = a + (p_j[i] - p_c[i])**2
b = b + 2*(p_j[i] - p_c[i])*(p_c[i] - x[i])
c = (p_c[i] - x[i])**2
c = c - trust_radius**2
tau_p = (-b + np.sqrt(b**2 - 4*a*c))/(2*a)
tau_m = (-b - np.sqrt(b**2 - 4*a*c))/(2*a)
#print(tau_p)
#print(tau_m)
if tau_p <= 1 and tau_p >=0:
return tau_p
elif tau_m <= 1 and tau_m >=0:
return tau_m
else:
print('error')
return 'error'
def model_function(p):
r = test_function(x)
J = Test_Jacobian(r, r.size)
return 0.5*vector_norm(r + J.dot(p), r.size)**2
The answer should be about [[1.57076525], [1. ]]
but here is the output after about 28-30 iterations:
ZeroDivisionError Traceback (most recent call last)
<ipython-input-359-a414711a1671> in <module>
1 x = create_point(2,1)
----> 2 Trust_Region(x)
<ipython-input-358-7cb77bd44d7b> in Trust_Region(x)
11 print(x, 'at iteration', i, "norm of r is", vector_norm(r, r.size))
12 p = dogleg(x, r, J, trust_radius)
---> 13 rho = ratio(x, J, p)
14
15 if rho < 0.25:
<ipython-input-358-7cb77bd44d7b> in ratio(x, J, p)
71 print (vector_norm(r_p, r_p.size)**2)
72 print (vector_norm(r + J.dot(p), r.size)**2)
---> 73 rho_k =(vector_norm(r, r.size)**2 - vector_norm(r_p, r_p.size)**2)/(vector_norm(r, r.size)**2 - vector_norm(r + J.dot(p), r.size)**2)
74 return rho_k
75
ZeroDivisionError: float division by zero
Related
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?
The code is solving an integral using the trapezium rule. I need to set limits for QH so if QH > 1 then QH = 1. I cant seem to get what I've done below to work properly.
## Solve ODE
QH = odeint(model, QH0, z, atol = 1.0e-8, rtol = 1.0e-8)
QHe = odeint(model1, QHe0, z, atol = 1.0e-8, rtol = 1.8e-8)
if QH > 1:
QH == 1
if QHe > 1:
QHe == 1
#Solving Thomson Optical Depth Integral for Hydrogen
def f_hydrogen(z_in):
Hz = H0*math.sqrt(OMEGAm*((1+z_in)**3)+OMEGAlam)
flatQH = QH.flatten()
QH_int = np.interp(z_in, z[::-1], flatQH[::-1])
return QH_int*(((1+z_in)**2)/Hz)
a = 0
z1 = 7
n = 1000
hei = (z1-a)/n
k = 0
#sum = 0
sum = np.zeros(n+1)
while (k<n):
x_in = a + (k*hei)
if k < n-1 :
sum[k + 1] = sum[k] + f_hydrogen(x_in)
k = k + 1
int_a = (hei/2)*((f_hydrogen(a) + f_hydrogen(z1)) + (2*sum))
tH = (c)*(sigma)*(nbarH)*(1+(y/(4*x)))*(int_a)
for index, val in enumerate(tH):
print("Thomson Optical Depth - Hydrogen = ", index, val)
How do I solve this error?
TypeError: NumPy boolean subtract, the `-` operator, is not supported, use the bitwise_xor, the `^` operator, or the logical_xor function instead.
I have programmed an optimizing program that must minimize the cost of a wall design. The wall is based on 3 parameters, x, k and m. There are constraints to the sizes of x, k and m as shown. Another constraint is that z (or deflection) must be kept under 100mm. The equation for deflection changes based on a certain t (or time) at which the blast wall is experiencing the blast. If t is below a certain time value which is calculated dependent on, x, k and m the equation is as shown. If t is above the same certain time value, the equation for z changes.
Here is the programming... Please help many thanks :)
import numpy as np
from numpy import linspace
from math import cos
from math import sin
from scipy.optimize import minimize
#Function for minimising
def calcCost(c):
k = c[0]
m = c[1]
x = c[2]
Cost = (900 + 825*k**2 - 1725) + (10*m - 200) + ((2400*x**2)/4)
return Cost
#Objective function
def objective(c):
return calcCost(c)
#Defining Variables
def calck(c):
k = c[0]
k=k
k.resize(12,)
return k
def calcm(c):
m = c[1]
m=m
m.resize(12,)
return m
def calcx(c):
x = c[2]
x=x
x.resize(12,)
return x
def calcz(c):
k = c[0]
x = c[1]
m = c[2]
l = linspace(0,140,141)
for t in l:
if t <= ((20 - 0.12*x**2 + 4.2*x)/1000):
deflection = ((((1000+9*x**2-183*x)*1000)/k)*(1-cos(t*((k/m)**0.5))) + (((1000+9*x**2-183*x)*1000)/k*((20 - 0.12*x**2 + 4.2*x)/1000))*((sin(t*((k/m)**0.5))/((k/m)**0.5))-t))*1000
else:
deflection = ((((1000+9*x**2-183*x)*1000)/(k*((k/m)**0.5)*((20 - 0.12*x**2 + 4.2*x)/1000)))*(sin(((k/m)**0.5)*t))-(sin(((k/m)**0.5)*(t-((20 - 0.12*x**2 + 4.2*x)/1000))))-(((1000+9*x**2-183*x)*1000)/k)*cos(((k/m)**0.5)*t))*1000
deflection.resize(12,)
return deflection
#Constraint functions
def kconstraint1(c):
k = c[0]
return k-(1*10**6) >= 0
def kconstraint2(c):
k = c[0]
return k-(7*10**6) <= 0
def mconstraint1(c):
m = c[0]
return m-200 >= 0
def mconstraint2(c):
m = c[0]
return m-1200 <= 0
def xconstraint1(c):
x = c[0]
return x >= 0
def xconstraint2(c):
x = c[0]
return x <= 10
def zconstraint1(c):
k = c[0]
x = c[1]
m = c[2]
l = linspace(0,140,141)
for t in l:
if t <= ((20 - 0.12*x**2 + 4.2*x)/1000):
deflection = ((((1000+9*x**2-183*x)*1000)/k)*(1-cos(t*((k/m)**0.5))) + (((1000+9*x**2-183*x)*1000)/k*((20 - 0.12*x**2 + 4.2*x)/1000))*((sin(t*((k/m)**0.5))/((k/m)**0.5))-t))*1000
else:
deflection = ((((1000+9*x**2-183*x)*1000)/(k*((k/m)**0.5)*((20 - 0.12*x**2 + 4.2*x)/1000)))*(sin(((k/m)**0.5)*t))-(sin(((k/m)**0.5)*(t-((20 - 0.12*x**2 + 4.2*x)/1000))))-(((1000+9*x**2-183*x)*1000)/k)*cos(((k/m)**0.5)*t))*1000
return deflection <= 99.99999999
b = (0.5,1)
be = (0.5,10)
bb = (0.1,2.0)
bnds = (b,be,bb,bb)
con1 = ({'type':'ineq','fun':kconstraint1})
con2 = ({'type':'ineq','fun':kconstraint2})
con3 = ({'type':'ineq','fun':mconstraint1})
con4 = ({'type':'ineq','fun':mconstraint2})
con5 = ({'type':'ineq','fun':xconstraint1})
con6 = ({'type':'ineq','fun':xconstraint2})
con7 = ({'type':'ineq','fun':zconstraint1})
cons = [con1,con2,con3,con4,con5,con6,con7]
xGUESS = 5
kGUESS = 3*10**6
mGUESS = 700
zGUESS = 90
x0 = np.array([xGUESS,kGUESS,mGUESS,zGUESS])
sol = minimize(objective,x0,method='SLSQP',bounds=bnds,constraints=cons,options={'disp':True})
xOpt = sol.x
CostOPT = sol.fun
kOPT = calck(xOpt)
xOPT = calcx(xOpt)
mOPT = calcm(xOpt)
zOPT = calcz(xOpt)
print(str(CostOPT))
print(str(calcx))
print(str(calcm))
print(str(calck))
print(str(calcz))
So I have an application in Python that calculates the variable number in the "PV = nRT" chemical equation. The code is like this:
r = 0.082
# Variables
p = float(input('Pressure = '))
p_unit = input('Unit = ')
print('_____________________')
v = float(input('Volume = '))
v_unit = input('Unit = ')
print('_____________________')
n = float(input('Moles = '))
print('_____________________')
t = float(input('Temperature = '))
t_unit = input('Unit = ')
# Unit Conversion
if p_unit == 'bar':
p = p * 0.987
if v_unit == 'cm3':
v = v / 1000
if v_unit == 'm3':
v = v * 1000
if t_unit == 'c':
t = t + 273
if t_unit == 'f':
t = ((t - 32) * (5 / 9)) + 273
# Solve Equation
def calc():
if p == 000:
return (n * r * t) / v
if v == 000:
return (n * r * t) / p
if n == 000:
return (p * v) / (r * t)
if t == 000:
return (p * v) / (n * r)
and then at the end I run the function to get the result. But the problem is I want to convert the result to a Scientific Number (e.g. 0.005 = 5 x 10^-3). I tried the solution below:
def conv_to_sci(num):
i = 0
if num > 10:
while num > 10:
num / 10
i = i - 1
if num < 10:
while num < 10:
num * 10
i = i + 1
return num + "x 10^" + i
but it didn't work. Any questions?
I'd just use numpy to get scientific notation
import numpy as np
num = 0.005
num_sc = np.format_float_scientific(num)
>>> num_sc
'5.e-03'
Use str.format
"{:.0e}".format(0.005)
This will print:
'5e-03'
Or,
def conv_to_sci(num):
i = 0
while int(num) != num:
num *= 10
i += 1
return "{0} x 10^{1}".format(int(num), i)
conv_to_sci(0.005)
Will give: '5 x 10^3'
I am trying the Newmark's constant average acceleration method. I am getting this error. How do I recover from this error?
IndexError Traceback (most recent call last)
41 for i in range(len(t)):
42 pn[i+1] = p[i+1]+ a1*u[i] + a2*v[i] + a3*a[i]
43 u[i+1] = pn[i+1]/kn
44 v[i+1] = y*(u[i+1]-u[i])/(b*dt) + (1-y/b)v[i] + dt (1-y/(2*b))*a[i]
IndexError: list assignment index out of range
y = 1/2
b = 1/4
u = []
v = []
t = []
p = [0,25,43.3013,50,43.3013,25,0,0,0,0,0,0]
a = []
pn = []
pn.append(0)
x = 0.0
for i in range(11):
z = 0.0 + x
t.append(z)
x = x + 0.1
m = 0.45594
k = 18
c = 0.2865
u.append(0)
v.append(0)
a.append((p[0]-c*v[0]-k*u[0])/m)
dt = 0.1
a1 =(m/(b*dt*dt)+y*c/(b*dt))
a2 = (m/(b*dt)+(y/b-1)*c)
a3 = (((1/(2*b))-1)*m + dt*((y/(2*b))-1)*c)
kn = k + a1
for i in range(len(t)-1):
pn[i+1] = p[i+1]+ a1*u[i] + a2*v[i] + a3*a[i]
u[i+1] = pn[i+1]/kn
v[i+1] = y*(u[i+1]-u[i])/(b*dt) + (1-y/b)*v[i] + dt* (1-y/(2*b))*a[i]
a[i+1] = (u[i+1]-u[i])/(b*dt*dt) - v[i]/(b*dt)-(1/(2*b)-1)*a[i]
Your pn, a, u, v are defined as a list with length 1, so there is no index such as pn[1]. You can use append or define the list with needed length.
for i in range(len(t)):
pn.append(p[i+1] + a1*u[i] + a2*v[i] + a3*a[i])
u.append(pn[i+1]/kn)
v.append(y*(u[i+1]-u[i])/(b*dt) + (1-y/b)*v[i] + dt* (1-y/(2*b))*a[i])
a.append((u[i+1]-u[i])/(b*dt*dt) - v[i]/(b*dt)-(1/(2*b)-1)*a[i])
or
pn, a, u, v = [0]*11, [0]*11, [0]*11 [0]*11
pn[0], u[0], v[0] = 0, 0, 0
a[0] = (p[0]-c*v[0]-k*u[0])/m
...
for i in range(len(t)-1):
pn[i+1] = p[i+1] + a1*u[i] + a2*v[i] + a3*a[i]
u[i+1] = pn[i+1]/kn
v[i+1] = y*(u[i+1]-u[i])/(b*dt) + (1-y/b)*v[i] + dt* (1-y/(2*b))*a[i]
a[i+1] = (u[i+1]-u[i])/(b*dt*dt) - v[i]/(b*dt)-(1/(2*b)-1)*a[i]