error in a python class with an not iterable object - python

i have a the following error message
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py", line 2721, in run_code
exec code_obj in self.user_global_ns, self.user_ns
File "<ipython-input-257-84ae6ec7b6f6>", line 1, in <module>
accuracy.ra_os
File "<ipython-input-255-a91d95432efe>", line 32, in ra_os
return np.average([(ref.intersection(s).area/s.area) for s in seg])
TypeError: 'Polygon' object is not iterable
where Polygon is the Polygon class of shapely.
i have my own class Accuracy: stat values between reference (one) and segmented (one or more) polygons
ref = <shapely.geometry.polygon.Polygon at 0x4997b38>
seg = [<shapely.geometry.polygon.Polygon at 0x4b972e8>, <shapely.geometry.polygon.Polygon at 0x49c7390>]
import math
import numpy as np
from shapely.geometry import Polygon
nan = np.nan
class Accuracy(object):
def __init__(self, ref, seg=None):
self.ref = ref
self.seg = seg
#property
def area(self):
return self.ref.area
#property
def perimeter(self):
return self.ref.length
#property
def centroidX(self):
return self.ref.centroid.x
#property
def centroidY(self):
return self.ref.centroid.y
#property
def segments(self):
if self.seg:
return len(self.seg)
else:
return 0
#property
def ra_or(self):
if self.seg:
return np.average([(ref.intersection(s).area/ref.area) for s in seg])
else:
return nan
#property
def ra_os(self):
if self.seg:
return np.average([(ref.intersection(s).area/s.area) for s in seg])
else:
return nan
accuracy = Accuracy(ref, seg_overlap)
accuracy.ra_os
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py", line 2721, in run_code
exec code_obj in self.user_global_ns, self.user_ns
File "<ipython-input-45-84ae6ec7b6f6>", line 1, in <module>
accuracy.ra_os
File "<ipython-input-7-1e04291926b0>", line 35, in ra_os
return np.average([(ref.intersection(s).area/s.area) for s in seg])
TypeError: 'Polygon' object is not iterable
if i run the function outside the class i have not this error
np.average([(ref.intersection(s).area/ref.area) for s in seg_overlap])
Out[47]: 0.48709794373000681

Did you mean to say self.seg instead of just seg:
return np.average([(ref.intersection(s).area/ref.area) for s in self.seg])
^^^^^
(in both functions)
I think you're accidentally referring to the global object with the same name.

Related

Python pass variable to multiprocessing pool

I been trying to figure out this for ages, but wondering if anyone might know how I can pass the s variable to the pool without making it into an argument?
import ctypes
import multiprocessing as mp
import os
def worker1(n):
k = n*3
print(k)
print(s)
# print(ctypes_int.value)
if __name__ == '__main__':
# global s
somelist = [1,2,3]
# ctypes_int = mp.Value(ctypes.c_wchar_p , "hi")
s = "TESTING"
# worker1(1)
p = mp.Pool(1)
p.map(worker1,somelist)
This is the error I am getting:
3
6
9
multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
File "C:\Program Files\Python\Python37\lib\multiprocessing\pool.py", line 121, in worker
result = (True, func(*args, **kwds))
File "C:\Program Files\Python\Python37\lib\multiprocessing\pool.py", line 44, in mapstar
return list(map(*args))
File "C:\Users\light\AppData\Local\Temp\tempCodeRunnerFile.python", line 10, in worker1
print(s)
NameError: name 's' is not defined
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\light\AppData\Local\Temp\tempCodeRunnerFile.python", line 21, in <module>
p.map(worker1,somelist)
File "C:\Program Files\Python\Python37\lib\multiprocessing\pool.py", line 268, in map
return self._map_async(func, iterable, mapstar, chunksize).get()
File "C:\Program Files\Python\Python37\lib\multiprocessing\pool.py", line 657, in get
raise self._value
NameError: name 's' is not defined
You can pass your variable along with each item in somelist:
import multiprocessing as mp
def worker1(p):
n,s = p
k = n*3
print(k)
print(s)
if __name__ == '__main__':
somelist = [1,2,3]
s = "TESTING"
p = mp.Pool(1)
p.map(worker1,[(n,s) for n in somelist])
The parameter (n,s) gets passed as p and I unpack it into n,s.

TypeError: 'list' object is not callable in Python in mathematical programming

