I have the following script:
guess = np.linspace(0,20/1000, num = 21)
def calc_U_LC_a(t)-> "U_LC_a":
alpha_c = calc_alpha_c(t)
S_p = calc_S_p(t)
M_p = calc_M_p(t)
p_b_LC = calc_p_b(t, min(fy,fu/1.15))
Y_p = calc_Y_p(t)
p_c_LC = calc_p_c(t)
if pl_net_LC >= 0:
U_P = (Y_p * pl_net_LC) / (alpha_c * p_b_LC)
else:
U_P = 1.02 * 2 * (- pl_net_LC / p_c_LC)
M_Sd_a = 500e3
S_Sd_a = 500e4
U_M = (1.02 * 2 / alpha_c) * (abs(M_Sd_a)/M_p)
U_S = (1.02 * 2 / alpha_c) * (S_Sd_a/S_p)
U_LC_a = ((U_M + U_S ** 2) ** 2) + U_P ** 2
return U_LC_a
def fun_LC_a(t):
return calc_U_LC_a(t) - 1
def calc_iter(fun,guess):
for i in range(0,len(guess)):
try:
tmin = optimize.newton(fun,guess[i]) #, disp = False)
except RuntimeError:
print('guess = ', guess[i],' failed to converge.')
else:
break
return tmin
tmin_X = calc_iter(fun_LC_a,guess)
All variables that are not defined here are constant values.
When I run this script, I get the error "UnboundLocalError: local variable 'Y_p' referenced before assignment"
and I am not sure why.
Related
I have a for loop as follows:
import MDAnalysis as mda
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from tqdm import tqdm as tq
import MDAnalysis.analysis.pca as pca
import random
def PCA_projection(pdb,dcd,atomgroup):
u = mda.Universe(pdb,dcd)
PSF_pca = pca.PCA(u, select=atomgroup)
PSF_pca.run(verbose=True)
n_pcs = np.where(PSF_pca.results.cumulated_variance > 0.95)[0][0]
atomgroup = u.select_atoms(atomgroup)
pca_space = PSF_pca.transform(atomgroup, n_components=n_pcs)
PC1_proj = [pca_space[i][0] for i in range(len(pca_space))]
PC2_proj = [pca_space[i][1] for i in range(len(pca_space))]
return PC1_proj, PC2_proj
def Read_bias_potential(bias_potential):
Bias_potential = pd.read_csv(bias_potential)
Bias_potential = Bias_potential['En-User']
Bias_potential = Bias_potential.values.tolist()
W = [math.exp((-1 * i) / (0.001987*300)) for i in Bias_potential]
return W
def Bin(PC1_prj, PC2_prj, frame_num, min_br1, max_br1, min_br2, max_br2, bin_num, W):
#import pdb;pdb.set_trace()
data1 = PC1_prj[0:frame_num]
bins1 = np.linspace(min_br1, max_br1, bin_num)
bins1 = np.round(bins1,2)
digitized1 = np.digitize(data1, bins1)
binc1 = np.arange(min_br1 + (max_br1 - min_br1)/2*bin_num,
max_br1 + (max_br1 - min_br1)/2*bin_num, (max_br1 - min_br1)/bin_num, dtype = float)
binc1 = np.around(binc1,3)
data2 = PC2_prj[0:frame_num]
bins2 = np.linspace(min_br2, max_br2, bin_num)
bins2 = np.round(bins2,2)
digitized2 = np.digitize(data2, bins2)
binc2 = np.arange(min_br2 + (max_br2 - min_br2)/2*bin_num, max_br2 + (max_br2 - min_br2)/2*bin_num, (max_br2 - min_br2)/bin_num, dtype = float)
binc2 = np.around(binc2,3)
w_array = np.zeros((bin_num,bin_num))
for j in range(frame_num):
w_array[digitized1[j]][digitized2[j]] += (W[digitized1[j]] + W[digitized2[j]])
for m in range(bin_num):
for n in range(bin_num):
if w_array[m][n] == 0:
w_array[m][n] = 1e-100
return w_array, binc1, binc2
def gaussian(Sj1,Slj1,Sj2,Slj2,count):
sigma1 = 0.5
sigma2 = 0.5
Kb = 0.001987204
T = 300
h0 = 0.0001
g = 0
C1 = 0
C2 = 0
for i in range((np.where(Slj2 == Sj2)[0][0] - 5),(np.where(Slj2 == Sj2)[0][0] + 6)):
if i < 0:
C2 = i + 1000
elif i > 999:
C2 = i - 1000
else:
C2 = i
for j in range((np.where(Slj1 == Sj1)[0][0] - 5),(np.where(Slj2 == Sj2)[0][0] + 6)):
if j < 0:
C1 = j + 1000
elif j > 999:
C1 = j -1000
else:
C1 = j
g = g + count[C2,C1] * h0 * np.exp( (-(Sj1 - Slj1[C1]) ** 2 / (2 * sigma1 ** 2)) + (-(Sj2 - Slj2[C2]) ** 2 / (2 * sigma2 ** 2)) )
return np.exp(-g / (Kb * T))
def resampling(binc1, binc2, w_array):
# import pdb;pdb.set_trace()
l =1000
F = np.zeros((l,l))
count = np.zeros((l,l))
Wn = w_array
for i in tq(range(10000000)):
SK1 = random.choice(binc1)
SK2 = random.choice(binc2)
SL1 = random.choice(binc1)
SL2 = random.choice(binc2)
while SK1 == SL1:
SL1 = random.choice(binc1)
while SK2 == SL2:
SL2 = random.choice(binc2)
F[np.where(binc2 == SK2)[0][0]][np.where(binc1 == SK1)[0][0]] = gaussian(SK1,binc1,SK2,binc2,count)
F[np.where(binc2 == SK2)[0][0]][np.where(binc1 == SK1)[0][0]] = gaussian(SL1,binc1,SL2,binc2,count)
W_SK = Wn[np.where(binc2 == SK2)[0][0]][np.where(binc1 == SK1)[0][0]] * F[np.where(binc2 == SK2)[0][0]][np.where(binc1 == SK1)[0][0]]
W_SL = Wn[np.where(binc2 == SL2)[0][0]][np.where(binc1 == SL1)[0][0]] * F[np.where(binc2 == SL2)[0][0]][np.where(binc1 == SL1)[0][0]]
if W_SK <= W_SL:
SK1 = SL1
SK2 = SL2
else:
a = random.random()
if W_SL/W_SK >= a:
SK1 = SL1
SK2 = SL2
else:
SK1 = SK1
SK2 = SK2
#print('SK =',SK)
count[np.where(binc2 == SK2)[0][0]][np.where(binc1 == SK1)[0][0]] += 1
return F
where binc1 and binc2 are two np.arrays, gaussian is a gaussian fxn I defined, is there anyway I can speed up this for loop? Now 1000000 steps takes approximately 50 mins. I am thinking about using pytorch but I got no idea on how to do it. Any suggestions would be helpful!
Thanks
I tried to use pytorch, like put all the variables on gpu but it only does worse.
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?
I went through the other post on this same topic.
UnboundLocalError: local variable … referenced before assignment
But in my case, I have never mentioned local variables in another part of the code. Pycharm is indicating the problem is following function specifically "shell_cost". Which Is a part of the module 'economic' I call in a separate script. It says
column_investment_cost = 4.74 * (shell_cost + (stages - 2) * sieve_tray_cost)
UnboundLocalError: local variable 'shell_cost' referenced before assignment
The function is
def column(tray_area, height, stages):
tray_diameter = (tray_area * 4 / 3.1415926)**0.5
if tray_diameter <= 0.5:
shell_cost = 15.401 * height**2 + 1588.5 * height + 1495.5
elif tray_diameter <= 1:
shell_cost = 13.929 * height ** 2 + 2028.4 * height + 1850.6
elif tray_diameter <= 2:
shell_cost = 3.011 * height ** 2 + 3139.4 * height + 7166.9
elif tray_diameter <= 3:
shell_cost = -23.555 * height ** 2 + 5119.4 * height + 10945
elif tray_diameter <= 4:
shell_cost = -4.9723 * height ** 2 + 5021.1 * height + 24285 #???
# else:
# shell_cost = 'out of range'
sieve_tray_cost = -32.7 * tray_diameter**3 + 234.91 * tray_diameter**2 - 66.321 * tray_diameter + 293.53
column_investment_cost = 4.74 * (shell_cost + (stages - 2) * sieve_tray_cost)
return column_investment_cost
I am using an optimization tool Rbfopt, which calls another function name Optimization and optimization uses the 'economic' module to calculate objective function.
bb = rbfopt.RbfoptUserBlackBox(3, lower_bound, upper_bound, ['I', 'I', 'I'], optimization)
settings = rbfopt.RbfoptSettings(minlp_solver_path='C://Python_package//bonmin.exe', nlp_solver_path='C://Python_package//ipopt.exe', max_evaluations=2000)
alg = rbfopt.RbfoptAlgorithm(settings, bb)
val, x, itercount, evalcount, fast_evalcount = alg.optimize()
print(x)
#update the bound based on the first optimization results
t1_stop = perf_counter()
print("Elapsed time:", t1_stop, t1_start)
print("Elapsed time during the whole program in seconds:", t1_stop - t1_start)
Total Error Massage
Traceback (most recent call last):
File "C:/Users/XXX/Desktop/L/EOoptx.py", line 144, in <module>
val, x, itercount, evalcount, fast_evalcount = alg.optimize()
File "C:\Users\XXX\Anaconda3\envs\Rdsk\lib\site-packages\rbfopt\rbfopt_algorithm.py", line 803, in optimize
self.optimize_serial(pause_after_iters)
File "C:\Users\XXX\Anaconda3\envs\Rdsk\lib\site-packages\rbfopt\rbfopt_algorithm.py", line 1131, in optimize_serial
self.fixed_vars])
File "C:\Users\XXX\Anaconda3\envs\Rdsk\lib\site-packages\rbfopt\rbfopt_algorithm.py", line 2829, in objfun
return data[0].evaluate(point)
File "C:\Users\czm0131\Anaconda3\envs\Rdsk\lib\site-packages\rbfopt\rbfopt_user_black_box.py", line 152, in evaluate
return self.obj_funct(x)
File "C:/Users/XXX/Desktop/L/EOoptx.py", line 120, in optimization
D2_column_cost = economic.column(Tray_area_D2, H_D2, C2_stages)
File "C:\Users\XXX\Desktop\L\Economic.py", line 89, in column
column_investment_cost = 4.74 * (shell_cost + (stages - 2) * sieve_tray_cost)
UnboundLocalError: local variable 'shell_cost' referenced before assignment
Your tray_diameter value goes above 4, and thus shell_cost is never assigned. It does not exist.
A 'quick fix' would be to avoid calculating the column_investment_cost when tray_diameter is above 4 and return a None value instead. But you'd need to be able to handle that value where you try to call column():
def column(tray_area, height, stages):
tray_diameter = (tray_area * 4 / 3.1415926)**0.5
if tray_diameter > 4:
return None
if tray_diameter <= 0.5:
shell_cost = 15.401 * height**2 + 1588.5 * height + 1495.5
elif tray_diameter <= 1:
shell_cost = 13.929 * height ** 2 + 2028.4 * height + 1850.6
elif tray_diameter <= 2:
shell_cost = 3.011 * height ** 2 + 3139.4 * height + 7166.9
elif tray_diameter <= 3:
shell_cost = -23.555 * height ** 2 + 5119.4 * height + 10945
elif tray_diameter <= 4:
shell_cost = -4.9723 * height ** 2 + 5021.1 * height + 24285 #???
# else:
# shell_cost = 'out of range'
sieve_tray_cost = -32.7 * tray_diameter**3 + 234.91 * tray_diameter**2 - 66.321 * tray_diameter + 293.53
column_investment_cost = 4.74 * (shell_cost + (stages - 2) * sieve_tray_cost)
return column_investment_cost
You could also move the tray_diameter to its own function, and only calculate shell_cost and the rest if the conditions are met:
def calculate_tray_diameter(tray_area):
tray_diameter = (tray_area * 4 / 3.1415926)**0.5
return tray_diameter
def column(tray_diameter, height, stages)
if tray_diameter <= 0.5:
shell_cost = 15.401 * height**2 + 1588.5 * height + 1495.5
elif tray_diameter <= 1:
shell_cost = 13.929 * height ** 2 + 2028.4 * height + 1850.6
elif tray_diameter <= 2:
shell_cost = 3.011 * height ** 2 + 3139.4 * height + 7166.9
elif tray_diameter <= 3:
shell_cost = -23.555 * height ** 2 + 5119.4 * height + 10945
else:
shell_cost = -4.9723 * height ** 2 + 5021.1 * height + 24285 #???
# else:
# shell_cost = 'out of range'
sieve_tray_cost = -32.7 * tray_diameter**3 + 234.91 * tray_diameter**2 - 66.321 * tray_diameter + 293.53
column_investment_cost = 4.74 * (shell_cost + (stages - 2) * sieve_tray_cost)
return column_investment_cost
tray_diameter = calculate_tray_diameter(some_value)
if tray_diameter > 4:
print("Cannot calculate cost!")
else:
column_investment_cost = column(tray_diameter, height_value, stages_value)
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'
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?