I am making a syntax error, some how my syntax is leading python to think I am writing +.log some where?
Please take a look at the code and let me know.
Can any one suggest, a function that can be used instead to solve this Algorithm
import numpy as np
import sympy as sp
answer = 0
x = sp.Symbol('x')
y = sp.Symbol('y')
W = sp.Symbol('W')
R = sp.Symbol('R')
a = sp.Symbol('a')
n = sp.Symbol('n')
m = sp.Symbol('m')
O = sp.Symbol('O')
'''
answer = sp.solve(((((-1* (np.log(1+(x/R))))/(np.log(1+((10**6)/R))))+1)*(Os/((np.log(np.exp(1)+(x/a)**n))**m)))-W,x)
'''
answer = sp.solve(((((-1* (sp.log(1+(x/R))))/(sp.log(1+((10**6)/R))))+1)*(O/((sp.log(np.exp(1)+(x/a)**n))**m)))-W,x)
print(answer)
Results:
OLD
line 15, in <module>
answer = sp.solve(((((-1* (np.log(1+(x/R))))/(np.log(1+((10**6)/R))))+1)*(Os/((np.log(np.exp(1)+(x/a)**n))**m)))-W,x)
AttributeError: 'Add' object has no attribute 'log'
Process finished with exit code 1
Results:
New
Continuum\Anaconda3\lib\site-packages\sympy\solvers\solvers.py", line 1414, in _solve
"\nNo algorithms are implemented to solve equation %s" % f)
NotImplementedError: multiple generators [log((x/a)**n + 54365636569181/20000000000000)**m, log(1 + x/R)]
No algorithms are implemented to solve equation O*(1 - log(1 + x/R)/log(1 + 1000000/R))*log((x/a)**n + 54365636569181/20000000000000)**(-m) - W
Process finished with exit code 1
I think you should use sp.log instead of np.log. I run your code but it seems like the equation is too complex and no algorithms are implemented to solve it.
Related
I'm new to python and pyomo, so I would kindly appreciate your help,
I'm currently having trouble trying to add a constraint to my mathematical model in Pyomo, the problem is while I try to add the "feasibility_cut", it says "Constraint 'feasibility_cut[1]' does not have a proper value. Found 'True' ", what I understand from this is that, pyomo sees this constraint as a logical comparative constraint, which is I don't know why!
Here is a part of the code that I think is necessary to see:
RMP = ConcreteModel()
RMP.ymp = Var(SND.E, within=Integers)
RMP.z = Var(within = Reals)
S1 = (len(SND.A), len(SND.K))
S2 = (len(SND.A), len(SND.A))
uBar= np.zeros(S1)
vBar=np.zeros(S2)
RMP.optimality_cut = ConstraintList()
RMP.feasibility_cut = ConstraintList()
expr2 = (sum(SND.Fixed_Cost[i,j]*RMP.ymp[i,j] for i,j in SND.E) + RMP.z)
RMP.Obj_RMP = pe.Objective(expr = expr2, sense = minimize)
iteration=0
epsilon = 0.01
while (UB-LB)>epsilon :
iteration = iteration +1
DSPsolution = Solver.solve(DSP)
for i in SND.A:
for k in SND.K:
uBar[i-1,k-1] = value(DSP.u[i,k])
for i,j in SND.E:
vBar[i-1,j-1] = value(DSP.v[i,j])
if value(DSP.Obj_DSP) == DSPinf:
RMP.feasCut.add()
else:
RMP.optimCut.add()
RMPsolution = solver.solve(RMP)
UB=min(UB,)
LB=max(LB,value(RMP.Obj_RMP))
if value(DSP.Obj_DSP) == DSPinf:
RMP.feasibility_cut.add( 0>= sum(-SND.Capacity[i,j]*vBar[i-1,j-1]*RMP.ymp[i,j] for i,j in
SND.E) + sum(uBar[i-1,k-1]*SND.New_Demand[k,i] for i in SND.A for k in SND.K if (k,i) in
SND.New_Demand) )
else:
RMP.optimality_cut.add( RMP.z >= sum(SND.Fixed_Cost[i,j]*RMP.ymp[i,j] for i,j in SND.E) +
sum(uBar[i-1,k-1]*SND.New_Demand[k,i] for i in SND.A for k in SND.K) -
sum(SND.Capacity[i,j]*vBar[i-1,j-1]*RMP.ymp[i,j] for i,j in SND.E) )
Welcome to the site.
A couple preliminaries... When you post code that generates an error, it is customary (and easier for those to help) if you post the entire code necessary to reproduce the error and the stack trace, or at least identify what line is causing the error.
So when you use a constraint list in pyomo, everything you add to it must be a legal expression in terms of the model variables, parameters, and other constants etc. You are likely getting the error because you are adding an expression that evaluates to True. So it is likely that an expression you are adding does not depend on a model variable. See the example below.
Also, you need to be careful mingling numpy and pyomo models, numpy arrays etc. can cause some confusion and odd errors. I'd recommend putting all data into the model or using pure python data types (lists, sets, dictionaries).
Here are 2 errors. You have an empty add() in your code too, which will throw an error.
In [1]: from pyomo.environ import *
In [2]: m = ConcreteModel()
In [3]: m.my_constraints = ConstraintList()
In [4]: m.X = Var()
In [5]: m.my_constraints.add(m.X >= 5) # good!
Out[5]: <pyomo.core.base.constraint._GeneralConstraintData at 0x7f8778cfa880>
In [6]: m.my_constraints.add() # error!
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-cf466911f3a1> in <module>
----> 1 m.my_constraints.add()
TypeError: add() missing 1 required positional argument: 'expr'
In [7]: m.my_constraints.add(3 <= 4) # error: trivial evaluation!
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-7-a0bec84404b0> in <module>
----> 1 m.my_constraints.add(3 <= 4)
...
ValueError: Invalid constraint expression. The constraint expression resolved to a trivial Boolean (True) instead of a Pyomo object. Please modify your rule to return Constraint.Feasible instead of True.
Error thrown for Constraint 'my_constraints[2]'
In [8]:
Team Pyomo, I kindly need help with the above-stated error. I have done everything I could, but still can't get my model to work. Below is the formulation of my 'Objective Function', and the errors message. Thank you.
## Define Objective ##
def objective_rule(model):
s1=sum(1000*(model.fmax[j] - model.fmin[j])+ model.cmax[j] - model.cmin[j] for j in model.j)
s2=sum(model.x[i,k]*model.k*model.t[i] for k in model.k for i in model.i)
return s1 + 300 * s2
model.objective = Objective(expr=objective_rule, sense=minimize, doc='the objective function')
all the code that is before the objective function is fine (no errors). So, I will include below the code that comes after...it may be the one that caused the problem
## Display of the output ##
def pyomo_postprocess(options=None, instance=None, results=None):
instance.x.display()
writer = ExcelWriter("Data/output!G5:AJ27.csv")
df.to_excel(writer,index=False)
writer.save()
# pyomo command-line
if __name__ == '__main__':
# This emulates what the pyomo command-line tools does
from pyomo.opt import SolverFactory
import pyomo.environ
instance = model.create_instance()
instance.pprint()
opt = solvers.SolverFactory("cplex")
results = opt.solve(instance, tee=True)
# sends results to stdout
instance.solutions.load_from(results)
print("\nDisplaying Solution\n" + '-' * 60)
pyomo_postprocess(None, instance, results)
When I execute the program, I have the next error message:
ERROR: Constructing component 'objective' from data=None failed:
TypeError: Cannot treat the value '<function objective_rule at
0x0000000007C31D08>' as a constant because it has unknown type
'function'
The problem is that you're using the wrong keyword argument in your Objective component declaration. You should be using rule not expr:
model.objective = Objective(rule=objective_rule, sense=minimize, doc='the objective function')
The expr keyword is typically used when you have a very simple objective function expression and want to avoid writing a Python function to return the objective expression. You would use it like:
model.objective = Objective(expr=m.x**2+m.y**2, sense=minimize, doc='the objective function')
I would like Z3 to check whether it exists an integer t that satisfies my formula. I'm getting the following error:
Traceback (most recent call last):
File "D:/z3-4.6.0-x64-win/bin/python/Expl20180725.py", line 18, in <module>
g = ForAll(t, f1(t) == And(t>=0, t<10, user[t].rights == ["read"] ))
TypeError: list indices must be integers or slices, not ArithRef
Code:
from z3 import *
import random
from random import randrange
class Struct:
def __init__(self, **entries): self.__dict__.update(entries)
user = [Struct() for i in range(10)]
for i in range(10):
user[i].uid = i
user[i].rights = random.choice(["create","execute","read"])
s=Solver()
f1 = Function('f1', IntSort(), BoolSort())
t = Int('t')
f2 = Exists(t, f1(t))
g = ForAll(t, f1(t) == And(t>=0, t<10, user[t].rights == ["read"] ))
s.add(g)
s.add(f2)
print(s.check())
print(s.model())
You are mixing and matching Python and Z3 expressions, and while that is the whole point of Z3py, it definitely does not mean that you can mix/match them arbitrarily. In general, you should keep all the "concrete" parts in Python, and relegate the symbolic parts to "z3"; carefully coordinating the interaction in between. In your particular case, you are accessing a Python list (your user) with a symbolic z3 integer (t), and that is certainly not something that is allowed. You have to use a Z3 symbolic Array to access with a symbolic index.
The other issue is the use of strings ("create"/"read" etc.) and expecting them to have meanings in the symbolic world. That is also not how z3py is intended to be used. If you want them to mean something in the symbolic world, you'll have to model them explicitly.
I'd strongly recommend reading through http://ericpony.github.io/z3py-tutorial/guide-examples.htm which is a great introduction to z3py including many of the advanced features.
Having said all that, I'd be inclined to code your example as follows:
from z3 import *
import random
Right, (create, execute, read) = EnumSort('Right', ('create', 'execute', 'read'))
users = Array('Users', IntSort(), Right)
for i in range(10):
users = Store(users, i, random.choice([create, execute, read]))
s = Solver()
t = Int('t')
s.add(t >= 0)
s.add(t < 10)
s.add(users[t] == read)
r = s.check()
if r == sat:
print s.model()[t]
else:
print r
Note how the enumerated type Right in the symbolic land is used to model your "permissions."
When I run this program multiple times, I get:
$ python a.py
5
$ python a.py
9
$ python a.py
unsat
$ python a.py
6
Note how unsat is produced, if it happens that the "random" initialization didn't put any users with a read permission.
in last equation i need to solve for q. Here is the problem from miranda feckler , I need to develop equivalent python code If my function is based on many variables and i need to solve non linear root finding problem for only one variable then how will i write-
when i write all the three variable, I get following error
TypeError: 'numpy.ndarray' object is not callable
and when i write only one of variables-
i get error-
TypeError: resid() missing 2 required positional arguments: 'p' and 'phi'
can anyone tell me my mistake and a better code for this.
broyden1(resid(co, p_node, q), co)
breaks because the term resid(co, p_node, q) gets evaluated (returning an array) before passing into the function.
broyden1(resid, co)
breaks because when broyden1 evaluates it calls resid(co) which is clearly not well defined. You want to be able to pass the initial guess as a single object (e.g. a tuple) in broyden1, so a simple solution is to just redefine resid to take in a tuple instead of three sepearate arguments, like so:
def resid(arg):
c,p,phi = arg
return p + (phi * c) * ((-1 / eta) * (p ** (eta + 1))) \
- alpha * (np.sqrt(np.abs(phi * c))) - (phi * c) ** 2
c1 = scipy.optimize.broyden1(resid, (co, p_node, q))
I am trying to partition a large string F to m blocks as follows:
import random
from largeprimes import generateRandom
def generateRandom(length):
t = random.randint(0, 2**length)
str = "{0:b}".format(t)
if (len(str) < length):
str.zfill(length)
return str
def divide_file_block (): #return bi: int
b = []
for i in range (0, m):
b_i = F[(i*blocklen) : ((i+1)* blocklen)]
temp = int(b_i, 2) % q
b.append(temp)
return b
F = generateRandom(102400)
m = 100
blocklen = len(F)/m
q = generateLargePrime(1024) # generateLargePrime is from https://langui.sh/2009/03/07/generating-very-large-primes/
print divide_file_block ()
Note: you shall copy the code from 1 to the current directory, remove the last print statement there and name it largpeprimes.py. This makes the generateLargePrime function importable.
When I test on a small example, it printed out correct result. But when I test on b_i and q having 1024 bits, it printed out the error:
temp = int(b_i, 2) % q
TypeError: unsupported operand type(s) for %: 'int' and 'str'
Could you please explain me why and give me a suggestion to show this problem. Thanks in advance.
The function generateLargePrime sometime returns string
Trying the code I run into the same problem.
Testing it in debugger I got the cause: q has a value of `'Failure after 1100.0 tries.'
This is definitely a string an causes the failures.
I would recommend modifying the generateLargePrime code to throw an exception instead of reporting the failure by returned value.
Few tips for detecting this kind of problems
print out the problematic value
This is the simplest (and probably most popular) quick solution.
something like
b_i = F[(i*blocklen) : ((i+1)* blocklen)]
print "q", q # here is all the magic
temp = int(b_i, 2) % q
would tell you the value
place assert into your code
b_i = F[(i*blocklen) : ((i+1)* blocklen)]
assert isinstance(q, int)
temp = int(b_i, 2) % q
would throw an exception as soon as q is not of type int
run the code in debugger
pdb comes with Python, I prefer ipdb which comes with IPython, both would help you.
have the failing code written as a script
Try to run it via Python interpreter
$ python failingscript.py
as it fails, you simply try once more, but instead of python use pdb or ipdb
$ ipdb failingscript.py
the debugger let you control running the code line by line. Usually I let it run by "c" (continue) command and it soon crashes at the problematic point. Then I use "l" (list) to see, what line of code we are at, and finally use "p" (print) command to print values of variables, which are making problems. This way I used "p q" and found, it is a string.
It takes a moment to learn pdb or ipdb, but it works as turbo resolver so it is definitely the skill to learn. Great tutorial is at PMotW