Strange TypeError: can't convert complex to float

Andreas Pritschet <[email protected]>
Newsgroups gmane.comp.python.pyro
Message-ID <[email protected]>
Hi there,
after getting used to Pyro with some simple examples I tried to re-write
my numerical calculation script to run on Pyro.

But for some very weird reason, Pyro throws this "TypeError: can't
convert complex to float" exception even when there is not even one
complex typed variable around.
The server is receiving the correct data even if it contains complex
numbers. The client apparently always crashes after successfully sending
the data.

Script and traceback are appended to this mail.

Here's my system configuration:
Ubuntu 12.04 (64bit)
Python 2.7.3
Pyro 3.14

As I'm quite new to Pyro I would appreciate any help.

Cheers
Andi
-- 
Andreas Pritschet
Phone:       +49 151 11728439
Homepage:    http://www.pritschet.me
GPG Pub Key: http://goo.gl/4mOsM

------------------------------------------------------------------------------
LogMeIn Central: Instant, anywhere, Remote PC access and management.
Stay in control, update software, and manage PCs from one command center
Diagnose problems and improve visibility into emerging IT issues
Automate, monitor and manage. Do more in less time with Central
http://p.sf.net/sfu/logmein12331_d2d

_______________________________________________
Pyro-core mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/pyro-core
numfft.py (text/x-python, 20.6 KB)
#!/usr/bin/env python

import sys
import os
import os.path
import datetime
import functools
import copy_reg
import types
import multiprocessing
import numpy
import numpy.ma
import scipy.integrate
import scipy.interpolate
import scipy.special
import pylab
import matplotlib.cm as cm
import Pyro.core
import Queue
import threading

Usage = "Usage: num_fft.py server|client [uri]"

cbar_ticks = pylab.arange(-1,1.1,.5)*pylab.pi
cbar_labels = ["$-\pi$","$-\pi/2$","$0$","$\pi/2$","$\pi$"]

# Microscope and geometry setting:
L = 2.5e-6
f = 1e3
gridsize = 64
R = 29
d1 = 33.2
d2 = -33.2

# Integration settings:
epsabs=1e-16
epsrel=1e-9
maxsubdivs=50

# Image settings:
dpis = 100
fsize = (7,7)

shiftterm = lambda d,q: numpy.exp(-2j*numpy.pi*d*q)

def reduce_method(m):
    return (getattr, (m.__self__, m.__func__.__name__))

copy_reg.pickle(types.MethodType, reduce_method)

def r(R,Theta,r0=0,theta0=0):
	"Radial component of translation vector in polar coordinates"
	return numpy.sqrt(R**2+r0**2+2*R*r0*numpy.cos(-theta0+Theta))

def theta(R,Theta,r0=0,theta0=0):
	"Azimuthal component of translation vector in polar coordinates"
	my_r = r(R,Theta,r0=0,theta0=0)

	return numpy.arccos((R*numpy.cos(Theta)+r0*numpy.cos(theta0))/my_r)
	
