B-fields
Adding a 1d-field
You can use addnewdipo (from lattice.py) to add a constant b-field in a area from z_start to z_end. By using a for loop you can therefore add a 1d b-field profile as in the following example:
N = 40 # number of grid cells for magnetic field
mag_grid = fzeros([3,3,N],'d') # also save information for later plotting
z_start = 0.0
length = 1.0
delta = length/N
for i in range(N):
zstart = z_start+i*delta
zstop = z_start+(i+1)*delta
zmid = (zstop+zstart)/2.0
field = MagField(zmid) # MagField returns the field in Tesla
mag_grid[:,:,i] = field
addnewdipo(zstart,zstop,by=field)
...
# plot the b-field
ppgeneric(grid=transpose(mag_grid[:,2,:]),filled=1,contours=20,
ymin=w3d.xmmin,ymax=w3d.xmmax,xmin=z_start,xmax=z_stop)
Adding a 2d/3d-field
Similar to the above you can add a 2d grid as follows (the example shows a constant By field):
N=40
mag_grid = fzeros([N,3,N],'d')
for i in range(N):
zstart = z_start+i*z_delta
zstop = z_start+(i+1)*z_delta
zmid = (zstop+zstart)/2.0
for j in range(N):
xstart = x_start+j*x_delta
xstop = x_start+(j+1)*x_delta
xmid = (xstop+xstart)/2.0
field = calcBfield( zmid,xmid)
mag_grid[j,:,i] = field
print >> f, " "
addnewbgrd(z_start,z_stop,xs=x_start,dx=x_delta,ys=w3d.ymmin,dy=(w3d.ymmax-w3d.ymmin),nx=N,nz=N,ny=1,by=mag_grid)
Interpolating data from a measured field
If you have a data in a text file (say r[mm], B[T]) you can use this to generate a calcBfield function that case be used as in the 2d example:
#include to be able to read data from file and to interpolate
import numpy as np
#read b-field data
fielddata = np.genfromtxt("b-field.txt", delimiter=" ")
import scipy.interpolate as sp
# masage date from file into usable format
rfield = fielddata[:,0]
#scale from mm to m
rfield = rfield*mm
Bfield = fielddata[:,1]
calcBfield = sp.interpolate.interp1d(rfield, Bfield,fill_value=0.0,bounds_error=false)
...
field = calcBfield( sqrt( (zmid-zc)*(zmid-zc)+xmid*xmid)) # could be used like this in the 2d example