I have a funtion defined in a class
class someClass:
def objFunction(self, weights):
return [self.obj1(weights), self.obj2(weights), self.obj3(weights)]
def asf(self, f):
def obj(x):
return np.max(np.array(f(x[0],x[1],x[2])))+0.00001*np.sum(f(x[0],x[1],x[2]))
res=minimize(obj,
[0.3,0.3,0.4], method='SLSQP'
,jac=ad.gh(obj)[0],options = {'disp':True, 'ftol': 1e-20,
'maxiter': 1000})
return res
where obj1, obj2 and obj3 are some objective functions to optimized. I am running this method making an object separately:
newObj = SomeClass()
newObj.objFunction(weights)
This works fine and give expected results. But when I used the same method inside another method in the class it returns the above mentioned error. This is how I am doing:
a = someClass()
a.asf(a.objFunction(weights)
It throws this:
Traceback (most recent call last):
File "D:/*******.py", line 332, in <module>
print(investment.asf(obj1(w),ref,ideal,nadir, rho))
File "*******.py", line 313, in asf
,options = {'disp':True, 'ftol': 1e-20, 'maxiter': 1000})
File "C:\Users\*****\Downloads\WinPython-64bit-3.5.1.2\python-3.5.1.amd64\lib\site-packages\scipy\optimize\_minimize.py", line 455, in minimize
constraints, callback=callback, **options)
File "C:\Users\*****\Downloads\WinPython-64bit-3.5.1.2\python-3.5.1.amd64\lib\site-packages\scipy\optimize\slsqp.py", line 363, in _minimize_slsqp
fx = func(x)
File "C:\Users\*******\Downloads\WinPython-64bit-3.5.1.2\python-3.5.1.amd64\lib\site-packages\scipy\optimize\optimize.py", line 289, in function_wrapper
return function(*(wrapper_args + args))
File "D:********.py", line 305, in obj
return np.max(np.array(f(x[0], x[1], x[2], x[3])))+rho*np.sum(f(x[0], x[1], x[2], x[3]))
TypeError: 'list' object is not callable
I think I am doing some OOP (object oriented programming) error in coding because I am not good at it. Any suggestions for this ? Thanks
a.objFunction(weights) returns a list, that's clear from the definition.
a.asf expects one argument called f, which in the definition gets used like:
f(x[0],x[1],x[2])
So you are giving a.asf a list and trying to call it like a function.

Fixed_quad Error With Functions

Keeping it simple:
----------------------------------
from mpmath import *
from scipy.integrate import *
mp.dps=30
def F(x):
return Q**(x)
Q=735
print fixed_quad(F,0,1,n=1)[0]
print fixed_quad(F,0,1,n=2)[0]
print fixed_quad(F,0,1,n=3)[0]
--------------------
returns
27.1108834235
93.1213589089
109.673420158
However, if I change F(x) from “Q**(x)” to even just a simple function—e.g., “cos(x)”—I get
--------------------
Traceback (most recent call last):
File "Test.py", line 7, in <module>
print fixed_quad(F,0,1,n=1)[0]
File "/usr/lib/python2.7/dist-packages/scipy/integrate/quadrature.py", line 67, in fixed_quad
return (b-a)/2.0*sum(w*func(y,*args),0), None
File "Test.py", line 5, in F
return cos(x)
File "/usr/lib/pymodules/python2.7/mpmath/ctx_mp_python.py", line 984, in f
x = ctx.convert(x)
File "/usr/lib/pymodules/python2.7/mpmath/ctx_mp_python.py", line 662, in convert
return ctx._convert_fallback(x, strings)
File "/usr/lib/pymodules/python2.7/mpmath/ctx_mp.py", line 614, in _convert_fallback
raise TypeError("cannot create mpf from " + repr(x))
TypeError: cannot create mpf from array([ 0.5])
Is this some known bug? Or is “fixed_quad” only meant for certain uses, not general integration (like “trapz”)?
All of the other regulars (“quad”, “dblquad”, “tplquad”, “nquad”) donʼt seem to have that problem/error.

Python class and function

