Unable to solve a LP Problem in python using docplex - python

from docplex.mp.model import Model
m = Model(name="LP_Problem")
x1 = m.continuous_var(name="x1")
x2 = m.continuous_var(name="x2")
c11 = m.add_constraint( x1 + x2 <= 722)
c12 = m.add_constraint( 25 * x1 + x2 <= 685)
c13 = m.add_constraint( 48 * x1 + x2 <= 678.05)
c14 = m.add_constraint( x1 + x2 >= 705)
c15 = m.add_constraint( 25 * x1 + x2 >= 658.25)
c16 = m.add_constraint( 48 * x1 + x2 >= 650)
m.minimize(2085.05 - 74 * x1 - 3 * x2)
m.print_information()
s = m.solve()
m.print_solution()
OUTPUT
(venv) C:\Usears\goram\Code_files>python C:\Users\goram\Code_files\exp.py
Model: LP_Problem
- number of variables: 2
- binary=0, integer=0, continuous=2
- number of constraints: 6
- linear=6
- parameters: defaults
- objective: minimize
- problem type is: LP
Traceback (most recent call last):
File "C:\Users\goram\Code_files\exp.py", line 15, in <module>
m.print_solution()
File "C:\Users\goram\Code_files\venv\lib\site-packages\docplex\mp\model.py", line 6071, in print_solution
self._check_has_solution()
File "C:\Users\goram\Code_files\venv\lib\site-packages\docplex\mp\model.py", line 5189, in _check_has_solution
self.fatal("Model<{0}> did not solve successfully", self.name)
File "C:\Users\goram\Code_files\venv\lib\site-packages\docplex\mp\model.py", line 1080, in fatal
self._error_handler.fatal(msg, args)
File "C:\Users\goram\Code_files\venv\lib\site-packages\docplex\mp\error_handler.py", line 210, in fatal
raise DOcplexException(resolved_message)
docplex.mp.utils.DOcplexException: Model<LP_Problem>
did not solve successfully

Related

Receiving error message in Python when using if statement(closed)

I am not sure why but i am receiving a syntax error in the following code segment:
def motor_sat(self, wheel_angular_velocities, limit_value):
phi1 = wheel_angular_velocities[0]
phi2 = wheel_angular_velocities[1]
phi3 = wheel_angular_velocities[2]
if phi1 < -limit_value
phi1_bar = -limit_value
elif phi1 <= limit_value and phi1 >= -limit_value
phi1_bar = phi1
elif phi1 > limit_value
phi1_bar = limit_value
The error message is:
[lab3demo1] Traceback (most recent call last):
[lab3demo1] File "lab3demo1.py", line 8, in <module>
[lab3demo1] from myRobot import *
[lab3demo1] File "/home/user/ele719/controllers/lab3demo1/myRobot.py", line 66
[lab3demo1] if phi1 < -limit_value
[lab3demo1] ^
[lab3demo1] SyntaxError: invalid syntax
You are missing colons(:) at the end of each if/elif statements, the correct code would be:
def motor_sat(self, wheel_angular_velocities, limit_value):
phi1 = wheel_angular_velocities[0]
phi2 = wheel_angular_velocities[1]
phi3 = wheel_angular_velocities[2]
if phi1 < -limit_value:
phi1_bar = -limit_value
elif phi1 <= limit_value and phi1 >= -limit_value:
phi1_bar = phi1
elif phi1 > limit_value:
phi1_bar = limit_value

Implicit differentiation in sympy function

I'm trying to perform implicit differentiation to the function Lrdot which is -2*rdot/(1 - 1/r(t)), wrt an affine parameter s, where rdot is dr/ds. The error below pops up and i'm not sure how to debug.
from sympy import *
from sympy.physics.mechanics import *
r = dynamicsymbols('r')
rdot = dynamicsymbols('r', 1)
t = dynamicsymbols('t')
tdot = dynamicsymbols('t', 1)
phi = dynamicsymbols('phi')
phidot = dynamicsymbols('phi', 1)
s = symbols('s')
def F(x):
return 1-(1/x)
# Largangian
def L(a,b,c, adot, bdot, cdot, photon = true): #r,t,phi
return F(a)*(bdot)**2 - adot**2/F(a) - (a*cdot)**2
L = L(r, t, phi, rdot, tdot, phidot, photon = true)
Lr = diff(L, r)
Lrdot = diff(L, rdot)
diffLrdot = idiff(-2*rdot/(1-1/r), r, s)
print(diffLrdot)
Traceback (most recent call last):
File "/Users/myname/PycharmProjects/untitled/.idea/14.1.py", line 40, in <module>
diffLrdot = idiff(-2*rdot/(1-1/r), r, s)
File "/Users/myname/PycharmProjects/untitled/venv/lib/python3.6/site-packages/sympy/geometry/util.py", line 578, in idiff
f = {s: Function(s.name)(x) for s in eq.free_symbols
File "/Users/myname/PycharmProjects/untitled/venv/lib/python3.6/site-packages/sympy/geometry/util.py", line 579, in <dictcomp>
if s != x and s in dep}
NameError: free variable 'dep' referenced before assignment in enclosing scope