def displaystore(q,y,save=True):
	"""Function for storing plots.
	
	Expected arguments:
	q:	axis extent (ndarray)
	y:	Dictionary or sequence of dictionaries containing array data. Expected dictionary keywords:
		'type':		string, one of: ['radial', 'phase','diff']
		'data':		array containing data to plot
		'title': 	Figure title (optional)
		'xlabel':	X axis label (optional)
		'ylabel':	Y axis label (optional)
		'dpi':		Resolution (optional)
		'fsize':	Figure size in inch (optional)
		'command':	plotting command (optional, default: pylab.imshow)
	"""
	
	if not type(y) in [type({}),type(()),type([])] : raise TypeError, "Dictionary or sequence of dictionaries with plotable arrays expected! Got %s instead" % type(y)
	
	if type(y) == type({}): y = [y,]
	
	if save:
		i = 0
		pathname = datetime.datetime.now().strftime("%Y-%m-%d--%H-%M")
		if not os.path.exists(pathname):
			os.mkdir(pathname)
	
	for Y in y:
		pylab.figure(figsize=Y.get('fsize',fsize),dpi=Y.get("dpi",dpis))
		
		if Y.has_key("title"): pylab.title(Y["title"])
		if Y.has_key("xlabel"): pylab.xlabel(Y["xlabel"])
		if Y.has_key("ylabel"): pylab.xlabel(Y["ylabel"])
		
		if Y.has_key("command"):
			mycommand = Y["command"]
		else:
			mycommand = pylab.imshow
		
		if not Y.has_key("type"): raise ValueError, "Plotting type required!"
		if Y["type"]=="radial":
			mycommand(Y["data"],extent=[-q[0,0]*L*f,q[0,-1]*L*f,-q[0,0]*L*f,q[-1,0]*L*f],cmap=cm.spectral)
			pylab.colorbar(orientation="horizontal", fraction=.1,shrink=.7)
		elif Y["type"]=="phase":
			mycommand(Y["data"],extent=[-q[0,0]*L*f,q[0,-1]*L*f,-q[0,0]*L*f,q[-1,0]*L*f],cmap=cm.hsv)
			cbar = pylab.colorbar(orientation="horizontal", fraction=.1,shrink=.7,ticks=cbar_ticks)
			cbar.ax.set_xticklabels(cbar_labels)
		elif Y["type"]=="diff":
			mycommand(Y["data"],extent=[-q[0,0]*L*f,q[0,-1]*L*f,-q[0,0]*L*f,q[-1,0]*L*f],cmap=cm.coolwarm,vmin=-.5,vmax=.5)
			pylab.colorbar(orientation="horizontal", fraction=.1,shrink=.7)
		else:
			raise ValueError, "Expected one of['radial', 'phase','diff']. Got '%s'." % Y["type"]
			
		if save:
			i += 1
			pylab.savefig(os.path.join(pathname,"%03d.png" % i))
	if not save:
		pylab.show()

def display(q,y,y1,y2,save=False):
	"General display function. Displays 4 plots in a figure"

	pylab.subplot(221)
	pylab.title("Amplitude")
	pylab.imshow(abs(y),cmap=cm.spectral,extent=[-q[0,0]*L*f,q[0,-1]*L*f,-q[0,0]*L*f,q[-1,0]*L*f])
	pylab.colorbar(orientation="horizontal")

	pylab.subplot(222)
	pylab.title("Phase Front")
	pylab.imshow(numpy.angle(y),cmap=cm.hsv,extent=[-q[0,0]*L*f,q[0,-1]*L*f,-q[0,0]*L*f,q[-1,0]*L*f])
	cbar = pylab.colorbar(orientation="horizontal",ticks=cbar_ticks)
	cbar.ax.set_xticklabels(cbar_labels)

	pylab.subplot(223)
	pylab.title("Intensity")
	pylab.imshow(abs(y)**2,cmap=cm.spectral,extent=[-q[0,0]*L*f,q[0,-1]*L*f,-q[0,0]*L*f,q[-1,0]*L*f])
	pylab.colorbar(orientation="horizontal")

	pylab.subplot(224)
	pylab.title("Phase Difference")
	pylab.imshow((numpy.angle(y1)-numpy.angle(y2)+numpy.pi)%(2*numpy.pi)-numpy.pi,cmap=cm.hsv,extent=[-q[0,0]*L*f,q[0,-1]*L*f,-q[0,0]*L*f,q[-1,0]*L*f])
	cbar = pylab.colorbar(orientation="horizontal",ticks=cbar_ticks)
	cbar.ax.set_xticklabels(cbar_labels)

	if save:
		pylab.savefig("%s.png" % datetime.datetime.now().strftime("%Y-%m-%d--%H-%M"))
	else:
		pylab.show()

