I have this string:
"487351.25373014854 - 152956.2387091797 P_1(x) +
14288.881396831219 P_2(x) - 708.4250106547449 P_3(x) +
22.029508388530736 P_4(x) - 0.46451906903633394 P_5(x) +
0.006931166409021728 P_6(x) - 7.493824771409185e-05 P_7(x) +
5.934862864562062e-07 P_8(x) - 3.442722590115344e-09 P_9(x) +
1.4457000568406937e-11 P_10(x) - 4.276159814629395e-14 P_11(x) +
8.446505496408776e-17 P_12(x) - 9.998295324026605e-20 P_13(x) +
5.362954837187194e-23 P_14(x)"
I'm trying to replace all P_n(x) by *(x**n).
For example:
"1 - 2 P_1(x) + 3 P_2(x) - 708.4250106547449 P_3(x)"
would return:
"1 - 2*(x**1) + 3*(x**2) - 708.4250106547449*(x**3)"
You can use re.sub() to replace all occurrences of that pattern.
import re
s = "1 - 2 P_1(x) + 3 P_2(x) - 708.4250106547449 P_3(x)"
pattern = r' P_(\d+)\(x\)' # (\d+) captures the n in P_n
replace = r' * (x**\1)' # \1 uses the last captured n as a replacement
s_2 = re.sub(pattern, replace, s)
print(s_2)
Output:
1 - 2 * (x**1) + 3 * (x**2) - 708.4250106547449 * (x**3)
And with your full input:
s_3 = """487351.25373014854 - 152956.2387091797 P_1(x) +
14288.881396831219 P_2(x) - 708.4250106547449 P_3(x) +
22.029508388530736 P_4(x) - 0.46451906903633394 P_5(x) +
0.006931166409021728 P_6(x) - 7.493824771409185e-05 P_7(x) +
5.934862864562062e-07 P_8(x) - 3.442722590115344e-09 P_9(x) +
1.4457000568406937e-11 P_10(x) - 4.276159814629395e-14 P_11(x) +
8.446505496408776e-17 P_12(x) - 9.998295324026605e-20 P_13(x) +
5.362954837187194e-23 P_14(x)
"""
s_4 = re.sub(pattern, replace, s_3)
print(s_4)
Output:
487351.25373014854 - 152956.2387091797 * (x**1) +
14288.881396831219 * (x**2) - 708.4250106547449 * (x**3) +
22.029508388530736 * (x**4) - 0.46451906903633394 * (x**5) +
0.006931166409021728 * (x**6) - 7.493824771409185e-05 * (x**7) +
5.934862864562062e-07 * (x**8) - 3.442722590115344e-09 * (x**9) +
1.4457000568406937e-11 * (x**10) - 4.276159814629395e-14 * (x**11) +
8.446505496408776e-17 * (x**12) - 9.998295324026605e-20 * (x**13) +
5.362954837187194e-23 * (x**14)
I would suggest a simple for loop with the replace() function
for i in range(n):
mystr = mystr.replace('P_'+str(i)+'(x)', '*(x**'+str(i)+'2)')
Related
I have a function with different parameters that I want to optimize to fit some existing data.
The function runs fine on its own, but when I try to pass it through the scipy.optimize.curve_fit function, I get this error :
IndexError: invalid index to scalar variable.
I don't understand why the function would work on its own, and I would not get any errors.
What can I do ?
The original function used dictionnaries and I thought that might be the problem but I modified it and it still doesn't work.
This is the function I'm using :
def function_test(xy,X1,X2,X3,X4):
precip = xy\[0\]
potential_evap = xy\[1\]
nUH1 = int(math.ceil(X4))
nUH2 = int(math.ceil(2.0*X4))
uh1_ordinates = [0] * nUH1
uh2_ordinates = [0] * nUH2
UH1 = [0] * nUH1
UH2 = [0] * nUH2
for t in range(1, nUH1 + 1):
uh1_ordinates[t - 1] = s_curves1(t, X4) - s_curves1(t-1, X4)
for t in range(1, nUH2 + 1):
uh2_ordinates[t - 1] = s_curves2(t, X4) - s_curves2(t-1, X4)
production_store = X1*0.60# S
routing_store = X3*0.70# R
qsim = []
for j in range(2191):
if precip[j] > potential_evap[j]:
net_evap = 0
scaled_net_precip = (precip[j] - potential_evap[j])/X1
if scaled_net_precip > 13:
scaled_net_precip = 13.
tanh_scaled_net_precip = tanh(scaled_net_precip)
reservoir_production = (X1 * (1 - (production_store/X1)**2) * tanh_scaled_net_precip) / (1 + production_store/X1 * tanh_scaled_net_precip)
routing_pattern = precip[j]-potential_evap[j]-reservoir_production
else:
scaled_net_evap = (potential_evap[j] - precip[j])/X1
if scaled_net_evap > 13:
scaled_net_evap = 13.
tanh_scaled_net_evap = tanh(scaled_net_evap)
ps_div_x1 = (2 - production_store/X1) * tanh_scaled_net_evap
net_evap = production_store * (ps_div_x1) / \
(1 + (1 - production_store/X1) * tanh_scaled_net_evap)
reservoir_production = 0
routing_pattern = 0
production_store = production_store - net_evap + reservoir_production
percolation = production_store / (1 + (production_store/2.25/X1)**4)**0.25
routing_pattern = routing_pattern + (production_store-percolation)
production_store = percolation
for i in range(0, len(UH1) - 1):
UH1[i] = UH1[i+1] + uh1_ordinates[i]*routing_pattern
UH1[-1] = uh1_ordinates[-1] * routing_pattern
for j in range(0, len(UH2) - 1):
UH2[j] = UH2[j+1] + uh2_ordinates[j]*routing_pattern
UH2[-1] = uh2_ordinates[-1] * routing_pattern
groundwater_exchange = X2 * (routing_store / X3)**3.5
routing_store = max(0, routing_store + UH1[0] * 0.9 + groundwater_exchange)
R2 = routing_store / (1 + (routing_store / X3)**4)**0.25
QR = routing_store - R2
routing_store = R2
QD = max(0, UH2[0]*0.1+groundwater_exchange)
Q = QR + QD
qsim.append(Q)
return qsim
I am trying to return all value pairs from three sequences, however I am only getting a single value pair for the first sequence. Does anyone know what happens?. The example sequences are "ALLKAIIAI", "AHHAKKAKLLA", "APPALLAIIKAMMA", see it in the code bellow:
def ComputeSeqs():
input_seq = ["ALLKAIIAI", "AHHAKKAKLLA", "APPALLAIIKAMMA"]
for sequence in input_seq:
ANDN920101={'A':4.35,'L':4.17,'R':4.38,'K':4.36,'N':4.75,
'M':4.52,'D':4.76,'F':4.66,'C':4.65,'P':4.44,
'Q':4.37,'S':4.50,'E':4.29,'T':4.35,'G':3.97,
'W':4.70,'H':4.63,'Y':4.60,'I':3.95,'V':3.95}
ARGP820101={'A':0.61,'L':1.53,'R':0.60,'K':1.15,'N':0.06,
'M':1.18,'D':0.46,'F':2.02,'C':1.07,'P':1.95,
'Q':0.0,'S':0.05,'E':0.47,'T':0.05,'G':0.07,
'W':2.65,'H':0.61,'Y':1.88,'I':2.22,'V':1.32}
aaindex_values = []
aaindex_listT = [ANDN920101, ARGP820101]
for i in aaindex_listT:
a_a = ((sequence.count("A") * i["A"])) / len(sequence)
c_c = ((sequence.count("C") * i["C"])) / len(sequence)
d_d = ((sequence.count("D") * i["D"])) / len(sequence)
e_e = ((sequence.count("E") * i["E"])) / len(sequence)
f_f = ((sequence.count("F") * i["F"])) / len(sequence)
g_g = ((sequence.count("G") * i["G"])) / len(sequence)
h_h = ((sequence.count("H") * i["H"])) / len(sequence)
i_i = ((sequence.count("I") * i["I"])) / len(sequence)
k_k = ((sequence.count("K") * i["K"])) / len(sequence)
l_l = ((sequence.count("L") * i["L"])) / len(sequence)
m_m = ((sequence.count("M") * i["M"])) / len(sequence)
n_n = ((sequence.count("N") * i["N"])) / len(sequence)
p_p = ((sequence.count("P") * i["P"])) / len(sequence)
q_q = ((sequence.count("Q") * i["Q"])) / len(sequence)
r_r = ((sequence.count("R") * i["R"])) / len(sequence)
s_s = ((sequence.count("S") * i["S"])) / len(sequence)
t_t = ((sequence.count("T") * i["T"])) / len(sequence)
v_v = ((sequence.count("V") * i["V"])) / len(sequence)
w_w = ((sequence.count("W") * i["W"])) / len(sequence)
y_y = ((sequence.count("Y") * i["Y"])) / len(sequence)
aaindex_comp = round(((a_a + c_c + d_d + e_e + f_f + g_g + h_h + i_i + k_k + l_l + m_m + n_n + p_p + q_q + r_r + s_s + t_t + v_v + w_w + y_y) / 20),3)
aaindex_values.append(aaindex_comp)
return aaindex_values
print(ComputeSeqs())
You need to initialize aaindex_values before the loop, and return it after the loop.
You're never creating nested lists for results of summing the multipliers from each dictionary in aaindex_listT. This is easiest done using a list comprehension. And you can loop over the dictionary and use sum() rather than creating 26 different variables.
def ComputeSeqs():
input_seq = ["ALLKAIIAI", "AHHAKKAKLLA", "APPALLAIIKAMMA"]
ANDN920101={'A':4.35,'L':4.17,'R':4.38,'K':4.36,'N':4.75,
'M':4.52,'D':4.76,'F':4.66,'C':4.65,'P':4.44,
'Q':4.37,'S':4.50,'E':4.29,'T':4.35,'G':3.97,
'W':4.70,'H':4.63,'Y':4.60,'I':3.95,'V':3.95}
ARGP820101={'A':0.61,'L':1.53,'R':0.60,'K':1.15,'N':0.06,
'M':1.18,'D':0.46,'F':2.02,'C':1.07,'P':1.95,
'Q':0.0,'S':0.05,'E':0.47,'T':0.05,'G':0.07,
'W':2.65,'H':0.61,'Y':1.88,'I':2.22,'V':1.32}
aaindex_listT = [ANDN920101, ARGP820101]
aaindex_values = []
for sequence in input_seq:
aaindex_comp = [sum(sequence.count(key) * value for key, value in i.items()) / len(sequence) for i in aaindex_listT]
aaindex_values.append(aaindex_comp)
return aaindex_values
print(ComputeSeqs())
Using the formula from https://engineersfield.com/cubic-equation-formula/:
class CubicEquation():
def __init__(self,a,b,c,d):
'''initialize constants and formula'''
q = (3*c - b**2) / 9
r = -27*d + b*(9*c - 2*b**2)
discriminant = q**3 + r**2
s = r + sqrt(discriminant)
t = r - sqrt(discriminant)
term1 = sqrt(3 * ((-t + s) / 2))
r13 = 2 * sqrt(q)
self.cubic_equation = [\
'-term1 + r13*cos(q**3 / 3)',\
'-term1 + r13*cos(q**3 + (2 * pi)/3)',\
'-term1 + r13*cos(q**3 + (4 * pi)/3)'\
]
def solve(self):
*--snip--*
and then later calling it with answer = eval(self.cubic_equation[index])
when calling this formula with args (1,1,1,1), I receive the solution:
-6.803217085397121, -8.226355957420402, -8.208435953185608
and yes I have triple-checked my formulas with those on the site.
What is the correct code for this function, and what went wrong with my current program?
I am getting an error that says I am not accounting for obscured light and that my specular is getting added when the light is obscured. This is what the specular part that is being added onto is with x representing r, g, orb of my Color class: light.color.x * s.finish.specular * specIntense
def in_shadow (sphere_list, sphere, ray_to_light, light):
new_list = list()
for s in sphere_list:
if sphere != s:
new_list.append(s)
for s in new_list:
if sphere_intersection_point(ray_to_light, s):
x1 = ray_to_light.pt.x - light.pt.x
y1 = ray_to_light.pt.y - light.pt.y
z1 = ray_to_light.pt.z - light.pt.z
dist1 = math.sqrt(x1 + y1 + z1)
x2 = ray_to_light.pt.x - s.center.x
y2 = ray_to_light.pt.y - s.center.y
z2 = ray_to_light.pt.z - s.center.z
dist2 = math.sqrt(x2 + y2 + z2)
# distance to light, distance to sphere
# check if distance to sphere < distance to light
# if so return 0
if dist2 < dist1:
return 0
return 1
def cast_ray(ray, sphere_list, color, light, point):
# count = 0
dist = -1
cp = Color(1.0, 1.0, 1.0)
for s in sphere_list:
if sphere_intersection_point(ray, s):
# count += 1
p = sphere_intersection_point(ray, s)
vec = vector_from_to(s.center, p)
N = normalize_vector(vec)
norm_scaled = scale_vector(N, 0.01)
pe = translate_point(p, norm_scaled)
l = vector_from_to(pe, light.pt)
l_dir = normalize_vector(l)
dot = dot_vector(N, l_dir)
r = Ray(pe, l_dir)
dotNScaled = dot * 2
reflecVec = difference_vector(l_dir, scale_vector(N, dotNScaled))
V = vector_from_to(point, pe)
Vdir = normalize_vector(V)
spec = dot_vector(reflecVec, Vdir)
m = in_shadow(sphere_list, s, r, light)
if (dot <= 0):
m = 0
x = (ray.pt.x - p.x) ** 2
y = (ray.pt.y - p.y) ** 2
z = (ray.pt.z - p.z) ** 2
curdist = math.sqrt(x + y + z)
# print curdist
if (dist < 0) or (dist > curdist):
dist = curdist
if (spec <= 0 ):
r = ( s.color.r * s.finish.ambient * color.r ) \
+ ( light.color.r * s.finish.diffuse * dot * s.color.r * m )
g = ( s.color.g * s.finish.ambient * color.g ) \
+ (light.color.g * s.finish.diffuse * dot * s.color.g * m )
b = ( s.color.b * s.finish.ambient * color.b ) \
+ (light.color.b * s.finish.diffuse * dot * s.color.b * m )
cp = Color(r, g, b)
if ( spec >= 0 ):
specIntense = spec ** (1/s.finish.roughness)
print type(s.finish.diffuse)
r = (s.color.r * s.finish.ambient * color.r) \
+ (light.color.r * s.finish.diffuse * dot * s.color.r * m) \
+ (light.color.r * s.finish.specular * specIntense)
g = (s.color.g * s.finish.ambient * color.g) \
+ (light.color.g * s.finish.diffuse * dot * s.color.g * m) \
+ (light.color.g * s.finish.specular * specIntense)
b = (s.color.b * s.finish.ambient * color.b) \
+ (light.color.b * s.finish.diffuse * dot * s.color.b * m) \
+ (light.color.b * s.finish.specular * specIntense)
cp = Color(r, g, b)
# if count > 1:
# print 'intersects two!'
return cp
I think somewhere I am not accounting for the case where the sphere has another one in front of it therefore the specular part is being added to it when it shouldn't, creating this weird white light behind the first sphere that isn't supposed to be there. I'm sure there is a bug in this code somewhere but I cannot find it.
I'm supposed to write a program that ends up such as this:
* *
* *
* *
*
I have the code written for a regular one, but I'm not sure how to incorporate spaces into it.
def triangle(i, t = 0):
if i == 0
return 0
else:
print ' ' * (t + 1) + '*' * (i * 2 - 1)
return triangle(i - 1, t + 1)
Advice?
Try:
def triangle(i, t = 0):
if i == 0:
print (t+1) *' '+ '*'
else:
print ' ' * (t + 1)+ '*' + ' ' * (i * 2 - 1) + '*'
triangle(i - 1, t + 1)
triangle(5)
this code print:
* *
* *
* *
* *
* *
*
Let's label some areas in a line:
startSpaces * middleSpaces * endSpaces
For a given line you want startSpaces + 1 + middleSpaces + 1 + endSpaces to equal a constant. This constant is 2*(i+t) + 1
line 1 will have t=0 spaces before the *
the final line will have t=i spaces before the * (here I'm using the original i, I know it changes through recursion)
So can you find a pattern for startSpaces, middleSpaces and endSpaces that will give you the proper pattern?
Keep in mind that you will need an additional else if case for i==1 so that you can handle the row with only one *
This should be enough for you to get a lot closer to solving your problem. I'm assuming it's homework so I won't solve it for you, if you get stuck ask for more clues.
Building on #kharazi's answer (because this reminds me of my early GWBasic programming which is what got me excited about programming as a kid):
def triangle(i, leftShape='*', rightShape='*', bottomShape='*', spaceShape=' ', t = 0):
if i <= 0:
print ((t+1)*spaceShape)+bottomShape+((t+1)*spaceShape)
else:
print (spaceShape*(t + 1))+leftShape+(spaceShape*(i*2-1))+rightShape+(spaceShape*(t + 1))
triangle(i-1, leftShape, rightShape, bottomShape, spaceShape, t+1)
if __name__== '__main__':
triangle(3)
triangle(3, '\\', '/')
triangle(3, '\\', '/', '~')
triangle(5, '╚╗', '╔╝', '╚╦╝')
triangle(5, '╚╗', '╔╝', '╚╦╝', '|')
triangle(-2)
Produces the following output:
triangle(3)
* *
* *
* *
*
triangle(3, '\\', '/')
\ /
\ /
\ /
*
triangle(3, '\\', '/', '~')
\ /
\ /
\ /
~
triangle(5, '╚╗', '╔╝', '╚╦╝')
╚╗ ╔╝
╚╗ ╔╝
╚╗ ╔╝
╚╗ ╔╝
╚╗ ╔╝
╚╦╝
triangle(5, '╚╗', '╔╝', '╚╦╝', '|')
|╚╗|||||||||╔╝|
||╚╗|||||||╔╝||
|||╚╗|||||╔╝|||
||||╚╗|||╔╝||||
|||||╚╗|╔╝|||||
||||||╚╦╝||||||
triangle(-2)
*
you should be using a for loop for this, recursion works but it is not the best idea to use it all the time. this is what i did:
def GioTri(i):
foo = i - 1
bar = 0
for i in range(i-1):
print ' ' * bar + "*" + " " * (foo*2 - 1) + "*" + " " * bar
foo = foo - 1
bar = bar + 1
print " " * bar + "*" + " " * bar
the result of this looks like this:
* *
* *
* *
*