I am trying to output an answer to a differential equation.
My Code:
function = "cos(z)"
def Complex_Function(z):
f1=eval(function)
return f1
f_subsituted = Complex_Function(a+b*exp(x)) # make z = a+b e^x
DerivativeN1_Func = sm.diff(f_subsituted , a) #differntiate f_subsituted once
DerivativeN2_Func = sm.diff(DerivativeN1_Func , a) # differntiate f_subsituted twice
display(Latex(r"$y'''(x)+y(x)=-b^2 e^{-2x}$")) #Output needed (Here is the problem)
display(DerivativeN2_Func)
The correct output should be:
y'''(x)+y(x)=-b^2 e^{-2x} *DerivativeN2_Func
But whatever I try it shows the "DerivativeN2_Func" in a new line.
I tried to:
display(Latex(r"$y'''(x)+y(x)=-b^2 e^{-2x}$"), DerivativeN2_Func)
use (end"") method.
non of them worked.
Can you help me solving this issue please?
I am trying to write a pyomo model in python3, but I am facing this error that I can't seem to figure out - 'list' object has no attribute 'is_expression_type'. Below is my pyomo model, any help would be appreciated.
R_avg_tolist = [[0.00043159478649482775,
0.00045388639592182584,
0.0006735271301199177,
0.00044026758948786,
0.0037176592984565836]]
Cov_list = [[5.884677519869241e-05,
5.756542207262417e-05,
6.017027849080026e-05,
6.180151597797322e-05,
-0.0005074353586106837],
[5.756542207262417e-05,
6.0380562653096757e-05,
6.613608499966434e-05,
6.737370769879904e-05,
-0.0005362752804115953],
[6.017027849080026e-05,
6.613608499966434e-05,
8.206495000024503e-05,
8.01694525889321e-05,
-0.0005958716888916681],
[6.180151597797322e-05,
6.737370769879904e-05,
8.01694525889321e-05,
0.00010129901491226823,
-0.000608829853150321],
[-0.0005074353586106837,
-0.0005362752804115953,
-0.0005958716888916681,
-0.000608829853150321,
0.007373689071617548]]
import pyomo.environ as pyo
# Optimization Problem
def create_model(rho,R_avg,Cov):
m = pyo.ConcreteModel()
init_x = {}
m.idx = pyo.Set(initialize=[0,1,2,3,4])
for i in m.idx:
init_x[i] = 0
m.x = pyo.Var(m.idx,initialize=init_x,bounds=(0,None))
def Obj_func(m):
b = []
mult_result = 0
for i in m.idx:
a = 0
for j in m.idx:
a+= m.x[j]*Cov[j][i]
b.append(a)
for i in m.idx:
mult_result += b[i]*m.x[i]
return mult_result
m.OBJ = pyo.Objective(rule=Obj_func)
def constraint1(m):
sum=0
for i in m.idx:
sum+=m.x[i]
return sum ==100
m.C1 = pyo.Constraint(rule=constraint1(m))
def constraint2(m):
sum=0
for i in m.idx:
sum += R_avg_tolist[i]*m.x[i]
return sum >=0.08
m.C2 = pyo.Constraint(rule=constraint2(m))
return m
When I run model using below code, I face the attribute error - 'list' object has no attribute 'is_expression_type'.
rho = 0.0008
model1 = create_model(rho,R_avg_tolist,Cov_list)
solver = SolverFactory('ipopt')
results = solver.solve(model1, tee = True)
Probably not what you want to hear, but your model has many syntax probs. It's obviously a course assignment... Do you have somebody (instructor/TA) to go over this with who can advise a bit?
You didn't include enough info about which line of code caused the issue, but there are several problem areas. I've posted many simple pyomo examples if you scan through some of them, you'll get some ideas, along with the documentation and whatever you have from your course notes....
A few pointers may help:
Do NOT overwrite keywords/functions by using them as variables. When you write:
sum = 0
sum ....
you are nuking the python function sum by making that name a variable and assigning it the value of 0. You should be using sum in several of your functions with verbiage like:
sum(m.X[i] for i in m.idx) # or similar
You seem to be confused on making valid pyomo expressions. That is the core job of pyomo ... to make expressions and fill the model. For example, in your constraint1, you can just make an expression (without a function) and add it to your model. You can do a 1-liner there because the constraint is not a "for each". You could:
m.C1 = pyo.Constraint(expr=sum(m.x[i] for x in m.idx) == 100)
In general, when you are starting:
Add 1 thing to your model, and then print the model:
model.pprint()
See if it looks right, if not, fix it. Then repeat!
It is now one week that i am stuck with this and i don't know why it is happening. So i want to present to you my problem to see if you have a solution.
I have this code. My purpose here is to update this variables A and B using a loop. So, i first execute all calcs using A and B that i give when i call the class, then the code compute gamma and xi and finally i want to compute new A and B.
I create in my class first the functions that i use to find the values that i need to use for computing gamma and xi. Then i create functions that i use to find gamma and xi. In this function i call the previous functions with self.fun.
Then i create the function that i show here to compute new A and B values and i insert this in a loop because i want to iterate this function until i reach a convergence.
But...
This method works correctly to compute A, but, when it needs to compute B, it uses the new A before computing B. It implies that, when it computes A, old A and B are used to compute gamma and xi and then A. Where it computes B, it uses new A and B to compute gamma and xi but i want that it uses the same that it uses to compute first A.
def update(self):
for n in range(self.iter):
gamma = self.gamma()
xi = self.xi()
# new trans matrix
new_A = []
for i in range(len(self.A)):
temp = []
for j in range(len(self.A[i])):
numerator = 0
denominator = 0
for r in range(len(self.seq)):
for t in range(len(xi[r])):
numerator += xi[r][t][i][j]
denominator += gamma[r][t][i]
aij = numerator / denominator
temp.append(aij)
new_A.append(temp)
self.A = new_A
emission_signals = unique(self.seq[0])
emission_matrix = []
for k in range(len(emission_signals)):
emission_matrix.append([])
for i in range(len(self.A)):
gamma_vec = []
gamma_num = []
for r in range(len(self.seq)):
for t in range(len(self.seq[r])):
gamma_append = gamma[r][t][i]
gamma_vec.append(gamma_append)
if self.seq[r][t] == emission_signals[k]:
gamma_num_append = gamma[r][t][i]
gamma_num.append(gamma_num_append)
bik = sum(gamma_num) / sum(gamma_vec)
emission_matrix[k].append(bik)
new_B = {}
keys = emission_signals
for i in range(len(keys)):
new_B[keys[i]] = emission_matrix[i]
self.A = new_A
self.B = new_B
return {'A': self.A, 'B': self.B}
I don't know if i'm explaining well but this is my problem.
Hope that you can help me!
Thank you !
It's difficult without seeing the rest of your code, but it looks like you are referencing mutable objects A and B (list and dict) multiple times, and editing them from different places.
Just take into account, in python, every time you assign a mutable object to a variable, you are only creating a new reference to same object and not copying it. So every edit you do on that object, will be reflected on all its references.
Ok. the problem was this:
print(self.update().get('A'))
print(self.update().get('B'))
I change it in this way and now it works but i do not understand the logic behind this.
a = self.update()
print('\n---New transition matrix... ---')
print(a.get('A'))
print('\n---New Emission matrix... ---')
print(a.get('B'))
Maybe in the previous way i call update 2 times and then calculations go wrong. i don't know.
I have a question regarding my code (sorry if it is really easy or stupid, I have never coded before and tried this for a project). I tried running a probability weighting function for certain probability vector. I however get an error and I do not know how to fix it. When i run the argument of the function first seperatly and then call it in the function it works, but why does it not work in the function itself?
Code Below
I hope you can help me.
Thanks a lot!
import numpy as np
p = np.arange(0.01, 1, 0.01) # probalities equaly spread between 0 & 1 in steps of 0.01
alpha_1 = 0.5
alpha = np.zeros((1, 99)) + alpha_1 # vector of same length as p with all entries being 0.5
term_in_exopnential_of_weighting_function = - (- np.log(p))**alpha
w = np.exp(term_in_exopnential_of_weighting_function) # weighted probability function
# probability weighting function
#w(p)=np.exp(-(- np.log(p))**alpha)
# --> error, but why?`
It looks like what you're trying to do is to create a function which is named w. In Python the syntax for a function definition is
def f(a, b, c):
# do something here
result = <something involving a, b, and c>
return result
Then you can call the function as f(1, 2, 3) or whatever for a, b, and c.
In the example you gave, I think maybe what you need is
>>> def w(alpha, p):
... return np.exp(-(- np.log(p))**alpha)
...
Where >>> is the Python interpreter input prompt. Note that the function body must be indented, as enforced by the interpreter. The ... with nothing following it means I just hit the Enter key without typing anything. With that definition of w, I get the following result, given alpha and p as you specified:
>>> w(alpha, p)
array([[0.116955 , 0.13836178, 0.15372645, 0.16627328, 0.17713938,
0.18687366, 0.19578782, 0.20407777, 0.21187567, 0.21927533,
0.2263461 , 0.23314086, 0.23970099, 0.24605961, 0.25224365,
0.25827542, 0.26417363, 0.26995416, 0.27563063, 0.28121487,
0.28671721, 0.29214677, 0.29751164, 0.30281908, 0.30807562,
0.31328717, 0.31845916, 0.32359653, 0.32870387, 0.33378542,
0.33884514, 0.34388676, 0.34891376, 0.35392947, 0.35893704,
0.36393949, 0.36893972, 0.37394054, 0.37894464, 0.38395468,
0.38897324, 0.39400286, 0.39904606, 0.40410531, 0.40918309,
0.41428186, 0.41940411, 0.42455233, 0.42972903, 0.43493677,
0.44017815, 0.44545582, 0.45077251, 0.45613099, 0.46153416,
0.466985 , 0.4724866 , 0.47804216, 0.48365505, 0.48932878,
0.49506703, 0.50087369, 0.50675283, 0.5127088 , 0.51874619,
0.52486989, 0.53108512, 0.53739747, 0.54381293, 0.55033797,
0.55697957, 0.56374529, 0.57064336, 0.57768275, 0.58487331,
0.59222586, 0.59975235, 0.60746605, 0.61538177, 0.62351608,
0.63188769, 0.64051783, 0.64943073, 0.65865431, 0.66822097,
0.67816868, 0.68854243, 0.69939617, 0.71079551, 0.72282159,
0.73557672, 0.74919294, 0.76384569, 0.77977671, 0.79733511,
0.81705854, 0.8398553 , 0.86750307, 0.90461 ]])
I write below code but that is very slow. And, of course, does not work correct!
I have what I do?
for i in range(image_shape[0]):
for j in range(filter_shape[0]):
pmin = self.pooled_out[i][j].min()
pmax = self.pooled_out[i][j].max()
self.pooled_out = T.set_subtensor(T.set_subtensor(self.pooled_out[i], self.pooled_out[i])[j],self.pooled_out[i][j] - pmin)
self.pooled_out = T.set_subtensor(T.set_subtensor(self.pooled_out[i], self.pooled_out[i])[j],self.pooled_out[i][j] / pmax)
First that section of your code do nothing. Just remove this line
T.set_subtensor(self.pooled_out[i], self.pooled_out[i])
Without full code, I can't test my solution, but I think this would do what you want:
pmin = self.pooled_out.min(axis=[2,3], keepdims=True)
pmax = self.pooled_out.max(axis=[2,3], keepdims=True)
normalized_pooled_out = (self.pooled_out - pmin)/pmax
Then normalized_pooled_out contain the symbolic variable that have the value I think you want.