class Cbase(object):
	save = False
	omega = 1/64.
	
	def alpha(self,U):
		return 1.338232337703*U
		
	def beta(self,U):
		return 0.04680839054607*pylab.arccosh(U+1)
		
	def alphas(self,U):
		return 1.0534913127886e2*U
		
	def betas(self,U):
		return  -2.1060737402437e-2*U
		
	def phase(self,r,U,t=0):
		return pylab.cosh(self.beta(U)*r)-1+self.alpha(U)+2*numpy.pi*self.omega*t
	
	def streuphase(self,R,U,t=0):
		return 2*numpy.pi*self.omega*t + self.betas(U)+self.alphas(U)/R**2
		
	def crossover(self,t=0):
		q = numpy.linspace(0,.2,gridsize)
		y,z = self.G(R,0,q,t), self.G(R,1.15,q,t)
		ry = scipy.interpolate.interp1d(q,y,kind="cubic",bounds_error=False)
		rz = scipy.interpolate.interp1d(q,z,kind="cubic",bounds_error=False)
		q = numpy.linspace(-q[-1],q[-1],2*gridsize)
		X,Y = numpy.meshgrid(q,q)
		Q = numpy.sqrt(X**2+Y**2)
	
		y1 = ry(Q)*shiftterm(-33.2,X)
		y2 = rz(Q)*shiftterm(33.2,X)
		y = numpy.ma.masked_array(y1+y2,numpy.select([Q<q.max(),],[0],default=1))
		tmp = scipy.integrate.trapz(abs(y)**2,dx=q[1]-q[0])
		tmp = scipy.integrate.trapz(tmp,dx=q[1]-q[0])
		y /= tmp

		displaystore(Q,[
			{
				'data': abs(y),
				'title': 'Amplitude',
				'type': 'radial',
			},
			{
				'data': numpy.angle(y),
				'title': 'Phase Front',
				'type': 'phase',
			},
			{
				'data': abs(y)**2,
				'title': 'Intensity',
				'type': 'radial',
			},
			{
				'data': (numpy.angle(y1)-numpy.angle(y2)+numpy.pi)%(2*numpy.pi)-numpy.pi,
				'title': 'Phase Difference',
				'type': 'phase',
			},
		],self.save)

	def fft_cmp(self):
		q = numpy.linspace(0,.1,gridsize)
		Q = numpy.linspace(-q[-1],q[-1],2*gridsize)
		X,Y = numpy.meshgrid(Q,Q)
		Q = numpy.sqrt(X**2+Y**2)
		U = numpy.linspace(0,2.3,8)
		data = []
		for u in U:
			y,z = self.G(R,u,q), self.F(R,self.phase(0,u),q)
			ry = scipy.interpolate.interp1d(q,y,kind="cubic",bounds_error=False)
			rz = scipy.interpolate.interp1d(q,z,kind="cubic",bounds_error=False)
	
			y = numpy.ma.masked_array(ry(Q),numpy.select([Q<q.max(),],[0],default=1))
			z = numpy.ma.masked_array(rz(Q),numpy.select([Q<q.max(),],[0],default=1))
			tmp = scipy.integrate.trapz(abs(y)**2,dx=q[1]-q[0])
			tmp = scipy.integrate.trapz(tmp,dx=q[1]-q[0])
			y /= tmp
			tmp = scipy.integrate.trapz(abs(z)**2,dx=q[1]-q[0])
			tmp = scipy.integrate.trapz(tmp,dx=q[1]-q[0])
			z /= tmp
		
			data.append({
				'data': abs(y)**2,
				'type': 'radial',
				'title': "Intensity - Hyp. cosine phase shift for U=%0.2fV" % u
			})
			data.append({
				'data': abs(z)**2,
				'type': 'radial',
				'title': "Intensity - Constant phase shift (%0.2f $\pi$) for U=%0.2fV" % (self.phase(0,u)/numpy.pi,u)
			})
			data.append({
				'data': (abs(y)**2-abs(z)**2)/abs(y)**2,
				'type': 'diff',
				'title': 'Relative difference in intensity for U=%0.2fV' % u
			})
		
		displaystore(Q,data,self.save)
	
	def crossover_cmp(self):
		q = numpy.linspace(0,.1,gridsize)
		Q = numpy.linspace(-q[-1],q[-1],2*gridsize)
		X,Y = numpy.meshgrid(Q,Q)
		Q = numpy.sqrt(X**2+Y**2)
		U = numpy.linspace(0,2.3,8)
		data = []
		wave0 = self.F(R,0,q)
		wave0 = scipy.interpolate.interp1d(q,wave0,kind="cubic",bounds_error=False)
		for u in U:
			y = self.G(R,u,q)
			z = self.F(R,self.phase(0,u),q)
			ry = scipy.interpolate.interp1d(q,y,kind="cubic",bounds_error=False)
			rz = scipy.interpolate.interp1d(q,z,kind="cubic",bounds_error=False)
	
			y = numpy.ma.masked_array(wave0(Q)*shiftterm(-33.2,X)+ry(Q)*shiftterm(33.2,X),numpy.select([Q<q.max(),],[0],default=1))
			z = numpy.ma.masked_array(wave0(Q)*shiftterm(-33.2,X)+rz(Q)*shiftterm(33.2,X),numpy.select([Q<q.max(),],[0],default=1))
			tmp = scipy.integrate.trapz(abs(y)**2,dx=q[1]-q[0])
			tmp = scipy.integrate.trapz(tmp,dx=q[1]-q[0])
			y /= tmp
			tmp = scipy.integrate.trapz(abs(z)**2,dx=q[1]-q[0])
			tmp = scipy.integrate.trapz(tmp,dx=q[1]-q[0])
			z /= tmp
		
			data.append({
				'data': abs(y)**2,
				'type': 'radial',
				'title': "Intensity - Hyp. cosine phase shift for U=%0.2fV" % u
			})
			data.append({
				'data': abs(y),
				'type': 'radial',
				'title': "Amplitude - Hyp. cosine phase shift for U=%0.2fV" % u
			})
			data.append({
				'data': numpy.angle(y),
				'type': 'phase',
				'title': "Phase Front - Hyp. cosine phase shift for U=%0.2fV" % u
			})
			data.append({
				'data': ((numpy.angle(wave0(Q)*shiftterm(-33.2,X))-numpy.angle(ry(Q)*shiftterm(33.2,X))+numpy.pi)%(2*numpy.pi))-numpy.pi,
				'type': 'phase',
				'title': "Phase Difference - Hyp. cosine phase shift for U=%0.2fV" % u
			})
			data.append({
				'data': abs(z)**2,
				'type': 'radial',
				'title': "Intensity - Constant phase shift (%0.2f $\pi$) for U=%0.2fV" % (self.phase(0,u)/numpy.pi,u)
			})
			data.append({
				'data': abs(z),
				'type': 'radial',
				'title': "Amplitude - Constant phase shift for U=%0.2fV" % u
			})
			data.append({
				'data': numpy.angle(z),
				'type': 'phase',
				'title': "Phase Front - Constant phase shift for U=%0.2fV" % u
			})
			data.append({
				'data': ((numpy.angle(wave0(Q)*shiftterm(-33.2,X))-numpy.angle(rz(Q)*shiftterm(33.2,X))+numpy.pi)%(2*numpy.pi))-numpy.pi,
				'type': 'phase',
				'title': "Phase Difference - Constant phase shift for U=%0.2fV" % u
			})
			data.append({
				'data': (abs(y)**2-abs(z)**2)/abs(y)**2,
				'type': 'diff',
				'title': 'Relative difference in intensity for U=%0.2fV' % u
			})
		
		displaystore(Q,data,self.save)
		
