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

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

Related

Unable to solve a LP Problem in python using docplex

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

CVXOPT Quadratic Optimization

When using CVXOPT to optimize my SVM problem, I receive the error given below.
Traceback (most recent call last):
File "C:\Users\mospic\AppData\Roaming\Python\Python310\site-packages\cvxopt\misc.py", line 1429, in factor
lapack.potrf(F['S'])
ArithmeticError: 25
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\mospic\AppData\Roaming\Python\Python310\site-packages\cvxopt\coneprog.py", line 2065, in coneqp
try: f = kktsolver(W)
File "C:\Users\mospic\AppData\Roaming\Python\Python310\site-packages\cvxopt\coneprog.py", line 1981, in kktsolver
return factor(W, P)
File "C:\Users\mospic\AppData\Roaming\Python\Python310\site-packages\cvxopt\misc.py", line 1444, in factor
lapack.potrf(F['S'])
ArithmeticError: 25
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\mospic\Desktop\EXP2_files\src1\main.py", line 28, in <module>
test_svm(1, 'Linear', 1e-4)
File "C:\Users\mospic\Desktop\EXP2_files\src1\main.py", line 21, in test_svm
model.fit(train_features, train_labels)
File "C:\Users\mospic\Desktop\EXP2_files\src1\SVM.py", line 66, in fit
sol = cvxopt.solvers.qp(P, q, G, h, A, b)
File "C:\Users\mospic\AppData\Roaming\Python\Python310\site-packages\cvxopt\coneprog.py", line 4485, in qp
return coneqp(P, q, G, h, None, A, b, initvals, kktsolver = kktsolver, options = options)
File "C:\Users\mospic\AppData\Roaming\Python\Python310\site-packages\cvxopt\coneprog.py", line 2067, in coneqp
raise ValueError("Rank(A) < p or Rank([P; A; G]) < n")
ValueError: Rank(A) < p or Rank([P; A; G]) < n
And the Code given below:
n = train_data.shape[0]
K = np.zeros((n, n))
for i in range(n):
for j in range(n):
K[i][j] = train_label[i] * train_label[j] * SupportVectorMachine().KERNEL(train_data[i], train_data[j])
#Calculate Kernal Matrix with label i and label j
# 1/2x^TPx + q^Tx
P = cvxopt.matrix(K)
q = cvxopt.matrix(-1 * np.ones(n))
# Gx <= h
temp_G1 = np.identity(n)
temp_G2 = -1 * (np.identity(n))
G = cvxopt.matrix(np.vstack((temp_G1, temp_G2)))
temp_h1 = self.C * np.ones(n)
temp_h2 = np.zeros(n)
h = cvxopt.matrix(np.hstack((temp_h1, temp_h2)).reshape(-1, 1))
# Ax = b
A = cvxopt.matrix(train_label.astype(np.double), (1, n))
b = cvxopt.matrix(0.0)
sol = cvxopt.solvers.qp(P, q, G, h, A, b)
alpha = np.array(sol['x'])
n is the length of training data, and sol is the optimal solution of the SVM question.But the Error ValueError: Rank(A) < p or Rank([P; A; G]) < n is confusing me.

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

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 .

AttributeError: 'module' object has no attribute 'get_altitude'

This section of my pysolarrobot7.py code is throwing an AttributeError
def tomorrow_heading():
increment_min = 1
incrementeddatetime = 0
tomorrow_corrected = 90
if pysolar.get_altitude(maplat, maplon, datetime.datetime.utcnow()) < 0:
while pysolar.get_altitude(maplat, maplon, (datetime.datetime.utcnow() + datetime.timedelta(minutes=incrementeddatetime))) < 0:
incrementeddatetime = incrementeddatetime + increment_min
sunrise_time=(datetime.datetime.utcnow() + datetime.timedelta(minutes=incrementeddatetime))
tomorrow_heading = pysolar.GetAzimuth(maplat, maplon, sunrise_time)
if tomorrow_heading < 0:
if (tomorrow_heading >= -180):
tomorrow_corrected = ((tomorrow_heading * -1) + 180)
if (tomorrow_heading < -180):
tomorrow_corrected = ((tomorrow_heading * -1) - 180)
if tomorrow_heading >= 0:
The following is the error code
root#Primerpi:/tools# python3 solarrobot7-core.py
Traceback (most recent call last):
File "solarrobot7-core.py", line 237, in <module>
tomorrow_static = tomorrow_heading()
File "solarrobot7-core.py", line 176, in tomorrow_heading
if pysolar.get_altitude(maplat, maplon, datetime.datetime.utcnow()) < 0:
AttributeError: 'module' object has no attribute 'get_altitude'
I've been googling for a while now and can't seem to find the answer. The original code from solarrobot7.py used GetAltitude and Pysolar (PascalCase) and I changed it to get_altitude and pysolar (snake_case).
pysolar don't have an "get_altitude" method:
You want the sub-module "solar" :)
from pysolar import solar
solar.get_altitude #this will work :)

Categories