Why I am getting Traceback most recent call last and file string at line 6

My python code is below. when I run this code in compiler every single time I'm getting an error like this below.
ERROR:
Traceback (most recent call last):
File "main.py", line 4, in <module>
turtle.setup(850, 850)
File "<string>", line 6, in setup
File "/usr/lib64/python2.7/lib-tk/turtle.py", line 3553, in Screen
Turtle._screen = _Screen()
File "/usr/lib64/python2.7/lib-tk/turtle.py", line 3569, in __init__
_Screen._root = self._root = _Root()
File "/usr/lib64/python2.7/lib-tk/turtle.py", line 458, in __init__
TK.Tk.__init__(self)
File "/usr/lib64/python2.7/lib-tk/Tkinter.py", line 1820, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
MY CODE:
import random
import turtle
turtle.setup(850, 850)
turtle.penup()
turtle.speed('fastest')
turtle.tracer(0, 0)
x = 0
y = 0
for i in range(1, 16000):
r = random.uniform(0, 1)
if r < 0.1:
nextX = 0
nextY = float(0.16 * y)
x = nextX
y = nextY
elif r < 0.88:
nextX = float(0.85 * x * 0.04 * y)
nextY = float(-0.04 * x * 0.85 * y + 1.6)
x = nextX
y = nextY
elif r < 0.93:
nextX = float(0.20 * x * -0.26 * y)
nextY = float(0.23 * x * 0.22 * y + 1.6)
x = nextX
y = nextY
else:
nextX = float(-0.15 * x * 0.28 * y)
nextY = float(0.26 * x * 0.24 * y + 0.44)
x = nextX
y = nextY
turtle.goto(x*40, y*40)
turtle.dot(2, 'green')
turtle.done()
This is one of the undefined error I found for the first time.
How can I fix this? what is wrong in this code. Thank you so much in advance for solving this
That happens typical, if you start your script on the remote host via ssh as example, because there is no display and the DISPLAY environment variable can not be set. Where do you running your script?

Numba gives: ' TypingError: %r not allowed in a homogenous sequence'