class C1D(Cbase):
# Fourier Transform
#   - \infty            -2i pi ( x kx + y ky)
#  |          f(x,y) * e                      dx dy
# -   -\infty
# becomes in radial coords:
#   - 2 pi   - \infty                -2i pi r q cos(theta-phi)
#  |        |          f(r,theta) * e                          r dr d*theta
# -  0     -  0
# for radial symmetric f(r,theta)=f(r) simplifies to
#        - \infty          
# 2 pi  |         r f(r) * J (2 pi R q) dr
#      -  0                 0

#                                   i ( alpha - 1 + cosh(beta r) )
#         { 1, r <= R           { e
# f(r) = {            , g(r) = {
#         { 0, r > R            { 0, r > R

	def F(self,R,phase,q):
		"Constant phase shift in aperture"
		fkt = numpy.zeros_like(q,dtype="complex")
		for i in range(len(q)):
			fkt[i] = numpy.exp(1j*phase)*scipy.integrate.quad(lambda r: r*scipy.special.jv(0,2*numpy.pi*q[i]*r),0,R,epsabs=epsabs,epsrel=epsrel)[0]

		return 2*numpy.pi*fkt

	def G(self,R,U,q,t=0):
		"Hyperbolic cosine shaped phase shift in aperture"

		fkt = numpy.zeros_like(q,dtype="complex")
	
		for i in range(len(q)):
			fkt[i] = scipy.integrate.quad(lambda r: r*numpy.cos(self.phase(r,U,t))*scipy.special.jv(0,2*numpy.pi*q[i]*r),0,R,epsabs=epsabs,epsrel=epsrel)[0] +\
			1j*scipy.integrate.quad(lambda r: r*numpy.sin(self.phase(r,U,t))*scipy.special.jv(0,2*numpy.pi*q[i]*r),0,R,epsabs=epsabs,epsrel=epsrel)[0]

		return 2*numpy.pi*fkt