I defined a function in my class, but when i called this function into my main program:
class real :
def __init__(self):
self.nmodes = 4
self.L_ch = 1
self.w = 2
def func1(self,x):
self.k_ch=self.nmodes*self.L_ch*self.w
f=x**3+4*x*self.k_ch+15*self.k_ch
return f
And my main program is:
from dev import *
A=real()
C=A.func1(x)
Unfortunately i got this error:
Traceback (most recent call last):
File "PBC.py", line 4, in <module>
C=A.func1(0.2)
AttributeError: real instance has no attribute 'func1'
When i don't include the function in my class, my parameters are not recognized and i got this error:
Traceback (most recent call last):
File "PBC.py", line 75, in <module>
R_0=scipy.optimize.fsolve(func1,float(eps_real),args=(eps))
File "/usr/local/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 127, in fsolve
res = _root_hybr(func, x0, args, jac=fprime, **options)
File "/usr/local/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 183, in _root_hybr
_check_func('fsolve', 'func', func, x0, args, n, (n,))
File "/usr/local/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 14, in _check_func
res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
File "/home/cfd1/ndiaye/ATACAMAC/BCT_dev.py", line 75, in func1
self.k_ch=self.nmodes*self.pi/self.L_ch+eps/self.L_ch
AttributeError: 'numpy.ndarray' object has no attribute 'nmodes'
What can i do to avoid all this? Thank you for your answers.
Your above code runs if you just fix the indentation:
class real :
def __init__(self):
self.nmodes = 4
self.L_ch = 1
self.w = 2
def func1(self,x):
self.k_ch=self.nmodes*self.L_ch*self.w
f=x**3+4*x*self.k_ch+15*self.k_ch
return f
A=real()
C=A.func1(5)
You have an indentation error. The lines starting def func1 should be lined up with def __init__.

Is it possible to define a function in a Class

I have a problem with my python code specialy when I'm trying to define a function in a Class. Indeed, I want to call this function (which is in a file i called BC.py) in my main program which i called PBC.py
Class BC():
self.nmodes
self.L_ch
self.w
def func1(self,x):
self.k_ch=self.nmodes*self.L_ch*self.w
f=x**3+4*x*self.k_ch+15*self.k_ch
return f
In my main programm i did:
from BC import *
A=BC()
C=func1(self,x)
Then I got this error:
The parameters file have been imported succesfully
Traceback (most recent call last):
File "PBC.py", line 35, in <module>
C =func1(A,eps)
NameError: name 'func1' is not defined
Please do you know where i am wrong?
The thing is, when i don't include the function in my class everything works well,
Class BC():
self.nmodes
self.L_ch
self.w
def func1(self,x):
self.k_ch=self.nmodes*self.L_ch*self.w
f=x**3+4*x+15
return f
Exept that when i use only the function, all the parameters I defined before are not recognized???
For example:
r_0=scipy.optimize.fsolve(func1,0.003,args=(0.032))
I got this error:
The parameters file have been imported succesfully
Traceback (most recent call last):
File "PBC.py", line 75, in <module>
R_0=scipy.optimize.fsolve(func1,float(eps_real),args=(eps))
File "/usr/local/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 127, in fsolve
res = _root_hybr(func, x0, args, jac=fprime, **options)
File "/usr/local/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 183, in _root_hybr
_check_func('fsolve', 'func', func, x0, args, n, (n,))
File "/usr/local/lib64/python2.7/site-packages/scipy/optimize/minpack.py", line 14, in _check_func
res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
File "/home/cfd1/ndiaye/ATACAMAC/BCT_dev.py", line 75, in func1
self.k_ch=self.nmodes*self.pi/self.L_ch+eps/self.L_ch
AttributeError: 'numpy.ndarray' object has no attribute 'nmodes'
Someone can help?
Thank you very much.
Thank you for your answer but it isn't working, i still got this error:
Traceback (most recent call last):
File "PBC.py", line 36, in <module>
C =A.func1(x)
Now i'm trying with a very simplified script:
class real :
def __init__(self):
self.nmodes = 4
self.L_ch = 1
self.w = 2
def func1(self,x):
self.k_ch=self.nmodes*self.L_ch*self.w
f=x**3+4*x*self.k_ch+15*self.k_ch
return f
And my main program is:
from dev import *
A=real()
C=A.func1(x)
Unfortunately it seems not working to caus' i have the same traceback error.
Thank you.
You should call it this way:
from BC import *
A=BC()
C=A.func1(x)
Edit for comment:
Please take care of the code format:
class real :
def __init__(self):
self.nmodes = 4
self.L_ch = 1
self.w = 2
def func1(self,x):
self.k_ch=self.nmodes*self.L_ch*self.w
f=x**3+4*x*self.k_ch+15*self.k_ch
return f
Call the function this way (recommended):
A = BC()
C = A.func1(x)
or this other (less used and not recommended, just mentioned as information):
C = BC.func1(A, x)
Note: I would recommend you to rename your file with a name different than the class BC, because it confuses Python. Also, don't forget to declare x.

Categories

Resources