Python class and function - python

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__.

Related

I'm trying to find a periodic orbit using the shooting method

def integrate_ode(ode,u0,T):
sol=solve_ivp(ode,T,u0)
return sol.y[:,-1]
def phase(ode,u0):
return ode(0,u0)[0] #dx/dt(0)
def shooting(ode,U):
print(len(U))
u0=U[0:-1]
#print(u0)
T=U[-1]
#print(T)
G=np.concatenate((integrate_ode(ode,u0,T)-u0,phase(ode,u0)))
return G
To get the solutions I'm using:
fsolve(lambda U:shooting(ode1,U),...(initial conditions))
I'm getting this error:
IndexError: invalid index to scalar variable.
Here is my full traceback:
Traceback (most recent call last):
"...Python\workweek16.py", line 62, in <module>
G=fsolve(lambda U:shooting(ode1,U),(0,0))
File "C:\Users\tmara\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\scipy\optimize\minpack.py", line 160, in fsolve
res = _root_hybr(func, x0, args, jac=fprime, **options)
File "C:\Users\tmara\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\scipy\optimize\minpack.py", line 226, in _root_hybr
shape, dtype = _check_func('fsolve', 'func', func, x0, args, n, (n,))
File "C:\Users\tmara\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\scipy\optimize\minpack.py", line 24, in _check_func
res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
File "...Python\workweek16.py", line 62, in <lambda>
G=fsolve(lambda U:shooting(ode1,U),(0,0))
File "...Python\workweek16.py", line 51, in shooting
G=np.concatenate((integrate_ode(ode,u0,T)-u0,phase(ode,u0)))
File "...Python\workweek16.py", line 40, in integrate_ode
sol=solve_ivp(ode,T,u0)
File "C:\Users\tmara\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\scipy\integrate\_ivp\ivp.py", line 508, in solve_ivp
t0, tf = float(t_span[0]), float(t_span[1])
IndexError: invalid index to scalar variable.
Does anyone know what to do?
The t_span argument for solve_ivp needs to actually be a time span. So replace T there with [0,T].

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.

Passing IPython parallel cluster object into custom class for batch execution

I am a novice programmer trying to use python for scientific programming. I think these posts (How to work with interactively-defined classes in IPython.parallel? and ipython parallel push custom object) touches on a similar issue but are not useful for me. I want to run my code as a script (for PBS or SGE queued schedulers) and I don't know how I would use dill.
Essentially, I am trying to use Ipython parallel cluster for splitting up computation that is defined in a custom class method.
I want to pass a cluster object into my custom class instance, then use the cluster to split up computation that operate on pieces of data defined as a member.
Having started a cluster using ipcluster (/path/to/ipcontroller-client.json),
Then, I want to run, python test_parallel.py
Where, test_parallel.py is
class Foo(object):
def __init__(self):
from numpy import arange
self.data = arange(10)*10
def A(self, y):
print "in A:", y
self.data[y]
def parallelA(self, z, cl):
print "in parallelA:", cl[:].map_sync(self.A, z)
def serialA(self, z):
print "in serialA:", map(self.A, z)
if __name__ == "__main__":
from IPython.parallel import Client
f = '/path/to/security/ipcontroller-client.json'
c = Client(f)
asdf = Foo()
asdf.serialA([1, 3, 5]) ## works
asdf.parallelA([1, 3, 5], c) ## doesn't work
The output is
$ ~/Projects/parcellation$ python test_parallel.py
in serialA: in A: 1
in A: 3
in A: 5
[None, None, None]
in parallelA:
Traceback (most recent call last):
File "test_parallel.py", line 24, in <module>
asdf.parallelA([1, 3, 5], c) ## doesn't work
File "test_parallel.py", line 11, in parallelA
print "in parallelA:", cl[:].map_sync(self.A, z)
File "/usr/local/lib/python2.7/dist-packages/IPython/parallel/client/view.py", line 366, in map_sync
return self.map(f,*sequences,**kwargs)
File "<string>", line 2, in map
File "/usr/local/lib/python2.7/dist-packages/IPython/parallel/client/view.py", line 66, in sync_results
ret = f(self, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/IPython/parallel/client/view.py", line 624, in map
return pf.map(*sequences)
File "/usr/local/lib/python2.7/dist-packages/IPython/parallel/client/remotefunction.py", line 271, in map
ret = self(*sequences)
File "<string>", line 2, in __call__
File "/usr/local/lib/python2.7/dist-packages/IPython/parallel/client/remotefunction.py", line 78, in sync_view_results
return f(self, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/IPython/parallel/client/remotefunction.py", line 243, in __call__
ar = view.apply(f, *args)
File "/usr/local/lib/python2.7/dist-packages/IPython/parallel/client/view.py", line 233, in apply
return self._really_apply(f, args, kwargs)
File "<string>", line 2, in _really_apply
File "/usr/local/lib/python2.7/dist-packages/IPython/parallel/client/view.py", line 66, in sync_results
ret = f(self, *args, **kwargs)
File "<string>", line 2, in _really_apply
File "/usr/local/lib/python2.7/dist-packages/IPython/parallel/client/view.py", line 51, in save_ids
ret = f(self, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/IPython/parallel/client/view.py", line 567, in _really_apply
ident=ident)
File "/usr/local/lib/python2.7/dist-packages/IPython/parallel/client/client.py", line 1263, in send_apply_request
item_threshold=self.session.item_threshold,
File "/usr/local/lib/python2.7/dist-packages/IPython/kernel/zmq/serialize.py", line 145, in pack_apply_message
arg_bufs = flatten(serialize_object(arg, buffer_threshold, item_threshold) for arg in args)
File "/usr/local/lib/python2.7/dist-packages/IPython/utils/data.py", line 30, in flatten
return [x for subseq in seq for x in subseq]
File "/usr/local/lib/python2.7/dist-packages/IPython/kernel/zmq/serialize.py", line 145, in <genexpr>
arg_bufs = flatten(serialize_object(arg, buffer_threshold, item_threshold) for arg in args)
File "/usr/local/lib/python2.7/dist-packages/IPython/kernel/zmq/serialize.py", line 89, in serialize_object
buffers.insert(0, pickle.dumps(cobj, PICKLE_PROTOCOL))
cPickle.PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed
Any help in understanding why this does not work, and a fix that requires minimal code change would be very helpful.
Thank you!
I figured out a solution:
class Foo(object):
def __init__(self):
from numpy import arange
self.data = arange(10)*10
#staticmethod
def A(data, y):
print "in A:", y ## doesn't produce an output
return data[y]
def parallelA(self, z, cl):
print "in parallelA:", cl[:].map_sync(self.A, [self.data]*len(z), z)
if __name__ == "__main__":
from IPython.parallel import Client
f = '/path/to/security/ipcontroller-client.json'
c = Client(f)
asdf = Foo()
asdf.parallelA([1, 3, 5], c)
Output when above code is run:
$ python test_parallel.py
in parallelA: [10, 30, 50]

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.

error in a python class with an not iterable object

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.

Categories

Resources