class C1Dvideo(C1D):
	no = 0
	
	def crossover(self,t=0):
		q = numpy.linspace(0,.2,gridsize)
		y,z = self.G(R,0,q,t), self.G(R,1.15,q,t)
		ry = scipy.interpolate.interp1d(q,y,kind="cubic",bounds_error=False)
		rz = scipy.interpolate.interp1d(q,z,kind="cubic",bounds_error=False)
		q = numpy.linspace(-q[-1],q[-1],2*gridsize)
		X,Y = numpy.meshgrid(q,q)
		Q = numpy.sqrt(X**2+Y**2)
	
		y1 = ry(Q)*shiftterm(-33.2,X)
		y2 = rz(Q)*shiftterm(33.2,X)
		y = numpy.ma.masked_array(y1+y2,numpy.select([Q<q.max(),],[0],default=1))
		tmp = scipy.integrate.trapz(abs(y)**2,dx=q[1]-q[0])
		tmp = scipy.integrate.trapz(tmp,dx=q[1]-q[0])
		y /= tmp
		
		pylab.clf()
		Y = abs(y)**2
		Y /= Y.max()
		Z = numpy.zeros((2*gridsize,2*gridsize,4),dtype="float")
		Z[:,:,3] = 1.-Y
		pylab.imshow((numpy.angle(y1)-numpy.angle(y2)+numpy.pi)%(2*numpy.pi)-numpy.pi,cmap=cm.hsv)
		cbar = pylab.colorbar(orientation="horizontal", fraction=.1,shrink=.7,ticks=cbar_ticks)
		cbar.ax.set_xticklabels(cbar_labels)
		pylab.imshow(Z)
		pylab.savefig("/tmp/img_%03d.png" % self.no )
		self.no += 1
		
	def crossover_cmp(self):
		q = numpy.linspace(0,.1,gridsize)
		Q = numpy.linspace(-q[-1],q[-1],2*gridsize)
		X,Y = numpy.meshgrid(Q,Q)
		Q = numpy.sqrt(X**2+Y**2)
		U = numpy.linspace(0,2.3,16)
		data = []
		wave0 = self.F(R,0,q)
		wave0 = scipy.interpolate.interp1d(q,wave0,kind="cubic",bounds_error=False)
		for u in U:
			#y = self.G(R,u,q)
			y = self.F(R,self.phase(0,u),q)
			ry = scipy.interpolate.interp1d(q,y,kind="cubic",bounds_error=False)
	
			y1 = numpy.ma.masked_array(wave0(Q)*shiftterm(-33.2,X),numpy.select([Q<q.max(),],[0],default=1))
			y2 = numpy.ma.masked_array(ry(Q)*shiftterm(33.2,X),numpy.select([Q<q.max(),],[0],default=1))
			y = y1+y2

			tmp = scipy.integrate.trapz(abs(y)**2,dx=q[1]-q[0])
			tmp = scipy.integrate.trapz(tmp,dx=q[1]-q[0])
			y /= numpy.sqrt(tmp)
		
			pylab.clf()
			Y = abs(y)**2
			if not self.no:
				Z = numpy.zeros((2*gridsize,2*gridsize,4),dtype="float")
			Z[:,:,3] = 1.-Y/Y.max()
			#pylab.imshow((numpy.angle(y1)-numpy.angle(y2)+numpy.pi)%(2*numpy.pi)-numpy.pi,cmap=cm.hsv,vmin=-numpy.pi,vmax=numpy.pi)
			pylab.imshow(numpy.angle(y),cmap=cm.hsv,vmin=-numpy.pi,vmax=numpy.pi)
			cbar = pylab.colorbar(orientation="horizontal", fraction=.1,shrink=.7,ticks=cbar_ticks)
			cbar.ax.set_xticklabels(cbar_labels)
			pylab.imshow(Z)
			pylab.savefig("/tmp/img_%03d.png" % self.no )
			self.no += 1
			
