This question is related to the other one I posted days ago; I've read this question about the issue related to multiprocessing
pickling with instance methods. The problem is that I did not understand how to apply the solution provided to my case:
def _pickle_method(method):
# Author: Steven Bethard
# http://bytes.com/topic/python/answers/552476-why-cant-you-pickle-instancemethods
func_name = method.im_func.__name__
obj = method.im_self
cls = method.im_class
cls_name = ''
if func_name.startswith('__') and not func_name.endswith('__'):
cls_name = cls.__name__.lstrip('_')
if cls_name:
func_name = '_' + cls_name + func_name
return _unpickle_method, (func_name, obj, cls)
def _unpickle_method(func_name, obj, cls):
# Author: Steven Bethard
# http://bytes.com/topic/python/answers/552476-why-cant-you-pickle-instancemethods
for cls in cls.mro():
try:
func = cls.__dict__[func_name]
except KeyError:
pass
else:
break
return func.__get__(obj, cls)
copy_reg.pickle(types.MethodType, _pickle_method, _unpickle_method)
class Circle(Feature):
# Stuff...
def __points_distance(self,points):
xa = n.array([self.xc,self.yc]).reshape((1,2))
d = n.abs(dist.cdist(points,xa) - self.radius)
return d
def points_distance(self,points,pool=None):
if pool:
return pool.map(self.__points_distance,points)
else:
return self.__points_distance(points)
This gives ValueError: XA must be a 2-dimensional array
error when running this:
import tra.features as fts
import numpy as np
import multiprocessing as mp
points = np.random.random(size=(1000,2))
circle_points = np.random.random(size=(3,2))
feature = fts.Circle(circle_points)
pool = mp.Pool()
ds = feature.points_distance(points,pool=pool)
but it (obviously) work when doing:
pool = None
ds = feature.points_distance(points,pool=pool)
Any clues?
This is different from this (I checked this implementation) because the method is used inside another class that instantiate the Circle
class and calls its points_distance
method. In any case another difference is that points_distance
method uses scipy.spatial.distance.cdist
that expects (n,2)-shaped numpy.ndarray
. It works when using the serial version but raises the exception I mentioned when used in parallel. I suppose there's a caveat of arguments passing with cPickle.