I really have no clue what that error is about, since I dont even directly use %r. I suspect that somewhere there's a mixing of types, but I can not fathom where that would happen. That aside other suggestions to speed up the code would be much appreciated.
import numpy as np
from numba import jit, float64
c = 3*10**8
epsilon = 8.854187817 * 10**(-12)
mu = 4*np.pi *10**(-7)
#jit( nopython=True)
def cross(vec1, vec2):
result = np.array([0.,0.,0.])
a1, a2, a3 = vec1[0],vec1[1], vec1[2]
b1, b2, b3 = vec2[0], vec2[1], vec2[2]
result[0] = a2 * b3 - a3 * b2
result[1] = a3 * b1 - a1 * b3
result[2] = a1 * b2 - a2 * b1
return result
#jit( float64[:,:](float64[:],float64,float64,float64[:],float64[:],float64[:]), nopython = True)
def jit_EM_field(position,length,ladung,velocity,acceleration,R):
#using solutions to lienard wiechert potential
radius = np.linalg.norm(R - position)
if radius != 0:
unitradius = (R - position)/radius
else:
unitradius = np.array([0.,0.,0.])
if radius != 0 and np.dot(unitradius, velocity)!=1:
charge = ladung / ( (1 - np.dot(unitradius, velocity)/c)** 3)
if radius < length:
radius = length
radius2 = radius ** 2
velocity_in_c = velocity/c
oneMinusV2 = 1 - np.dot(velocity_in_c, velocity_in_c)
uMinusV = unitradius - velocity_in_c
aCrossUmV = cross(uMinusV, acceleration)
Eleft = (oneMinusV2 * (unitradius - velocity_in_c)) / radius2
Eright = cross(unitradius, aCrossUmV) / (radius*c**2)
E = (charge/(4*np.pi*epsilon)) * (Eleft - Eright)
B = cross(unitradius/c, ((mu*epsilon*charge*c**2) * (Eleft - Eright)))
EM_field = np.array([E,B], dtype = float)
else:
EM_field = np.zeros((2,3), dtype = float)
return EM_field
jit_EM_field( np.array([0.,1.,0.]),1.,0.1,np.array([0.,1.,0.]),np.array([0.,1.,0.])
,np.array([7.2,5.6,0.1]))
And here's the full error message.
runfile('C:/Users/Elios/testingjit.py', wdir='C:/Users/Elios')
Traceback (most recent call last):
File "<ipython-input-26-221208a798d4>", line 1, in <module>
runfile('C:/Users/Elios/testingjit.py', wdir='C:/Users/Elios')
File "C:\Users\Elios\Anaconda4\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "C:\Users\Elios\Anaconda4\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/Elios/testingjit.py", line 32, in <module>
#jit( float64[:,:](float64[:],float64,float64,float64[:],float64[:],float64[:]), nopython = True)
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\decorators.py", line 176, in wrapper
disp.compile(sig)
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\dispatcher.py", line 531, in compile
cres = self._compiler.compile(args, return_type)
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\dispatcher.py", line 80, in compile
flags=flags, locals=self.locals)
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\compiler.py", line 725, in compile_extra
return pipeline.compile_extra(func)
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\compiler.py", line 369, in compile_extra
return self.compile_bytecode(bc, func_attr=self.func_attr)
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\compiler.py", line 378, in compile_bytecode
return self._compile_bytecode()
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\compiler.py", line 690, in _compile_bytecode
return self._compile_core()
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\compiler.py", line 677, in _compile_core
res = pm.run(self.status)
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\compiler.py", line 257, in run
raise patched_exception
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\compiler.py", line 249, in run
stage()
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\compiler.py", line 476, in stage_nopython_frontend
self.locals)
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\compiler.py", line 828, in type_inference_stage
infer.propagate()
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\typeinfer.py", line 717, in propagate
raise errors[0]
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\typeinfer.py", line 127, in propagate
constraint(typeinfer)
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\typeinfer.py", line 372, in __call__
self.resolve(typeinfer, typevars, fnty)
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\typeinfer.py", line 385, in resolve
sig = typeinfer.resolve_call(fnty, pos_args, kw_args)
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\typeinfer.py", line 972, in resolve_call
return self.context.resolve_function_type(fnty, pos_args, kw_args)
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\typing\context.py", line 124, in resolve_function_type
return func.get_call_type(self, args, kws)
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\types\functions.py", line 49, in get_call_type
sig = temp.apply(args, kws)
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\typing\templates.py", line 216, in apply
sig = typer(*args, **kws)
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\typing\npydecl.py", line 456, in typer
ndim, seq_dtype = _parse_nested_sequence(self.context, object)
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\typing\npydecl.py", line 423, in _parse_nested_sequence
n, dtype = _parse_nested_sequence(context, typ.dtype)
File "C:\Users\Elios\Anaconda4\lib\site-packages\numba\typing\npydecl.py", line 421, in _parse_nested_sequence
raise TypingError("%r not allowed in a homogenous sequence")
TypingError: %r not allowed in a homogenous sequence
Numba seems to lack support for nested arrays. Have managed to circumvent the issue in the following code. jit_EM_field() now returns an array of length 6 instead of 2 nested arrays of length 3 which you can see as #jit( float64[:] in the jit decorator. Also removed a redundant else clause.
import numpy as np
from numba import jit, float64
c = 3*10**8
epsilon = 8.854187817 * 10**(-12)
mu = 4*np.pi *10**(-7)
#jit( nopython=True)
def cross(vec1, vec2):
result = np.array([0.,0.,0.])
a1, a2, a3 = vec1[0],vec1[1], vec1[2]
b1, b2, b3 = vec2[0], vec2[1], vec2[2]
result[0] = a2 * b3 - a3 * b2
result[1] = a3 * b1 - a1 * b3
result[2] = a1 * b2 - a2 * b1
return result
#jit( float64[:](float64[:],float64,float64,float64[:],float64[:],float64[:]), nopython=True)
def jit_EM_field(position,length,ladung,velocity,acceleration,R):
#using solutions to lienard wiechert potential
EM_field = np.array([0.,0.,0.,0.,0.,0.])
radius = np.linalg.norm(R - position)
if radius != 0:
unitradius = (R - position)/radius
if np.dot(unitradius, velocity) != 1:
charge = ladung / ( (1 - np.dot(unitradius, velocity)/c)** 3)
if radius < length:
radius = length
radius2 = radius ** 2
velocity_in_c = velocity/c
oneMinusV2 = 1 - np.dot(velocity_in_c, velocity_in_c)
uMinusV = unitradius - velocity_in_c
aCrossUmV = cross(uMinusV, acceleration)
Eleft = (oneMinusV2 * (unitradius - velocity_in_c)) / radius2
Eright = cross(unitradius, aCrossUmV) / (radius*c**2)
E = (charge/(4*np.pi*epsilon)) * (Eleft - Eright)
B = cross(unitradius/c, ((mu*epsilon*charge*c**2) * (Eleft - Eright)))
EM_field = np.array([E[0],E[1],E[2],B[0],B[1],B[2]])
return EM_field
em_field = jit_EM_field(np.array([0.,1.,0.]),1.,0.1,np.array([0.,1.,0.]),np.array([0.,1.,0.]),np.array([7.2,5.6,0.1]))
em_field_zero = jit_EM_field(np.array([0.,1.,0.]),1.,0.1,np.array([0.,1.,0.]),np.array([0.,1.,0.]),np.array([0.,1.,0.]))
import pprint as pp
pp.pprint(em_field)
pp.pprint(em_field_zero)