class C2D(Cbase):
	
	def F(self,R,phase,q):
		"Constant phase shift in aperture"
		fkt = numpy.zeros((len(q),len(q)),dtype="complex")

		for x in range(len(q)):
			for y in range(len(q)):
				Q = numpy.sqrt(q[x]**2+q[y]**2)
				Phi = numpy.angle(q[x]+1j*q[y])
				fkt[x,y] = scipy.integrate.dblquad(lambda theta,r: r*numpy.cos(phase+2*numpy.pi*Q*r*numpy.cos(theta-Phi)),0,R,lambda x: 0, lambda y: 2*numpy.pi,epsabs=epsabs,epsrel=epsrel)[0]+ \
				1j*scipy.integrate.dblquad(lambda theta,r: r*numpy.sin(phase+2*numpy.pi*Q*r*numpy.cos(theta-Phi)),0,R,lambda x: 0, lambda y: 2*numpy.pi,epsabs=epsabs,epsrel=epsrel)[0]

		return fkt

	def G(self,R,U,q):
		"Hyperbolic cosine shaped phase shift in aperture"
		fkt = numpy.zeros_like(q,dtype="complex")
	
		for i in range(len(q)):
			fkt[i] = scipy.integrate.dblquad(lambda theta,r: r*numpy.cos(self.phase(r,U))*scipy.special.jv(0,2*numpy.pi*q[i]*r),0,R,lambda x: 0, lambda y: 2*numpy.pi,epsabs=epsabs,epsrel=epsrel)[0]

		return 2*numpy.pi*fkt

	def H(self,R,d,U,q,xval=None):
		"Acentral stray potential caused by nearby ring electrode"
		
		# R: float, radius of aperture
		# d: complex, displacement vector
		# U: float, applied potential
		# q: float, Fourier space coordinate
		
		if xval: xval = (xval,)
		else: xval = range(len(q))
		
		for x in xval:
			for y in range(len(q)):
				Q = numpy.sqrt(q[x]**2+q[y]**2)
				Phi = numpy.angle(q[x]+1j*q[y])
				
				self.fkt[x,y] = scipy.integrate.dblquad(
						lambda theta,rho: rho*numpy.cos(self.streuphase(r(Q,Phi,r0=abs(d)+10.6,theta0=numpy.angle(-d)),U)*2*numpy.pi*Q*rho*numpy.cos(theta-Phi)),
						0,R,
						lambda x: 0, lambda y: 2*numpy.pi,
						epsabs=epsabs,epsrel=epsrel
					)[0]+ \
					1j*scipy.integrate.dblquad(
						lambda theta,rho: rho*numpy.sin(self.streuphase(r(Q,Phi,r0=abs(d)+10.6,theta0=numpy.angle(-d)),U)*2*numpy.pi*Q*rho*numpy.cos(theta-Phi)),
						0,R,
						lambda x: 0, lambda y: 2*numpy.pi,
						epsabs=epsabs,epsrel=epsrel
					)[0]
				
		return True

	def show_object(self,R,U,d1,d2):
		x,y = numpy.mgrid[-1.1*(R-d1):1.1*(R+d2):256j,-1.1*R:1.1*R:128j]
		
		# Reference polar coordinate system
		myr = numpy.sqrt((x)**2+y**2)
		mytheta = numpy.angle(x+1j*y)
		
		# Translated coordinate system for aperture 1
		myR = r(myr,mytheta,r0=abs(d1),theta0=numpy.angle(d1))
		myTheta = theta(myr,mytheta,r0=abs(d1),theta0=numpy.angle(d1))
		
		# Translated coordinate system for stray potential in aperture 1
		myR2 = r(myr,mytheta,r0=10.6,theta0=0)
		myTheta2 = theta(myr,mytheta,r0=10.6,theta0=0)
		y1 = numpy.select([myR<=R],[self.streuphase(myR2,U,0),],default=0)
		#y1 = self.streuphase(myR,U,0)
		
		#  Translated coordinate system for aperture 2
		myR = r(myr,mytheta,r0=abs(d2),theta0=numpy.angle(d2))
		myTheta = theta(myr,mytheta,r0=abs(d2),theta0=numpy.angle(d2))
		y2 = numpy.select([myR<=R],[self.phase(myR,U,0),],default=0)
		
		pylab.imshow(numpy.rot90(y1+y2),cmap=cm.spectral,extent=[x.min(),x.max(),y.min(),y.max()])
		pylab.colorbar()
		
		pylab.show()
		
	def do_calc(self,U=0):
		c1d = C1D()
		q = numpy.linspace(0,3,gridsize)
		q = numpy.linspace(-q[-1],q[-1],2*gridsize)
		
		self.fkt = numpy.zeros((len(q),len(q)),dtype="complex")
		pool = multiprocessing.Pool(processes=multiprocessing.cpu_count()-1)
		Calc = functools.partial(self.H,R,-33.2,U,q)
		pool.map(Calc,range(len(q)),1)
		pool.close()
		pool.join()
		
		#y1 = self.H(R,-33.2,U,q)
		y2 = c1d.G(R,U,q)
		X,Y = numpy.meshgrid(q,q)
		Q = numpy.sqrt(X**2+Y**2)
		ry2 = scipy.interpolate.interp1d(q,y2,kind="cubic",bounds_error=False)
		y2 = ry2(Q)*shiftterm(33.2,X)
		y1 = self.fkt*shiftterm(-33.2,X)
		y = numpy.ma.masked_array(y1+y2,numpy.select([Q<q.max(),],[0],default=1))
		tmp = scipy.integrate.trapz(abs(y)**2,dx=q[1]-q[0])
		tmp = scipy.integrate.trapz(tmp,dx=q[1]-q[0])
		y /= tmp

		display(Q,y,y1,y2,self.save)

