1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#!/usr/bin/env python

import time
import sys
import os.path
import numpy
import mayavi.mlab
import Queue
import scipy.fftpack as fftpack
import multiprocessing

use_saved = False

def worker(myslice,q,A):
    if myslice[1] >= A.shape[1]:
        myslice[1] = A.shape[1]-1

    for a in range(myslice[0],myslice[1]):
        for b in range(A.shape[2]):
            for c in range(A.shape[3]):
                # ra is the position where the fields shall be
                # calculated.                   
                ra = numpy.array([x[a,b,c],y[a,b,c],z[a,b,c]])
                
                # Calculation of the vector potential and magnetic
                # field.
                a_sum = numpy.array((0,0,0),dtype='float')
                for d in range(m.shape[1]):
                    for e in range(m.shape[2]):
                        for f in range(m.shape[3]):
                            rm = numpy.array((x[d,e,f],y[d,e,f],z[d,e,f]))
                            M = m[:,d,e,f]
                            R = ra - rm
                            cube = betrag(R)**3
                            if cube.all() != 0:
                                a_sum += kreuzprodukt(M,R)/cube
                            else:
                                a_sum += numpy.zeros(3)
                A[:,a,b,c] = a_sum
                a_sum = numpy.zeros_like(a_sum)
    q.put((myslice,A))
    print "Finished!"
    return None

def partial(A,x=0):
    "Calculate partial derivative of a 3D pylab array along one axis."
    
    A_prime = numpy.zeros_like(A)
    l = list(A.shape)
    if len(l) > x: del l[x]
    
    for i in range(l[0]):
        for j in range(l[1]):
            if x==0:
                s = A[:,i,j].copy()
                A_prime[:,i,j] = fftpack.diff(s)
            elif x==1:
                s = A[i,:,j].copy()
                A_prime[i,:,j] = fftpack.diff(s)
            elif x==2:
                s = A[i,j,:].copy()
                A_prime[i,j,:] = fftpack.diff(s)
            else:
                raise ValueError, "No valid direction: %s" % x
                
    return A_prime
                
def betrag(a):
    return numpy.sqrt(abs(numpy.dot(a,a)))

def kreuzprodukt(a,b):
    tmp = numpy.array([
        a[1]*b[2] - a[2]*b[1],
        a[2]*b[0] - a[0]*b[2],
        a[0]*b[1] - a[1]*b[1]
    ])

    return tmp

data_file = "vector_field_A__switch_multiproc.npy"

# Queue for splitting the A compontents for passing to Threads
# Shape of queue elements: [begin,end]
try:
    max_threads = multiprocessing.cpu_count()
except Exception, e:
    print e
    max_threads = 2
print "No of Processes:", max_threads
# The coordinate grid
x,y,z = numpy.mgrid[-6:6:17j,-6:6:17j,-6:6:9j]

# The distribution of magnetic moments
m = numpy.array([
    numpy.zeros_like(x),
    numpy.zeros_like(y),
    numpy.select([x**2+y**2<9],[numpy.select([abs(z)<2,abs(z)>=2],[numpy.sign(x),0])])
])

if use_saved and os.path.isfile(data_file):
    A = numpy.load(data_file)
else:
    # The magnetic vector potential
    A = numpy.zeros_like(m)
    a = A.shape[1]/max_threads+1
    q = multiprocessing.Queue()
    for i in range(max_threads):
        myslice = [i*a,i*a+a]
        print myslice
        w = multiprocessing.Process(target=worker,args=(myslice,q,A))
        w.start()

    time.sleep(60)
    qItems = 0
    while multiprocessing.active_children():
        time.sleep(5)
        print q.qsize()
        try:
            myslice,A2 = q.get(True,timeout=10)
        except Exception,e:
            print "Caught exception:", e
            if qItems >=max_threads: break
        qItems += 1
        if myslice[1]> A.shape[1]: myslice[1] = A.shape[1]-1
        print myslice
        A[:,myslice[0]:myslice[1],:,:] = A2[:,myslice[0]:myslice[1],:,:].copy()
    numpy.save(data_file, A)
    
B = [
    partial(A[1],2) - partial(A[2],1),
    partial(A[2],0) - partial(A[0],2),
    partial(A[0],1) - partial(A[1],0)
]

mayavi.mlab.figure(size=(1280,800))
# Using plot functions
mayavi.mlab.quiver3d(x,y,z,m[0],m[1],m[2],name="Magnetic Moments")
mayavi.mlab.quiver3d(x,y,z,A[0],A[1],A[2],name="Vector Potential")
#mayavi.mlab.quiver3d(X,Y,Z,B[0],B[1],B[2],name="Magnetic Field")
# Creating the plot using the pipeline
src = mayavi.mlab.pipeline.vector_field(x,y,z,B[0],B[1],B[2],name="Magnetic Field")
mayavi.mlab.pipeline.vectors(src, mask_points=1, scale_factor=2.)
mayavi.mlab.pipeline.vector_cut_plane(src, mask_points=1, scale_factor=2.)

mayavi.mlab.outline()
mayavi.mlab.colorbar()
mayavi.mlab.show()
#mayavi.mlab.savefig("bla.png")