How to correctly initialize pool worker and run method

Background:
I am trying to get a pool of workers going to solve a task. My issue is that I am trying to pass it a shared variable, but I get an error. I have written an initializer method for the workers that expect my variables, but I can't seem to get it to work.
Here is my code:
from matplotlib import pyplot
import time
import multiprocessing
#initialize some multiprocessing stuff
num_processes = 8
y = multiprocessing.Array('d', 1000, lock=False)
new_y = multiprocessing.Array('d', 1000, lock=False)
dt = multiprocessing.Value('d',0, lock=False)
y_len = multiprocessing.Value('i',len(y), lock=False)
def init(y_to_share, new_y_to_share):
global y, new_y
y = y_to_share
new_y = new_y_to_share
y[480:520] = [1] * 40
dt.value = 0.01
# our rule for reaction-diffusion
def advance():
global y, new_y
n = len(y)
new_y = list(y)
for j in xrange(n):
new_y[j] += dt * (20 * (y[j - 1] - 2 * y[j] + y[(j + 1) % n])
- y[j] * (1 - y[j]) * (0.3 - y[j]))
y = new_y
return y
# advance through t (t = i * dt) is at least 100; plot
# every 20
chunks = len(y)/num_processes
y_range = range(len(y))
y_range = [y_range[i:i+chunks] for i in range(0, len(y_range), chunks)]
p = multiprocessing.Pool(num_processes, initializer=init, initargs=(y, new_y))
i = 0
start = time.time()
while i * dt.value <= 100:
if i * dt.value % 20 == 0:
pyplot.plot(y, label='t = %g' % (i * dt.value))
arr = p.map(advance, (y, new_y))#hand in an array of indices
i += 1
#print i * dt.value
end = time.time()
elapsed = end-start
print elapsed
pyplot.legend()
pyplot.show()
Edit: Post the actual error
The error:
runfile('/home/kevin/Downloads/cbb750_parallel_hw/propagating-signal-parallel.py', wdir='/home/kevin/Downloads/cbb750_parallel_hw')
Traceback (most recent call last):
File "<ipython-input-64-5ad3fdf93b59>", line 1, in <module>
runfile('/home/kevin/Downloads/cbb750_parallel_hw/propagating-signal-parallel.py', wdir='/home/kevin/Downloads/cbb750_parallel_hw')
File "/usr/local/lib/python2.7/dist-packages/spyder/utils/site/sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "/usr/local/lib/python2.7/dist-packages/spyder/utils/site/sitecustomize.py", line 94, in execfile
builtins.execfile(filename, *where)
File "/home/kevin/Downloads/cbb750_parallel_hw/propagating-signal-parallel.py", line 45, in <module>
arr = p.map(advance, (y, new_y))#hand in an array of indices
File "/usr/lib/python2.7/multiprocessing/pool.py", line 251, in map
return self.map_async(func, iterable, chunksize).get()
File "/usr/lib/python2.7/multiprocessing/pool.py", line 567, in get
raise self._value
PicklingError: Can't pickle <class 'multiprocessing.sharedctypes.c_double_Array_1000'>: attribute lookup multiprocessing.sharedctypes.c_double_Array_1000 failed
Can anyone help me solve this? I am not sure what I am doing wrong, but I would like to use pool.map .

Categories