class C2dServer(Pyro.core.ObjBase):
	queue = Queue.Queue()
	
	def __init__(self):
		Pyro.core.ObjBase.__init__(self)
	
	def queue_get(self):
		return self.queue.get()
		
	def queue_done(self):
		self.queue.task_done()
		return True
		
	def conf(self,R,d1,d2,U,q):
		"Preparations for remote computations"
		
		self.R = R
		self.d1 = d1
		self.d2 = d2
		self.U = U
		self.qsym = q
		self.q = numpy.linspace(-q[-1],q[-1],gridsize)
		self.fkt = numpy.zeros((len(q),len(q)))
		
	def get_conf(self):
		return (self.R,self.d1,self.U,self.q)
		
	def H(self):
		"Preparations for remote computations"
		
		fields = numpy.array([[(i,j) for i in self.q] for j in self.q]).reshape(len(self.q)**2,2)
		for xy in fields:
			self.queue.put(xy)
			
	def result(self,x,y,valR,valI):
		print "Received", x,y,valR,valI
		self.fkt[x,y] = valR+1j*valI
		
	def do_calc(self):
		c1d = C1D()
				
		
		y2 = c1d.G(self.R,self.U,self.qsym)
		X,Y = numpy.meshgrid(self.q,self.q)
		Q = numpy.sqrt(X**2+Y**2)
		ry2 = scipy.interpolate.interp1d(self.q,y2,kind="cubic",bounds_error=False)
		
		numpy.save("y1",self.fkt)
		numpy.save("y2",ry2(Q))
		
		y2 = ry2(Q)*shiftterm(self.d2,X)
		y1 = self.fkt*shiftterm(self.d1,X)
		y = numpy.ma.masked_array(y1+y2,numpy.select([Q<self.q.max(),],[0],default=1))
		tmp = scipy.integrate.trapz(abs(y)**2,dx=self.q[1]-self.q[0])
		tmp = scipy.integrate.trapz(tmp,dx=self.q[1]-self.q[0])
		y /= tmp

		numpy.save("y",y)

		display(Q,y,y1,y2,self.save)

class QueueThread(threading.Thread):
	def __init__(self):
		threading.Thread.__init__(self)
		self.c2d = C2dServer()
		
	def run(self):
		Pyro.core.initServer()
		self.pdaemon=Pyro.core.Daemon()

		self.uri=self.pdaemon.connect(self.c2d,"fourier")

		print "The daemon runs on port:",self.pdaemon.port
		print "The object's uri is:",self.uri

		try:
			self.pdaemon.requestLoop()
		except KeyboardInterrupt:
			print "Bye Bye"

class C2dClient(Cbase):
	
	def __init__(self,uri):
		self.uri = uri
		self.remoteObj = Pyro.core.getProxyForURI(self.uri)
		self.R,self.d,self.U,self.q = self.remoteObj.get_conf()
		while True:
			try:
				xy = self.remoteObj.queue_get()
			except Queue.Empty:
				break
			tmp = self.h(xy[0],xy[1])
			print type(tmp[0]),type(tmp[1])
			print tmp
			self.remoteObj.result(xy[0],xy[1],tmp[0],tmp[1])
			self.remoteObj.queue_done()
	
	def h(self,x,y):
		"Method for remote computation of one element in fkt"
		
		Q = numpy.sqrt(self.q[x]**2+self.q[y]**2)
		Phi = numpy.angle(self.q[x]+1j*self.q[y])
				
		return (
			scipy.integrate.dblquad(
						lambda theta,rho: rho*numpy.cos(self.streuphase(r(Q,Phi,r0=abs(self.d)+10.6,theta0=numpy.angle(-self.d)),self.U)*2*numpy.pi*Q*rho*numpy.cos(theta-Phi)),
						0,R,
						lambda x: 0, lambda y: 2*numpy.pi,
						epsabs=epsabs,epsrel=epsrel
					)[0],
			scipy.integrate.dblquad(
						lambda theta,rho: rho*numpy.sin(self.streuphase(r(Q,Phi,r0=abs(self.d)+10.6,theta0=numpy.angle(-self.d)),self.U)*2*numpy.pi*Q*rho*numpy.cos(theta-Phi)),
						0,R,
						lambda x: 0, lambda y: 2*numpy.pi,
						epsabs=epsabs,epsrel=epsrel
					)[0]
		)
					
if __name__ == '__main__':
	if not len(sys.argv) in (2,3):
		print Usage
		sys.exit(1)
		
	if sys.argv[1] == "server":
		server = QueueThread()
		server.c2d.conf(R,-33.2,33.2,1.15,numpy.linspace(0,3,gridsize/2))
		server.start()
		server.c2d.H()
		server.c2d.queue.join()
		server.c2d.do_calc()
	elif sys.argv[1] == "client":
		client = C2dClient(sys.argv[2])
	else:
		print Usage
		sys.exit(1)
	
# Old code		
#m = C2D()
#m.show_object(R,1.15,-33.2,33.2)
#m.do_calc(1.15)
traceback.txt (text/plain, 901 B)
Traceback (most recent call last):
  File "./numfft.py", line 664, in <module>
    client = C2dClient(sys.argv[2])
  File "./numfft.py", line 627, in __init__
    self.remoteObj.result(xy[0],xy[1],tmp[0],tmp[1])
  File "/usr/lib/pymodules/python2.7/Pyro/core.py", line 381, in __call__
    return self.__send(self.__name, args, kwargs)
  File "/usr/lib/pymodules/python2.7/Pyro/core.py", line 456, in _invokePYRO
    return self.adapter.remoteInvocation(name, Pyro.constants.RIF_VarargsAndKeywords, vargs, kargs)
  File "/usr/lib/pymodules/python2.7/Pyro/protocol.py", line 457, in remoteInvocation
    return self._remoteInvocation(method, flags, *args)
  File "/usr/lib/pymodules/python2.7/Pyro/protocol.py", line 532, in _remoteInvocation
    answer.raiseEx()
  File "/usr/lib/pymodules/python2.7/Pyro/errors.py", line 72, in raiseEx
    raise self.excObj
TypeError: can't convert complex to float
signature.asc (application/pgp-signature, 551 B)
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.11 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://www.enigmail.net/

iQEcBAEBAgAGBQJQlnnVAAoJEMMdfJo8Sd0MucgIAKtAz8g2+hGkT41uIBnc5VFN
0FfXSg9BQI15xWkDOG63bbdFU9AwLNhWLoqx6NlRtisABJTuw7nA8/7/wtC02DCR
hMA7PMb83VhCtaXsARMcbH0xTXuDECrDhRU7doKqBosk125WNZ3T6mRecRrFw1c6
RLXvu38SbAOb7FzwmQWghZ06xhj04PZEaOxAB8/vAePoNSQZNph1+BsKR1iEvzLq
9J1nzgXhtuEgX43lisKucms1vcjy9sFVuWPKjU3mGkmuIQ2jdvc5wHo1sYSp8DIc
Px28s2K4y5FzLbBa2LrV3owbA5v/xgWyc664Q6r2UU+O1YsvIfgot/KO/XZyXKU=
=4hCQ
-----END PGP SIGNATURE-----
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.