repo
stringlengths 2
99
| file
stringlengths 13
225
| code
stringlengths 0
18.3M
| file_length
int64 0
18.3M
| avg_line_length
float64 0
1.36M
| max_line_length
int64 0
4.26M
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
finmag
|
finmag-master/dev/sandbox/skyrmions/skyrmion2dmesh.py
|
""" Attempt to visualise some dynimacs using python's visual module.
Visualisation probably okay, but some convergence problem in the time
integration means this does not look smooth at all, and is very slow.
"""
import dolfin
import dolfin as df
import numpy
from scipy.integrate import odeint
from finmag.sim.llg import LLG
"""
Compute the behaviour of a one-dimensional strip of magnetic material,
with exchange interaction.
"""
nm=1e-9
xdim = 30
ydim = 30
mesh = dolfin.Rectangle(0,0,xdim*nm,ydim*nm, xdim/3, ydim/3)
plotmesh = dolfin.Box(0,0,0,xdim*nm,ydim*nm, nm, xdim/3, ydim/3,1)
plotV = dolfin.VectorFunctionSpace(plotmesh,"CG",1)
plotM = dolfin.Function(plotV)
llg = LLG(mesh)
llg.alpha=1.0
llg.H_app=(0,0,0)
llg.A =1.3e-11
llg.D = 4e-3
#llg.set_m((
# 'MS * (2*x[0]/L - 1)',
# 'sqrt(MS*MS - MS*MS*(2*x[0]/L - 1)*(2*x[0]/L - 1))',
# '0'), L=length, MS=llg.Ms)
llg.set_m((
'MS',
'0',
'0'), MS=llg.Ms)
llg.setup(use_dmi=True,use_exchange=True)
llg.pins = []
print "point 0:",mesh.coordinates()[0]
print "Solving problem..."
ts = numpy.linspace(0, 1e-9, 50)
tol = 1e-4
for i in range(len(ts)-1):
print "step=%4d, time=%12.6g " % (i,ts[i]),
#ys,infodict = odeint(llg.solve_for, llg.m, [ts[i],ts[i+1]], full_output=True,printmessg=True,rtol=tol,atol=tol)
ys,infodict = odeint(llg.solve_for, llg.m, [ts[i],ts[i+1]], full_output=True,printmessg=False)
print "NFE=%4d, NJE=%4d" % (infodict['nfe'],infodict['nje'])
#how to plot? -- viper refuses to plot 3d data on a 2d mesh.
#thus: create a face 3d mesh that carries the data
Nplot = len(plotmesh.coordinates())
for i in range(Nplot):
point = plotmesh.coordinates()[i]
#print i,point
x,y = point[0:2]
plotM.vector()[i] = llg._m( (x,y) )[0]
plotM.vector()[i+Nplot] = llg._m( (x,y) )[1]
plotM.vector()[i+2*Nplot] = llg._m( (x,y) )[2]
df.plot(plotM)
df.interactive()
print "Done"
| 1,979 | 25.756757 | 116 |
py
|
finmag
|
finmag-master/dev/sandbox/skyrmions/spin_waves.py
|
import dolfin as df
import numpy as np
import pylab as plt
from finmag.energies import Exchange, DMI, Zeeman
from finmag import Simulation as Sim
tstart = 0
tstatic = 1e-9
tpulse = 0.02e-9
tend = 4e-9
toffset = 1e-20
xdim = 7e-9
ydim = 7e-9
zdim = 1e-9
xv = 5
yv = 5
Ms = 1.567e5 #A/m
H_pulse = [0.7*Ms, 0.7*Ms, 0.7*Ms]
sw_alpha = 1e-20
mesh = df.BoxMesh(0, 0, 0, xdim, ydim, zdim, xv, yv, 1)
sim = Sim(mesh, Ms)
sim.set_m((1,0,0))
A = 3.57e-13 #J/m
D = 2.78e-3 #J/m**2
H = [0,0,0]
sim.add(Exchange(A))
sim.add(DMI(D))
sim.add(Zeeman(H))
tsim = np.linspace(tstart, tstatic, 51)
#Simulate to ground state
sim.alpha = 1
for t in tsim:
sim.run_until(t)
m = sim.llg._m
df.plot(m)
#Excite the system
tsim = np.linspace(tstatic+toffset,tstatic+tpulse,51)
sim.add(Zeeman(H_pulse))
for t in tsim:
sim.run_until(t)
m = sim.llg._m
df.plot(m)
#Record spin waves
tsim = np.linspace(tstatic+tpulse+toffset,tend,51)
sim.alpha = sw_alpha
sim.add(Zeeman([0,0,0]))
xs = np.linspace(0,xdim-1e-22,xv+1)
ys = np.linspace(0,ydim-1e-22,yv+1)
z = 0
mx = np.zeros([xv+1,yv+1,len(tsim-1)])
my = np.zeros([xv+1,yv+1,len(tsim-1)])
mz = np.zeros([xv+1,yv+1,len(tsim-1)])
for i in xrange(len(tsim)):
sim.run_until(tsim[i])
m = sim.llg._m
df.plot(m)
for j in range(len(xs)):
for k in range(len(ys)):
mx[j,k,i] = m(xs[j], ys[k], 0)[0]
my[j,k,i] = m(xs[j], ys[k], 0)[1]
mz[j,k,i] = m(xs[j], ys[k], 0)[2]
tsim = tsim - (tstatic+tpulse+toffset)
#save the file into the output.npz
np.savez('output_sinc', tsim=tsim, mx=mx, my=my, mz=mz)
| 1,616 | 18.719512 | 55 |
py
|
finmag
|
finmag-master/dev/sandbox/skyrmions/retrieve_timeseries.py
|
from dolfin import *
mesh = Box(0,0,0,30e-9,30e-9,3e-9,10,10,1)
V = VectorFunctionSpace(mesh, "CG", 1)
m = Function(V)
series = TimeSeries("solution/m")
times = series.vector_times()
output = File("vtk-files/skyrmion.pvd")
for t in times:
vector = Vector()
series.retrieve(vector, t)
m.vector()[:] = vector
output << m
| 339 | 19 | 42 |
py
|
finmag
|
finmag-master/dev/sandbox/skyrmions/skyrmion_varying_D.py
|
import numpy as np
import dolfin as df
from finmag import Simulation
from finmag.energies import Exchange, DMI, Zeeman
def m_init_fun(pos):
return np.random.random(3)-0.5
def spatial_D(pos):
x = pos[0]
if x<50:
return 4e-3
else:
return -4e-3
def relax(mesh):
Ms = 8.6e5
sim = Simulation(mesh, Ms, pbc='2d',unit_length=1e-9)
sim.set_m(m_init_fun)
sim.add(Exchange(1.3e-11))
sim.add(DMI(D = spatial_D))
sim.add(Zeeman((0,0,0.45*Ms)))
sim.alpha = 0.5
ts = np.linspace(0, 1e-9, 101)
for t in ts:
sim.run_until(t)
p = df.plot(sim.llg._m)
sim.save_vtk()
df.plot(sim.llg._m).write_png("vortex")
df.interactive()
if __name__=='__main__':
mesh = df.RectangleMesh(0,0,100,100,40,40)
relax(mesh)
| 820 | 16.847826 | 57 |
py
|
finmag
|
finmag-master/dev/sandbox/skyrmions/spiral.py
|
""" Attempt to visualise some dynimacs using python's visual module.
Visualisation probably okay, but some convergence problem in the time
integration means this does not look smooth at all, and is very slow.
"""
import dolfin
import dolfin as df
import numpy
from scipy.integrate import odeint
from finmag.sim.llg import LLG
"""
Compute the behaviour of a one-dimensional strip of magnetic material,
with exchange interaction.
"""
nm=1e-9
simplexes = 20
mesh = dolfin.Box(0,0,0,60*nm,3*nm, 3*nm, simplexes, 1, 1)
llg = LLG(mesh)
llg.alpha=1.0
llg.H_app=(0,0,0)
llg.A = 1.3e-11
llg.D = 4e-3
#llg.set_m((
# 'MS * (2*x[0]/L - 1)',
# 'sqrt(MS*MS - MS*MS*(2*x[0]/L - 1)*(2*x[0]/L - 1))',
# '0'), L=length, MS=llg.Ms)
llg.set_m((
'MS',
'0',
'0'), MS=llg.Ms)
llg.setup(use_dmi=True,use_exchange=True)
llg.pins = []
print "point 0:",mesh.coordinates()[0]
print "Solving problem..."
ts = numpy.linspace(0, 3e-9, 150)
tol = 1e-4
for i in range(len(ts)-1):
print "step=%4d, time=%12.6g " % (i,ts[i]),
#ys,infodict = odeint(llg.solve_for, llg.m, [ts[i],ts[i+1]], full_output=True,printmessg=True,rtol=tol,atol=tol)
ys,infodict = odeint(llg.solve_for, llg.m, [ts[i],ts[i+1]], full_output=True,printmessg=False)
print "NFE=%4d, NJE=%4d" % (infodict['nfe'],infodict['nje'])
df.plot(llg._m)
df.interactive()
print "Done"
| 1,384 | 23.732143 | 116 |
py
|
finmag
|
finmag-master/dev/sandbox/skyrmions/fftanalysis.py
|
import numpy as np
import pylab as plt
import matplotlib.cm as cm
npzfile = np.load('output_sinc.npz')
mx = npzfile['mx']
my = npzfile['my']
mz = npzfile['mz']
tsim = npzfile['tsim']
mx -= np.average(mx)
my -= np.average(my)
mz -= np.average(mz)
spx = []
spy = []
spz = []
for i in range(mx.shape[0]):
for j in range(mx.shape[1]):
spx.append(np.fft.fft(mx[i,j,:]))
spy.append(np.fft.fft(my[i,j,:]))
spz.append(np.fft.fft(mz[i,j,:]))
sax = 0
say = 0
saz = 0
for i in xrange(mx.shape[0]*mx.shape[1]):
sax += spx[i]
say += spy[i]
saz += spz[i]
sax /= mx.shape[0]*mx.shape[1]
say /= mx.shape[0]*mx.shape[1]
saz /= mx.shape[0]*mx.shape[1]
ftx = sax
fty = say
ftz = saz
freq = np.fft.fftfreq(tsim.shape[-1], d=9e-12)
f = freq[0:len(freq)/2+1]
fftx = np.absolute(ftx[0:len(ftx)/2+1])
ffty = np.absolute(fty[0:len(fty)/2+1])
fftz = np.absolute(ftz[0:len(ftz)/2+1])
plt.figure(1)
p1 = plt.subplot(311)
p1.plot(f, fftx, label='mx')
plt.xlim([0,0.5e10])
plt.legend()
plt.xlabel('f')
plt.ylabel('|S|^2')
p2 = plt.subplot(312)
p2.plot(f, ffty, label='my')
plt.xlim([0,0.5e10])
plt.legend()
plt.xlabel('f')
plt.ylabel('|S|^2')
p3 = plt.subplot(313)
p3.plot(f, fftz, label='mz')
plt.xlim([0,0.5e10])
plt.legend()
plt.xlabel('f')
plt.ylabel('|S|^2')
plt.show()
def find_max(a):
index = []
for i in range(1,len(a)-1):
if a[i-1]<a[i]>a[i+1] and a[i]>100:
index.append(i)
return index
mode_indices = find_max(fftx)
print mode_indices
x_c = range(mx.shape[0])
y_c = range(mx.shape[1])
#for imode in mode_indices:
fig = 2
mode = np.zeros([mx.shape[0], mx.shape[1]])
for i in range(mx.shape[0]):
for j in range(mx.shape[1]):
ftrans = np.fft.fft(my[i,j,:])
mode[i,j] = np.absolute(ftrans[10])#**2
plt.figure(fig)
#X, Y = plt.meshgrid(x_c,y_c)
#plt.pcolor(X, Y, mode, cmap=plt.cm.RdBu)
plt.imshow(mode, cmap = cm.Greys_r)
plt.show()
fig += 1
| 1,937 | 18.575758 | 47 |
py
|
finmag
|
finmag-master/dev/sandbox/skyrmions/rundmi.py
|
""" Attempt to visualise some dynimacs using python's visual module.
Visualisation probably okay, but some convergence problem in the time
integration means this does not look smooth at all, and is very slow.
"""
import dolfin
import dolfin as df
import numpy
from scipy.integrate import odeint
from finmag.sim.llg import LLG
"""
Compute the behaviour of a one-dimensional strip of magnetic material,
with exchange interaction.
"""
length = 60e-9 # in meters
simplexes = 20
#mesh = dolfin.Interval(simplexes, 0, length)
#mesh = dolfin.Rectangle(0,0,length,length, simplexes, simplexes)
mesh = dolfin.Box(0,0,0,length,length, length/20, simplexes, simplexes, simplexes/20)
llg = LLG(mesh)
llg.alpha=0.1
llg.H_app=(0,0,0)
llg.A = 1.3e-11
llg.D = 4e-3
#llg.set_m((
# 'MS * (2*x[0]/L - 1)',
# 'sqrt(MS*MS - MS*MS*(2*x[0]/L - 1)*(2*x[0]/L - 1))',
# '0'), L=length, MS=llg.Ms)
llg.set_m((
'MS',
'0',
'0'), MS=llg.Ms)
llg.setup(use_dmi=True,use_exchange=True)
llg.pins = []
print "point 0:",mesh.coordinates()[0]
print "Solving problem..."
y = llg.m[:]
y.shape=(3,len(llg.m)/3)
ts = numpy.linspace(0, 7e-10, 1000)
tol = 1e-4
for i in range(len(ts)-1):
print i
ys,infodict = odeint(llg.solve_for, llg.m, [ts[i],ts[i+1]], full_output=True,printmessg=True,rtol=tol,atol=tol)
df.plot(llg._m)
df.interactive()
print "Done"
| 1,381 | 22.827586 | 115 |
py
|
finmag
|
finmag-master/dev/sandbox/skyrmions/skyrmion_current.py
|
import numpy as np
import dolfin as df
from finmag import Simulation
from finmag.energies import Exchange, DMI, Zeeman
def m_init_fun(pos):
return np.random.random(3)-0.5
def relax(mesh):
Ms = 8.6e5
sim = Simulation(mesh, Ms, pbc='2d',unit_length=1e-9)
sim.set_m(m_init_fun)
sim.alpha = 0.5
sim.add(Exchange(1.3e-11))
sim.add(DMI(D = 4e-3))
sim.add(Zeeman((0,0,0.45*Ms)))
ts = np.linspace(0, 1e-9, 101)
for t in ts:
sim.run_until(t)
p = df.plot(sim.llg._m)
df.plot(sim.llg._m).write_png("vortex")
df.interactive()
#sim.relax()
np.save('m0.npy',sim.m)
def init_J(pos):
return (1e7,0,0)
def move_skyrmion(mesh):
Ms = 8.6e5
sim = Simulation(mesh, Ms, pbc='2d',unit_length=1e-9)
sim.set_m(np.load('m0.npy'))
sim.add(Exchange(1.3e-11))
sim.add(DMI(D = 4e-3))
sim.add(Zeeman((0,0,0.45*Ms)))
sim.alpha=0.01
sim.set_zhangli(init_J, 1.0,0.01)
ts = np.linspace(0, 10e-9, 101)
for t in ts:
sim.run_until(t)
print t
#p = df.plot(sim.llg._m)
sim.save_vtk(filename='vtks/v1e7_.pvd')
df.plot(sim.llg._m).write_png("vortex")
#df.interactive()
if __name__=='__main__':
mesh = df.RectangleMesh(0,0,100,100,40,40)
#mesh = df.BoxMesh(0, 0, 0, 100, 100, 2, 40, 40, 1)
#relax(mesh)
move_skyrmion(mesh)
| 1,432 | 19.183099 | 57 |
py
|
finmag
|
finmag-master/dev/sandbox/skyrmions/skyrmion-vtk.py
|
""" Attempt to visualise some dynimacs using python's visual module.
Visualisation probably okay, but some convergence problem in the time
integration means this does not look smooth at all, and is very slow.
"""
import dolfin
import dolfin as df
import numpy
from scipy.integrate import odeint
from finmag.sim.llg import LLG
"""
Compute the behaviour of a one-dimensional strip of magnetic material,
with exchange interaction.
"""
nm=1e-9
xdim = 30
ydim = 30
zdim = 3
mesh = dolfin.Box(0,0,0,xdim*nm,ydim*nm, zdim*nm, xdim/3, ydim/3, zdim/3)
llg = LLG(mesh)
llg.alpha=1.0
llg.H_app=(0,0,0)
llg.A =1.3e-11
llg.D = 4e-3
#llg.set_m((
# 'MS * (2*x[0]/L - 1)',
# 'sqrt(MS*MS - MS*MS*(2*x[0]/L - 1)*(2*x[0]/L - 1))',
# '0'), L=length, MS=llg.Ms)
llg.set_m((
'MS',
'0',
'0'), MS=llg.Ms)
llg.setup(use_dmi=True,use_exchange=True)
llg.pins = []
print "point 0:",mesh.coordinates()[0]
print "Solving problem..."
ts = numpy.linspace(0, 1e-9, 50)
tol = 1e-4
file = df.File('s.pvd')
for i in range(len(ts)-1):
print "step=%4d, time=%12.6g " % (i,ts[i]),
#ys,infodict = odeint(llg.solve_for, llg.m, [ts[i],ts[i+1]], full_output=True,printmessg=True,rtol=tol,atol=tol)
ys,infodict = odeint(llg.solve_for, llg.m, [ts[i],ts[i+1]], full_output=True,printmessg=False)
print "NFE=%4d, NJE=%4d" % (infodict['nfe'],infodict['nje'])
file << llg._m
df.plot(llg._m)
df.interactive()
print "Done"
| 1,453 | 23.644068 | 116 |
py
|
finmag
|
finmag-master/dev/sandbox/skyrmions/skyrmion_timings.py
|
import dolfin as df
from finmag import Simulation
from finmag.energies import Exchange, DMI
output = open("timings.txt", "w")
mesh = df.Box(0, 0, 0, 30e-9, 30e-9, 3e-9, 10, 10, 1)
def run_sim(exc_jac, dmi_jac):
sim = Simulation(mesh, Ms=8.6e5)
sim.set_m((1, 0, 0))
exchange = Exchange(A=1.3e-11)
exchange.in_jacobian = exc_jac
sim.add(exchange)
dmi = DMI(D=4e-3)
dmi.in_jacobian = dmi_jac
sim.add(dmi)
#sim.run_until(1e-9)
sim.relax()
output.write(sim.timings(5))
output.write("Neither in Jacobian:\n")
run_sim(exc_jac=False, dmi_jac=False)
#output.write("\nOnly DMI in Jacobian:\n")
#run_sim(exc_jac=False, dmi_jac=True) # CVODE fails with CV_TOO_MUCH_WORK
output.write("\nOnly Exchange in Jacobian:\n")
run_sim(exc_jac=True, dmi_jac=False)
output.write("\nBoth in Jacobian:\n")
run_sim(exc_jac=True, dmi_jac=True)
output.close()
print "Timings written to timings.txt"
| 919 | 26.878788 | 73 |
py
|
finmag
|
finmag-master/dev/sandbox/skyrmions/skyrmiondemo.py
|
import numpy as np
import dolfin as df
from finmag import Simulation
from finmag.energies import Exchange, DMI, Demag, Zeeman
from finmag.util.meshes import cylinder
#mesh = df.BoxMesh(0,0,0,30,30,3,10,10,1)
mesh = cylinder(60, 3, 3)
Ms = 8.6e5
sim = Simulation(mesh, Ms, unit_length=1e-9)
sim.set_m((1, 1, 1))
A = 1.3e-11
D = 4e-3
sim.add(Exchange(A))
sim.add(DMI(D))
sim.add(Zeeman((0, 0, 0.25*Ms)))
#sim.add(Demag())
def loop(final_time, steps=100):
t = np.linspace(sim.t + 1e-12, final_time, steps)
for i in t:
sim.run_until(i)
p = df.plot(sim.llg._m)
df.interactive()
loop(5e-9)
| 620 | 18.40625 | 56 |
py
|
finmag
|
finmag-master/dev/sandbox/skyrmions/skyrmion.py
|
""" Attempt to visualise some dynimacs using python's visual module.
Visualisation probably okay, but some convergence problem in the time
integration means this does not look smooth at all, and is very slow.
"""
import dolfin
import dolfin as df
import numpy
from scipy.integrate import odeint
from finmag.sim.llg import LLG
"""
Compute the behaviour of a one-dimensional strip of magnetic material,
with exchange interaction.
"""
nm=1e-9
xdim = 30
ydim = 30
zdim = 3
mesh = dolfin.Box(0,0,0,xdim*nm,ydim*nm, zdim*nm, xdim/3, ydim/3, zdim/3)
llg = LLG(mesh)
llg.alpha=1.0
llg.H_app=(0,0,0)
llg.A =1.3e-11
llg.D = 4e-3
#llg.set_m((
# 'MS * (2*x[0]/L - 1)',
# 'sqrt(MS*MS - MS*MS*(2*x[0]/L - 1)*(2*x[0]/L - 1))',
# '0'), L=length, MS=llg.Ms)
llg.set_m((
'MS',
'0',
'0'), MS=llg.Ms)
llg.setup(use_dmi=True,use_exchange=True)
llg.pins = []
print "point 0:",mesh.coordinates()[0]
print "Solving problem..."
ts = numpy.linspace(0, 1e-9, 50)
tol = 1e-4
for i in range(len(ts)-1):
print "step=%4d, time=%12.6g " % (i,ts[i]),
#ys,infodict = odeint(llg.solve_for, llg.m, [ts[i],ts[i+1]], full_output=True,printmessg=True,rtol=tol,atol=tol)
ys,infodict = odeint(llg.solve_for, llg.m, [ts[i],ts[i+1]], full_output=True,printmessg=False)
print "NFE=%4d, NJE=%4d" % (infodict['nfe'],infodict['nje'])
df.plot(llg._m)
df.interactive()
print "Done"
| 1,411 | 23.344828 | 116 |
py
|
finmag
|
finmag-master/dev/sandbox/skyrmions/skyrmion_pbc_demo_sllg.py
|
import numpy as np
import dolfin as df
from finmag import Simulation
from finmag.energies import Exchange, DMI, Demag, Zeeman
from finmag.util.helpers import vector_valued_function
from finmag.physics.llb.sllg import SLLG
R=150
N=50
#mesh = df.RectangleMesh(0,0,R,R,20,20)
mesh = df.RectangleMesh(0,0,R,R,N,N)
def m_init_fun(pos):
return np.random.random(3)-0.5
pbc=True
Ms = 8.6e5
sim = (mesh, Ms,unit_length=1e-9,pbc2d=pbc)
sim.set_m(m_init_fun)
sim.T=temperature
#A = 3.57e-13
#D = 2.78e-3
A = 1.3e-11
D = 4e-3
sim.add(Exchange(A,pbc2d=pbc))
sim.add(DMI(D,pbc2d=pbc))
sim.add(Zeeman((0,0,0.35*Ms)))
#sim.add(Demag())
def loop(final_time, steps=200):
t = np.linspace(sim.t + 1e-12, final_time, steps)
for i in t:
sim.run_until(i)
p = df.plot(sim._m)
df.interactive()
loop(5e-10)
| 823 | 18.162791 | 56 |
py
|
finmag
|
finmag-master/dev/sandbox/skyrmions/skyrmion_sim.py
|
import numpy as np
import dolfin as df
from finmag import Simulation
from finmag.energies import Exchange, DMI_Old, DMI
mesh = df.Box(0,0,0,30e-9,30e-9,3e-9,10,10,1)
Ms = 8.6e5
sim = Simulation(mesh, Ms)
sim.set_m((Ms, 0, 0))
A = 1.3e-11
D = 4e-3
sim.add(Exchange(A))
sim.add(DMI( D))
series = df.TimeSeries("solution/m")
t = np.linspace(0, 1e-9, 1000)
for i in t:
sim.run_until(i)
p = df.plot(sim.llg._m)
p.write_png("m_{}".format(i))
series.store(sim.llg._m.vector(), i)
df.interactive()
| 509 | 20.25 | 50 |
py
|
finmag
|
finmag-master/dev/sandbox/skyrmions/sw_no_dmi.py
|
import dolfin as df
import numpy as np
import pylab as plt
from finmag.energies import Exchange, Zeeman, Demag
from finmag import Simulation as Sim
from math import pi
def plot_excitation(tsinc, Hsinc):
"""Plot the external excitation signal both in time and frequency domain."""
#time domain
plt.subplot(211)
plt.plot(tsinc, Hsinc)
#frequency domain
s_excitation = np.fft.fft(Hsinc)
f_excitation = np.fft.fftfreq(len(s_excitation), d=tsinc[1]-tsinc[0])
plt.subplot(212)
plt.plot(f_excitation, np.absolute(s_excitation))
plt.xlim([-2e12,2e12])
plt.show()
#output npz file name
file_name = 'sw_no_dmi'
tstart = 0
#time to converge into the static state
tstatic = 1e-9 #1ns
#excitation pulse duration
tpulse = 0.08e-9
#end time for recording oscilations
tend = 5e-9
#number of steps for recording oscilations
n_osc_steps = 5001
#number of time steps in excitation signal
n_sinc_steps = 501
toffset = 1e-20
#dimensions of the square thin-film sample
xdim = 7e-9
ydim = 7e-9
zdim = 1e-9
#mesh size in x, y and z directions
xv = 10
yv = 10
zv = 1
#magnetisation saturation
Ms = 1.567e5 #A/m
#simulated frequency maximum
fc = 200e9 #200GHz
#excitation signal amplitude
Hamp = 0.05*Ms
# Hsinc = f(tsinc) for the duration of tpulse
tsinc = np.linspace(-tpulse/2, tpulse/2, n_sinc_steps)
Hsinc = Hamp * np.sinc(2*pi*fc*tsinc)
#Gilbert damping for the spin waves recording
sw_alpha = 1e-20
mesh = df.BoxMesh(0, 0, 0, xdim, ydim, zdim, xv, yv, zv)
sim = Sim(mesh, Ms)
sim.set_m((1,1,1))
#exchange energy constant
A = 3.57e-13 #J/m
#external magnetic field
H = [0,0,0] #A/m
sim.add(Exchange(A)) #exchnage interaction
sim.add(Zeeman(H)) #Zeeman interaction
sim.add(Demag()) #demagnitasion field
#time series for the static state simulation
tsim = np.linspace(tstart, tstatic, 21)
############################################################
#simulation to the ground state
sim.alpha = 1 #dynamics neglected
for t in tsim:
sim.run_until(t)
df.plot(sim.llg._m)
############################################################
############################################################
#excite the system with an external sinc field
tsim = np.linspace(tstatic+toffset, tstatic+tpulse, n_sinc_steps)
i = 0 #index for the extrenal excitation
for t in tsim:
H = [Hsinc[i], Hsinc[i], Hsinc[i]]
sim.add(Zeeman(H))
sim.run_until(t)
df.plot(sim.llg._m)
i += 1
############################################################
############################################################
#record spin waves
tsim = np.linspace(tstatic+tpulse+toffset, tend, n_osc_steps)
#decrease the Gilbert damping to previously chosen value
sim.alpha = sw_alpha
#turn off an external field
sim.add(Zeeman([0,0,0]))
#points at which the magnetisation is recorded
xs = np.linspace(0, xdim-1e-20, xv+1)
ys = np.linspace(0, ydim-1e-20, yv+1)
z = 0 #magnetisation read only in one x-y plane at z = 0
#make empty arrays for mx, my and mz recording
#don't remember why tsim-1
mx = np.zeros([xv+1, yv+1, n_osc_steps])
my = np.zeros([xv+1, yv+1, n_osc_steps])
mz = np.zeros([xv+1, yv+1, n_osc_steps])
for i in xrange(len(tsim)):
#simulate up to next time step
sim.run_until(tsim[i])
df.plot(sim.llg._m)
#record the magnetisation state
for j in range(len(xs)):
for k in range(len(ys)):
mx[j,k,i] = sim.llg._m(xs[j], ys[k], 0)[0]
my[j,k,i] = sim.llg._m(xs[j], ys[k], 0)[1]
mz[j,k,i] = sim.llg._m(xs[j], ys[k], 0)[2]
#############################################################
tsim = tsim - (tstatic+tpulse+toffset)
#save the file into the file_name.npz file
np.savez(file_name, tsim=tsim, mx=mx, my=my, mz=mz)
| 3,712 | 27.128788 | 80 |
py
|
finmag
|
finmag-master/dev/sandbox/skyrmions/test_curl_operator.py
|
from dolfin import *
mesh=UnitCubeMesh(1,1,1)
V=VectorFunctionSpace(mesh,"CG",1)
M=interpolate(Constant((1,1,1)),V)
#E=dot(M,M)*dx
E=inner(M,curl(M))*dx
print "energy=",assemble(E)
dE_dM=derivative(E,M)
dE_dMvec=assemble(dE_dM)
print "vector=",dE_dMvec.array()
#curlM=project(somecurlform,V)
#print curlM.vector().array()
| 330 | 14.761905 | 34 |
py
|
finmag
|
finmag-master/dev/sandbox/skyrmions/skyrmion_stt_nonlocal.py
|
import numpy as np
import dolfin as df
from finmag import Simulation
from finmag.energies import Exchange, DMI, Zeeman
def m_init_fun(pos):
return np.random.random(3)-0.5
def relax(mesh):
Ms = 8.6e5
sim = Simulation(mesh, Ms, pbc='2d',unit_length=1e-9)
sim.set_m(m_init_fun)
sim.alpha = 0.5
sim.add(Exchange(1.3e-11))
sim.add(DMI(D = 4e-3))
sim.add(Zeeman((0,0,0.45*Ms)))
ts = np.linspace(0, 1e-9, 101)
for t in ts:
sim.run_until(t)
p = df.plot(sim.llg._m)
df.plot(sim.llg._m).write_png("vortex")
df.interactive()
#sim.relax()
np.save('m0.npy',sim.m)
def init_J(pos):
return (1e7,0,0)
def move_skyrmion(mesh):
Ms = 8.6e5
sim = Simulation(mesh, Ms, pbc='2d',unit_length=1e-9, kernel='llg_stt')
sim.set_m(np.load('m0.npy'))
sim.add(Exchange(1.3e-11))
sim.add(DMI(D = 4e-3))
sim.add(Zeeman((0,0,0.45*Ms)))
sim.alpha=0.01
sim.llg.set_parameters(J_profile=init_J, speedup=50)
ts = np.linspace(0, 5e-9, 101)
for t in ts:
sim.run_until(t)
print t
#p = df.plot(sim.llg._m)
sim.save_vtk(filename='nonlocal/v1e7_.pvd')
df.plot(sim.llg._m).write_png("vortex")
#df.interactive()
if __name__=='__main__':
mesh = df.RectangleMesh(0,0,100,100,40,40)
#mesh = df.BoxMesh(0, 0, 0, 100, 100, 2, 40, 40, 1)
#relax(mesh)
move_skyrmion(mesh)
| 1,472 | 19.746479 | 75 |
py
|
finmag
|
finmag-master/dev/sandbox/skyrmions/skyrmion_pbc_demo.py
|
import numpy as np
import dolfin as df
from finmag import Simulation
from finmag.energies import Exchange, DMI, Zeeman
def m_init_fun(pos):
return np.random.random(3)-0.5
def relax(mesh):
Ms = 8.6e5
sim = Simulation(mesh, Ms, pbc='2d',unit_length=1e-9)
sim.set_m(m_init_fun)
sim.add(Exchange(1.3e-11))
sim.add(DMI(D = 4e-3))
sim.add(Zeeman((0,0,0.45*Ms)))
sim.alpha = 0.5
ts = np.linspace(0, 1e-9, 101)
for t in ts:
sim.run_until(t)
p = df.plot(sim.llg._m)
sim.save_vtk()
df.plot(sim.llg._m).write_png("vortex")
df.interactive()
if __name__=='__main__':
mesh = df.RectangleMesh(0,0,100,100,40,40)
relax(mesh)
| 725 | 16.707317 | 57 |
py
|
finmag
|
finmag-master/dev/sandbox/cvode_parallel/hdf5_to_vtk.py
|
import numpy as np
import dolfin as df
df.parameters.reorder_dofs_serial = True
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
#mpirun -n 2 python test.py
if __name__ == '__main__':
mesh = df.BoxMesh(0, 0, 0, 30, 30, 100, 6, 6, 20)
S3 = df.VectorFunctionSpace(mesh, 'CG', 1, dim=3)
m_init = df.Constant([1, 1, 1.0])
m = df.interpolate(m_init, S3)
file_vtk = df.File('m.pvd')
file = df.HDF5File(m.vector().mpi_comm(),'test.h5','r')
ts = np.linspace(0, 2e-10, 101)
for t in ts:
#sim.field.vector().set_local(sim.llg.effective_field.H_eff)
file.read(m,'/m_%g'%t)
file_vtk << m
| 721 | 20.878788 | 68 |
py
|
finmag
|
finmag-master/dev/sandbox/cvode_parallel/test.py
|
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
import dolfin as df
import numpy as np
import finmag.native.cvode_petsc as cvode
#from mpi4py import MPI
#comm = MPI.COMM_WORLD
#rank1 = comm.Get_rank()
#size1 = comm.Get_size()
mpi_world = df.mpi_comm_world()
rank = df.MPI.rank(mpi_world)
size = df.MPI.size(mpi_world)
#mpirun -n 2 python test.py
"""
Solve equation du/dt = sin(t) based on dolfin vector and sundials/cvode in parallel.
"""
class Test(object):
def __init__(self, mesh):
self.mesh = mesh
self.V = df.FunctionSpace(mesh, 'CG', 1)
zero = df.Expression('0')
self.u = df.interpolate(zero, self.V)
self.spin = self.u.vector().get_local()
self.spin[:] = 0.1*rank
self.u.vector().set_local(self.spin)
#print rank, len(self.spin),self.spin
#print rank, len(self.u.vector().array()), self.u.vector().array()
self.t = 0
self.m_petsc = df.as_backend_type(self.u.vector()).vec()
def set_up_solver(self, rtol=1e-8, atol=1e-8):
self.ode = cvode.CvodeSolver(self.sundials_rhs, 0, self.m_petsc, rtol, atol)
#self.ode.test_petsc(self.m_petsc)
def sundials_rhs(self, t, y, ydot):
print 'rank=%d t=%g local=%d size=%d'%(rank, t, y.getLocalSize(), ydot.getSize())
ydot.setArray(np.cos((rank+1)/2.0*t))
return 0
def run_until(self,t):
if t <= self.t:
return
ode = self.ode
flag = ode.run_until(t)
if flag < 0:
raise Exception("Run cython run_until failed!!!")
self.u.vector().set_local(ode.y_np)
self.spin = self.u.vector().get_local()
#print self.spin[0]
#self.spin[:] = ode.y[:]
def plot_m(ts, m):
fig = plt.figure()
plt.plot(ts, m, ".", label="sim", color='DarkGreen')
m2 = 2.0/(rank+1.0)*np.sin((rank+1)/2.0*ts)+0.1*rank
plt.plot(ts, m2, label="exact", color='red')
plt.xlabel('Time')
plt.ylabel('y')
plt.legend()
fig.savefig('m_rank_%d.pdf'%rank)
if __name__ == '__main__':
nx = ny = 10
mesh = df.UnitSquareMesh(nx, ny)
sim = Test(mesh)
sim.set_up_solver()
ts = np.linspace(0, 5, 101)
us = []
file = df.File('u_time.pvd')
file << sim.u
for t in ts:
sim.run_until(t)
#file << sim.u
us.append(sim.spin[0])
plot_m(ts,us)
| 2,518 | 23.940594 | 89 |
py
|
finmag
|
finmag-master/dev/sandbox/cvode_parallel/setup.py
|
#!/usr/bin/env python
import os
#$ python setup.py build_ext --inplace
# Set the environment variable SUNDIALS_PATH if sundials
# is installed in a non-standard location.
SUNDIALS_PATH = os.environ.get('SUNDIALS_PATH', '/usr')
print "[DDD] Using SUNDIALS_PATH='{}'".format(SUNDIALS_PATH)
from numpy.distutils.command import build_src
import Cython.Compiler.Main
build_src.Pyrex = Cython
build_src.have_pyrex = False
def have_pyrex():
import sys
try:
import Cython.Compiler.Main
sys.modules['Pyrex'] = Cython
sys.modules['Pyrex.Compiler'] = Cython.Compiler
sys.modules['Pyrex.Compiler.Main'] = Cython.Compiler.Main
return True
except ImportError:
return False
build_src.have_pyrex = have_pyrex
def configuration(parent_package='',top_path=None):
INCLUDE_DIRS = ['/usr/lib/openmpi/include/', os.path.join(SUNDIALS_PATH, 'include')]
LIBRARY_DIRS = [os.path.join(SUNDIALS_PATH, 'lib')]
LIBRARIES = ['sundials_cvodes', 'sundials_nvecparallel', 'sundials_nvecserial']
# PETSc
PETSC_DIR = os.environ.get('PETSC_DIR','/usr/lib/petsc')
PETSC_ARCH = os.environ.get('PETSC_ARCH', 'linux-gnu-c-opt')
if os.path.isdir(os.path.join(PETSC_DIR, PETSC_ARCH)):
INCLUDE_DIRS += [os.path.join(PETSC_DIR, 'include')]
LIBRARY_DIRS += [os.path.join(PETSC_DIR, PETSC_ARCH, 'lib')]
else:
raise Exception('Seems PETSC_DIR or PETSC_ARCH are wrong!')
LIBRARIES += [#'petscts', 'petscsnes', 'petscksp',
#'petscdm', 'petscmat', 'petscvec',
'petsc']
# PETSc for Python
import petsc4py
INCLUDE_DIRS += [petsc4py.get_include()]
print "[DDD] INCLUDE_DIRS = {}".format(INCLUDE_DIRS)
# Configuration
from numpy.distutils.misc_util import Configuration
config = Configuration('', parent_package, top_path)
config.add_extension('cvode2',
sources = ['sundials/cvode2.pyx'],
depends = [''],
include_dirs=INCLUDE_DIRS + [os.curdir],
libraries=LIBRARIES,
library_dirs=LIBRARY_DIRS,
runtime_library_dirs=LIBRARY_DIRS)
config.add_extension('llg_petsc',
sources = ['llg/llg_petsc.pyx', 'llg/llg.c'],
depends = [''],
include_dirs=INCLUDE_DIRS + [os.curdir],
libraries=LIBRARIES,
library_dirs=LIBRARY_DIRS,
runtime_library_dirs=LIBRARY_DIRS)
return config
if __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
| 2,761 | 35.826667 | 88 |
py
|
finmag
|
finmag-master/dev/sandbox/cvode_parallel/test_llg.py
|
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
import dolfin as df
import numpy as np
import finmag.native.cvode_petsc as cvode2
import finmag.native.llg_petsc as llg_petsc
from finmag.physics.llg import LLG
from finmag.energies import Exchange, Zeeman, Demag
df.parameters.reorder_dofs_serial = True
from mpi4py import MPI
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
#mpirun -n 2 python test.py
"""
Solve equation du/dt = sin(t) based on dolfin vector and sundials/cvode in parallel.
"""
class Test(object):
def __init__(self, mesh):
self.mesh = mesh
self.S1 = df.FunctionSpace(mesh, 'CG', 1)
self.S3 = df.VectorFunctionSpace(mesh, 'CG', 1, dim=3)
#zero = df.Expression('0.3')
m_init = df.Constant([1, 1, 1.0])
self.m = df.interpolate(m_init, self.S3)
self.field = df.interpolate(m_init, self.S3)
self.dmdt = df.interpolate(m_init, self.S3)
self.spin = self.m.vector().array()
self.t = 0
#It seems it's not safe to specify rank in df.interpolate???
self._alpha = df.interpolate(df.Constant("0.001"), self.S1)
self._alpha.vector().set_local(self._alpha.vector().array())
print 'dolfin',self._alpha.vector().array()
self.llg = LLG(self.S1, self.S3, unit_length=1e-9)
#normalise doesn't work due to the wrong order
self.llg.set_m(m_init, normalise=True)
parameters = {
'absolute_tolerance': 1e-10,
'relative_tolerance': 1e-10,
'maximum_iterations': int(1e5)
}
demag = Demag()
demag.parameters['phi_1'] = parameters
demag.parameters['phi_2'] = parameters
self.exchange = Exchange(13e-12)
self.zeeman = Zeeman([0, 0, 1e5])
self.llg.effective_field.add(self.exchange)
#self.llg.effective_field.add(demag)
self.llg.effective_field.add(self.zeeman)
self.m_petsc = df.as_backend_type(self.llg.m_field.f.vector()).vec()
self.h_petsc = df.as_backend_type(self.field.vector()).vec()
self.alpha_petsc = df.as_backend_type(self._alpha.vector()).vec()
self.dmdt_petsc = df.as_backend_type(self.dmdt.vector()).vec()
alpha = 0.001
gamma = 2.21e5
LLG1 = -gamma/(1+alpha*alpha)*df.cross(self.m, self.field) - alpha*gamma/(1+alpha*alpha)*df.cross(self.m, df.cross(self.m, self.field))
self.L = df.dot(LLG1, df.TestFunction(self.S3)) * df.dP
def set_up_solver(self, rtol=1e-8, atol=1e-8):
self.ode = cvode2.CvodeSolver(self.sundials_rhs, 0, self.m_petsc, rtol, atol)
def sundials_rhs(self, t, y, ydot):
self.llg.effective_field.update(t)
self.field.vector().set_local(self.llg.effective_field.H_eff)
#print y, self.h_petsc, self.m_petsc
y.copy(self.m_petsc)
df.assemble(self.L, tensor=self.dmdt.vector())
self.dmdt_petsc.copy(ydot)
"""
#llg_petsc.compute_dm_dt(y,
self.h_petsc,
ydot,
self.alpha_petsc,
self.llg.gamma,
self.llg.do_precession,
self.llg.c)
"""
return 0
def run_until(self,t):
if t <= self.t:
ode = self.ode
self.spin = self.m.vector().array()
return
ode = self.ode
flag = ode.run_until(t)
if flag < 0:
raise Exception("Run cython run_until failed!!!")
self.m.vector().set_local(ode.y_np)
self.spin = self.m.vector().array()
#print self.spin[0]
#self.spin[:] = ode.y[:]
def plot_m(ts, m):
plt.plot(ts, m, "-", label="m", color='DarkGreen')
plt.xlabel('Time')
plt.ylabel('energy')
plt.savefig('mm_rank_%d.pdf'%rank)
if __name__ == '__main__':
mesh = df.RectangleMesh(0,0,100.0,20.0,25,5)
mesh = df.BoxMesh(0, 0, 0, 30, 30, 100, 6, 6, 20)
#mesh = df.IntervalMesh(10,0,10)
sim = Test(mesh)
sim.set_up_solver()
ts = np.linspace(0, 2e-10, 101)
energy = []
#file = df.File('u_time.pvd')
file = df.HDF5File(sim.m.vector().mpi_comm(),'test.h5','w')
mm = []
tt=[]
for t in ts:
sim.run_until(t)
print t, sim.spin[0]
#sim.field.vector().set_local(sim.llg.effective_field.H_eff)
file.write(sim.m,'/m_%g'%t)
energy.append(sim.llg.effective_field.total_energy())
mm.append(sim.spin[0])
tt.append(t)
plot_m(tt,mm)
| 4,789 | 30.30719 | 143 |
py
|
finmag
|
finmag-master/dev/sandbox/basics-fe/shapefunctions.py
|
import numpy as np
import dolfin as df
import pylab
class Potential(object):
"""
Idea: Have a potential, say
.. math::
V(x) = 0.5*k*(f(x)-m(x))^2
Have degrees of freedom m(x) that can adjust to this
potential. The force field H is
.. math::
H = -dV/dm = k*(f(x)-m(x))
For k=1 and m(x) =0, this simplifies to the force field being
H(x)==f(x).
Do some tests in this file, to demonstrate what
- the shape functions look like (vary order of basis functions)
- the volume of the shape function means (and why we need to divide
by it)
Observations: the potential above is quadratic in m. if we use CG order=2 as the basis functiosn, then the resulting field H is the same as f.
For CG order 1, a slight error occurs at the left - and right most
intervals.
The project method seems to work fine (even the quadratic case in
m seems t owork numerically exactly).
This calculation is very similar to how the exchange, anisotropy
and DMI field are calculated.
"""
def __init__(self, f, m, V):
# Testfunction
self.v = df.TestFunction(V)
k=1
# V
self.E = 0.5*(k*(f-m)**2)*df.dx
# Gradient
self.dE_dM = df.Constant(-1.0)*df.derivative(self.E, m)
# Volume
self.vol = df.assemble(df.dot(self.v,
df.Constant(1)) * df.dx).array()
# Store for later
self.V = V
self.m = m
#method = 'project'
method = 'box-assemble'
if method=='box-assemble':
self.__compute_field = self.__compute_field_assemble
elif method == 'box-matrix-numpy':
self.__setup_field_numpy()
self.__compute_field = self.__compute_field_numpy
raise NotImplementedError("Never tested for this example")
elif method == 'box-matrix-petsc':
self.__setup_field_petsc()
self.__compute_field = self.__compute_field_petsc
raise NotImplementedError("Never tested for this example")
elif method=='project':
self.__setup_field_project()
self.__compute_field = self.__compute_field_project
else:
raise NotImplementedError("""Only methods currently implemented are
* 'box-assemble',
* 'box-matrix-numpy',
* 'box-matrix-petsc'
* 'project'""")
def compute_field(self):
"""
Compute the field.
*Returns*
numpy.ndarray
The anisotropy field.
"""
H = self.__compute_field()
return H
def compute_energy(self):
"""
Compute the anisotropy energy.
*Returns*
Float
The anisotropy energy.
"""
E=df.assemble(self.E)
return E
def __setup_field_numpy(self):
"""
Linearise dE_dM with respect to M. As we know this is
linear ( should add reference to Werner Scholz paper and
relevant equation for g), this creates the right matrix
to compute dE_dM later as dE_dM=g*M. We essentially
compute a Taylor series of the energy in M, and know that
the first two terms (dE_dM=Hex, and ddE_dMdM=g) are the
only finite ones as we know the expression for the
energy.
"""
g_form = df.derivative(self.dE_dM, self.m)
self.g = df.assemble(g_form).array() #store matrix as numpy array
def __setup_field_petsc(self):
"""
Same as __setup_field_numpy but with a petsc backend.
"""
g_form = df.derivative(self.dE_dM, self.m)
self.g_petsc = df.PETScMatrix()
df.assemble(g_form,tensor=self.g_petsc)
self.H_ani_petsc = df.PETScVector()
def __setup_field_project(self):
#Note that we could make this 'project' method faster by computing
#the matrices that represent a and L, and only to solve the matrix
#system in 'compute_field'(). IF this method is actually useful,
#we can do that. HF 16 Feb 2012
#Addition: 9 April 2012: for this example, this seems to work.
H_ani_trial = df.TrialFunction(self.V)
self.a = df.dot(H_ani_trial, self.v) * df.dx
self.L = self.dE_dM
self.H_ani_project = df.Function(self.V)
def __compute_field_assemble(self):
H_ani=df.assemble(self.dE_dM).array() / self.vol
#H_ani=df.assemble(self.dE_dM).array() #/ self.vol
return H_ani
def __compute_field_numpy(self):
Mvec = self.m.vector().array()
H_ani = np.dot(self.g,Mvec)/self.vol
return H_ani
def __compute_field_petsc(self):
self.g_petsc.mult(self.m.vector(), self.H_ani_petsc)
H_ani = self.H_ani_petsc.array()/self.vol
return H_ani
def __compute_field_project(self):
df.solve(self.a == self.L, self.H_ani_project)
H_ani = self.H_ani_project.vector().array()
return H_ani
def make_shapefunction(V,i,coeff=1):
"""
V - function space
i - node
Return a (dolfin) function that, when plotted, shows the shape
function associated with node i.
"""
f = df.Function(V)
f.vector()[:] *= 0
f.vector()[i] = coeff
print "i=%d, coeef=%f" % (i,coeff)
return f
def plot_shapes_of_function(f):
"""For a given function f, create a plot that shows how the function
is composed out of basis functions.
"""
import pylab
V=f.function_space()
mesh = V.mesh()
coordinates = mesh.coordinates()
xrange = max(coordinates),min(coordinates)
n = len(coordinates)
small_x = np.linspace(xrange[0],xrange[1],n*10)
fcoeffs = f.vector().array()
n = len(f.vector().array())
for i in range(n):
f_i = make_shapefunction(V,i,coeff=fcoeffs[i])
f_i_values = [ f_i(x) for x in small_x ]
pylab.plot(small_x,f_i_values,'--',label='i=%2d' % i)
f_total_values = [ f(x) for x in small_x ]
pylab.plot(small_x,f_total_values,label='superposition')
f_total_mesh_values = [ f(x) for x in coordinates ]
pylab.plot(coordinates,f_total_mesh_values,'o')
pylab.legend()
pylab.grid()
pylab.show()
return f
def plot_shapes_of_functionspace(V):
"""Create an overview of basis functions by plotting them.
Expects (scalar) dolfin FunctionSpace object."""
import pylab
mesh = V.mesh()
coordinates = mesh.coordinates()
xrange = max(coordinates),min(coordinates)
n = len(coordinates)
small_x = np.linspace(xrange[0],xrange[1],n*100)
n = len(f.vector().array())
for i in range(n):
f_i = make_shapefunction(V,i)
f_i_values = [ f_i(x) for x in small_x ]
pylab.plot(small_x,f_i_values,label='i=%2d' % i)
pylab.legend()
pylab.grid()
pylab.show()
def compute_shape_function_volumes(V):
v = df.TestFunction(V)
Vs = df.assemble(1*v*df.dx)
return Vs.array()
def test_shape_function_volumes(V):
"""Compace shape function volumes as computed in function
above, and by integrating the functions numerically with
scipy.integrate.quad."""
import scipy.integrate
mesh = V.mesh()
coordinates = mesh.coordinates()
xrange = min(coordinates),max(coordinates)
n = len(coordinates)
shape_function_volumes = compute_shape_function_volumes(V)
for i in range(n):
f_i = make_shapefunction(V,i)
shape_func_vol_quad = scipy.integrate.quad(f_i,xrange[0],xrange[1])[0]
rel_error = (shape_function_volumes[i]-shape_func_vol_quad)/shape_function_volumes[i]
print "i=%g, rel_error = %g" % (i,rel_error)
assert rel_error <1e-15
if __name__=="__main__":
minx = -3
maxx = 2
n = 5
mesh = df.IntervalMesh(n,minx,maxx)
#V = df.FunctionSpace(mesh,"CG",1)
V = df.FunctionSpace(mesh,"CG",2)
test_shape_function_volumes(V)
m = df.Function(V)
f = df.interpolate(df.Expression("-1*x[0]"),V)
fproj = df.project(df.Expression("-1*x[0]"),V)
plot_shapes_of_functionspace(V)
print compute_shape_function_volumes(V)
plot_shapes_of_function(f)
p=Potential(f,m,V)
Hcoeff=p.compute_field()
H = df.Function(V)
H.vector()[:]=Hcoeff[:]
print mesh.coordinates()
#compare f with force
xs = np.linspace(minx,maxx,n*10)
ftmp = [ f(x) for x in xs ]
fprojtmp = [ fproj(x) for x in xs ]
Htmp = [ H(x) for x in xs ]
pylab.plot(xs,ftmp,label='f(x)')
pylab.plot(xs,fprojtmp,'o',label='fproj(x)')
pylab.plot(xs,Htmp,label='H(x)')
pylab.legend()
pylab.show()
| 8,817 | 29.512111 | 146 |
py
|
finmag
|
finmag-master/dev/sandbox/basics-fe/test_assemble.py
|
from dolfin import *
import dolfin as df
from fractions import Fraction
import numpy
def my_print_array(a):
(m,n)=a.shape
for j in range(n):
for i in range(m):
x=a[i][j]
y= Fraction(x).limit_denominator()
print "%6s"%y,
print ''
def compute_assemble(u1,v1,u3,v3,dolfin_str):
tmp_str='A=df.assemble(%s)'%(dolfin_str)
exec tmp_str
print '='*70,dolfin_str,A.array().shape
my_print_array(A.array())
def test_assemble(mesh):
V = FunctionSpace(mesh, 'Lagrange', 1)
Vv=VectorFunctionSpace(mesh, 'Lagrange', 1)
u1 = TrialFunction(V)
v1 = TestFunction(V)
u3 = TrialFunction(Vv)
v3 = TestFunction(Vv)
test_list=[
"u1*v1*dx",
"inner(grad(u1),grad(v1))*dx",
"inner(u3,v3)*dx",
"inner(grad(u1), v3)*dx",
"inner(u3, grad(v1))*dx"
]
for i in test_list:
compute_assemble(u1,v1,u3,v3,i)
if __name__ == "__main__":
mesh = df.UnitCubeMesh(1,1,1)
mesh = RectangleMesh(0, 0, 2, 2, 1, 1)
test_assemble(mesh)
| 1,135 | 17.031746 | 47 |
py
|
finmag
|
finmag-master/dev/sandbox/saving_data/example.py
|
import savingdata as sd
import dolfin as df
import numpy as np
# Define mesh, functionspace, and functions.
mesh = df.UnitSquareMesh(5, 5)
fs = df.VectorFunctionSpace(mesh, 'CG', 1, 3)
f1 = df.Function(fs)
f2 = df.Function(fs)
f3 = df.Function(fs)
f1.assign(df.Constant((1, 1, 1)))
f2.assign(df.Constant((2, 2, 2)))
f3.assign(df.Constant((3, 1, 6)))
# Filenames. At the moment both npz and json files are implemented.
h5filename = 'hdf5file.h5'
jsonfilename = 'jsonfile.json'
npzfilename = 'npzfile.npz'
# SAVING DATA.
sdata = sd.SavingData(h5filename, npzfilename, jsonfilename, fs)
sdata.save_mesh(name='mesh')
sdata.save_field(f1, 'm', t=0)
sdata.save_field(f2, 'm', t=1e-12)
sdata.save_field(f3, 'm', t=2e-12)
# Temporarily disable close. Problems on virtual machine.
#sdata.close()
# LOADING DATA.
ldata = sd.LoadingData(h5filename, npzfilename, jsonfilename, fs)
meshl = ldata.load_mesh(name='mesh')
f1l = ldata.load_field(field_name='m', t=0)
f2l = ldata.load_field(field_name='m', t=1e-12)
f3l = ldata.load_field(field_name='m', t=2e-12)
f1lj = ldata.load_field_with_json_data(field_name='m', t=0)
f2lj = ldata.load_field_with_json_data(field_name='m', t=1e-12)
f3lj = ldata.load_field_with_json_data(field_name='m', t=2e-12)
# Temporarily disable closing. Problems on virtual machine.
# ldata.close()
# ASSERTIONS. Is the saved data the same as loaded.
assert np.all(mesh.coordinates() == meshl.coordinates())
assert np.all(f1l.vector().array() == f1.vector().array())
assert np.all(f2l.vector().array() == f2.vector().array())
assert np.all(f3l.vector().array() == f3.vector().array())
assert np.all(f1lj.vector().array() == f1.vector().array())
assert np.all(f2lj.vector().array() == f2.vector().array())
assert np.all(f3lj.vector().array() == f3.vector().array())
| 1,798 | 26.257576 | 67 |
py
|
finmag
|
finmag-master/dev/sandbox/saving_data/savingdata_test.py
|
import dolfin as df
import numpy as np
import json
from collections import OrderedDict
from savingdata import SavingData, LoadingData
h5filename = 'file.h5'
npzfilename = 'file.npz'
jsonfilename = 'file.json'
mesh = df.UnitSquareMesh(10, 10)
functionspace = df.VectorFunctionSpace(mesh, 'CG', 1, 3)
f = df.Function(functionspace)
t_array = np.linspace(0, 1e-9, 5)
def test_save_data():
sd = SavingData(h5filename, npzfilename, jsonfilename, functionspace)
sd.save_mesh()
for i in range(len(t_array)):
f.assign(df.Constant((t_array[i], 0, 0)))
sd.save_field(f, 'f', t_array[i])
sd.close()
def test_load_data():
ld = LoadingData(h5filename, npzfilename, jsonfilename, functionspace)
mesh_loaded = ld.load_mesh()
for t in t_array:
f_loaded = ld.load_field('f', t)
f.assign(df.Constant((t, 0, 0)))
assert np.all(f.vector().array() == f_loaded.vector().array())
ld.close()
def test_load_data_with_json_data():
ld = LoadingData(h5filename, npzfilename, jsonfilename, functionspace)
mesh_loaded = ld.load_mesh()
for t in t_array:
f_loaded = ld.load_field_with_json_data('f', t)
f.assign(df.Constant((t, 0, 0)))
assert np.all(f.vector().array() == f_loaded.vector().array())
ld.close()
def test_saved_json_data():
with open(jsonfilename) as jsonfile:
jsonData = json.load(jsonfile, object_pairs_hook=OrderedDict)
jsonfile.close()
# assert times from keys
for i, t in enumerate(t_array):
name = "f{}".format(i)
jsonTime = jsonData['f'][name]
assert(jsonTime == t)
# assert times by iterating through values (as they should be ordered)
index = 0
for jsonTime in jsonData['f'].itervalues():
assert(jsonTime == t_array[index])
index += 1
| 1,845 | 23.613333 | 74 |
py
|
finmag
|
finmag-master/dev/sandbox/saving_data/savingdata.py
|
import dolfin as df
import numpy as np
import json
from collections import OrderedDict
"""
Problems:
1. We have to know the mesh in advance.
2. Merge loading and saving into single class (r, w flags).
3. Appending data.
4. Looking into the file (we have to use python module).
"""
class SavingData(object):
def __init__(self, h5filename, npzfilename, jsonfilename, functionspace):
self.functionspace = functionspace
self.h5filename = h5filename
self.npzfilename = npzfilename
self.h5file = df.HDF5File(df.mpi_comm_world(), self.h5filename, 'w')
self.jsonfilename = jsonfilename
self.field_index = 0
self.t_array = []
self.fieldsDict = {} # dictionary of all field types e.g. 'm', 'H_eff'
# create json file
with open(self.jsonfilename, 'w') as jsonfile:
json.dump(self.fieldsDict, jsonfile, sort_keys=False)
jsonfile.close()
def save_field(self, f, field_name, t):
name = field_name + str(self.field_index)
self.h5file.write(f, name)
self.t_array.append(t)
np.savez(self.npzfilename, t_array=self.t_array)
# todo: method of doing this without having to open
# and close json file all time?
if not self.fieldsDict.has_key(field_name):
self.fieldsDict[field_name] = OrderedDict()
self.fieldsDict[field_name][name] = t
with open(self.jsonfilename, 'w') as jsonfile:
json.dump(self.fieldsDict, jsonfile, sort_keys=False)
jsonfile.close()
self.field_index += 1
def save_mesh(self, name='mesh'):
self.h5file.write(self.functionspace.mesh(), name)
def close(self):
self.h5file.close(df.mpi_comm_world())
class LoadingData(object):
def __init__(self, h5filename, npzfilename, jsonfilename, functionspace):
self.functionspace = functionspace
self.h5filename = h5filename
self.npzfilename = npzfilename
self.h5file = df.HDF5File(df.mpi_comm_world(), self.h5filename, 'r')
self.jsonfilename = jsonfilename
npzfile = np.load(self.npzfilename)
self.t_array = npzfile['t_array']
def load_mesh(self, name='mesh'):
mesh_loaded = df.Mesh()
self.h5file.read(mesh_loaded, name, False)
return mesh_loaded
def load_field(self, field_name, t):
index = np.where(self.t_array==t)[0][0]
name = field_name + str(index)
f_loaded = df.Function(self.functionspace)
# todo: removed last parameter, False to make it work.
# (originally was self.h5file.read(f_loaded, name))
# Need to check if this is needed...
self.h5file.read(f_loaded, name)
return f_loaded
def load_field_with_json_data(self, field_name, t):
with open(self.jsonfilename) as jsonfile:
fieldsDict = json.load(jsonfile, object_pairs_hook=OrderedDict)
jsonfile.close()
# todo: this next line is v. bad!
# The json file format can easily be changed to a more aproppiate one
# depending on how we actually want to use the data stored in the json file.
# For example a dictionary of lists rather than the current dictionary of
# ordererDictionaries.
name = str([item[0] for item in fieldsDict[field_name].items() if item[1]==t][0])
# name = field_name + str(index)
f_loaded = df.Function(self.functionspace)
# todo: removed last parameter, False to make it work.
# (originally was self.h5file.read(f_loaded, name))
# Need to check if this is needed...
self.h5file.read(f_loaded, name)
return f_loaded
def close(self):
self.h5file.close()
| 3,776 | 31.008475 | 89 |
py
|
finmag
|
finmag-master/dev/sandbox/scipy_integrate/test_scipy_integrate_odeint_with_dolfin.py
|
"""One test. We integrate
du
-- = -2*u
dt
using (i) scipy.integrate.odeint as one normally does and
(ii) within the dolfin framework.
The test here is whether we update the right function (u) in the
right-hand side when using dolfin.
For dolfin, we solve the ODE above on a mesh, where on every mesh
point we should(!) have exactly the same value (in each time
timestep).
It turns out that there is a slight deviation (within one timestep)
across the mesh. This, however, is of the order of 1-e16 (and thus the
usually numeric noise), and grows and shrinks over time.
While it is not clear where exactly this comes from (as the positional
coordinates do not enter the calculation?), this is not a blocker.
"""
import numpy
import scipy.integrate
import dolfin as df
from dolfin import dx
import logging
#suppres dolfin outpet when solving matrix system
df.set_log_level(logging.WARNING)
def test_scipy_uprime_integration_with_fenics():
iterations = 0
NB_OF_CELLS_X = NB_OF_CELLS_Y = 2
mesh = df.UnitSquare(NB_OF_CELLS_X, NB_OF_CELLS_Y)
V = df.FunctionSpace(mesh, 'CG', 1)
u0 = df.Constant('1.0')
uprime = df.TrialFunction(V)
uprev = df.interpolate(u0,V)
v = df.TestFunction(V)
#ODE is du/dt= uprime = -2*u, exact solution is u(t)=exp(-2*t)
a = uprime*v*dx
L = -2*uprev*v*dx
uprime_solution = df.Function(V)
uprime_problem = df.LinearVariationalProblem(a, L, uprime_solution)
uprime_solver = df.LinearVariationalSolver(uprime_problem)
def rhs_fenics(y,t):
"""A somewhat strange case where the right hand side is constant
and thus we don't need to use the information in y."""
#print "time: ",t
uprev.vector()[:]=y
uprime_solver.solve()
return uprime_solution.vector().array()
def rhs(y,t):
"""
dy/dt = f(y,t) with y(0)=1
dy/dt = -2y -> solution y(t) = c * exp(-2*t)"""
print "time: %g, y=%.10g" % (t,y)
tmp = iterations + 1
return -2*y
T_MAX=2
ts = numpy.arange(0,T_MAX+0.1,0.5)
ysfenics,stat=scipy.integrate.odeint(rhs_fenics, uprev.vector().array(), ts, printmessg=True,full_output=True)
def exact(t,y0=1):
return y0*numpy.exp(-2*t)
print "With fenics:"
err_abs = abs(ysfenics[-1][0]-exact(ts[-1])) #use value at mesh done 0 for check
print "Error: abs=%g, rel=%g, y_exact=%g" % (err_abs,err_abs/exact(ts[-1]),exact(ts[-1]))
fenics_error=err_abs
print "Without fenics:"
ys = scipy.integrate.odeint(rhs, 1, ts)
err_abs = abs(ys[-1]-exact(ts[-1]))
print "Error: abs=%g, rel=%g, y_exact=%g" % (err_abs,err_abs/exact(ts[-1]),exact(ts[-1]))
non_fenics_error = float(err_abs)
print("Difference between fenics and non-fenics calculation: %g" % abs(fenics_error-non_fenics_error))
assert abs(fenics_error-non_fenics_error)<7e-16
#should also check that solution is the same on all mesh points
for i in range(ysfenics.shape[0]): #for all result rows
#each row contains the data at all mesh points for one t in ts
row = ysfenics[i,:]
number_range = abs(row.min()-row.max())
print "row: %d, time %f, range %g" % (i,ts[i],number_range)
assert number_range < 10e-16
if False:
from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed()
ipshell()
if False:
import pylab
pylab.plot(ts,ys,'o')
pylab.plot(ts,numpy.exp(-2*ts),'-')
pylab.show()
return stat
if __name__== "__main__":
stat = test_scipy_uprime_integration_with_fenics()
| 3,644 | 27.928571 | 114 |
py
|
finmag
|
finmag-master/dev/sandbox/scipy_integrate/test_scipy_integrate_odeint_with_dolfin_sin.py
|
"""One test. We integrate
du
-- = -2*u
dt
using (i) scipy.integrate.odeint as one normally does and
(ii) within the dolfin framework.
The test here is whether we update the right function (u) in the
right-hand side when using dolfin.
For dolfin, we solve the ODE above on a mesh, where on every mesh
point we should(!) have exactly the same value (in each time
timestep).
It turns out that there is a slight deviation (within one timestep)
across the mesh. This, however, is of the order of 1-e16 (and thus the
usually numeric noise), and grows and shrinks over time.
While it is not clear where exactly this comes from (as the positional
coordinates do not enter the calculation?), this is not a blocker.
"""
import math
import logging
import numpy
import scipy.integrate
import dolfin as df
from dolfin import dx
#suppres dolfin outpet when solving matrix system
df.set_log_level(logging.WARNING)
def test_scipy_uprime_integration_with_fenics():
NB_OF_CELLS_X = NB_OF_CELLS_Y = 2
mesh = df.UnitSquare(NB_OF_CELLS_X, NB_OF_CELLS_Y)
V = df.FunctionSpace(mesh, 'CG', 1)
f = df.Expression("cos(t)",t=0)
uprime = df.TrialFunction(V)
uprev = df.interpolate(f,V)
v = df.TestFunction(V)
#ODE is du/dt= uprime = cos(t), exact solution is u(t)=sin(t)
a = uprime*v*dx
L = f*v*dx
uprime_solution = df.Function(V)
uprime_problem = df.LinearVariationalProblem(a, L, uprime_solution)
uprime_solver = df.LinearVariationalSolver(uprime_problem)
def rhs_fenics(y,t):
"""A somewhat strange case where the right hand side is constant
and thus we don't need to use the information in y."""
#print "time: ",t
uprev.vector()[:]=y
f.t = t #dolfin needs to know the current time for cos(t)
uprime_solver.solve()
return uprime_solution.vector().array()
def rhs(y,t):
"""
dy/dt = f(y,t) with y(0)=1
dy/dt = -2y -> solution y(t) = c * exp(-2*t)"""
return math.cos(t)
T_MAX=2
ts = numpy.arange(0,T_MAX+0.1,0.5)
ysfenics=scipy.integrate.odeint(rhs_fenics, uprev.vector().array(), ts)
def exact(t,y0=1):
return y0*numpy.sin(t)
print "With fenics:"
err_abs = abs(ysfenics[-1][0]-exact(ts[-1])) #use value at mesh done 0 for check
print "Error: abs=%g, rel=%g, y_exact=%g" % (err_abs,err_abs/exact(ts[-1]),exact(ts[-1]))
fenics_error=err_abs
print "Without fenics:"
ys = scipy.integrate.odeint(rhs, 1, ts)
err_abs = abs(ys[-1]-exact(ts[-1]))
print "Error: abs=%g, rel=%g, y_exact=%g" % (err_abs,err_abs/exact(ts[-1]),exact(ts[-1]))
non_fenics_error = float(err_abs)
print("Difference between fenics and non-fenics calculation: %g" % abs(fenics_error-non_fenics_error))
assert abs(fenics_error-non_fenics_error)<7e-15
#should also check that solution is the same on all mesh points
for i in range(ysfenics.shape[0]): #for all result rows
#each row contains the data at all mesh points for one t in ts
row = ysfenics[i,:]
number_range = abs(row.min()-row.max())
print "row: %d, time %f, range %g" % (i,ts[i],number_range)
assert number_range < 16e-15
#for debugging
if False:
from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed()
ipshell()
if False:
import pylab
pylab.plot(ts,ys,'o')
pylab.plot(ts,numpy.exp(-2*ts),'-')
pylab.show()
if __name__== "__main__":
test_scipy_uprime_integration_with_fenics()
| 3,572 | 28.528926 | 106 |
py
|
finmag
|
finmag-master/dev/sandbox/neb/neb_tests.py
|
import os
import dolfin as df
import matplotlib as mpl
#mpl.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import inspect
from neb import NEB_Sundials
#from finmag.physics.neb import plot_energy_3d
def plot_data_2d():
data = np.loadtxt('neb_energy.ndt')
fig=plt.figure()
xs = range(1, len(data[0,:]))
plt.plot(xs, data[-1,1:], '.-')
K = 1e4
a = 30
b = 10
c = 10
v = 4.0/3*np.pi*a*b*c*1e-27
expected_energy = K*v + np.min(data[-1,1:])
line_x = [xs[0],xs[-1]]
line_y = expected_energy*np.array([1,1])
#plt.plot(line_x, line_y, '-',label='expected')
plt.legend()
plt.grid()
fig.savefig('last_energy.pdf')
class Sim1(object):
"""
Two independent spins with different anisotropies.
"""
def energy(self,xs):
x = xs[0]
y = xs[1]
return np.sin(x)**2+2*np.sin(y)**2
def gradient(self, xs):
x = xs[0]
y = xs[1]
gx = -2*np.sin(x)*np.cos(x)
gy = -4*np.sin(y)*np.cos(y)
return np.array([gx, gy])
def Sim1Test():
init_images=[(0,0),(np.pi,np.pi)]
interpolations = [31]
sim = Sim1()
neb = NEB_Sundials(sim, init_images, interpolations, name='neb', spring=0.01)
neb.relax(max_steps=500, stopping_dmdt=1e-6)
plot_data_2d()
plot_energy_3d('neb_energy.ndt')
class Sim2(object):
"""
Two independent spins with different anisotropies but with four parameters
"""
def energy(self,xs):
x = xs[0]
y = xs[2]
return np.sin(x)**2+2*np.sin(y)**2
def gradient(self, xs):
x = xs[0]
y = xs[2]
gx = -2*np.sin(x)*np.cos(x)
gy = -4*np.sin(y)*np.cos(y)
return np.array([gx,0,gy,0])
def Sim2Test():
init_images=[(0,0,0,0),(np.pi,0,np.pi,0)]
interpolations = [31]
sim = Sim2()
neb = NEB_Sundials(sim, init_images, interpolations, name='neb', spring=0.5)
neb.relax(max_steps=500, stopping_dmdt=1e-6)
plot_data_2d()
plot_energy_3d('neb_energy.ndt')
class Sim3(object):
"""
One spin with two anisotropies
"""
def check(self,xs):
x = xs[0]
y = xs[1]
if x > np.pi:
xs[0] = np.pi
elif x<0:
xs[0]=0
if y > np.pi:
xs[1] -= 2*np.pi
elif y < -np.pi:
xs[1] += 2*np.pi
def energy(self,xs):
self.check(xs)
x = xs[0]
y = xs[1]
return np.sin(x)**2+2*np.sin(x)**2*np.sin(y)**2
def gradient(self, xs):
self.check(xs)
x = xs[0]
y = xs[1]
gx = -2*np.sin(x)*np.cos(x)*(1+2*np.sin(y)**2)
gy = -4*np.sin(y)*np.cos(y)*np.sin(x)**2
return np.array([gx, gy])
def Sim3Test():
init_images=[(0,0),(np.pi/2,np.pi/2-1.0),(np.pi,0)]
interpolations = [12,9]
sim = Sim3()
neb = NEB_Sundials(sim, init_images, interpolations, name='neb', spring=0.2)
neb.relax(max_steps=1000, stopping_dmdt=1e-6, dt=0.1)
plot_data_2d()
#plot_energy_3d('neb_energy.ndt')
class SimTwoSpins(object):
"""
Two spins but using Cartesian coordinates
"""
def energy(self,xs):
x = xs[0]
y = xs[3]
return -(x**2 + 2*y**2)
def gradient(self, xs):
x = xs[0]
y = xs[3]
gx = 2*x
gy = 4*y
return np.array([gx,0,0, gy,0,0])
def SimTwoSpinsTest():
init_images=[(-1,0,0,-1,0,0),(1,0,0,1,0,0)]
interpolations = [31]
sim = SimTwoSpins()
neb = NEB_Sundials(sim, init_images, interpolations, name='neb', spring=0.5, normalise=True)
neb.relax(max_steps=1000, stopping_dmdt=1e-8)
plot_data_2d()
plot_energy_3d('neb_energy.ndt')
class OneSpin(object):
"""
One spin with jump coordinate, for example, [3*pi/2, pi/2]
E = - K my^2 + Kp mz^2
"""
def energy(self,xs):
x = xs[0]
y = xs[1]
return -np.sin(x)**2*np.sin(y)**2 + 2*np.cos(x)**2
def gradient(self, xs):
x = xs[0]
y = xs[1]
gx = 2*np.sin(x)*np.cos(x)*(np.sin(y)**2 + 2)
gy = 2*np.sin(y)*np.cos(y)*np.sin(x)**2
return np.array([gx, gy])
def OneSpinTest():
xs1 = np.linspace(np.pi*3/2, 2*np.pi, 15, endpoint=False)
#xs1 = np.linspace(-np.pi/2, 0, 15, endpoint=False)
xs2 = np.linspace(0, np.pi/2, 15)
init_images = []
for i in range(len(xs1)):
init_images.append([np.pi/2-i*0.05, xs1[i]])
for i in range(len(xs2)):
init_images.append([np.pi/2-(len(xs2)-i-1)*0.05, xs2[i]])
sim = OneSpin()
neb = NEB_Sundials(sim, init_images, interpolations=None, name='neb', spring=0.01)
neb.relax(max_steps=5000, stopping_dmdt=1e-4)
plot_data_2d()
plot_energy_3d('neb_energy.ndt')
if __name__ == '__main__':
#OneSpinTest()
Sim3Test()
| 5,143 | 20.79661 | 96 |
py
|
finmag
|
finmag-master/dev/sandbox/neb/neb2_tests.py
|
import os
import dolfin as df
import matplotlib as mpl
#mpl.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from neb import NEB_Sundials
class Sim3(object):
"""
One spin with two anisotropies
"""
def check(self,xs):
x = xs[0]
y = xs[1]
if x > np.pi:
xs[0] = np.pi
elif x<0:
xs[0]=0
if y > np.pi:
xs[1] -= 2*np.pi
elif y < -np.pi:
xs[1] += 2*np.pi
def energy(self,xs):
self.check(xs)
x = xs[0]
y = xs[1]
return 1.0*np.sin(x)**2+2.0*np.sin(x)**2*np.sin(y)**2
def gradient(self, xs):
self.check(xs)
x = xs[0]
y = xs[1]
gx = -2.0*np.sin(x)*np.cos(x)*(1+2*np.sin(y)**2)
gy = -4.0*np.sin(y)*np.cos(y)*np.sin(x)**2
return np.array([gx, gy])
def Sim3Test():
init_images=[(0,0),(np.pi/2,np.pi/2-1),(np.pi,0)]
interpolations = [12,9]
sim = Sim3()
neb = NEB_Sundials(sim, init_images, interpolations, name='neb', spring=0)
neb.relax(max_steps=1000, stopping_dmdt=1e-6, dt=0.1)
if __name__ == '__main__':
Sim3Test()
| 1,294 | 17.239437 | 78 |
py
|
finmag
|
finmag-master/dev/sandbox/neb/neb2.py
|
import os
import dolfin as df
import numpy as np
import inspect
from aeon import default_timer
from finmag.native import sundials
import logging
log = logging.getLogger(name="finmag")
def normalise(a):
"""
normalise the n dimensional vector a
"""
x = a>np.pi
a[x] = 2*np.pi-a[x]
x = a<-np.pi
a[x] += 2*np.pi
length = np.linalg.norm(a)
if length>0:
length=1.0/length
a[:] *= length
def linear_interpolation_two_direct(m0, m1, n):
m0 = np.array(m0)
m1 = np.array(m1)
dm = 1.0*(m1 - m0)/(n+1)
coords=[]
for i in range(n):
m = m0+(i+1)*dm
coords.append(m)
return coords
def compute_dm(m0, m1):
dm = m0-m1
length = len(dm)
dm = np.sqrt(np.sum(dm**2))/length
return dm
def compute_tangents(y, images_energy, m_init, m_final, image_num):
y.shape = (image_num, -1)
tangents = np.zeros(y.shape)
for i in range(image_num):
if i==0:
m_a = m_init
else:
m_a = y[i-1]
if i == image_num-1:
m_b = m_final
else:
m_b = y[i+1]
energy_a = images_energy[i]
energy = images_energy[i+1]
energy_b = images_energy[i+2]
t1 = y[i] - m_a
t2 = m_b - y[i]
if energy_a<energy and energy<energy_b:
tangent = t2
elif energy_a>energy and energy>energy_b:
tangent = t1
else:
e1 = energy_a - energy
e2 = energy_b - energy
if abs(e1)>abs(e2):
max_e=abs(e1)
min_e=abs(e2)
else:
max_e=abs(e2)
min_e=abs(e1)
normalise(t1)
normalise(t2)
if energy_b > energy_a:
tangent = t1*min_e + t2*max_e
else:
tangent = t1*max_e + t2*min_e
normalise(tangent)
tangents[i,:]=tangent[:]
y.shape=(-1,)
tangents.shape=(-1,)
return tangents
class NEB_Sundials(object):
"""
Nudged elastic band method by solving the differential equation using Sundials.
"""
def __init__(self, sim, initial_images, interpolations=None, spring=0, name='unnamed'):
self.sim = sim
self.name = name
self.spring = spring
if interpolations is None:
interpolations=[0 for i in range(len(initial_images)-1)]
self.initial_images = initial_images
self.interpolations = interpolations
if len(interpolations)!=len(initial_images)-1:
raise RuntimeError("""the length of interpolations should equal to
the length of the initial_images minus 1, i.e.,
len(interpolations) = len(initial_images) -1""")
if len(initial_images)<2:
raise RuntimeError("""At least two images are needed to be provided.""")
self.image_num = len(initial_images) + sum(interpolations) - 2
self.nxyz = len(initial_images[0])
self.all_m = np.zeros(self.nxyz*self.image_num)
self.Heff = np.zeros(self.all_m.shape)
self.images_energy = np.zeros(self.image_num+2)
self.last_m = np.zeros(self.all_m.shape)
self.t = 0
self.step = 1
self.integrator=None
self.ode_count=1
self.initial_image_coordinates()
def initial_image_coordinates(self):
image_id = 0
self.all_m.shape=(self.image_num,-1)
for i in range(len(self.interpolations)):
n = self.interpolations[i]
m0 = self.initial_images[i]
if i!=0:
self.all_m[image_id][:]=m0[:]
image_id = image_id + 1
m1 = self.initial_images[i+1]
coords = linear_interpolation_two_direct(m0,m1,n)
for coord in coords:
self.all_m[image_id][:]=coord[:]
image_id = image_id + 1
self.m_init = self.initial_images[0]
self.images_energy[0] = self.sim.energy(self.m_init)
self.m_final = self.initial_images[-1]
self.images_energy[-1] = self.sim.energy(self.m_final)
for i in range(self.image_num):
self.images_energy[i+1]=self.sim.energy(self.all_m[i])
self.all_m.shape=(-1,)
print self.all_m
def create_integrator(self, reltol=1e-6, abstol=1e-6, nsteps=10000):
integrator = sundials.cvode(sundials.CV_BDF, sundials.CV_NEWTON)
integrator.init(self.sundials_rhs, 0, self.all_m)
integrator.set_linear_solver_sp_gmr(sundials.PREC_NONE)
integrator.set_scalar_tolerances(reltol, abstol)
integrator.set_max_num_steps(nsteps)
self.integrator = integrator
def compute_effective_field(self, y):
y.shape=(self.image_num, -1)
self.Heff.shape = (self.image_num,-1)
for i in range(self.image_num):
self.Heff[i,:] = self.sim.gradient(y[i])[:]
self.images_energy[i+1] = self.sim.energy(y[i])
y.shape=(-1,)
self.Heff.shape=(-1,)
def sundials_rhs(self, t, y, ydot):
if self.ode_count<3:
print '%0.20g'%t,y
self.ode_count+=1
default_timer.start("sundials_rhs", self.__class__.__name__)
self.compute_effective_field(y)
tangents = compute_tangents(y, self.images_energy, self.m_init, self.m_final, self.image_num)
y.shape=(self.image_num, -1)
ydot.shape=(self.image_num, -1)
self.Heff.shape = (self.image_num,-1)
tangents.shape = (self.image_num,-1)
for i in range(self.image_num):
h = self.Heff[i,:]
t = tangents[i,:]
h3 = h - np.dot(h,t)*t
ydot[i,:] = h3[:]
"""
The magic thing is that I will get different simulation result
if I uncomment the following line even it is isolated.
(good news is that it doesn't matter in alo)
"""
#never_used_variable_h3 = h - np.dot(h,t)*t
y.shape = (-1,)
self.Heff.shape=(-1,)
ydot.shape=(-1,)
default_timer.stop("sundials_rhs", self.__class__.__name__)
return 0
def run_until(self, t):
if t <= self.t:
return
self.integrator.advance_time(t, self.all_m)
m = self.all_m
y = self.last_m
m.shape=(self.image_num,-1)
y.shape=(self.image_num,-1)
max_dmdt=0
for i in range(self.image_num):
dmdt = compute_dm(y[i],m[i])/(t-self.t)
if dmdt>max_dmdt:
max_dmdt = dmdt
m.shape = (-1,)
y.shape = (-1,)
self.last_m[:] = m[:]
self.t=t
return max_dmdt
def relax(self, dt=1e-8, stopping_dmdt=1e4, max_steps=1000, save_ndt_steps=1, save_vtk_steps=100):
if self.integrator is None:
self.create_integrator()
log.debug("Relaxation parameters: stopping_dmdt={} (degrees per nanosecond), "
"time_step={} s, max_steps={}.".format(stopping_dmdt, dt, max_steps))
for i in range(max_steps):
cvode_dt = self.integrator.get_current_step()
increment_dt = dt
if cvode_dt > dt:
increment_dt = cvode_dt
dmdt = self.run_until(self.t+increment_dt)
log.debug("step: {:.3g}, step_size: {:.3g} and max_dmdt: {:.3g}.".format(self.step,increment_dt,dmdt))
if dmdt<stopping_dmdt:
break
self.step+=1
log.info("Relaxation finished at time step = {:.4g}, t = {:.2g}, call rhs = {:.4g} and max_dmdt = {:.3g}".format(self.step, self.t, self.ode_count, dmdt))
print self.all_m
| 8,806 | 26.266254 | 162 |
py
|
finmag
|
finmag-master/dev/sandbox/neb/neb.py
|
import os
import dolfin as df
import numpy as np
import inspect
from aeon import default_timer
import finmag.util.consts as consts
from finmag.util import helpers
from finmag.physics.effective_field import EffectiveField
from finmag.util.vtk_saver import VTKSaver
from finmag import Simulation
from finmag.native import sundials
from finmag.util.fileio import Tablewriter, Tablereader
import finmag.native.neb as native_neb
import logging
log = logging.getLogger(name="finmag")
ONE_DEGREE_PER_NS = 17453292.5 # in rad/s
def linear_interpolation_two_direct(m0, m1, n):
m0 = np.array(m0)
m1 = np.array(m1)
dm = 1.0*(m1 - m0)/(n+1)
coords=[]
for i in range(n):
m = m0+(i+1)*dm
coords.append(m)
return coords
def cartesian2spherical(xyz):
xyz.shape=(3,-1)
r_xy = np.sqrt(xyz[0,:]**2 + xyz[1,:]**2)
theta = np.arctan2(r_xy, xyz[2,:])
phi = np.arctan2(xyz[1,:], xyz[0,:])
xyz.shape=(-1,)
return theta,phi
def spherical2cartesian(theta, phi):
mxyz = np.zeros(3*len(theta))
mxyz.shape=(3,-1)
mxyz[0,:] = np.sin(theta)*np.cos(phi)
mxyz[1,:] = np.sin(theta)*np.sin(phi)
mxyz[2,:] = np.cos(theta)
mxyz.shape=(-1,)
return mxyz
def linear_interpolation_two(m0, m1, n):
m0 = np.array(m0)
m1 = np.array(m1)
theta0, phi0 = cartesian2spherical(m0)
theta1, phi1 = cartesian2spherical(m1)
dtheta = (theta1-theta0)/(n+1)
dphi = (phi1-phi0)/(n+1)
coords=[]
for i in range(n):
theta = theta0+(i+1)*dtheta
phi = phi0+(i+1)*dphi
coords.append(spherical2cartesian(theta,phi))
return coords
def compute_dm(m0, m1):
dm = m0-m1
length = len(dm)
dm = np.sqrt(np.sum(dm**2))/length
return dm
def normalise_m(a):
"""
normalise the magnetisation length.
"""
a.shape=(3, -1)
lengths = np.sqrt(a[0]*a[0] + a[1]*a[1] + a[2]*a[2])
a[:] /= lengths
a.shape=(-1, )
class NEB_Sundials(object):
"""
Nudged elastic band method by solving the differential equation using Sundials.
"""
def __init__(self, sim, initial_images, interpolations=None, spring=0, name='unnamed', normalise=False):
self.sim = sim
self.name = name
self.spring = spring
self.normalise = normalise
if interpolations is None:
interpolations=[0 for i in range(len(initial_images)-1)]
self.initial_images = initial_images
self.interpolations = interpolations
if len(interpolations)!=len(initial_images)-1:
raise RuntimeError("""the length of interpolations should equal to
the length of the initial_images minus 1, i.e.,
len(interpolations) = len(initial_images) -1""")
if len(initial_images)<2:
raise RuntimeError("""At least two images are needed to be provided.""")
self.image_num = len(initial_images) + sum(interpolations)
self.nxyz = len(initial_images[0])
self.all_m = np.zeros(self.nxyz*self.image_num)
self.Heff = np.zeros(self.nxyz*(self.image_num-2))
self.Heff.shape=(self.image_num-2, -1)
self.tangents = np.zeros(self.Heff.shape)
self.images_energy = np.zeros(self.image_num)
self.last_m = np.zeros(self.all_m.shape)
self.spring_force = np.zeros(self.image_num-2)
self.t = 0
self.step = 1
self.integrator=None
self.ode_count=1
self.initial_image_coordinates()
self.tablewriter = Tablewriter('%s_energy.ndt'%name, self, override=True)
self.tablewriter.entities = {
'step': {'unit': '<1>',
'get': lambda sim: sim.step,
'header': 'steps'},
'energy': {'unit': '<J>',
'get': lambda sim: sim.images_energy,
'header': ['image_%d'%i for i in range(self.image_num+2)]}
}
keys = self.tablewriter.entities.keys()
keys.remove('step')
self.tablewriter.entity_order = ['step'] + sorted(keys)
self.tablewriter_dm = Tablewriter('%s_dms.ndt'%name, self, override=True)
self.tablewriter_dm.entities = {
'step': {'unit': '<1>',
'get': lambda sim: sim.step,
'header': 'steps'},
'dms': {'unit': '<1>',
'get': lambda sim: sim.distances,
'header': ['image_%d_%d'%(i, i+1) for i in range(self.image_num+1)]}
}
keys = self.tablewriter_dm.entities.keys()
keys.remove('step')
self.tablewriter_dm.entity_order = ['step'] + sorted(keys)
def initial_image_coordinates(self):
image_id = 0
self.all_m.shape=(self.image_num,-1)
for i in range(len(self.interpolations)):
n = self.interpolations[i]
m0 = self.initial_images[i]
self.all_m[image_id][:]=m0[:]
image_id = image_id + 1
m1 = self.initial_images[i+1]
if self.normalise:
coords = linear_interpolation_two(m0,m1,n)
else:
coords = linear_interpolation_two_direct(m0,m1,n)
for coord in coords:
self.all_m[image_id][:]=coord[:]
image_id = image_id + 1
m2 = self.initial_images[-1]
self.all_m[image_id][:] = m2[:]
for i in range(self.image_num):
self.images_energy[i]=self.sim.energy(self.all_m[i])
self.all_m.shape=(-1,)
print self.all_m
self.create_integrator()
def save_npys(self):
directory='npys_%s_%d'%(self.name,self.step)
if not os.path.exists(directory):
os.makedirs(directory)
img_id = 1
self.all_m.shape=(self.image_num,-1)
for i in range(self.image_num):
name=os.path.join(directory,'image_%d.npy'%img_id)
np.save(name,self.all_m[i, :])
img_id += 1
self.all_m.shape=(-1,)
def create_integrator(self, reltol=1e-6, abstol=1e-6, nsteps=10000):
integrator = sundials.cvode(sundials.CV_BDF, sundials.CV_NEWTON)
integrator.init(self.sundials_rhs, 0, self.all_m)
integrator.set_linear_solver_sp_gmr(sundials.PREC_NONE)
integrator.set_scalar_tolerances(reltol, abstol)
integrator.set_max_num_steps(nsteps)
self.integrator = integrator
def compute_effective_field(self, y):
y.shape=(self.image_num, -1)
for i in range(1,self.image_num-1):
if self.normalise:
normalise_m(y[i])
self.Heff[i-1,:] = self.sim.gradient(y[i])
self.images_energy[i] = self.sim.energy(y[i])
y.shape=(-1,)
def compute_tangents(self, ys):
ys.shape=(self.image_num, -1)
native_neb.compute_tangents(ys,self.images_energy, self.tangents)
for i in range(1, self.image_num-1):
dm1 = compute_dm(ys[i-1], ys[i])
dm2 = compute_dm(ys[i+1], ys[i])
self.spring_force[i-1] = self.spring*(dm2-dm1)
ys.shape=(-1, )
def sundials_rhs(self, time, y, ydot):
self.ode_count+=1
default_timer.start("sundials_rhs", self.__class__.__name__)
self.compute_effective_field(y)
self.compute_tangents(y)
y.shape=(self.image_num, -1)
ydot.shape=(self.image_num, -1)
for i in range(1, self.image_num-1):
h = self.Heff[i-1]
t = self.tangents[i-1]
sf = self.spring_force[i-1]
h3 = h - np.dot(h,t)*t + sf*t
#h4 = h - np.dot(h,t)*t + sf*t
ydot[i,:] = h3[:]
#it turns out that the following two lines are very important
ydot[0,:] = 0
ydot[-1,:] = 0
y.shape = (-1,)
ydot.shape=(-1,)
default_timer.stop("sundials_rhs", self.__class__.__name__)
return 0
def compute_distance(self):
distance = []
y = self.all_m
y.shape=(self.image_num, -1)
for i in range(self.image_num-1):
dm = compute_dm(y[i], y[i+1])
distance.append(dm)
y.shape =(-1, )
self.distances=np.array(distance)
def run_until(self, t):
if t <= self.t:
return
self.integrator.advance_time(t, self.all_m)
m = self.all_m
y = self.last_m
m.shape=(self.image_num,-1)
y.shape=(self.image_num,-1)
max_dmdt=0
for i in range(self.image_num):
dmdt = compute_dm(y[i],m[i])/(t-self.t)
if dmdt>max_dmdt:
max_dmdt = dmdt
m.shape=(-1,)
y.shape=(-1,)
self.last_m[:] = m[:]
self.t=t
return max_dmdt
def relax(self, dt=1e-8, stopping_dmdt=1e4, max_steps=1000, save_ndt_steps=1, save_vtk_steps=100):
if self.integrator is None:
self.create_integrator()
log.debug("Relaxation parameters: stopping_dmdt={} (degrees per nanosecond), "
"time_step={} s, max_steps={}.".format(stopping_dmdt, dt, max_steps))
for i in range(max_steps):
cvode_dt = self.integrator.get_current_step()
increment_dt = dt
if cvode_dt > dt:
increment_dt = cvode_dt
dmdt = self.run_until(self.t+increment_dt)
if i%save_ndt_steps==0:
self.compute_distance()
self.tablewriter.save()
self.tablewriter_dm.save()
log.debug("step: {:.3g}, step_size: {:.3g} and max_dmdt: {:.3g}.".format(self.step,increment_dt,dmdt))
if dmdt<stopping_dmdt:
break
self.step+=1
log.info("Relaxation finished at time step = {:.4g}, t = {:.2g}, call rhs = {:.4g} and max_dmdt = {:.3g}".format(self.step, self.t, self.ode_count, dmdt))
self.save_npys()
print self.all_m
| 10,698 | 28.719444 | 162 |
py
|
finmag
|
finmag-master/dev/sandbox/two-cubes/run.py
|
import os
import numpy as np
import dolfin as df
from finmag.util.meshes import from_geofile
from finmag import Simulation
from finmag.energies import UniaxialAnisotropy, Exchange, Demag
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
mesh = from_geofile(os.path.join(MODULE_DIR, "two-cubes.geo"))
#df.plot(mesh)
#
#df.interactive()
Ms = 0.86e6 # saturation magnetisation A/m
A = 13.0e-12 # exchange coupling strength J/m
init = (0, 0.1, 1)
sim = Simulation(mesh, Ms, unit_length=1e-9)
sim.add(Demag())
sim.add(Exchange(A))
sim.set_m(init)
f=df.File(os.path.join(MODULE_DIR,'cubes.pvd')) #same more data for paraview
ns=1e-9
dt=0.01*ns
v=df.plot(sim.llg._m)
for time in np.arange(0,150.5*dt,dt):
print "time=",time,"m=",
print sim.llg.m_average
sim.run_until(time)
v.update(sim.llg._m)
f << sim.llg._m
df.interactive()
| 918 | 17.019608 | 79 |
py
|
finmag
|
finmag-master/dev/sandbox/new_native_code/__init__.py
| 0 | 0 | 0 |
py
|
|
finmag
|
finmag-master/dev/sandbox/new_saving_data/example.py
|
import savingdata as sd
import dolfin as df
import numpy as np
# Define mesh, functionspace, and functions.
mesh = df.UnitSquareMesh(5, 5)
fs = df.VectorFunctionSpace(mesh, 'CG', 1, 3)
f1 = df.Function(fs)
f2 = df.Function(fs)
f3 = df.Function(fs)
f1.assign(df.Constant((1, 1, 1)))
f2.assign(df.Constant((2, 2, 2)))
f3.assign(df.Constant((3, 1, 6)))
# Filenames. At the moment both npz and json files are implemented.
h5filename = 'hdf5file.h5'
jsonfilename = 'jsonfile.json'
# SAVING DATA.
sdata = sd.SavingData(h5filename, jsonfilename, fs)
sdata.save_mesh(name='mesh')
sdata.save_field(f1, 'm', t=0)
sdata.save_field(f2, 'm', t=1e-12)
sdata.save_field(f3, 'm', t=2e-12)
# Temporarily disable close. Problems on virtual machine.
#sdata.close()
# LOADING DATA.
ldata = sd.LoadingData(h5filename, jsonfilename)
meshl = ldata.load_mesh(name='mesh')
f1l = ldata.load_field(field_name='m', t=0)
f2l = ldata.load_field(field_name='m', t=1e-12)
f3l = ldata.load_field(field_name='m', t=2e-12)
# ASSERTIONS. Is the saved data the same as loaded.
assert np.all(mesh.coordinates() == meshl.coordinates())
assert np.all(f1l.vector().array() == f1.vector().array())
assert np.all(f2l.vector().array() == f2.vector().array())
assert np.all(f3l.vector().array() == f3.vector().array())
| 1,293 | 22.962963 | 67 |
py
|
finmag
|
finmag-master/dev/sandbox/new_saving_data/savingdata_test.py
|
import dolfin as df
import numpy as np
import json
from collections import OrderedDict
from savingdata import SavingData, LoadingData
h5filename = 'file.h5'
jsonfilename = 'file.json'
mesh = df.UnitSquareMesh(10, 10)
functionspace = df.VectorFunctionSpace(mesh, 'CG', 1, 3)
f = df.Function(functionspace)
t_array = np.linspace(0, 1e-9, 5)
def test_save_data():
sd = SavingData(h5filename, jsonfilename, functionspace)
sd.save_mesh()
for i in range(len(t_array)):
f.assign(df.Constant((t_array[i], 0, 0)))
sd.save_field(f, 'f', t_array[i])
sd.close()
def test_load_data():
ld = LoadingData(h5filename, jsonfilename)
for t in t_array:
f_loaded = ld.load_field('f', t)
f.assign(df.Constant((t, 0, 0)))
assert np.all(f.vector().array() == f_loaded.vector().array())
ld.close()
def test_saved():
with open(jsonfilename) as jsonfile:
jsonData = json.load(jsonfile, object_pairs_hook=OrderedDict)
jsonfile.close()
# assert times from keys
for i, t in enumerate(t_array):
name = "f{}".format(i)
jsonTime = jsonData['f'][name]
assert(jsonTime == t)
# assert times by iterating through values (as they should be ordered)
index = 0
for jsonTime in jsonData['f'].itervalues():
assert(jsonTime == t_array[index])
index += 1
| 1,379 | 22.793103 | 74 |
py
|
finmag
|
finmag-master/dev/sandbox/new_saving_data/savingdata.py
|
import dolfin as df
import numpy as np
import json
from collections import OrderedDict
class SavingData(object):
def __init__(self, h5filename, jsonfilename, functionspace):
self.functionspace = functionspace
self.h5filename = h5filename
self.jsonfilename = jsonfilename
self.h5file = df.HDF5File(df.mpi_comm_world(), self.h5filename, 'w')
self.field_index = 0
self.t_array = []
self.fieldsDict = {} # dictionary of all field types e.g. 'm', 'H_eff'
# create json file
with open(self.jsonfilename, 'w') as jsonfile:
json.dump(self.fieldsDict, jsonfile, sort_keys=False)
jsonfile.close()
def save_mesh(self, name='mesh'):
self.h5file.write(self.functionspace.mesh(), name)
def save_field(self, f, field_name, t):
name = field_name + str(self.field_index)
self.h5file.write(f, name)
self.t_array.append(t)
if not self.fieldsDict.has_key(field_name):
self.fieldsDict[field_name] = OrderedDict()
self.fieldsDict[field_name][name] = t
self.fieldsDict['fs_family'] = self.functionspace.ufl_element().family()
self.fieldsDict['dim'] = self.functionspace.ufl_element().value_shape()[0]
with open(self.jsonfilename, 'w') as jsonfile:
json.dump(self.fieldsDict, jsonfile, sort_keys=False)
jsonfile.close()
self.field_index += 1
def close(self):
self.h5file.close()
class LoadingData(object):
def __init__(self, h5filename, jsonfilename):
self.h5filename = h5filename
self.jsonfilename = jsonfilename
self.h5file = df.HDF5File(df.mpi_comm_world(), self.h5filename, 'r')
with open(self.jsonfilename) as jsonfile:
fieldsDict = json.load(jsonfile, object_pairs_hook=OrderedDict)
jsonfile.close()
self.mesh = self.load_mesh()
self.fs_family = fieldsDict['fs_family']
self.dim = fieldsDict['dim']
self.functionspace = df.VectorFunctionSpace(self.mesh, self.fs_family,
1, self.dim)
def load_mesh(self, name='mesh'):
mesh_loaded = df.Mesh()
self.h5file.read(mesh_loaded, name, False)
return mesh_loaded
def load_field(self, field_name, t):
with open(self.jsonfilename) as jsonfile:
fieldsDict = json.load(jsonfile, object_pairs_hook=OrderedDict)
jsonfile.close()
name = str([item[0] for item in fieldsDict[field_name].items() if item[1]==t][0])
f_loaded = df.Function(self.functionspace)
# This line causes segmentation fault.
self.h5file.read(f_loaded, name)
return f_loaded
def close(self):
self.h5file.close()
| 2,853 | 29.688172 | 89 |
py
|
finmag
|
finmag-master/dev/sandbox/domains/use_regions.py
|
import dolfin as df
#
# The mesh contains two regions.
# region 1: A disk (cylinder).
# region 2: The cuboid around the disk.
#
mesh = df.Mesh("embedded_disk.xml.gz")
regions = df.MeshFunction("uint", mesh, "embedded_disk_mat.xml")
#
# Example 1
# Compute the volume of the regions and the total mesh.
#
dxx = df.dx[regions] # is this following "best practices" ?
volume_disk = df.assemble(df.Constant(1) * dxx(1), mesh=mesh)
volume_cuboid = df.assemble(df.Constant(1) * dxx(2), mesh=mesh)
print "Volume of the embedded disk: v1 = {}.".format(volume_disk)
print "Volume of the medium around it: v2 = {}.".format(volume_cuboid)
volume_total = df.assemble(df.Constant(1) * df.dx, mesh=mesh)
print "Total volume: vtot = {}. Same as v1 + v2 = {}.".format(
volume_total, volume_disk + volume_cuboid)
#
# Example 2
# Have a material value that is different on the two regions.
#
k_values = [10, 100]
DG0 = df.FunctionSpace(mesh, "DG", 0)
k = df.Function(DG0)
# Will this work with the new ordering introduced in dolfin-1.1.0?
# (dofs ordering won't correspond to geometry anymore)
for cell_no, region_no in enumerate(regions.array()):
k.vector()[cell_no] = k_values[region_no - 1]
#
# Example 3
# FunctionSpaces defined on regions instead of the whole mesh.
#
disk_mesh = df.SubMesh(mesh, regions, 1)
CG1_disk = df.FunctionSpace(disk_mesh, "Lagrange", 1)
cuboid_mesh = df.SubMesh(mesh, regions, 2)
CG1_cuboid = df.FunctionSpace(cuboid_mesh, "Lagrange", 1)
#
# Visualise the different regions and the values of k
#
k_CG1 = df.interpolate(k, df.FunctionSpace(mesh, "CG", 1))
k_disk = df.project(k, CG1_disk)
k_cuboid = df.project(k, CG1_cuboid)
df.common.plotting.Viper.write_png(df.plot(k), "k_DG0.png")
df.common.plotting.Viper.write_png(df.plot(k_CG1), "k_interpolated_CG1.png")
df.common.plotting.Viper.write_png(df.plot(k_disk), "k_projected_disk.png")
df.common.plotting.Viper.write_png(df.plot(k_cuboid), "k_projected_cuboid.png")
| 1,960 | 28.268657 | 79 |
py
|
finmag
|
finmag-master/dev/sandbox/domains/import_mesh.py
|
from finmag.util.meshes import from_geofile
from_geofile("embedded_disk.geo")
| 79 | 19 | 43 |
py
|
finmag
|
finmag-master/dev/sandbox/treecode/setup.py
|
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
import os
#python setup.py build_ext --inplace
#NFFT_DIR = os.path.expanduser('~/nfft-3.2.0')
ext_modules = [
Extension("fastsum_lib",
sources = ['fast_sum.c','fast_sum_lib.pyx'],
include_dirs = [numpy.get_include()],
libraries=['m','gomp'],
extra_compile_args=["-fopenmp"],
#extra_link_args=["-g"],
)
]
setup(
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)
| 602 | 22.192308 | 58 |
py
|
finmag
|
finmag-master/dev/sandbox/treecode/test_fast_sum.py
|
import dolfin as df
import numpy as np
import time
from fastsum_lib import FastSum
def exact(xs,xt,charge):
res=np.zeros(len(xt))
for j in range(len(xt)):
for k in range(len(xs)):
r=np.sqrt((xt[j,0]-xs[k,0])**2+(xt[j,1]-xs[k,1])**2+(xt[j,2]-xs[k,2])**2)
res[j]+=1.0*charge[k]/r
return res
if __name__ == '__main__':
x0 = y0 = z0 = 0
x1 = 1
y1 = 1
z1 = 1
nx = 25
ny = 25
nz = 25
mesh = df.Box(x0, y0, z0, x1, y1, z1, nx, ny, nz)
n = 20
mesh = df.UnitCubeMesh(n, n, n)
mesh.coordinates()[:]*=1e-1
number=mesh.num_vertices()
print 'vertices number:',number
xs=mesh.coordinates()
n=10
mesh = df.UnitCubeMesh(n, n, n)
mesh.coordinates()[:]*=1e-1
xt=mesh.coordinates()
number=mesh.num_vertices()
print 'target number:',number
#density=np.array([1,2,3,4,5,6,7,8])*1.0
fast_sum=FastSum(p=6,mac=0.5,num_limit=500)
#xs=np.array([(2,7,0),(6.5,9,0),(6,8,0),(8,7,0),(4.9,4.9,0),(2,1,0),(4,2,0),(7,2,0)])*0.1
#xt=np.array([(0,0,0)])*0.1
density=np.random.random(len(xs))+1
print xs,'\n',xt,'\n',density
fast_sum.init_mesh(xs,xt)
print xt
fast_sum.update_charge(density)
print density
exact=np.zeros(len(xt))
fast=np.zeros(len(xt))
start=time.time()
fast_sum.fastsum(fast)
stop=time.time()
print 'fast time:',stop-start
print 'fast\n',fast
start=time.time()
fast_sum.exactsum(exact)
stop=time.time()
print 'exact time:',stop-start
print 'exact\n',exact
diff=np.abs(fast-exact)/exact
print 'max:',np.max(diff)
print diff
print 'direct diff:\n',np.abs(fast-exact)
| 1,833 | 20.833333 | 97 |
py
|
finmag
|
finmag-master/dev/sandbox/treecode/compare.py
|
import dolfin as df
import numpy as np
from finmag.native import sundials
from finmag.util.timings import default_timer
from finmag.energies import Demag
if __name__ == '__main__':
x0 = y0 = z0 = 0
x1 = 500e-9
y1 = 500e-9
z1 = 2e-9
nx = 120
ny = 120
nz = 3
mesh = df.Box(x0, y0, z0, x1, y1, z1, nx, ny, nz)
print mesh.num_vertices()
Vv = df.VectorFunctionSpace(mesh, 'Lagrange', 1)
Ms = 8.6e5
expr = df.Expression(('1+x[0]', '1+2*x[1]','1+3*x[2]'))
m = df.project(expr, Vv)
m = df.project(df.Constant((1, 0, 0)), Vv)
demag = Demag("FK")
demag.setup(Vv, m, Ms)
demag.compute_field()
print default_timer
| 680 | 20.967742 | 59 |
py
|
finmag
|
finmag-master/dev/sandbox/treecode/fastdemag.py
|
from dolfin import *
import dolfin as df
import numpy as np
import time
from fastsum_lib import FastSum
import cProfile
_nodes =(
(0.,),
(-0.5773502691896257,
0.5773502691896257),
(-0.7745966692414834,
0.,
0.7745966692414834),
(-0.861136311594053,
-0.3399810435848562,
0.3399810435848562,
0.861136311594053),
(-0.906179845938664,
-0.5384693101056829,
0.,
0.5384693101056829,
0.906179845938664))
_weights=(
(2.,),
(1.,
1.),
(0.5555555555555553,
0.888888888888889,
0.5555555555555553),
(0.3478548451374539,
0.6521451548625462,
0.6521451548625462,
0.3478548451374539),
(0.2369268850561887,
0.4786286704993665,
0.5688888888888889,
0.4786286704993665,
0.2369268850561887))
dunavant_x=(
(0.333333333333333,),
(0.666666666666667,0.166666666666667,0.166666666666667),
(0.333333333333333,0.600000000000000,0.200000000000000,0.200000000000000),
(0.108103018168070,0.445948490915965,0.445948490915965,0.816847572980459,0.091576213509771,0.091576213509771)
)
dunavant_y=(
(0.333333333333333,),
(0.166666666666667,0.166666666666667,0.666666666666667),
(0.333333333333333,0.200000000000000,0.200000000000000,0.600000000000000),
(0.445948490915965,0.445948490915965,0.108103018168070,0.091576213509771,0.091576213509771,0.816847572980459)
)
dunavant_w=(
(1.0,),
(0.333333333333333,0.333333333333333,0.333333333333333),
(-0.562500000000000,0.520833333333333,0.520833333333333,0.520833333333333),
(0.223381589678011,0.223381589678011,0.223381589678011,0.109951743655322,0.109951743655322,0.109951743655322)
)
dunavant_n=[1,2,3,6]
tet_x=(
(0.25,),
(0.1381966011250110,0.5854101966249680,0.1381966011250110,0.1381966011250110)
)
tet_y=(
(0.25,),
(0.1381966011250110,0.1381966011250110,0.5854101966249680,0.1381966011250110)
)
tet_z=(
(0.25,),
(0.1381966011250110,0.1381966011250110,0.1381966011250110,0.5854101966249680)
)
tet_w=(
(1.0,),
(0.25,0.25,0.25,0.25)
)
def length(p1,p2):
return np.sqrt((p1[0]-p2[0])**2+(p1[1]-p2[1])**2+(p1[2]-p2[2])**2)
def length2(p1,p2):
return (p1[0]-p2[0])**2+(p1[1]-p2[1])**2+(p1[2]-p2[2])**2
def G(r1,r2):
r=length(r1,r2)
if r<1e-12:
print 'hahahahahahahhahahahah'
return 0
return 1.0/(r)
def compute_area(p1,p2,p3):
a=length(p1,p2)
b=length(p1,p3)
c=length(p2,p3)
s=(a+b+c)/2.0
return np.sqrt(s*(s-a)*(s-b)*(s-c))
def compute_cell_volume(mesh):
V = df.FunctionSpace(mesh, 'DG', 0)
v = df.TestFunction(V)
tet_vol=df.assemble(v * df.dx)
return tet_vol.array()
def compute_minus_node_volume_vector(mesh):
V=VectorFunctionSpace(mesh, 'Lagrange', 1)
v = df.TestFunction(V)
node_vol= df.assemble(df.dot(v,
df.Constant([-1,-1,-1])) * df.dx)
return node_vol.array()
def compute_node_volume(mesh):
V=FunctionSpace(mesh, 'Lagrange', 1)
v = df.TestFunction(V)
node_vol= df.assemble(v * df.dx)
return node_vol.array()
def compute_node_area(mesh):
V=FunctionSpace(mesh, 'Lagrange', 1)
v = df.TestFunction(V)
node_area = df.assemble(v * df.ds)
tmp=node_area.array()
print 'area is: ',sum(tmp)
for i in range(len(tmp)):
if tmp[i]==0:
tmp[i]=1
return tmp
def compute_det(x1,y1,z1,x2,y2,z2,x3,y3,z3):
J1=(x2-x1)*(z3-z1)-(x3-x1)*(z2-z1)
J2=(x2-x1)*(y3-y1)-(x3-x1)*(y2-y1)
J3=(y2-y1)*(z3-z1)-(y3-y1)*(z2-z1)
return J1,J2,J3
def compute_correction_simplified(sa,sb,sc,p1,p2,p3):
x1,y1,z1=p1
x2,y2,z2=p2
x3,y3,z3=p3
J1,J2,J3=compute_det(x1,y1,z1,x2,y2,z2,x3,y3,z3)
r1=np.sqrt((x2-x1)**2+(y2-y1)**2+(z2-z1)**2)
r2=np.sqrt((x3-x1)**2+(y3-y1)**2+(z3-z1)**2)
r3=np.sqrt((x3-x2)**2+(y3-y2)**2+(z3-z2)**2)
fa=np.sqrt(J1*J1+J2*J2+J3*J3)
fb=(sb-sc)*(r1-r2)/(2*r3*r3)
fc=(sb+sc+2*sa)/(4.0*r3)+(r2*r2-r1*r1)*(sb-sc)/(4.0*r3**3)
fd=np.log(r1+r2+r3)-np.log(r1+r2-r3)
return fa*(fb+fc*fd)
class FastDemag():
def __init__(self,Vv, m, Ms,triangle_p=1,tetrahedron_p=0,p=6,mac=0.5):
self.m=m
self.Vv=Vv
self.Ms=Ms
self.triangle_p=triangle_p
self.tetrahedron_p=tetrahedron_p
self.mesh=Vv.mesh()
self.V=FunctionSpace(self.mesh, 'Lagrange', 1)
self.phi = Function(self.V)
self.phi_charge = Function(self.V)
self.field = Function(self.Vv)
u = TrialFunction(self.V)
v = TestFunction(self.Vv)
a = inner(grad(u), v)*dx
self.G = df.assemble(a)
self.L = compute_minus_node_volume_vector(self.mesh)
#self.compute_gauss_coeff_triangle()
#self.compute_gauss_coeff_tetrahedron()
#self.compute_affine_transformation_surface()
#self.compute_affine_transformation_volume()
#self.nodes=np.array(self.s_nodes+self.v_nodes)
#self.weights=np.array(self.s_weight+self.v_weight)
#self.charges=np.array(self.s_charge+self.v_charge)
self.compute_triangle_normal()
fast_sum=FastSum(p=p,mac=mac,num_limit=500,triangle_p=triangle_p,tetrahedron_p=tetrahedron_p)
xt=self.mesh.coordinates()
tet_nodes=np.array(self.mesh.cells(),dtype=np.int32)
fast_sum.init_mesh(xt,self.t_normals,self.face_nodes_array,tet_nodes)
self.fast_sum=fast_sum
self.res=np.zeros(len(self.mesh.coordinates()))
def compute_gauss_coeff_triangle(self):
n=self.triangle_p
self.s_x=dunavant_x[n]
self.s_y=dunavant_y[n]
self.s_w=np.array(dunavant_w[n])/2.0
print self.s_x,self.s_y
def compute_gauss_coeff_tetrahedron(self):
n=self.tetrahedron_p
self.v_x=tet_x[n]
self.v_y=tet_y[n]
self.v_z=tet_z[n]
self.v_w=np.array(tet_w[n])/6.0
def compute_triangle_normal(self):
self.face_nodes=[]
self.face_norms=[]
self.t_normals=[]
for face in df.faces(self.mesh):
t=face.normal() #one must call normal() before entities(3),...
cells = face.entities(3)
if len(cells)==1:
face_nodes=face.entities(0)
self.face_nodes.append(face_nodes)
self.face_norms.append(t)
self.t_normals.append([t.x(),t.y(),t.z()])
self.t_normals=np.array(self.t_normals)
self.face_nodes_array=np.array(self.face_nodes,dtype=np.int32)
def compute_affine_transformation_surface(self):
m=self.m.vector().array()
m=m.reshape((-1,3),order='F')
cs=self.mesh.coordinates()
self.face_nodes=[]
self.face_norms=[]
self.t_normals=[]
for face in df.faces(self.mesh):
t=face.normal() #one must call normal() before entities(3),...
cells = face.entities(3)
if len(cells)==1:
face_nodes=face.entities(0)
self.face_nodes.append(face_nodes)
self.face_norms.append(t)
self.t_normals.append([t.x(),t.y(),t.z()])
self.t_normals=np.array(self.t_normals)
self.face_nodes_array=np.array(self.face_nodes,dtype=np.int32)
self.s_nodes=[]
self.s_weight=[]
self.s_charge=[]
def compute_det_xy(x1,y1,z1,x2,y2,z2,x3,y3,z3):
a = y2*z1 - y3*z1 - y1*z2 + y3*z2 + y1*z3 - y2*z3
b = x2*z1 - x3*z1 - x1*z2 + x3*z2 + x1*z3 - x2*z3
c = x2*y1 - x3*y1 - x1*y2 + x3*y2 + x1*y3 - x2*y3
det=abs((x2-x1)*(y3-y1)-(x3-x1)*(y2-y1))
det*=np.sqrt((a*a+b*b)/(c*c)+1)
return det
for i in range(len(self.face_nodes)):
f_c=self.face_nodes[i]
x1,y1,z1=cs[f_c[0]]
x2,y2,z2=cs[f_c[1]]
x3,y3,z3=cs[f_c[2]]
c11=x2-x1
c12=x3-x1
c21=y2-y1
c22=y3-y1
c31=z2-z1
c32=z3-z1
t=self.face_norms[i]
if abs(t.z())>abs(t.x()) and abs(t.z())>abs(t.y()):
det=compute_det_xy(x1,y1,z1,x2,y2,z2,x3,y3,z3)
elif abs(t.y())>abs(t.x()):
det=compute_det_xy(z1,x1,y1,z2,x2,y2,z3,x3,y3)
else:
det=compute_det_xy(y1,z1,x1,y2,z2,x2,y3,z3,x3)
sa=(m[f_c[0]][0]*t.x()+m[f_c[0]][1]*t.y()+m[f_c[0]][2]*t.z())
sb=(m[f_c[1]][0]*t.x()+m[f_c[1]][1]*t.y()+m[f_c[1]][2]*t.z())
sc=(m[f_c[2]][0]*t.x()+m[f_c[2]][1]*t.y()+m[f_c[2]][2]*t.z())
for j in range(len(self.s_x)):
x=c11*self.s_x[j]+c12*self.s_y[j]+x1
y=c21*self.s_x[j]+c22*self.s_y[j]+y1
z=c31*self.s_x[j]+c32*self.s_y[j]+z1
self.s_nodes.append([x,y,z])
self.s_weight.append(det*self.s_w[j])
self.s_charge.append(sa+(sb-sa)*self.s_x[j]+(sc-sa)*self.s_y[j])
def compute_affine_transformation_volume(self):
v = TestFunction(self.V)
K = df.assemble(df.div(self.m) * v * df.dx)
L = df.assemble(v * df.dx)
rho = K.array()/L.array()
cs=self.mesh.coordinates()
m=self.m.vector().array()
n=len(m)/3
def compute_divergence(cell):
i=cell.entities(0)
x1,y1,z1=cs[i[1]]-cs[i[0]]
x2,y2,z2=cs[i[2]]-cs[i[0]]
x3,y3,z3=cs[i[3]]-cs[i[0]]
m0 = np.array([m[i[0]],m[i[0]+n],m[i[0]+2*n]])
m1 = np.array([m[i[1]],m[i[1]+n],m[i[1]+2*n]]) - m0
m2 = np.array([m[i[2]],m[i[2]+n],m[i[2]+2*n]]) - m0
m3 = np.array([m[i[3]],m[i[3]+n],m[i[3]+2*n]]) - m0
a1 = [y3*z2 - y2*z3, -x3*z2 + x2*z3, x3*y2 - x2*y3]
a2 = [-y3*z1 + y1*z3, x3*z1 - x1*z3, -x3*y1 + x1*y3]
a3 = [y2*z1 - y1*z2, -x2*z1 + x1*z2, x2*y1 - x1*y2]
v = x3*y2*z1 - x2*y3*z1 - x3*y1*z2 + x1*y3*z2 + x2*y1*z3 - x1*y2*z3
tmp=0
for j in range(3):
tmp += a1[j]*m1[j]+a2[j]*m2[j]+a3[j]*m3[j]
tmp=-1.0*tmp/v
return tmp,abs(v)
self.v_nodes=[]
self.v_weight=[]
self.v_charge=[]
for cell in df.cells(self.mesh):
i=cell.entities(0)
rho,det=compute_divergence(cell)
x0,y0,z0=cs[i[0]]
c11,c12,c13=cs[i[1]]-cs[i[0]]
c21,c22,c23=cs[i[2]]-cs[i[0]]
c31,c32,c33=cs[i[3]]-cs[i[0]]
for j in range(len(self.v_w)):
x=c11*self.v_x[j]+c21*self.v_y[j]+c31*self.v_z[j]+x0
y=c12*self.v_x[j]+c22*self.v_y[j]+c32*self.v_z[j]+y0
z=c13*self.v_x[j]+c23*self.v_y[j]+c33*self.v_z[j]+z0
self.v_charge.append(rho)
self.v_nodes.append([x,y,z])
self.v_weight.append(det*self.v_w[j])
def sum_directly(self):
cs=self.mesh.coordinates()
m=len(cs)
n=len(self.nodes)
res=np.zeros(m)
for i in range(m):
for j in range(n):
res[i]+=G(cs[i],self.nodes[j])*self.weights[j]*self.charges[j]
print 'directly',res
self.phi.vector().set_local(res)
def compute_field(self):
m=self.m.vector().array()
self.fast_sum.update_charge(m)
self.fast_sum.fastsum(self.res)
#self.fast_sum.exactsum(res)
self.fast_sum.compute_correction(m,self.res)
self.phi.vector().set_local(self.res)
self.phi.vector()[:]*=(self.Ms/(4*np.pi))
demag_field = self.G * self.phi.vector()
return demag_field.array()/self.L
class Demag():
def __init__(self,triangle_p=1,tetrahedron_p=1,p=3,mac=0.3,num_limit=100):
self.triangle_p=triangle_p
self.tetrahedron_p=tetrahedron_p
self.p=p
self.mac=mac
self.num_limit=num_limit
self.in_jacobian=False
def setup(self,Vv,m,Ms,unit_length=1):
self.m=m
self.Vv=Vv
self.Ms=Ms
self.mesh=Vv.mesh()
self.find_max_d()
self.mesh.coordinates()[:]/=self.max_d
self.V=FunctionSpace(self.mesh, 'Lagrange', 1)
self.phi = Function(self.V)
self.phi_charge = Function(self.V)
self.field = Function(self.Vv)
u = TrialFunction(self.V)
v = TestFunction(self.Vv)
a = inner(grad(u), v)*dx
self.G = df.assemble(a)
self.L = compute_minus_node_volume_vector(self.mesh)
self.compute_triangle_normal()
fast_sum=FastSum(p=self.p,mac=self.mac,num_limit=self.num_limit,\
triangle_p=self.triangle_p,tetrahedron_p=self.tetrahedron_p)
xt=self.mesh.coordinates()
tet_nodes=np.array(self.mesh.cells(),dtype=np.int32)
fast_sum.init_mesh(xt,self.t_normals,self.face_nodes_array,tet_nodes)
self.fast_sum=fast_sum
self.res=np.zeros(len(self.mesh.coordinates()))
self.mesh.coordinates()[:]*=self.max_d
def compute_triangle_normal(self):
self.face_nodes=[]
self.face_norms=[]
self.t_normals=[]
for face in df.faces(self.mesh):
t=face.normal() #one must call normal() before entities(3),...
cells = face.entities(3)
if len(cells)==1:
face_nodes=face.entities(0)
self.face_nodes.append(face_nodes)
self.face_norms.append(t)
self.t_normals.append([t.x(),t.y(),t.z()])
self.t_normals=np.array(self.t_normals)
self.face_nodes_array=np.array(self.face_nodes,dtype=np.int32)
def find_max_d(self):
xt=self.mesh.coordinates()
max_v=xt.max(axis=0)
min_v=xt.min(axis=0)
max_d=max(max_v-min_v)
self.max_d=max_d
def compute_field(self):
m=self.m.vector().array()
self.fast_sum.update_charge(m)
self.fast_sum.fastsum(self.res)
self.fast_sum.compute_correction(m,self.res)
self.phi.vector().set_local(self.res)
self.phi.vector()[:]*=(self.Ms/(4*np.pi))
demag_field = self.G * self.phi.vector()
return demag_field.array()/self.L
if __name__ == "__main__":
n=10
#mesh = UnitCubeMesh(n, n, n)
#mesh = Box(-1, 0, 0, 1, 1, 1, 10, 2, 2)
mesh = UnitSphere(5)
mesh.coordinates()[:]*=1
Vv = df.VectorFunctionSpace(mesh, 'Lagrange', 1)
Ms = 8.6e5
#expr = df.Expression(('cos(x[0])', 'sin(x[0])','0'))
m = interpolate(Constant((1, 0, 0)), Vv)
demag=Demag(triangle_p=1,tetrahedron_p=1,mac=0)
demag.setup(Vv,m,Ms)
demag.compute_field()
print '='*100,'exact\n',demag.res
exact=demag.res
for p in [2,3,4,5,6,7]:
demag=Demag(triangle_p=1,tetrahedron_p=1,mac=0.4,p=p)
demag.setup(Vv,m,Ms)
demag.compute_field()
print '='*100,'mac=0.4 p=%d\n'%p,np.average(np.abs((demag.res-exact)/exact))
| 15,200 | 26.994475 | 114 |
py
|
finmag
|
finmag-master/dev/sandbox/treecode/__init__.py
| 0 | 0 | 0 |
py
|
|
finmag
|
finmag-master/dev/sandbox/fkdemag_solver_benchmark/post_processing.py
|
import numpy as np
import dolfin as df
import matplotlib.pyplot as plt
def column_chart(results, solvers, preconditioners, offset=None, ymax=10):
slowest = results.max(0)
fastest = results.min(0)
default = results[0]
no_prec = results[1]
fig = plt.figure(figsize=(8, 4))
ax = fig.add_subplot(111)
width = 0.2
ind = np.arange(len(solvers))
ax.axhline(results[0, 0], color=(0.3, 0.3, 0.3), ls=":", zorder=0)
rects_fastest = ax.bar(ind, fastest, width, color="green", label="fastest prec.")
ax.bar(width + ind, default, width, color=(0.3, 0.3, 0.3), label="default prec.")
ax.bar(2 * width + ind, no_prec, width, color=(0.8, 0.8, 0.8), label="no prec.")
ax.bar(3 * width + ind, slowest, width, color="red", label="slowest prec.")
# annotate fastest runs with name of preconditioner
fastest_ind = results.argmin(0)
for i, rect in enumerate(rects_fastest):
height = rect.get_height()
offset = offset if offset is not None else 1.05 * height
ax.text(rect.get_x() + rect.get_width() / 2.0, height + offset,
preconditioners[fastest_ind[i]],
ha='center', va='bottom', rotation=90)
ax.set_xlabel("method")
ax.set_ylabel("time (ms)")
ax.set_ylim((0, ymax))
ax.legend()
ax.set_xticks(ind + 2 * width)
xtickNames = plt.setp(ax, xticklabels=solvers)
plt.setp(xtickNames, rotation=0)
return fig
if __name__ == "__main__":
ms = 1e3
solvers = [s[0] for s in df.krylov_solver_methods()]
preconditioners = [p[0] for p in df.krylov_solver_preconditioners()]
ymax = [[6, 6], [6, 10]]
for i, system in enumerate(["ball", "film"]):
for j, potential in enumerate(["1", "2"]):
results = ms * np.ma.load(system + "_" + potential + ".pickle")
with open(system + "_" + potential + ".txt", "w") as f:
f.write("& {} \\\\\n".format(" & ".join(solvers)))
f.write("\\hline\n")
for pi, p in enumerate(preconditioners):
numbers = ["{:.3}".format(r) for r in results[pi]]
f.write("{} & {} \\\\\n".format(p, " & ".join(numbers)))
fig = column_chart(results, solvers, preconditioners, offset=0.2, ymax=ymax[i][j])
plt.savefig(system + "_" + potential + ".png")
plt.close()
| 2,372 | 38.55 | 94 |
py
|
finmag
|
finmag-master/dev/sandbox/fkdemag_solver_benchmark/benchmark.py
|
import dolfin as df
import numpy as np
import finmag.energies.demag.fk_demag as fk
from finmag.util.helpers import vector_valued_function
from finmag.native.llg import compute_bem_fk
from aeon import default_timer
def prepare_demag(S3, m, Ms, unit_length, s_param, solver, p_param, preconditioner, bem, boundary_to_global):
demag = fk.FKDemag()
if bem is not None:
# Use the precomputed BEM if it was provided.
demag.precomputed_bem(bem, boundary_to_global)
demag.parameters[s_param] = solver
demag.parameters[p_param] = preconditioner
demag.setup(S3, m, Ms, unit_length)
return demag
def prepare_benchmark(S3, m, Ms, unit_length, H_expected=None, tol=1e-3, repeats=10, bem=None, boundary_to_global=None):
def benchmark(timed_method_name, s_param, solvers, p_param, preconditioners, name):
results = np.ma.zeros((len(preconditioners), len(solvers)))
log = open(name + ".log", "w")
log.write("Benchmark with name {} for params {}, {}.\n".format(name, s_param, p_param))
for i, prec in enumerate(preconditioners):
print ""
print "{:>2}".format(i),
log.write("\nUsing preconditioner {}.\n".format(prec))
for j, solv in enumerate(solvers):
log.write("Using solver {}.\n".format(solv))
demag = prepare_demag(S3, m, Ms, unit_length, s_param, solv, p_param, prec, bem, boundary_to_global)
try:
checked_result = False
for _ in xrange(repeats): # to average out little fluctuations
H = demag.compute_field() # this can fail
if not checked_result:
checked_result = True
max_diff = np.max(np.abs(H - H_expected))
if max_diff > tol:
print "x",
log.write("Error {:.3} higher than allowed {:.3}.\n".format(max_diff, tol))
results[i, j] = np.ma.masked
break
else:
log.write("Result okay.\n")
print "o",
except RuntimeError as e:
log.write("Failed with RuntimeError.\n")
print "x",
results[i, j] = np.ma.masked
else:
time = fk.fk_timer.time_per_call(timed_method_name, "FKDemag")
results[i, j] = time
del(demag)
default_timer.reset()
fk.fk_timer.reset()
log.close()
results.dump(name + ".pickle")
return results
return benchmark
def run_demag_benchmark(m, mesh, unit_length, tol, repetitions=10, name="bench", H_expected=None):
S3 = df.VectorFunctionSpace(mesh, "CG", 1)
m = vector_valued_function(m, S3)
Ms = 1
# pre-compute BEM to save time
bem, boundary_to_global = compute_bem_fk(df.BoundaryMesh(mesh, 'exterior', False))
if H_expected is not None:
H = vector_valued_function(H_expected, S3)
H_expected = H.vector().array()
else: # if no H_expected was passed, use default/default as reference
demag = fk.FKDemag()
demag.precomputed_bem(bem, boundary_to_global)
demag.setup(S3, m, Ms, unit_length)
H_expected = demag.compute_field()
del(demag)
# gather all solvers and preconditioners
solvers = [s[0] for s in df.krylov_solver_methods()]
preconditioners = [p[0] for p in df.krylov_solver_preconditioners()]
benchmark = prepare_benchmark(S3, m, Ms, unit_length, H_expected, tol, repetitions, bem, boundary_to_global)
results_1 = benchmark("first linear solve",
"phi_1_solver", solvers,
"phi_1_preconditioner", preconditioners,
name=name + "_1")
results_2 = benchmark("second linear solve",
"phi_2_solver", solvers,
"phi_2_preconditioner", preconditioners,
name=name + "_2")
return solvers, preconditioners, results_1, results_2
| 4,268 | 43.46875 | 120 |
py
|
finmag
|
finmag-master/dev/sandbox/fkdemag_solver_benchmark/measurement_runner.py
|
import dolfin as df
import pickle
import numpy as np
import finmag.energies.demag.fk_demag as fk
import matplotlib.pyplot as plt
from table_printer import TablePrinter
from finmag.util.helpers import vector_valued_function
from finmag.native.llg import compute_bem_fk
from aeon import default_timer
def _prepare_demag_object(S3, m, Ms, unit_length, s_param, solver, p_param, preconditioner, bem, boundary_to_global):
demag = fk.FKDemag()
if bem is not None:
# Use the precomputed BEM if it was provided.
demag.precomputed_bem(bem, boundary_to_global)
demag.parameters[s_param] = solver
demag.parameters[p_param] = preconditioner
demag.setup(S3, m, Ms, unit_length)
return demag
def _loaded_results_table(timed_method_name, results, solvers, preconditioners):
print "Time shown for {} in s.".format(timed_method_name)
print "Results loaded from file.\n"
table = TablePrinter(preconditioners, xlabels_width_min=10)
for solver in solvers:
table.new_row(solver)
for prec in preconditioners:
try:
time = results[solver][prec]
except KeyError:
time = "-"
table.new_entry(time)
default = results['default']['default']
fastest = fastest_run(results, solvers)
print "\n\nDefault combination ran in {:.3} s.".format(default)
print "Fastest combination {}/{} ran in {:.3} s.".format(fastest[0], fastest[1], fastest[2])
print "That is an {:.1%} improvement.\n".format(1 - fastest[2] / default)
class ToleranceNotReachedException(Exception):
pass
def create_measurement_runner(S3, m, Ms, unit_length, H_expected=None, tol=1e-3, repeats=10, bem=None, boundary_to_global=None):
def runner(timed_method_name, s_param, solvers, p_param, preconditioners, skip=[], full_timings_log="timings.txt", results_cache=None):
r = np.ma.zeros((len(solvers), len(preconditioners)))
results, failed = {}, []
try:
with open(str(results_cache), "r") as f:
results = pickle.load(f)
_loaded_results_table(timed_method_name, results, solvers, preconditioners)
return results, failed
except IOError:
print "No recorded results found. Will run benchmarks."
print "Time shown for {} in s.\n".format(timed_method_name)
for timer in (default_timer, fk.fk_timer):
timer.reset()
log = open(full_timings_log, "w")
table = TablePrinter(preconditioners)
for solver in solvers:
table.new_row(solver)
#print "\nsolving with {}\n".format(solver)
results_for_this_solver = {}
# Compute the demagnetising field with the current solver and each of the preconditioners.
for prec in preconditioners:
#print "\nprec {} entry {}\n".format(prec, table.entry_counter)
if (solver, prec) in skip:
table.new_entry("s")
continue
demag = _prepare_demag_object(S3, m, Ms, unit_length, s_param, solver, p_param, prec, bem, boundary_to_global)
checked_result = False
try:
for _ in xrange(repeats): # Repeat to average out little fluctuations.
H = demag.compute_field() # This can fail with some method/preconditioner combinations.
if not checked_result:
# By checking here, we can avoid computing the
# field ten times if it's wrong.
checked_result = True
max_diff = np.max(np.abs(H - H_expected))
if max_diff > tol:
# We need to raise an exception, otherwise the 'else' clause below is
# executed and the measurement will be recorded twice.
raise ToleranceNotReachedException
except ToleranceNotReachedException:
table.new_entry("x")
failed.append({'solver': solver, 'preconditioner': prec, 'message': "error {:.3} higher than allowed {:.3}"})
except RuntimeError as e:
default_timer.get("compute_field", "FKDemag").stop()
table.new_entry("x")
failed.append({'solver': solver, 'preconditioner': prec, 'message': e.message})
else:
measured_time = fk.fk_timer.time_per_call(timed_method_name, "FKDemag")
table.new_entry(measured_time)
results_for_this_solver[prec] = measured_time
log.write("\nTimings for {} with {}.\n".format(solver, prec))
log.write(fk.fk_timer.report() + "\n")
default_timer.reset()
fk.fk_timer.reset()
del(demag)
results[solver] = results_for_this_solver
if results_cache is not None:
with open(results_cache, "w") as f:
pickle.dump(results, f)
log.close()
default = results['default']['default']
fastest = fastest_run(results, solvers)
print "\nDefault combination ran in {:.3} s.".format(default)
print "Fastest combination {}/{} ran in {:.3} s.".format(fastest[0], fastest[1], fastest[2])
print "That is an {:.1%} improvement.".format(1 - fastest[2] / default)
return results, failed
return runner
def run_measurements(m, mesh, unit_length, tol, repetitions=10, H_expected=None, name="", skip=[]):
S3 = df.VectorFunctionSpace(mesh, "CG", 1)
m = vector_valued_function(m, S3)
Ms = 1
bem, boundary_to_global = compute_bem_fk(df.BoundaryMesh(mesh, 'exterior', False))
if H_expected is not None:
H = vector_valued_function(H_expected, S3)
H_expected = H.vector().array()
else:
# use default/default as reference then.
demag = fk.FKDemag()
demag.precomputed_bem(bem, boundary_to_global)
demag.setup(S3, m, Ms, unit_length)
H_expected = demag.compute_field()
del(demag)
if name == "":
pass
else:
name = name + "_"
runner = create_measurement_runner(S3, m, Ms, unit_length,
H_expected, tol, repetitions,
bem, boundary_to_global)
solvers = [s[0] for s in df.krylov_solver_methods()]
preconditioners = [p[0] for p in df.krylov_solver_preconditioners()]
results_1, failed_1 = runner("first linear solve",
"phi_1_solver", solvers,
"phi_1_preconditioner", preconditioners,
skip,
"{}timings_log_1.txt".format(name),
"{}results_1.pickled".format(name))
results_2, failed_2 = runner("second linear solve",
"phi_2_solver", solvers,
"phi_2_preconditioner", preconditioners,
skip,
"{}timings_log_2.txt".format(name),
"{}results_2.pickled".format(name))
return solvers, preconditioners, results_1, failed_1, results_2, failed_2
def fastest_run(results, solvers):
return _extremum(results, solvers, min)
def fastest_runs(results, solvers):
return _extremum(results, solvers, min, per_solver=True)
def slowest_run(results, solvers):
return _extremum(results, solvers, max)
def slowest_runs(results, solvers):
return _extremum(results, solvers, max, per_solver=True)
def _extremum(results, solvers, func, per_solver=False):
fastest = []
for solver in solvers:
p = func(results[solver].keys(), key=lambda x: results[solver][x])
fastest.append((solver, p, results[solver][p]))
if per_solver:
return fastest
return func(fastest, key=lambda x: x[2])
def _runs_with_preconditioner(results, solvers, preconditioner):
indices = []
times = []
for i, solver in enumerate(solvers):
try:
times.append(results[solver][preconditioner])
except KeyError:
pass # Run with this combination didn't succeed.
else:
indices.append(i) # Will allow us to skip bars in the column chart.
return times, np.array(indices)
def column_chart(results, solvers, offset=None):
times_slowest = [r[2] for r in slowest_runs(results, solvers)]
times_fastest, names_fastest = zip(* [(r[2], r[1]) for r in fastest_runs(results, solvers)])
times_without_prec, iwop = _runs_with_preconditioner(results, solvers, "none")
times_with_default_prec, idp = _runs_with_preconditioner(results, solvers, "default")
fig = plt.figure()
ax = fig.add_subplot(111)
width = 0.2
ind = np.arange(len(results))
ax.axhline(results['default']['default'], color=(0.3, 0.3, 0.3), ls=":", zorder=0)
ax.bar(width + idp, times_with_default_prec, width, color=(0.3, 0.3, 0.3), label="default prec.")
ax.bar(2 * width + iwop, times_without_prec, width, color=(0.8, 0.8, 0.8), label="no prec.")
ax.bar(3 * width + ind, times_slowest, width, color="red", label="slowest prec.")
rects_fastest = ax.bar(ind, times_fastest, width, color="green", label="fastest prec.")
for i, rect in enumerate(rects_fastest):
height = rect.get_height()
offset = offset if offset is not None else 1.05 * height
ax.text(rect.get_x() + rect.get_width() / 2.0, height + offset, names_fastest[i], ha='center', va='bottom', rotation=90)
ax.set_xlabel("Solver")
ax.set_ylabel("Time (s)")
ax.legend()
ax.set_xticks(ind + 2 * width)
xtickNames = plt.setp(ax, xticklabels=solvers)
plt.setp(xtickNames, rotation=45)
return fig
| 10,002 | 40.506224 | 139 |
py
|
finmag
|
finmag-master/dev/sandbox/fkdemag_solver_benchmark/run.py
|
import dolfin as df
from finmag.util.meshes import sphere
from benchmark import run_demag_benchmark
print "List of Krylov subspace methods.\n"
for name, description in df.krylov_solver_methods():
print "{:<20} {}".format(name, description)
print "\nList of preconditioners.\n"
for name, description in df.krylov_solver_preconditioners():
print "{:<20} {}".format(name, description)
m = len(df.krylov_solver_methods())
n = len(df.krylov_solver_preconditioners())
print "\nThere are {} solvers, {} preconditioners and thus {} diferent combinations of solver and preconditioner.".format(m, n, m * n)
print "\nSolving first system.\n"
ball = sphere(20.0, 1.2, directory="meshes")
m_ball = df.Constant((1, 0, 0))
unit_length = 1e-9
print "The used mesh has {} vertices.".format(ball.num_vertices())
H_expected_ball = df.Constant((-1.0/3.0, 0.0, 0.0))
tol = 0.002
repetitions = 10
solvers, preconditioners, b1, b2 = run_demag_benchmark(m_ball, ball, unit_length, tol, repetitions, "ball", H_expected_ball)
print "\nSolving second system.\n"
film = box(0, 0, 0, 500, 50, 1, maxh=2.0, directory="meshes")
m_film = df.Constant((1, 0, 0))
unit_length = 1e-9
print "The used mesh has {} vertices.".format(film.num_vertices())
tol = 1e-6
repetitions = 10
solvers, preconditioners, f1, f2 = run_measurements(m_film, film, unit_length, tol, repetitions, "film", H_expected_film)
| 1,383 | 33.6 | 134 |
py
|
finmag
|
finmag-master/dev/sandbox/fkdemag_solver_benchmark/table_printer.py
|
"""
Contains helpers to build and output tables which look like the following.
| xlabel0 xlabel1 xlabel2 ... xlabeln
--------|----------------------------------------------------
ylabel0 | entry0 entry1 entry2 ... entryn
ylabel1 | entry0 entry1 entry2 ... entryn
ylabel2 | entry0 entry1 entry2 ... entryn
... | entry0 entry1 entry2 ... entryn
ylabeln | entry0 entry1 entry2 ... entryn
Note that the output is performed one entry at a time, one row after the other.
This means that extraneous output will break the table.
The advantage is that this can be used for continually showing the progress
of some long-running operation (the result of which depends on the two variables
described by the labels) in a way which is informative and nice to look at.
"""
def table_header(xlabels, xlabels_width_min=10, ylabels_width=15):
"""
Output the table header.
Given the list of strings `xlabels`, this will print the table header
using the strings as labels and return the width of the columns
associated with them.
The xlabels will be right-aligned and short xlabels will be padded to
a minimum width of 10. That value can be changed using `xlabels_width_min`.
The first column width is those of the ylabels column, which can be
controlled with the optional argument `ylabels_width` (default=15).
"""
columns = [ylabels_width]
print " " * columns[0] + "|",
for label in xlabels:
width = max(xlabels_width_min, len(label))
print "{:>{w}}".format(label, w=width),
columns.append(width)
print "\n" + "-" * columns[0] + "|" + "-" * (len(columns) + sum(columns[1:])),
return columns
def table_new_row(ylabel, width):
"""
Start a new table row with the label `ylabel` of width `width`.
The label will be right-aligned to fit `width`.
"""
print "\n{:<{w}}|".format(ylabel, w=width),
def table_new_entry(entry, width, fmt="{:>{w}.3}"):
"""
Print the table entry `entry` of width `width`.
By default it will use a format for floating point numbers, which it will
right-align with spaces to fill `width`. This behaviour can be controlled
py passing a new format string in `fmt` (with enclosing curly braces). The
width is passed to that format string as `w` and must be used or else
python will raise a KeyError.
"""
print fmt.format(entry, w=width),
class TablePrinter(object):
"""
Wrapper around the `table_header`, `table_new_row` and `table_new_entry`
functions in this module to avoid having to keep track of
the columns widths.
"""
def __init__(self, xlabels, xlabels_width_min=10, ylabels_width=10):
self.widths = table_header(xlabels, xlabels_width_min, ylabels_width)
self.entry_counter = 0
def new_row(self, ylabel):
table_new_row(ylabel, self.widths[0])
self.entry_counter = 0
def new_entry(self, entry, fmt="{:>{w}.3}"):
table_new_entry(entry, self.widths[self.entry_counter+1], fmt)
self.entry_counter += 1
def test_usage_example():
xlabels = ["True", "False"]
ylabels = ["True", "False"]
print "Conjunction.\n"
widths = table_header(xlabels, xlabels_width_min=6, ylabels_width=6)
for i, bv1 in enumerate(ylabels):
table_new_row(bv1, widths[0])
for j, bv2 in enumerate(xlabels):
table_new_entry(bv1 == "True" and bv2 == "True", widths[j + 1], "{:>{w}}")
def test_usage_example_wrapper():
xlabels = ["True", "False"]
ylabels = ["True", "False"]
print "Disjunction.\n"
table = TablePrinter(xlabels, xlabels_width_min=6, ylabels_width=6)
for i, bv1 in enumerate(ylabels):
table.new_row(bv1)
for j, bv2 in enumerate(xlabels):
table.new_entry(bv1 == "True" or bv2 == "True", "{:>{w}}")
if __name__ == "__main__":
test_usage_example()
print "\n"
test_usage_example_wrapper()
| 4,028 | 33.435897 | 86 |
py
|
finmag
|
finmag-master/dev/sandbox/fkdemag_solver_benchmark/compare_with_lu/memory_profile.py
|
import time
import numpy as np
import dolfin as df
from finmag.energies import Demag
from finmag.util.meshes import sphere
@profile
def run_benchmark(solver):
radius = 10.0
maxh = 0.5
unit_length = 1e-9
mesh = sphere(r=radius, maxh=maxh, directory="meshes")
S3 = df.VectorFunctionSpace(mesh, "Lagrange", 1)
Ms = 1
m_0 = (1, 0, 0)
m = df.Function(S3)
m.assign(df.Constant(m_0))
H_ref = np.array((- Ms / 3.0, 0, 0))
if solver == "krylov":
parameters = {}
parameters["phi_1_solver"] = "default"
parameters["phi_1_preconditioner"] = "default"
parameters["phi_2_solver"] = "default"
parameters["phi_2_preconditioner"] = "default"
demag = Demag("FK", solver_type="Krylov", parameters=parameters)
elif solver == "lu":
demag = Demag("FK", solver_type="LU")
else:
import sys
print "Unknown solver {}.".format(solver)
sys.exit(1)
demag.setup(S3, m, Ms, unit_length)
REPETITIONS = 10
start = time.time()
for j in xrange(REPETITIONS):
H = demag.compute_field()
elapsed = (time.time() - start) / REPETITIONS
H = H.reshape((3, -1))
spread = abs(H[0].max() - H[0].min())
error = abs(H.mean(axis=1)[0] - H_ref[0]) / abs(H_ref[0])
print elapsed, error, spread
if __name__ == "__main__":
run_benchmark("krylov")
| 1,382 | 26.66 | 72 |
py
|
finmag
|
finmag-master/dev/sandbox/saving_timesteps_demo_for_FEniCS_guys/diffusion_demo_with_saving.py
|
"""
Extension of the FEniCS tutorial demo for the diffusion equation
with Dirichlet conditions.
"""
from dolfin import *
import numpy
from time import sleep
import tables as pytables
# Create mesh and define function space
nx = ny = 20
mesh = UnitSquareMesh(nx, ny)
V = FunctionSpace(mesh, 'Lagrange', 1)
# Define boundary conditions
alpha = 3; beta = 1.2
u0 = Expression('1 + x[0]*x[0] + alpha*x[1]*x[1] + beta*t',
alpha=alpha, beta=beta, t=0)
class Boundary(SubDomain): # define the Dirichlet boundary
def inside(self, x, on_boundary):
return on_boundary
boundary = Boundary()
bc = DirichletBC(V, u0, boundary)
# Initial condition
u_1 = interpolate(u0, V)
uuu = interpolate(u0, V)
uuu.rename('uuu', 'UUU')
dt = 0.3 # time step
# Define variational problem
u = TrialFunction(V)
v = TestFunction(V)
f = Constant(beta - 2 - 2*alpha)
a = u*v*dx + dt*inner(nabla_grad(u), nabla_grad(v))*dx
L = (u_1 + dt*f)*v*dx
A = assemble(a) # assemble only once, before the time stepping
b = None # necessary for memory saving assemeble call
u = Function(V) # the unknown at a new time level
T = 1.9 # total simulation time
t = dt
# For now we also write to xdmf and hdf5 files to see how dolfin does
# this at the moment, and to be able to compare with our proposed
# format. This will disappear in the final demo.
F = XDMFFile('solution_xdmf.xdmf')
G = HDF5File('solution_hdf5.h5', 'w')
F << (u_1, 0.0)
G.write(u_1.vector(), 'myvector_0')
# Prepare for saving to HDF5 file (using pytables)
class VectorDescription(pytables.IsDescription):
"""
Customized record for writing solution vectors including a counter
and time information.
"""
counter = pytables.Int64Col() # Signed 64-bit integer
values = pytables.FloatCol(shape=u_1.vector().array().shape) #
time = pytables.FloatCol() # double (double-precision)
h5file = pytables.openFile("diffusion_data.h5", mode='w')
group = h5file.createGroup('/', 'Vector')
table = h5file.createTable(group, 'myvector', VectorDescription)
tabdata = table.row
# Run the simulation
counter = 0
while t <= T:
print 'time =', t
b = assemble(L, tensor=b)
u0.t = t
bc.apply(A, b)
solve(A, u.vector(), b)
# Verify
u_e = interpolate(u0, V)
maxdiff = numpy.abs(u_e.vector().array() - u.vector().array()).max()
print 'Max error, t=%.2f: %-10.3f' % (t, maxdiff)
t += dt
u_1.assign(u)
# Write to xdmf and hdf5 using dolfin's API
F << (u_1, t)
F << (uuu, t)
G.write(u_1.vector(), 'myvector_{}'.format(counter))
# Write data in our own format using pytables
tabdata['counter'] = counter
tabdata['values'] = u_1.vector()
tabdata['time'] = t
tabdata.append()
counter += 1
# Close (and flush) the file
h5file.close()
| 2,827 | 25.933333 | 72 |
py
|
finmag
|
finmag-master/dev/sandbox/mesh/netgen_demag_test.py
|
import dolfin as df
import finmag
import numpy as np
from finmag.energies import Demag
from finmag import Simulation as Sim
from finmag.util.mesh_templates import Nanodisk
# #############################################
# ###### MESH GENERATOR
# LENGTHS
lex = 5.76 # nm (Exchange length)
# The length of the nanotube. when using 1100 is alright, but
# starting from ~ 1150, the memory blows up
L = 2000. # nm
r_ext = 3 * lex # External diameter in nm
r_int = 0.8 * r_ext
# Define the geometric structures to be processed
ntube_e = Nanodisk(d=2 * r_ext, h=L, center=(0, 0, 0),
valign='bottom', name='ntube_e')
# Internal cylinder to be substracted:
ntube_i = Nanodisk(d=2 * r_int, h=L, center=(0, 0, 0),
valign='bottom', name='ntube_i')
# Substract the small cylinder
ntube = ntube_e - ntube_i
# Create the mesh
mesh = ntube.create_mesh(maxh=4.0, save_result=False)
# #############################################
# ###### SIMULATION
# MATERIAL PARAMETERS
Ms = 7.96e5 # A m**-1 saturation magnetisation
# Inititate the simulation object with the lengths in nm
sim = Sim(mesh, Ms, unit_length=1e-9)
sim.add(Demag())
| 1,167 | 25.545455 | 61 |
py
|
finmag
|
finmag-master/dev/sandbox/mesh/extend_mesh.py
|
import dolfin as df
def test_triangle_mesh():
# Create mesh object and open editor
mesh = df.Mesh()
editor = df.MeshEditor()
editor.open(mesh, 2, 2)
editor.init_vertices(3)
editor.init_cells(1)
# Add vertices
editor.add_vertex(0, 0.0, 0.0)
editor.add_vertex(1, 1.0, 0.0)
editor.add_vertex(2, 0.0, 1.0)
# Add cell
editor.add_cell(0, 0, 1, 2)
# Close editor
editor.close()
return mesh
def test_triangle_mesh2():
# Create mesh object and open editor
mesh = df.Mesh()
editor = df.MeshEditor()
editor.open(mesh, 3, 3)
editor.init_vertices(4)
editor.init_cells(1)
# Add vertices
editor.add_vertex(0, 0.0, 0.0, 0.0)
editor.add_vertex(1, 1.0, 0.0, 0.0)
editor.add_vertex(2, 0.0, 1.0, 0.0)
editor.add_vertex(3, 0.0, 0.0, 1.0)
# Add cell
editor.add_cell(0, 0, 1, 2, 3)
# Close editor
editor.close()
return mesh
def create_3d_mesh(mesh, h=1):
assert mesh.topology().dim() == 2
for cell in df.cells(mesh):
print cell
print cell.entities(0)
print cell.get_vertex_coordinates()
nv = mesh.num_vertices()
nc = mesh.num_cells()
mesh3 = df.Mesh()
editor = df.MeshEditor()
editor.open(mesh3, 3, 3)
editor.init_vertices(2*nv)
editor.init_cells(3*nc)
for v in df.vertices(mesh):
i = v.global_index()
p = v.point()
editor.add_vertex(i, p.x(),p.y(),0)
editor.add_vertex(i+nv, p.x(),p.y(),h)
gid = 0
for c in df.cells(mesh):
#gid = c.global_index()
i,j,k = c.entities(0)
print i,j,k
editor.add_cell(gid, i, j, k, i+nv)
gid = gid + 1
editor.add_cell(gid, j, j+nv, k, i+nv)
gid = gid + 1
editor.add_cell(gid, k, k+nv, j+nv, i+nv)
gid = gid + 1
editor.close()
return mesh3
mesh = df.UnitSquareMesh(2,2)
mesh = df.UnitTriangleMesh()
tri = create_3d_mesh(mesh)
print tri.coordinates()
df.plot(tri)
df.interactive()
| 1,841 | 17.237624 | 44 |
py
|
finmag
|
finmag-master/dev/sandbox/mesh/mshr_demag_test.py
|
from mshr import Cylinder
import dolfin as df
import mshr
import finmag
import numpy as np
from finmag.energies import Demag
from finmag import Simulation as Sim
# #############################################
# ###### MESH GENERATOR
# LENGTHS
lex = 5.76 # nm (Exchange length)
L = 2000. # nm
r_ext = 3 * lex # External diameter in nm
r_int = 0.8 * r_ext
# Define the geometric structures to be processed
ntube = (Cylinder(df.Point(0., 0., 0.),
df.Point(0., 0., L),
r_ext,
r_ext,
)
-
Cylinder(df.Point(0., 0., 0.),
df.Point(0., 0., L),
r_int,
r_int,
)
)
# Create the mesh
diag = np.sqrt(L ** 2 + (3 * lex) ** 2)
resolut = diag / 3.
mesh = mshr.generate_mesh(ntube, resolut)
# Output Mesh
outp = file('mesh_info.dat', 'w')
outp.write(finmag.util.meshes.mesh_info(mesh))
# Save mesh to file
file = df.File("nanotube.xml")
file << mesh
# #############################################
# ###### SIMULATION
# Import mesh from the 'xml' file produced by the mesh generator script
mesh = df.Mesh('nanotube.xml')
# MATERIAL PARAMETERS
Ms = 7.96e5 # A m**-1 saturation magnetisation
# Inititate the simulation object with the lengths in nm
sim = Sim(mesh, Ms, unit_length=1e-9)
sim.add(Demag())
| 1,372 | 22.271186 | 71 |
py
|
finmag
|
finmag-master/dev/sandbox/pele/relax.py
|
import os
import dolfin as df
import numpy as np
from finmag.util import helpers
from finmag.physics.effective_field import EffectiveField
from finmag.energies import Exchange, DMI, UniaxialAnisotropy
from finmag import Simulation as Sim
import logging
log = logging.getLogger(name="finmag")
ONE_DEGREE_PER_NS = 17453292.5 # in rad/s
from pele.potentials import BasePotential
def cartesian2spherical(xyz):
xyz.shape=(3,-1)
r_xy = np.sqrt(xyz[0,:]**2 + xyz[1,:]**2)
theta = np.arctan2(r_xy, xyz[2,:])
phi = np.arctan2(xyz[1,:], xyz[0,:])
xyz.shape=(-1,)
theta_phi = np.concatenate((theta, phi))
return theta_phi
def spherical2cartesian(theta_phi):
theta_phi.shape=(2,-1)
theta=theta_phi[0]
phi = theta_phi[1]
mxyz = np.zeros(3*len(theta))
mxyz.shape=(3,-1)
mxyz[0,:] = np.sin(theta)*np.cos(phi)
mxyz[1,:] = np.sin(theta)*np.sin(phi)
mxyz[2,:] = np.cos(theta)
mxyz.shape=(-1,)
theta_phi.shape=(-1,)
return mxyz
def cartesian2spherical_field(field_c,theta_phi):
theta_phi.shape=(2,-1)
theta = theta_phi[0]
phi = theta_phi[1]
field_s = np.zeros(theta_phi.shape)
field_c.shape = (3,-1)
field_s.shape = (2,-1)
hx = field_c[0]
hy = field_c[1]
hz = field_c[2]
sin_t = np.sin(theta)
cos_t = np.cos(theta)
sin_p = np.sin(phi)
cos_p = np.cos(phi)
field_s[0] = (hx*cos_p + hy*sin_p)*cos_t - hz*sin_t
field_s[1] = (-hx*sin_p + hy*cos_p)*sin_t
field_c.shape=(-1,)
field_s.shape=(-1,)
theta_phi.shape=(-1,)
return field_s
def create_simulation():
from finmag.util.meshes import ellipsoid
#mesh = df.IntervalMesh(10,0,30)
#mesh = df.RectangleMesh(0,0,10,2,5,1)
mesh = ellipsoid(30,10,10,maxh=3.0)
sim = Sim(mesh, Ms=8.6e5, unit_length=1e-9)
sim.set_m((1,1,1))
sim.add(Exchange(1.3e-11))
sim.add(UniaxialAnisotropy(-1e5, (0, 0, 1), name='Kp'))
sim.add(UniaxialAnisotropy(1e4, (1, 0, 0), name='Kx'))
return sim
sim = create_simulation()
m_fun = sim.llg._m
effective_field = sim.llg.effective_field
class My1DPot(BasePotential):
"""1d potential"""
def getEnergy(self, x):
m=spherical2cartesian(x)
m_fun.vector().set_local(m)
effective_field.update()
return effective_field.total_energy()
def getEnergyGradient(self, x):
m=spherical2cartesian(x)
m_fun.vector().set_local(m)
effective_field.update()
E = effective_field.total_energy()
field = effective_field.H_eff
grad = cartesian2spherical_field(field, x)
return E, grad
from pele.systems import BaseSystem
class My1DSystem(BaseSystem):
def get_potential(self):
return My1DPot()
if __name__ == '__main__':
sys = My1DSystem()
database = sys.create_database()
x0 = cartesian2spherical(sim.llg.m)
bh = sys.get_basinhopping(database=database, coords=x0)
bh.run(20)
print "found", len(database.minima()), "minima"
min0 = database.minima()[0]
print "lowest minimum found at", spherical2cartesian(min0.coords), "with energy", min0.energy
for min in database.minima():
sim.set_m(spherical2cartesian(min.coords))
df.plot(m_fun)
df.interactive()
| 3,349 | 23.275362 | 97 |
py
|
finmag
|
finmag-master/dev/sandbox/fenmag/compute_jacobian.py
|
from dolfin import *
class MyLLG(object):
def __init__(self, V, alpha, gamma, Ms, M):
self.V = V
self.alpha = alpha
self.gamma = gamma
self.Ms = Ms
self.M = M
self.p = Constant(self.gamma / (1 + self.alpha ** 2))
def H_eff(self):
"""Very temporary function to make things simple."""
H_app = project((Constant((0, 1e5, 0))), self.V)
# Add more effective field terms here.
return H_app
def variational_forms(self):
u = TrialFunction(self.V)
v = TestFunction(self.V)
self.a = inner(u, v) * dx
self.L = inner(-self.p * cross(self.M, self.H_eff())
- self.p * self.alpha / self.Ms * cross(self.M, cross(self.M, self.H_eff())), v) * dx
def compute_jacobian(self):
self.variational_forms()
return derivative(self.L, self.M)
L = 50e-9
mesh = BoxMesh(Point(0, 0, 0), Point(L, L, L), 5, 5, 5)
V = VectorFunctionSpace(mesh, "Lagrange", 1)
M = project((Constant((8e6, 0, 0))), V)
llg = MyLLG(V=V, alpha=0.5, gamma=2.211e5, Ms=8e6, M=M)
jacobian = llg.compute_jacobian()
| 1,129 | 27.974359 | 104 |
py
|
finmag
|
finmag-master/dev/sandbox/fenmag/analytic_solution.py
|
import numpy as np
def macrospin_analytic_solution(alpha, gamma, H, t_array):
"""
Computes the analytic solution of magnetisation x component
as a function of time for the macrospin in applied external
magnetic field H.
Source: PhD Thesis Matteo Franchin,
http://eprints.soton.ac.uk/161207/1.hasCoversheetVersion/thesis.pdf,
Appendix B, page 127
"""
t0 = 1 / (gamma * alpha * H) * \
np.log(np.sin(np.pi / 2) / (1 + np.cos(np.pi / 2)))
mx_analytic = []
for t in t_array:
phi = gamma * H * t # (B16)
costheta = np.tanh(gamma * alpha * H * (t - t0)) # (B17)
sintheta = 1 / np.cosh(gamma * alpha * H * (t - t0)) # (B18)
mx_analytic.append(sintheta * np.cos(phi))
return np.array(mx_analytic)
| 827 | 32.12 | 72 |
py
|
finmag
|
finmag-master/dev/sandbox/normal_modes/cases.py
|
import dolfin as df
from finmag import Simulation
from finmag.energies import Demag, Exchange, Zeeman
from finmag.util.consts import Oersted_to_SI
class StdProblem(object):
def __init__(self):
self.box_size = [200., 200., 5.] # nm
self.box_divisions = [40,40,1] # divisions
def setup_sim(self, m0):
Hz = [8e4, 0, 0] # A/m
A = 1.3e-11 # J/m
Ms = 800e3 # A/m
alpha = 1.
mesh = df.BoxMesh(0, 0, 0, *(self.box_size + self.box_divisions))
sim = Simulation(mesh, Ms)
sim.alpha = alpha
sim.set_m(m0)
sim.add(Demag())
sim.add(Exchange(A))
sim.add(Zeeman(Hz))
return sim
def initial_m(self):
return [0,0,1]
def name(self):
return "stdproblem-%dx%dx%d" % tuple(self.box_divisions)
class Grimsditch2004(object):
def setup_sim(self, m0):
SX, SY, SZ = 116, 60, 20
nx, ny, nz = 29, 15, 5
# Fe, ref: PRB 69, 174428 (2004)
# A = 2.5e-6 erg/cm^3
# M_s = 1700 emu/cm^3
# gamma = 2.93 GHz/kOe
Ms = 1700e3
A = 2.5e-6*1e-5
gamma_wrong = 2.93*1e6/Oersted_to_SI(1.) # wrong by a factor of 6 (?)
Hzeeman = [10e3*Oersted_to_SI(1.), 0, 0]
mesh = df.BoxMesh(0, 0, 0, SX, SY, SZ, nx, ny, nz)
sim = Simulation(mesh, Ms)
sim.set_m(m0)
sim.add(Demag())
sim.add(Exchange(A))
sim.add(Zeeman(Hzeeman))
return sim
| 1,476 | 24.465517 | 77 |
py
|
finmag
|
finmag-master/dev/sandbox/normal_modes/normal_modes.py
|
import dolfin as df
import sys
from finmag import Simulation
from finmag.energies import Demag, Exchange, Zeeman
from finmag.util.consts import Oersted_to_SI, gamma
import h5py
import scipy.sparse.linalg
import numpy as np
from finmag.util.helpers import fnormalise
def read_relaxed_state(problem):
fn = problem.name() + "-groundstate.h5"
print "Reading the m vector from", fn
f = h5py.File(fn, "r")
return f['/VisualisationVector/0'][...]
def find_relaxed_state(problem):
sim = problem.setup_sim(problem.initial_m())
print "Finding the relaxed state for ", problem.name(), ", mesh",sim.mesh
def print_progress(sim):
print "Reached simulation time: {} ns".format(sim.t*1e9)
sim.schedule(print_progress, every=1e-9)
sim.relax()
m = sim.llg._m
# Save the result
filename = sim.name() + "-groundstate.xdmf"
f = df.File(filename)
f << m
f = None
print "Relaxed field saved to", filename
def differentiate_fd4(f, x, dx):
h = 0.01*np.sqrt(np.dot(x, x))/np.sqrt(np.dot(dx, dx)+1e-50)
if isinstance(dx, np.ndarray):
res = np.zeros(dx.size, dtype=dx.dtype)
else:
res = 0.
for w, a in zip([1./12., -2./3., 2./3., -1./12.], [-2., -1., 1., 2.]):
res += (w/h)*f(x + a*h*dx)
# print (res/(w/h)/ f(x + a * h * dx))[:4]
# print res[:4]
return res
def differentiate_fd2(f, x, dx):
h = 0.01*np.sqrt(np.dot(x, x))/np.sqrt(np.dot(dx, dx)+1e-50)
if isinstance(dx, np.ndarray):
res = np.zeros(dx.size, dtype=dx.dtype)
else:
res = 0.
for w, a in zip([-1./2., 1./2.], [-1., 1.]):
res += (w/h)*f(x + a*h*dx)
return res
def compute_H_func(sim):
def compute_H(m):
# no normalisation since we want linearity
sim.llg._m.vector()[:] = m
return sim.effective_field()
def compute_H_complex(m):
if np.iscomplexobj(m):
H_real = compute_H(np.real(m).copy())
H_imag = compute_H(np.imag(m).copy())
return H_real + 1j* H_imag
else:
return compute_H(m)
return compute_H_complex
def normalise(m):
assert m.shape == (3, 1, m.shape[2])
return m/np.sqrt(m[0]*m[0] + m[1]*m[1] + m[2]*m[2])
def transpose(a):
return np.transpose(a, [1,0,2])
# Matrix-vector or Matrix-matrix product
def mult_one(a, b):
# a and b are ?x?xn arrays where ? = 1..3
assert len(a.shape) == 3
assert len(b.shape) == 3
assert a.shape[2] == b.shape[2]
assert a.shape[1] == b.shape[0]
assert a.shape[0] <= 3 and a.shape[1] <= 3
assert b.shape[0] <= 3 and b.shape[1] <= 3
# One of the arrays might be complex, so we need to determine the type
# of the resulting array
res = np.zeros((a.shape[0], b.shape[1], a.shape[2]), dtype=type(a[0,0,0]+b[0,0,0]))
for i in xrange(res.shape[0]):
for j in xrange(res.shape[1]):
for k in xrange(a.shape[1]):
res[i,j,:] += a[i,k,:]*b[k,j,:]
return res
def mult(*args):
if len(args) < 2:
raise Exception("mult requires at least 2 arguments")
res = args[0]
for i in xrange(1, len(args)):
res = mult_one(res, args[i])
return res
def cross(a, b):
assert a.shape == (3, 1, a.shape[2])
res = np.empty(a.shape)
res[0] = a[1]*b[2] - a[2]*b[1]
res[1] = a[2]*b[0] - a[0]*b[2]
res[2] = a[0]*b[1] - a[1]*b[0]
return res
def precompute_arrays(m0):
n = m0.shape[2]
assert m0.shape == (3,1,n)
# Start with e_z and compute e_z x m
m_perp = cross(m0, [0.,0.,-1.])
m_perp[2] += 1e-100
m_perp = cross(normalise(m_perp), m0)
m_perp = normalise(m_perp)
# (108)
R = np.zeros((3,3,n))
R[:,2,:] = m0[:,0,:]
R[:,1,:] = m_perp[:,0,:]
R[:,0,:] = cross(m_perp, m0)[:,0,:]
# Matrix for the cross product m0 x v
Mcross = np.zeros((3,3,n))
Mcross[:,0,:] = cross(m0, [1.,0.,0.])[:,0,:]
Mcross[:,1,:] = cross(m0, [0.,1.,0.])[:,0,:]
Mcross[:,2,:] = cross(m0, [0.,0.,1.])[:,0,:]
B0 = -1j*Mcross
# (114), multiplying on the left again
B0p = mult(transpose(R), B0, R)
# Matrix for the projection onto the plane perpendicular to m0
Pm0 = np.zeros((3,3,n))
Pm0[0,0,:] = 1.
Pm0[1,1,:] = 1.
Pm0[2,2,:] = 1.
Pm0 -= mult(m0, transpose(m0))
# Matrix for the injection from 2n to 3n
S = np.zeros((3,2,n))
S[0,0,:] = 1.
S[1,1,:] = 1.
# Matrix for the projection from 3n to 2n is transpose(S)
B0pp = mult(transpose(S), B0p, S)
# The eigenproblem is
# D phi = omega phi
# D = B0pp * S- * R^t Pm0 (C+H0) R * S+
# D = Dleft * (C+H0) * Dright
#
Dright = mult(R, S).copy()
Dleft = mult(B0pp, transpose(S), transpose(R), Pm0).copy()
return R, Mcross, Pm0, B0pp, Dleft, Dright
def compute_A(sim):
m0_flat = sim.m.copy()
m0 = m0_flat.view()
m0.shape = (3, 1, -1)
n = m0.shape[2]
A = np.zeros((3*n,3*n))
compute_H = compute_H_func(sim)
H0 = compute_H(m0_flat).copy()
H0.shape = (1, 3, n)
H0 = mult(H0, m0)
H0.shape = (n,)
for k in xrange(n):
for i in xrange(3):
dm = np.zeros((3*n))
dm[3*i+k] = 1.
# v = np.zeros(3*n,)
v = differentiate_fd2(compute_H, m0_flat, dm)
v[3*i+k] += H0[k]
A[:,3*i+k] = v
return A, m0_flat
def find_normal_modes(sim):
# sim = problem.setup_sim(read_relaxed_state(problem))
m0_flat = sim.m.copy()
m0 = m0_flat.view()
m0.shape = (3,1,-1)
n = m0.shape[2]
R, Mcross, Pm0, B0pp, Dleft, Dright = precompute_arrays(m0)
# Compute h0
compute_H = compute_H_func(sim)
H0 = compute_H(m0_flat).copy()
H0.shape = (1,3,n)
H0 = mult(H0, m0)
H0.shape = (n,)
steps = [0]
def D_times_vec(phi):
steps[0] += 1
phi = phi.view()
# Multiply by Dright
phi.shape = (2,1,n)
dm = mult(Dright, phi)
# Multiply by gamma(C+H0)
dm.shape = (-1,)
v = differentiate_fd4(compute_H, m0_flat, dm)
v.shape = (3,n)
dm.shape = (3,n)
v[0] += H0*dm[0]
v[1] += H0*dm[1]
v[2] += H0*dm[2]
v *= gamma
# Multiply by Dleft
v.shape = (3, 1, n)
res = mult(Dleft, v)
res.shape = (-1,)
if steps[0] % 10 == 0:
print "Step #", steps[0]
return res
# Solve the eigenvalue problem using ARPACK
# The eigenvalue problem is not formulated correctly at all
# The correct formulation is in the paper from d'Aquino
D = scipy.sparse.linalg.LinearOperator((2*n, 2*n), matvec=D_times_vec, dtype=complex)
n_values = 1
w, v = scipy.sparse.linalg.eigs(D, n_values, which='LM')
print w.shape, v.shape
print "Computed %d largest eigenvectors for %s" % (n_values, sim.mesh)
print "Eigenvalues:", w
if __name__=="__main__":
pass
# df.plot(H_eff)
# df.interactive()
#
# external_field = Zeeman((0, Ms, 0))
# sim.add(external_field)
# sim.relax()
# t0 = sim.t # time needed for first relaxation
#
# external_field.set_value((0, 0, Ms))
# sim.relax()
# t1 = sim.t - t0 # time needed for second relaxation
#
# assert sim.t > t0
# assert abs(t1 - t0) < 1e-10
| 7,268 | 26.224719 | 89 |
py
|
finmag
|
finmag-master/dev/sandbox/normal_modes/normal_modes_tests.py
|
import dolfin as df
import math
import numpy as np
from finmag import Simulation
from finmag.energies import Demag, Zeeman, Exchange
from finmag.util.consts import mu0, Oersted_to_SI
from finmag.util.helpers import fnormalise
from normal_modes import differentiate_fd4
from normal_modes import differentiate_fd2
from normal_modes import compute_H_func, normalise, mult, transpose, precompute_arrays, cross, find_normal_modes, compute_A
def test_differentiate_fd4():
def f(x):
return np.array([math.exp(x[0])+math.sin(x[1]), 0.])
x = np.array([1.2, 2.4])
dx = np.array([3.5, 4.5])
value = dx[0]*math.exp(x[0]) + dx[1]*math.cos(x[1])
assert abs(differentiate_fd4(f, x, dx)[0] - value) < 1e-8
def test_differentiate_quadratic():
def f(x):
return x**2 + 3.5*x + 7
assert abs(differentiate_fd4(f, 2, 3) - (2*2+3.5)*3) < 1e-12
assert abs(differentiate_fd2(f, 2, 3) - (2*2+3.5)*3) < 1e-12
def test_differentiate_heff():
ns = [2, 2, 2]
mesh = df.BoxMesh(0, 0, 0, 1, 1, 1, *ns)
sim = Simulation(mesh, 1.2)
sim.set_m([1,0,0])
sim.add(Demag())
sim.add(Exchange(2.3*mu0))
compute_H = compute_H_func(sim)
# Check that H_eff is linear without Zeeman
np.random.seed(1)
m1 = fnormalise(np.random.randn(*sim.m.shape))
m2 = fnormalise(np.random.randn(*sim.m.shape))
# TODO: need to use a non-iterative solver here to increase accuracy
assert np.max(np.abs(compute_H(m1)+compute_H(m2) - compute_H(m1+m2))) < 1e-6
# Add the zeeman field now
sim.add(Zeeman([2.5,3.5,4.3]))
# Check that both fd2 and fd4 give the same result
assert np.max(np.abs(differentiate_fd4(compute_H, m1, m2)-differentiate_fd2(compute_H, m1, m2))) < 1e-10
def norm(a):
a = a.view()
a.shape = (-1,)
a = np.abs(a) # for the complex case
return np.sqrt(np.dot(a,a))
def test_compute_arrays():
n = 1
m0 = normalise(np.array([1.,2.,3.]).reshape((3,1,n)))
R, Mcross, Pm0, B0pp, Dleft, Dright = precompute_arrays(m0)
# R is a rotation matrix
assert norm(mult(transpose(R), R)[:,:,0]-np.eye(3)) < 1e-14
assert np.abs(np.linalg.det(R[:,:,0]) - 1.) < 1e-14
# Mcross is the matrix for the cross product m0 x v
assert norm(np.dot(Mcross[:,:,0], [0.,0.,1.]) - cross(m0, [0.,0.,1.])[:,0,0]) < 1e-14
# B0pp is a hermitian matrix with pure imaginary entries
assert norm(mult(B0pp, B0pp)[:,:,0] - np.diag([1,1,])) < 1e-14
# Pm0: Matrix for the projection onto the plane perpendicular to m0
assert norm(mult(Pm0, m0)) < 1e-14
def test_compute_main():
Ms = 1700e3
A = 2.5e-6*1e-5
Hz = [10e3*Oersted_to_SI(1.), 0, 0]
mesh = df.BoxMesh(0, 0, 0, 50, 50, 10, 6, 6, 2)
mesh = df.BoxMesh(0, 0, 0, 5, 5, 5, 1, 1, 1)
print mesh
# Find the ground state
sim = Simulation(mesh, Ms)
sim.set_m([1,0,0])
sim.add(Demag())
sim.add(Exchange(A))
sim.add(Zeeman(Hz))
sim.relax()
# Compute the eigenvalues - does not converge
# find_normal_modes(sim)
def test_compute_A():
Ms = 1700e3
A = 2.5e-6 * 1e-5
Hz = [10e3 * Oersted_to_SI(1.), 0, 0]
mesh = df.BoxMesh(0, 0, 0, 5, 5, 5, 2, 2, 2)
sim = Simulation(mesh, Ms)
sim.set_m([1, 0, 0])
sim.add(Demag())
# sim.add(Exchange(A))
# sim.add(Zeeman(Hz))
sim.relax()
print mesh
A0, m0 = compute_A(sim)
print A0[:3,:3]
print m0
| 3,392 | 30.416667 | 123 |
py
|
finmag
|
finmag-master/dev/sandbox/normal_modes/compute_ground_state.py
|
from sandbox.normal_modes.normal_modes import find_relaxed_state
if __name__=="__main__":
ns = [29, 15, 5]
find_relaxed_state(ns)
| 139 | 22.333333 | 64 |
py
|
finmag
|
finmag-master/dev/sandbox/normal_modes/__init__.py
|
__author__ = 'chern'
| 21 | 10 | 20 |
py
|
finmag
|
finmag-master/dev/sandbox/normal_modes/vecfields.py
| 0 | 0 | 0 |
py
|
|
finmag
|
finmag-master/dev/sandbox/demag/interiorboundary.py
|
"""A Utility Module for generating interior boundaries in Fenics"""
__author__ = "Gabriel Balaban"
__copyright__ = __author__
__project__ = "Finmag"
__organisation__ = "University of Southampton"
#Note when restricting forms ('+') will be on the outside of the submesh,
#and ('-') will be on the inside
#TODO Expand the class InteriorBoundary so it can handle multiple Boundaries
from dolfin import *
class InteriorBoundary():
"""Marks interior boundary and gives you a function newboundfunc
"""
def __init__(self,mesh):
"""Expects mesh"""
self.D = mesh.topology().dim()
self.mesh = mesh
self.orientation = []
self.boundaries = []
#TODO add the possibility of several subdomains
def create_boundary(self,submesh):
"""
Will find and return the boundary of the given submesh.
This appends a FacetFunction to
self.boundaries.
That FacetFunction takes the value 2 for all Facets on the bounday between submesh and the mesh.
Boundary facets at the outer boundray of the mesh are not included.
Also appends something (probably also a Facetfunction, or at
least something like it) to self.orientation which contains
a reference to the cells on the outside of the boundary for
every facet.
"""
#Compute FSI boundary and orientation markers on Omega
self.mesh.init()
newboundfunc = MeshFunction("uint",self.mesh,self.D-1) # D-1 means FacetFunction
#The next line creates a 'facet_orientation' attribute(or function) in the mesh object
neworientation= self.mesh.data().create_mesh_function("facet_orientation", self.D - 1)
neworientation.set_all(0)
newboundfunc.set_all(0)
#self.mesh.init(self.D - 1, self.D)
self.countfacets = 0
for facet in facets(self.mesh):
# Skip facets on the boundary
cells = facet.entities(self.D)
if len(cells) == 1:
continue
elif len(cells) != 2:
error("Strange, expecting one or two cells that share a boundary!")
# Create the two cells
c0, c1 = cells
cell0 = Cell(self.mesh, c0)
cell1 = Cell(self.mesh, c1)
# Get the two midpoints
p0 = cell0.midpoint()
p1 = cell1.midpoint()
# Check if the points are inside
p0_inside = submesh.intersected_cell(p0)
p1_inside = submesh.intersected_cell(p1)
p0_inside = translate(p0_inside)
p1_inside = translate(p1_inside)
# Just set c0, will be set only for facets below
neworientation[facet.index()] = c0
# Markers:
# 0 = Not Subdomain
# 1 = Subdomain
# 2 = Boundary
# Look for points where exactly one is inside the Subdomain
facet_index = facet.index() #global facet index
if p0_inside and not p1_inside:
newboundfunc[facet_index] = 2
neworientation[facet_index] = c1 #store cell object on the 'outside' of the facet,
#i.e. c1 is not in the given submesh.
self.countfacets += 1
elif p1_inside and not p0_inside:
newboundfunc[facet_index] = 2
neworientation[facet_index] = c0
self.countfacets += 1
elif p0_inside and p1_inside:
newboundfunc[facet_index] = 1
else:
newboundfunc[facet_index] = 0
self.boundaries += [newboundfunc]
self.orientation += [neworientation]
class inputerror(Exception):
def __str__(self):
return "Can only give Lagrange Element dimension for mesh dimensions 1-3"
def create_intbound(mesh,subdomain):
#Automatically generates the boundary and return the facet function
# '2' is the interior boundary
intbound = InteriorBoundary(mesh)
intbound.create_boundary(subdomain)
intfacet = intbound.boundaries[0]
return intfacet
def translate(p):
#Translate the result of the Mesh.intersected_cells method into a true or false statement
if p == -1:
p = False
else:
p = True
return p
#######################################################################
#Module Tests (For Visual inspection)
#######################################################################
class TestProblem():
def __init__(self):
self.mesh = RectangleMesh(0.0,0.0,4,4,4,4)
#plot(self.mesh)
self.cell_domains = MeshFunction("uint", self.mesh, 2)
class Structure(SubDomain):
def inside(self, x, on_boundary):
return x[1] < 2 + DOLFIN_EPS
#Create Submesh
self.Structure = Structure
self.cell_domains.set_all(0)
subdomain0 = Structure()
subdomain0.mark(self.cell_domains,1)
self.submesh = SubMesh(self.mesh,self.cell_domains,1)
#plot(submesh)
class TestProblemCube():
def __init__(self):
self.mesh = UnitCubeMesh(4,4,4)
#plot(self.mesh)
self.cell_domains = MeshFunction("uint", self.mesh, 3)
class Structure(SubDomain):
def inside(self, x, on_boundary):
return x[2] < 0.75 + DOLFIN_EPS
#Create Submesh
self.Structure = Structure
self.cell_domains.set_all(0)
subdomain = Structure()
subdomain.mark(self.cell_domains,1)
self.submesh = SubMesh(self.mesh,self.cell_domains,1)
#Test Case for the module
#Solve a test Laplace Equation with a Neumann boundary on the interior
#Changing the F should change the solution
if __name__ == "__main__":
problem = TestProblem()
intbound = InteriorBoundary(problem.mesh)
intbound.create_boundary(problem.submesh)
intfacet = intbound.boundaries[0]
N_S = FacetNormal(problem.submesh)
V = FunctionSpace(problem.mesh,"CG",1)
u = TrialFunction(V)
v = TestFunction(V)
sol = Function(V)
A = inner(grad(u),grad(v))*dx(1)
vec = Constant((3,1))
F = (dot(vec,N_S)*v)('-')*dS(2)
## F = sol*v*dx #If sol is initial this form is 0 when assembled
A = assemble(A,cell_domains=problem.cell_domains,interior_facet_domains=intbound.boundaries[0])
F = assemble(F,cell_domains=problem.cell_domains,interior_facet_domains=intbound.boundaries[0])
#Dirichlet BC
left = "near(x[0],0.0)"
right = "near(x[0],4.0)"
bcleft = DirichletBC(V,Constant(0.0),left)
bcright = DirichletBC(V,Constant(1.0),right)
bcleft.apply(A,F)
bcright.apply(A,F)
A.ident_zeros()
solve(A,sol.vector(),F,"lu")
plot(sol)
interactive()
| 6,856 | 34.900524 | 104 |
py
|
finmag
|
finmag-master/dev/sandbox/demag/FKtruncationsolver.py
|
from dolfin import *
from finmag.demag import solver_base as sb
import numpy as np
import progressbar as pb
##class FKSolver(sb.DeMagSolver):
## """Class containing methods shared by FK solvers"""
## def __init__(self, problem, degree=1):
## super(FKSolver, self).__init__(problem, degree)
class FKSolverTrunc(sb.TruncDeMagSolver):
"""FK Solver using domain truncation"""
###Only partially implemented at the moment
def __init__(self,problem, degree = 1):
self.problem = problem
self.degree = degree
def solve(self):
#Set up spaces,functions, measures etc.
V = FunctionSpace(self.problem.mesh,"CG",self.degree)
if self.problem.mesh.topology().dim() == 1:
Mspace = FunctionSpace(self.problem.mesh,"DG",self.degree)
else:
Mspace = VectorFunctionSpace(self.problem.mesh,"DG",self.degree)
phi0 = Function(V)
phi1 = Function(V)
dxC = self.problem.dxC
dSC = self.problem.dSC
N = FacetNormal(self.problem.coremesh)
#Define the magnetisation
M = interpolate(Expression(self.problem.M),Mspace)
########################################
#Solve for phi0
########################################
## #A boundary point used to specify the pure neumann problem
r = self.problem.r
class BoundPoint(SubDomain):
def inside(self, x, on_boundary):
return near(x[0], 0.5 - r)
dbc1 = DirichletBC(V, 0.0, BoundPoint())
#Forms for Neumann Poisson Equation for phi0
u = TrialFunction(V)
v = TestFunction(V)
a = dot(grad(u),grad(v))*dxC
f = (div(M)*v)*dxC #Source term in core
f += (dot(M,N)*v)('-')*dSC #Neumann Conditions on edge of core
A = assemble(a,cell_domains = self.problem.corefunc, interior_facet_domains = self.problem.coreboundfunc)
F = assemble(f,cell_domains = self.problem.corefunc, interior_facet_domains = self.problem.coreboundfunc)
dbc1.apply(A,F)
A.ident_zeros()
print A.array()
solve(A,phi0.vector(),F)
########################################
#Solve for phi1
########################################
L = FunctionSpace(self.problem.mesh,"CG",self.degree)
VD = FunctionSpace(self.problem.mesh,"DG",self.degree)
W = MixedFunctionSpace((V,L))
u,l = TrialFunctions(W)
v,q = TestFunctions(W)
sol = Function(W)
#Forms for phi1
a = dot(grad(u),grad(v))*dx
f = q('-')*phi0('-')*dSC
a += q('-')*jump(u)*dSC #Jump in solution on core boundary
a += (l*v)('-')*dSC
#Dirichlet BC at our approximate boundary
dbc = DirichletBC(W.sub(0),0.0,"on_boundary")
A = assemble(a,cell_domains = self.problem.corefunc, interior_facet_domains = self.problem.coreboundfunc)
F = assemble(f,cell_domains = self.problem.corefunc, interior_facet_domains = self.problem.coreboundfunc)
dbc.apply(A)
dbc.apply(F)
A.ident_zeros()
solve(A, sol.vector(),F)
solphi,sollag = sol.split()
phi1.assign(solphi)
phitot = Function(V)
print phi0.vector().array()
print phi1.vector().array()
phitot.vector()[:] = phi0.vector() + phi1.vector()
#Store Variables for outside testing
self.V = V
self.phitot = phitot
self.phi0 = phi0
self.phi1 = phi1
self.sol = sol
self.M = M
self.Mspace = Mspace
return phitot
| 3,618 | 32.82243 | 113 |
py
|
finmag
|
finmag-master/dev/sandbox/demag/timings_Krylov_vs_LU_solver/benchmark_solver_types.py
|
#!/usr/bin/env python
import dolfin as df
import numpy as np
import sys
try:
solver_type = sys.argv[1]
except IndexError:
print("Usage: time_solver_types.py SOLVER_TYPE [N]")
sys.exit()
try:
N = int(sys.argv[2])
except IndexError:
N = 3
from finmag.example import barmini, bar
from finmag.example.normal_modes import disk
timings = []
for i in xrange(N):
print("[DDD] Starting run #{}".format(i))
#sim = bar(demag_solver_type=solver_type)
sim = disk(d=100, h=10, maxh=3.0, relaxed=False, demag_solver_type=solver_type)
df.tic()
sim.relax()
timings.append(df.toc())
print("Latest run took {:.2f} seconds.".format(timings[-1]))
print("Timings (in seconds): {}".format(['{:.2f}'.format(t) for t in timings]))
print("Mean: {:.2f}".format(np.mean(timings)))
print("Median: {:.2f}".format(np.median(timings)))
print("Fastest: {:.2f}".format(np.min(timings)))
| 906 | 25.676471 | 83 |
py
|
finmag
|
finmag-master/dev/sandbox/demag/domain_truncation/doffinder.py
|
"""A Utility Module used to locate the Dofs that lie on a common boundary"""
__author__ = "Gabriel Balaban"
__copyright__ = __author__
__project__ = "Finmag"
__organisation__ = "University of Southampton"
from dolfin import *
import numpy as np
def bounddofs(fspace, facetfunc, num):
"""BOUNDary DOFS
fspace
- function space
facetfunc
- mesh facet function that marks the boundary
num
- the number that has been used to mark the boundary
returns the set of global indices for all degrees of freedoms on the boundary
that has been marked with 'num'.
"""
mesh = fspace.mesh()
d = mesh.topology().dim()
dm = fspace.dofmap()
#Array to store the facet dofs.
facet_dofs = np.zeros(dm.num_facet_dofs(),dtype=np.uintc)
#Initialize bounddofset
bounddofs= set([])
for facet in facets(mesh):
if facetfunc[facet.index()] == num:
cells = facet.entities(d)
# Create one cell (since we have CG)
cell = Cell(mesh, cells[0])
# Create a vector with length exactly = #dofs in cell
cell_dofs = np.zeros(dm.cell_dimension(cell.index()),dtype=np.uintc)
#Get the local to global map
dm.tabulate_dofs(cell_dofs,cell)
#Get the local index of the facet with respect to given cell
local_facet_index = cell.index(facet)
#Get *local* dofs
dm.tabulate_facet_dofs(facet_dofs, local_facet_index)
#Add the dofs to the global dof set.
bounddofs = bounddofs.union(set(cell_dofs[facet_dofs]))
return bounddofs
| 1,640 | 31.176471 | 81 |
py
|
finmag
|
finmag-master/dev/sandbox/demag/domain_truncation/prob_trunc_testcases.py
|
"""Standard Demagnetisation Testproblems for truncated solvers"""
__author__ = "Gabriel Balaban"
__copyright__ = __author__
__project__ = "Finmag"
__organisation__ = "University of Southampton"
from dolfin import *
import numpy as np
import prob_base as pb
class MagUnitInterval(pb.TruncDemagProblem):
"""Create 1d test problem where define a mesh,
and a part of the mesh has been marked to be vacuum (with 0) and
a part has been marked to be the ferromagnetic body (with 1).
Can later replace this with a meshfile generated with an external
mesher.
Once the constructor calls the constructor of the base class (TruncDemagProblem), we also
have marked facets.
"""
def __init__(self,n=10):
mesh = UnitInterval(n)
self.r = 0.1 #Radius of magnetic Core
self.gamma = 700 #Suggested parameter for nitsche solver
r = self.r
class IntervalCore(SubDomain):
def inside(self, x, on_boundary):
return x[0] < 0.5 + r + DOLFIN_EPS and x[0] > 0.5 - r - DOLFIN_EPS
#TODO: Make M into a 3d vector here
M = "1"
#Initialize Base Class
super(MagUnitInterval,self).__init__(mesh, IntervalCore(),M)
def desc(self):
return "unit interval demagnetisation test problem"
class MagUnitCircle(pb.TruncDemagProblem):
def __init__(self,n=10):
mesh = UnitCircle(n)
self.r = 0.2 #Radius of magnetic Core
self.gamma = 13.0 #Suggested parameter for nitsche solver
r = self.r
class CircleCore(SubDomain):
def inside(self, x, on_boundary):
return np.linalg.norm(x,2) < r + DOLFIN_EPS
#TODO Make M three dimensional
M = ("1","0")
#Initialize Base Class
super(MagUnitCircle,self).__init__(mesh,CircleCore(),M)
def desc(self):
return "unit circle demagnetisation test problem"
class MagUnitSphere(pb.TruncDemagProblem):
def __init__(self,n=10):
mesh = UnitSphere(10)
self.r = 0.2 #Radius of magnetic Core
self.gamma = 0.9 #Suggested parameter for nitsche solver
r = self.r
class SphereCore(SubDomain):
def inside(self, x, on_boundary):
return x[0]*x[0] + x[1]*x[1] + x[2]*x[2] < r*r + DOLFIN_EPS
M = ("1","0","0")
#Initialize Base Class
super(MagUnitSphere,self).__init__(mesh,SphereCore(),M)
def desc(self):
return "unit sphere demagnetisation test problem"
if __name__ == "__main__":
problem = MagUnitSphere()
print problem.r
print problem.coremesh.coordinates()
plot(problem.coremesh)
interactive()
| 2,679 | 32.5 | 93 |
py
|
finmag
|
finmag-master/dev/sandbox/demag/domain_truncation/test_doffinder.py
|
#Test the dofinder module
from doffinder import bounddofs
from prob_trunc_testcases import *
def test_doffinder1d():
problem = MagUnitInterval()
degree = 1
V = FunctionSpace(problem.mesh,"CG",degree)
bounddofset = bounddofs(V, problem.coreboundfunc,2)
print bounddofset
assert len(bounddofset) == 2,"Failure in doffinder module, a 1-d demagproblem should only have 2 boundary facets"
if __name__ == "__main__":
test_doffinder1d()
| 496 | 28.235294 | 117 |
py
|
finmag
|
finmag-master/dev/sandbox/demag/domain_truncation/prob_base.py
|
"""Base classes for Demagnetisation Problems"""
__author__ = "Gabriel Balaban"
__copyright__ = __author__
__project__ = "Finmag"
__organisation__ = "University of Southampton"
from dolfin import *
from finmag.util.interiorboundary import InteriorBoundary
class TruncDemagProblem(object):
"""Base class for demag problems with truncated domains"""
def __init__(self,mesh,subdomain,M,Ms = 1):
"""
mesh - is the problem mesh
subdomain- Subdomain an object of type SubDomain which defines an
inside of the mesh (to mark the magnetic region)
M - the initial magnetisation (Expression at the moment)
Ms - the saturation magnetisation
"""
#(Currently M is constant)
self.mesh = mesh
self.M = M
self.Ms = Ms
self.subdomain = subdomain
self.calculate_subsandbounds()
def calculate_subsandbounds(self):
"""Calulate the submeshs and their common boundary"""
#Mesh Function
self.corefunc = MeshFunction("uint", self.mesh, self.mesh.topology().dim())
self.corefunc.set_all(0)
self.subdomain.mark(self.corefunc,1)
#generate submesh for the core and vacuum
self.coremesh = SubMesh(self.mesh,self.corefunc,1)
self.vacmesh = SubMesh(self.mesh,self.corefunc,0)
#generate interior boundary
self.corebound = InteriorBoundary(self.mesh)
self.corebound.create_boundary(self.coremesh)
self.coreboundfunc = self.corebound.boundaries[0]
#Store Value of coreboundary number as a constant
self.COREBOUNDNUM = 2
#generate measures
self.dxC = dx(1) #Core
self.dxV = dx(0) #Vacuum
self.dSC = dS(self.COREBOUNDNUM) #Core Boundary
def refine_core(self):
"""Refine the Mesh inside the Magnetic Core"""
#Mark the cells in the core
cell_markers = CellFunction("bool", self.mesh)
cell_markers.set_all(False)
self.subdomain.mark(cell_markers,True)
#Refine
self.mesh = refine(self.mesh, cell_markers)
#Regenerate Subdomains and boundaries
self.calculate_subsandbounds()
| 2,241 | 32.969697 | 83 |
py
|
finmag
|
finmag-master/dev/sandbox/demag/domain_truncation/solver_nitsche.py
|
"""Nitsche's Method for a discontinuous variational formulation is used
to solve a given demag field problem. The parameter gamma tweaks the
amount of discontinuity we allow over the core boundary"""
__author__ = "Gabriel Balaban"
__copyright__ = __author__
__project__ = "Finmag"
__organisation__ = "University of Southampton"
import dolfin as df
import finmag.util.doffinder as dff
import finmag.energies.demag.solver_base as sb
class TruncDeMagSolver(object):
"""Base Class for truncated domain type Demag Solvers"""
def __init__(self,problem,degree = 1):
"""problem - Object from class derived from FEMBEMDemagProblem"""
self.problem = problem
self.degree = degree
#Create the space for the potential function
self.V = df.FunctionSpace(self.problem.mesh,"CG",degree)
#Get the dimension of the mesh
self.D = problem.mesh.topology().dim()
#Create the space for the Demag Field
if self.D == 1:
self.Hdemagspace = df.FunctionSpace(problem.mesh,"DG",0)
else:
self.Hdemagspace = df.VectorFunctionSpace(problem.mesh,"DG",0)
#Convert M into a function
#HF: I think this should always be
#Mspace = VectorFunctionSpace(self.problem.mesh,"DG",self.degree,3)
#GB: ToDo fix the magnetisation of the problems so Mspace is always 3d
#Some work on taking a lower dim Unit Normal and making it 3D is needed
if self.D == 1:
self.Mspace = df.FunctionSpace(self.problem.mesh,"DG",self.degree)
else:
self.Mspace = df.VectorFunctionSpace(self.problem.mesh,"DG",self.degree)
#Define the magnetisation
# At the moment this just accepts strings, tuple of strings
# or a dolfin.Function
# TODO: When the magnetisation no longer are allowed to be
# one-dimensional, remove " or isinstance(self.problem.M, str)"
if isinstance(self.problem.M, tuple) or isinstance(self.problem.M, str):
self.M = df.interpolate(df.Expression(self.problem.M),self.Mspace)
elif 'dolfin.functions.function.Function' in str(type(self.problem.M)):
self.M = self.problem.M
else:
raise NotImplementedError("%s is not implemented." \
% type(self.problem.M))
def restrictfunc(self,function,submesh):
"""
Restricts a function in a P1 space to a submesh
using the fact that the verticies and DOFS are
numbered the same way. A function defined on a P1
space is returned. This will ONLY work for P1 elements
For other elements the dolfin FunctionSpace.restrict()
should be used when it is implemented.
"""
wholemesh = function.function_space().mesh()
#Since compute_vertex_map only accepts a SubMesh object we need to
#create a trivial "SubMesh" of the whole mesh
dummymeshfunc = df.MeshFunction("uint",wholemesh,wholemesh.topology().dim())
dummymeshfunc.set_all(1)
#This is actually the whole mesh, but compute_vertex_map, only accepts a SubMesh
wholesubmesh = df.SubMesh(wholemesh,dummymeshfunc,1)
#Mapping from the wholesubmesh to the wholemesh
map_to_mesh = wholesubmesh.data().mesh_function("parent_vertex_indices")
#This is a dictionary mapping the matching DOFS from a Submesh to a SubMesh
vm = df.compute_vertex_map(submesh,wholesubmesh)
#Now we want to "restrict" the function to the restricted space
restrictedspace = df.FunctionSpace(submesh,"CG",1)
restrictedfunction = df.Function(restrictedspace)
for index,dof in enumerate(restrictedfunction.vector()):
restrictedfunction.vector()[index] = function.vector()[map_to_mesh[vm[index]]]
return restrictedfunction
def get_demagfield(self,phi = None,use_default_function_space = True):
"""
Returns the projection of the negative gradient of
phi onto a DG0 space defined on the same mesh
Note: Do not trust the viper solver to plot the DeMag field,
it can give some wierd results, paraview is recommended instead
use_default_function_space - If true project into self.Hdemagspace,
if false project into a Vector DG0 space
over the mesh of phi.
"""
if phi is None:
phi = self.phi
Hdemag = -df.grad(phi)
if use_default_function_space == True:
Hdemag = df.project(Hdemag,self.Hdemagspace)
else:
if self.D == 1:
Hspace = df.FunctionSpace(phi.function_space().mesh(),"DG",0)
else:
Hspace = df.VectorFunctionSpace(phi.function_space().mesh(),"DG",0)
Hdemag = df.project(Hdemag,Hspace)
return Hdemag
def save_function(self,function,name):
"""
The function is saved as a file name.pvd under the folder ~/results.
It can be viewed with paraviewer or mayavi
"""
file = File("results/"+ name + ".pvd")
file << function
class NitscheSolver(TruncDeMagSolver):
def __init__(self,problem, degree = 1):
"""
problem - Object from class derived from TruncDemagProblem
degree - desired polynomial degree of basis functions
"""
self.problem = problem
self.degree = degree
super(NitscheSolver,self).__init__(problem)
def solve(self):
"""Solve the demag problem and store the Solution"""
#Get the solution Space
V = self.V
W = df.MixedFunctionSpace((V,V)) # for phi0 and phi1
u0,u1 = df.TestFunctions(W)
v0,v1 = df.TrialFunctions(W)
sol = df.Function(W)
phi0 = df.Function(V)
phi1 = df.Function(V)
phi = df.Function(V)
self.phitest = df.Function(V)
h = self.problem.mesh.hmin() #minimum edge length or smallest diametre of mesh
gamma = self.problem.gamma
#Define the magnetisation
M = self.M
N = df.FacetNormal(self.problem.coremesh) #computes normals on the submesh self.problem.coremesh
dSC = self.problem.dSC #Boundary of Core
dxV = self.problem.dxV #Vacuum
dxC = self.problem.dxC #Core
#Define jumps and averages accross the boundary
jumpu = u1('-') - u0('+') #create a difference symbol
#- is the inward normal
#+ is the outward pointing normal or direction.
avggradu = (df.grad(u1('-')) + df.grad(u0('+')))*0.5
jumpv = (v1('-') - v0('+'))
avgv = (v1('-') + v0('+'))*0.5
avggradv = (df.grad(v1('-')) + df.grad(v0('+')))*0.5
#Forms for Poisson problem with Nitsche Method
a0 = df.dot(df.grad(u0),df.grad(v0))*dxV #Vacuum
a1 = df.dot(df.grad(u1),df.grad(v1))*dxC #Core
#right hand side
f = (-df.div(M)*v1)*dxC #Source term in core
f += (df.dot(M('-'),N('+'))*avgv )*dSC #Prescribed outer normal derivative
#Cross terms on the interior boundary
c = (-df.dot(avggradu,N('+'))*jumpv - df.dot(avggradv,N('+'))*jumpu + gamma*(1/h)*jumpu*jumpv)*dSC
a = a0 + a1 + c
#Dirichlet BC for phi0
dbc = df.DirichletBC(W.sub(0),0.0,"on_boundary") #Need to use W as assemble thinks about W-space
#The following arguments
# cell_domains = self.problem.corefunc, interior_facet_domains = self.problem.coreboundfunc
#tell the assembler about the marks 0 or 1 for the cells and markers 0, 1 and 2 for the facets.
A = df.assemble(a,cell_domains = self.problem.corefunc, interior_facet_domains = self.problem.coreboundfunc)
F = df.assemble(f,cell_domains = self.problem.corefunc, interior_facet_domains = self.problem.coreboundfunc)
#Solve for the solution
dbc.apply(A)
dbc.apply(F)
#Got to here working through the code with Gabriel (HF, 23 Feb 2011)
A.ident_zeros()
df.solve(A, sol.vector(),F)
#Seperate the mixed function and then add the parts
solphi0,solphi1 = sol.split()
phi0.assign(solphi0)
phi1.assign(solphi1)
phi.vector()[:] = phi0.vector() + phi1.vector()
self.phitest.assign(phi)
#Divide the value of phial by 2 on the core boundary
BOUNDNUM = 2
#Get the boundary dofs
corebounddofs = dff.bounddofs(V, self.problem.coreboundfunc, BOUNDNUM)
#Halve their value
for index,dof in enumerate(phi.vector()):
if index in corebounddofs:
phi.vector()[index] = dof*0.5
#Get the function restricted to the magnetic core
self.phi_core = self.restrictfunc(phi,self.problem.coremesh)
#Save the demag field over the core
self.Hdemag_core = self.get_demagfield(self.phi_core,use_default_function_space = False)
self.Hdemag = self.get_demagfield(phi)
#Store variables for outside testing
self.phi = phi
self.phi0 = phi0
self.phi1 = phi1
self.sol = sol
self.gamma = gamma
return phi
| 9,376 | 41.622727 | 116 |
py
|
finmag
|
finmag-master/dev/sandbox/demag/domain_truncation/test_meshsetup.py
|
"""A set of tests to insure that the quality of the submesh and boundary generation of
Interiorboundary and TruncDemagProblem"""
__author__ = "Gabriel Balaban"
__copyright__ = __author__
__project__ = "Finmag"
__organisation__ = "University of Southampton"
from dolfin import *
import prob_trunc_testcases as pttc
#Global Tolerance for inexact comparisons in percent
TOL = 0.01
class TestTruncMeshSetup(object):
def test_1d(self):
problem = pttc.MagUnitInterval()
self.problem_tests(problem)
def test_2d(self):
problem = pttc.MagUnitCircle()
self.problem_tests(problem)
def test_3d(self):
problem = pttc.MagUnitSphere()
self.problem_tests(problem)
def problem_tests(self,problem):
#Test to see if the internal boundary volume is correct
vol = self.bound_volume(problem)
voltrue = self.submesh_volume(problem)
assert self.compare(vol,voltrue), "Error in internal boundary creation for problem " + problem.desc() + \
" error in approximate volume %g is not within TOL %g of the true volume %g"%(vol,TOL,voltrue)
#Test to see if the number of internal boundary facets is correct
cfound = problem.corebound.countfacets
cactual = self.bound_facets(problem)
assert cfound == cactual, "Error in internal boundary creation for problem " + problem.desc() + \
" the number of facets in the generated boundary %d does not equal that of the coremesh boundary %d"%(cfound,cactual)
#Test to see if the core mesh refinement works
self.refinement_test(problem)
def bound_volume(self,problem):
"""Gives the volume of the surface of the magnetic core"""
V = FunctionSpace(problem.mesh,"CG",1)
one = interpolate(Constant(1),V)
volform = one('-')*problem.dSC
return assemble(volform,interior_facet_domains = problem.coreboundfunc)
def submesh_volume(self,problem):
"""coreboundmesh = BoundaryMesh(problem.coremesh)"""
V = FunctionSpace(problem.coremesh,"CG",1)
one = interpolate(Constant(1),V)
volform = one*ds
return assemble(volform)
def bound_facets(self,problem):
"""Gives the number of facets in the boundary of the coremesh"""
boundmesh = BoundaryMesh(problem.coremesh)
return boundmesh.num_cells()
def compare(self,est,trueval):
"""Returns if the error in the estimate less than TOL percent of trueval"""
relerror = abs((est - trueval)/trueval )
print relerror
return relerror < TOL
def refinement_test(self,problem):
"""Test to see if the core refinement works"""
numcellsbefore =problem.mesh.num_cells()
problem.refine_core()
assert problem.mesh.num_cells() > numcellsbefore,"Error in core mesh refinement in problem " + problem.desc()+ " total number of cells did not increase"
| 2,994 | 41.183099 | 161 |
py
|
finmag
|
finmag-master/dev/sandbox/dg_sim/demag_test.py
|
import dolfin as df
import numpy as np
from math import pi
from finmag.util.meshes import sphere
from fk_demag import FKDemagDG as FKDemag
from finmag.util.consts import mu0
radius = 1.0
maxh = 0.2
unit_length = 1e-9
volume = 4 * pi * (radius * unit_length) ** 3 / 3
def setup_demag_sphere(Ms):
mesh = sphere(r=radius, maxh=maxh)
S3 = df.VectorFunctionSpace(mesh, "DG", 0)
m = df.Function(S3)
m.assign(df.Constant((1, 0, 0)))
demag = FKDemag()
demag.setup(S3, m, Ms, unit_length)
return demag
def test_interaction_accepts_name():
"""
Check that the interaction accepts a 'name' argument and has a 'name' attribute.
"""
demag = FKDemag(name='MyDemag')
assert hasattr(demag, 'name')
def test_demag_field_for_uniformly_magnetised_sphere():
demag = setup_demag_sphere(Ms=1)
H = demag.compute_field().reshape((3, -1))
H_expected = np.array([-1.0 / 3.0, 0.0, 0.0])
print "Got demagnetising field H =\n{}.\nExpected mean H = {}.".format(
H, H_expected)
TOL = 8e-3
diff = np.max(np.abs(H - H_expected[:, np.newaxis]), axis=1)
print "Maximum difference to expected result per axis is {}. Comparing to limit {}.".format(diff, TOL)
assert np.max(diff) < TOL
TOL = 12e-3
spread = np.abs(H.max(axis=1) - H.min(axis=1))
print "The values spread {} per axis. Comparing to limit {}.".format(spread, TOL)
assert np.max(spread) < TOL
def test_demag_energy_for_uniformly_magnetised_sphere():
Ms = 800e3
demag = setup_demag_sphere(Ms)
E = demag.compute_energy()
E_expected = (1.0 / 6.0) * mu0 * Ms ** 2 * volume # -mu0/2 Integral H * M with H = - M / 3
print "Got E = {}. Expected E = {}.".format(E, E_expected)
REL_TOL = 3e-2
rel_diff = abs(E - E_expected) / abs(E_expected)
print "Relative difference is {:.3g}%. Comparing to limit {:.3g}%.".format(
100 * rel_diff, 100 * REL_TOL)
assert rel_diff < REL_TOL
def test_energy_density_for_uniformly_magnetised_sphere():
Ms = 800e3
demag = setup_demag_sphere(Ms)
rho = demag.energy_density()
E_expected = (1.0 / 6.0) * mu0 * Ms**2 * volume # -mu0/2 Integral H * M with H = - M / 3
rho_expected = E_expected / volume
print "Got mean rho = {:.3e}. Expected rho = {:.3e}.".format(np.mean(rho), rho_expected)
REL_TOL = 1.8e-2
rel_diff = np.max(np.abs(rho - rho_expected)) / abs(rho_expected)
print "Maximum relative difference = {:.3g}%. Comparing to limit {:.3g}%.".format(
100 * rel_diff, 100 * REL_TOL)
assert rel_diff < REL_TOL
def test_energy_density_for_uniformly_magnetised_sphere_as_function():
Ms = 800e3
demag = setup_demag_sphere(Ms)
rho = demag.energy_density_function()
print "Probing the energy density at the center of the sphere."
rho_center = rho([0.0, 0.0, 0.0])
E_expected = (1.0 / 6.0) * mu0 * Ms**2 * volume # -mu0/2 Integral H * M with H = - M / 3
rho_expected = E_expected / volume
print "Got rho = {:.3e}. Expected rho = {:.3e}.".format(rho_center, rho_expected)
REL_TOL = 1.3e-2
rel_diff = np.max(np.abs(rho_center - rho_expected)) / abs(rho_expected)
print "Maximum relative difference = {:.3g}%. Comparing to limit {:.3g}%.".format(
100 * rel_diff, 100 * REL_TOL)
assert rel_diff < REL_TOL
def test_regression_Ms_numpy_type():
mesh = sphere(r=radius, maxh=maxh)
S3 = df.VectorFunctionSpace(mesh, "DG", 0)
m = df.Function(S3)
m.assign(df.Constant((1, 0, 0)))
Ms = np.sqrt(6.0 / mu0) # math.sqrt(6.0 / mu0) would work
demag = FKDemag()
demag.setup(S3, m, Ms, unit_length) # this used to fail
| 3,648 | 33.102804 | 106 |
py
|
finmag
|
finmag-master/dev/sandbox/dg_sim/sim.py
|
import logging
import numpy as np
import dolfin as df
from finmag.util import helpers
from finmag.util.meshes import mesh_volume
import finmag.util.consts as consts
from finmag.native import sundials
from finmag.native import llg as native_llg
from finmag.util.fileio import Tablewriter
from finmag.energies import Zeeman
#from exchange import ExchangeDG as Exchange
#from finmag.energies import Demag
from fk_demag import FKDemagDG
logger = logging.getLogger(name='finmag')
class Sim(object):
def __init__(self, mesh, Ms=8e5, unit_length=1.0, name='unnamed', auto_save_data=True):
self.mesh = mesh
self.unit_length=unit_length
self.DG = df.FunctionSpace(mesh, "DG", 0)
self.DG3 = df.VectorFunctionSpace(mesh, "DG", 0, dim=3)
self._m = df.Function(self.DG3)
self.Ms = Ms
self.nxyz_cell=mesh.num_cells()
self._alpha = np.zeros(self.nxyz_cell)
self.m = np.zeros(3*self.nxyz_cell)
self.H_eff = np.zeros(3*self.nxyz_cell)
self.dm_dt = np.zeros(3*self.nxyz_cell)
self.set_default_values()
self.auto_save_data = auto_save_data
self.sanitized_name = helpers.clean_filename(name)
if self.auto_save_data:
self.ndtfilename = self.sanitized_name + '.ndt'
self.tablewriter = Tablewriter(self.ndtfilename, self, override=True)
def set_default_values(self, reltol=1e-8, abstol=1e-8, nsteps=10000000):
self._alpha_mult = df.Function(self.DG)
self._alpha_mult.assign(df.Constant(1))
self._pins = np.array([], dtype="int")
self.volumes = df.assemble(df.TestFunction(self.DG) * df.dx).array()
self.real_volumes=self.volumes*self.unit_length**3
self.Volume = np.sum(self.volumes)
self.alpha = 0.5 # alpha for solve: alpha * _alpha_mult
self.gamma = consts.gamma
self.c = 1e11 # 1/s numerical scaling correction \
# 0.1e12 1/s is the value used by default in nmag 0.2
self.do_precession = True
self._pins = np.array([], dtype="int")
self.interactions = []
self.t = 0
def set_up_solver(self, reltol=1e-8, abstol=1e-8, nsteps=10000):
integrator = sundials.cvode(sundials.CV_BDF, sundials.CV_NEWTON)
integrator.init(self.sundials_rhs, 0, self.m)
integrator.set_linear_solver_sp_gmr(sundials.PREC_NONE)
integrator.set_scalar_tolerances(reltol, abstol)
integrator.set_max_num_steps(nsteps)
self.integrator = integrator
@property
def alpha(self):
"""The damping factor :math:`\\alpha`."""
return self._alpha
@alpha.setter
def alpha(self, value):
self._alpha = value
# need to update the alpha vector as well, which is
# why we have this property at all.
self.alpha_vec = self._alpha * self._alpha_mult.vector().array()
@property
def pins(self):
return self._pins
def compute_effective_field(self):
self.H_eff[:]=0
for interaction in self.interactions:
self.H_eff += interaction.compute_field()
def add(self,interaction):
interaction.setup(self.DG3,
self._m,
self.Ms,
unit_length=self.unit_length)
self.interactions.append(interaction)
def run_until(self, t):
if t < self.t:
return
elif t == 0:
if self.auto_save_data:
self.tablewriter.save()
return
self.integrator.advance_time(t,self.m)
self._m.vector().set_local(self.m)
self.t=t
if self.auto_save_data:
self.tablewriter.save()
def sundials_rhs(self, t, y, ydot):
self.t = t
self.m[:]=y[:]
self._m.vector().set_local(self.m)
self.compute_effective_field()
self.dm_dt[:]=0
char_time = 0.1 / self.c
self.m.shape=(3,-1)
self.H_eff.shape=(3,-1)
self.dm_dt.shape=(3,-1)
native_llg.calc_llg_dmdt(self.m, self.H_eff, t, self.dm_dt, self.pins,
self.gamma, self.alpha_vec,
char_time, self.do_precession)
self.m.shape=(-1)
self.dm_dt.shape=(-1)
self.H_eff.shape=(-1)
ydot[:] = self.dm_dt[:]
return 0
def set_m(self,value):
self.m[:]=helpers.vector_valued_dg_function(value, self.DG3, normalise=True).vector().array()
self._m.vector().set_local(self.m)
@property
def m_average(self):
"""
Compute and return the average polarisation according to the formula
:math:`\\langle m \\rangle = \\frac{1}{V} \int m \: \mathrm{d}V`
"""
mx = df.assemble(df.dot(self._m, df.Constant([1, 0, 0])) * df.dx)
my = df.assemble(df.dot(self._m, df.Constant([0, 1, 0])) * df.dx)
mz = df.assemble(df.dot(self._m, df.Constant([0, 0, 1])) * df.dx)
return np.array([mx, my, mz])/self.Volume
if __name__ == "__main__":
mesh = df.BoxMesh(0, 0, 0, 5, 5, 5, 1, 1, 1)
sim = Sim(mesh, 8.6e5, unit_length=1e-9)
sim.alpha = 0.01
sim.set_m((1, 0, 0))
sim.set_up_solver()
ts = np.linspace(0, 1e-10, 11)
H0 = 1e6
sim.add(Zeeman((0, 0, H0)))
exchange = ExchangeDG(13.0e-12)
sim.add(exchange)
print mesh.num_cells(), mesh.num_vertices()
demag=FKDemagDG()
sim.add(demag)
print demag.compute_field()
for t in ts:
sim.run_until(t)
print sim.m_average
| 5,948 | 28.019512 | 101 |
py
|
finmag
|
finmag-master/dev/sandbox/dg_sim/exchange.py
|
import dolfin as df
import numpy as np
import logging
from finmag.util.consts import mu0
from finmag.util import helpers
import scipy.sparse as sp
import scipy.sparse.linalg as spl
from scipy.sparse.linalg.dsolve import linsolve
logger=logging.getLogger('finmag')
"""
Compute the exchange field in DG0 space with the help of BDM1 space.
With the known magnetisation m in DG space, its gradient sigma in BDM
space can be obtained by solving the linear equation:
A sigma = K1 m
then the exchange fields F can be approached by
F = K2 sigma
"""
def copy_petsc_to_csc(pm):
(m,n) = pm.size(0), pm.size(1)
matrix = sp.lil_matrix((m,n))
for i in range(m):
ids, values = pm.getrow(i)
matrix[i,ids] = values
return matrix.tocsc()
def copy_petsc_to_csr(pm):
(m,n) = pm.size(0), pm.size(1)
matrix = sp.lil_matrix((m,n))
for i in range(m):
ids, values = pm.getrow(i)
matrix[i,ids] = values
return matrix.tocsr()
def sparse_inverse(A):
"""
suppose A is a sparse matrix and its inverse also a sparse matrix.
seems it's already speedup a bit, but we should be able to do better later.
"""
solve = spl.factorized(A)
n = A.shape[0]
assert (n == A.shape[1])
mat = sp.lil_matrix((n,n))
for i in range(n):
b = np.zeros(n)
b[i] = 1
x = solve(b)
ids = np.nonzero(x)[0]
for id in ids:
mat[id,i] = x[id]
return mat.tocsc()
def generate_nonzero_ids(mat):
"""
generate the nonzero column ids for every rows
"""
idxs,idys = mat.nonzero()
max_x=0
for x in idxs:
if x>max_x:
max_x=x
idy=[]
for i in range(max_x+1):
idy.append([])
for i, x in enumerate(idxs):
idy[x].append(idys[i])
assert(len(idy)==max_x+1)
return np.array(idy)
def compute_nodal_triangle():
"""
The nodal vectors are computed using the following normals
n0 = np.array([1,1])/np.sqrt(2)
n1 = np.array([1.0,0])
n2 = np.array([0,-1.0])
"""
v0=[[0,0],[0,0],[1,0],[0,0],[0,-1],[0,0]]
v1=[[1,0],[0,0],[0,0],[0,0],[0,0],[1,-1]]
v2=[[0,0],[0,1],[0,0],[1,-1],[0,0],[0,0]]
divs = np.array([1,1,-1,-1,1,1])/2.0
return v0, v1, v2, divs
def compute_nodal_tetrahedron():
"""
The nodal vectors are computed using the following normals
n0 = np.array([-1,-1, -1])/np.sqrt(3)
n1 = np.array([-1, 0, 0])
n2 = np.array([0, 1, 0])
n3 = np.array([0, 0, -1])
"""
v0 = [[0,0,0],[0,0,0],[0,0,0],[-1,0,0],[0,0,0],[0,0,0],\
[0,1,0],[0,0,0],[0,0,0],[0,0,-1],[0,0,0],[0,0,0]]
v1 = [[-1,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],\
[0,0,0],[-1,1,0],[0,0,0],[0,0,0],[1,0,-1],[0,0,0]]
v2 = [[0,0,0],[0,-1,0],[0,0,0],[0,0,0],[-1,1,0],[0,0,0],\
[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,0,0],[0,1,-1]]
v3 = [[0,0,0],[0,0,0],[0,0,-1],[0,0,0],[0,0,0],[-1,0,1],\
[0,0,0],[0,0,0],[0,1,-1],[0,0,0],[0,0,0],[0,0,0]]
divs = np.array([-1,-1,-1,1,1,1,-1,-1,-1,1,1,1])/6.0
return v0, v1, v2, v3, divs
def assemble_1d(mesh):
DG = df.FunctionSpace(mesh, "DG", 0)
n = df.FacetNormal(mesh)
h = df.CellSize(mesh)
h_avg = (h('+') + h('-'))/2
u = df.TrialFunction(DG)
v = df.TestFunction(DG)
a = 1.0/h_avg*df.dot(df.jump(v, n), df.jump(u, n))*df.dS
K = df.assemble(a)
L = df.assemble(v * df.dx).array()
return copy_petsc_to_csr(K), L
def assemble_2d(mesh):
v0, v1, v2, divs = compute_nodal_triangle()
cs = mesh.coordinates()
BDM = df.FunctionSpace(mesh, "BDM", 1)
fun = df.Function(BDM)
n = fun.vector().size()
mat = sp.lil_matrix((n,n))
m = mesh.num_cells()
mat_K = sp.lil_matrix((n,m))
map = BDM.dofmap()
for cell in df.cells(mesh):
i = cell.entities(0)
cm = []
cm.append(cs[i[1]] - cs[i[0]])
cm.append(cs[i[2]] - cs[i[0]])
A = np.transpose(np.array(cm))
B = np.dot(np.transpose(A),A)
J = np.linalg.det(A)
K = B/abs(J)
cfs = map.cell_dofs(cell.index())
for i in range(6):
for j in range(6):
existing = mat[cfs[i],cfs[j]]
add_new = np.dot(np.dot(K,v0[i]),v0[j]) \
+ np.dot(np.dot(K,v1[i]),v1[j]) \
+ np.dot(np.dot(K,v2[i]),v2[j])
mat[cfs[i],cfs[j]] = existing + add_new/6.0
id_c = cell.index()
for j in range(6):
existing = mat_K[cfs[j],id_c]
if J>0:
mat_K[cfs[j],id_c] = existing + divs[j]
else:
mat_K[cfs[j],id_c] = existing - divs[j]
idy = generate_nonzero_ids(mat)
#set the Neumann boundary condition here
mesh.init(1,2)
for edge in df.edges(mesh):
faces = edge.entities(2)
if len(faces)==1:
f = df.Face(mesh,faces[0])
cfs = map.cell_dofs(f.index())
ids = map.tabulate_facet_dofs(f.index(edge))
zid = cfs[ids]
for i in zid:
mat[i,idy[i]]=0
mat[idy[i],i]=0
mat[i,i] = 1
A_inv = spl.inv(mat.tocsc())
K3 = A_inv * mat_K.tocsr()
K3 = K3.tolil()
idy=generate_nonzero_ids(K3)
mesh.init(1,2)
for edge in df.edges(mesh):
faces = edge.entities(2)
if len(faces)==1:
f = df.Face(mesh,faces[0])
cfs = map.cell_dofs(f.index())
ids = map.tabulate_facet_dofs(f.index(edge))
for i in cfs[ids]:
K3[i,idy[i]] = 0
K1 = mat_K.transpose()
K = K1*K3.tocsr()
DG = df.FunctionSpace(mesh, "DG", 0)
v = df.TestFunction(DG)
L = df.assemble(v * df.dx).array()
return K,L
def assemble_3d(mesh):
v0, v1, v2, v3, divs = compute_nodal_tetrahedron()
cs = mesh.coordinates()
BDM = df.FunctionSpace(mesh, "BDM", 1)
fun = df.Function(BDM)
n = fun.vector().size()
mat = sp.lil_matrix((n,n))
m = mesh.num_cells()
mat_K = sp.lil_matrix((n,m))
map = BDM.dofmap()
for cell in df.cells(mesh):
ci = cell.entities(0)
cm = []
cm.append(cs[ci[1]] - cs[ci[0]])
cm.append(cs[ci[2]] - cs[ci[0]])
cm.append(cs[ci[3]] - cs[ci[0]])
A = np.transpose(np.array(cm))
B = np.dot(np.transpose(A),A)
J = np.linalg.det(A)
K = B/abs(J)
cfs = map.cell_dofs(cell.index())
for i in range(12):
for j in range(12):
tmp = mat[cfs[i],cfs[j]]
tmp_res = np.dot(np.dot(K,v0[i]),v0[j]) \
+ np.dot(np.dot(K,v1[i]),v1[j]) \
+ np.dot(np.dot(K,v2[i]),v2[j]) \
+ np.dot(np.dot(K,v3[i]),v3[j])
mat[cfs[i],cfs[j]] = tmp + tmp_res/24.0
id_c = cell.index()
for j in range(12):
tmp = mat_K[cfs[j],id_c]
if J>0:
mat_K[cfs[j],id_c] = tmp + divs[j]
else:
mat_K[cfs[j],id_c] = tmp - divs[j]
idy=generate_nonzero_ids(mat)
mesh.init(2,3)
for face in df.faces(mesh):
cells = face.entities(3)
if len(cells)==1:
c = df.Cell(mesh,cells[0])
cfs = map.cell_dofs(c.index())
ids = map.tabulate_facet_dofs(c.index(face))
zid = cfs[ids]
for i in zid:
mat[i,idy[i]]=0
mat[idy[i],i]=0
mat[i,i] = 1
import time
t1=time.time()
A_inv=sparse_inverse(mat.tocsc())
#t2=time.time()
#print 't2-t1 (s)',t2-t1
#A_inv = spl.inv(mat.tocsc())
#t3=time.time()
#print 't3-t2 (s)',t3-t2
K3 = A_inv * mat_K.tocsr()
K3 = K3.tolil()
idy=generate_nonzero_ids(K3)
mesh.init(2,3)
for face in df.faces(mesh):
cells = face.entities(3)
if len(cells)==1:
c = df.Cell(mesh,cells[0])
cfs = map.cell_dofs(c.index())
ids = map.tabulate_facet_dofs(c.index(face))
for i in cfs[ids]:
K3[i,idy[i]] = 0
K1 = mat_K.transpose()
K = K1*K3.tocsr()
DG = df.FunctionSpace(mesh, "DG", 0)
v = df.TestFunction(DG)
L = df.assemble(v * df.dx).array()
return K,L
class ExchangeDG(object):
def __init__(self, C, in_jacobian = False, name='ExchangeDG'):
self.C = C
self.in_jacobian=in_jacobian
self.name = name
#@mtimed
def setup(self, DG3, m, Ms, unit_length=1.0):
self.DG3 = DG3
self.m = m
self.Ms = Ms
self.unit_length = unit_length
mesh = DG3.mesh()
dim = mesh.topology().dim()
if dim == 1:
self.K, self.L = assemble_1d(mesh)
elif dim == 2:
self.K, self.L = assemble_2d(mesh)
elif dim == 3:
self.K, self.L = assemble_3d(mesh)
self.mu0 = mu0
self.exchange_factor = 2.0 * self.C / (self.mu0 * Ms * self.unit_length**2)
self.coeff = -self.exchange_factor/self.L
self.H = m.vector().array()
def compute_field(self):
mm = self.m.vector().array()
mm.shape = (3,-1)
self.H.shape=(3,-1)
for i in range(3):
self.H[i][:] = self.coeff * (self.K * mm[i])
mm.shape = (-1,)
self.H.shape=(-1,)
return self.H
def average_field(self):
"""
Compute the average field.
"""
return helpers.average_field(self.compute_field())
class ExchangeDG2(object):
def __init__(self, C, in_jacobian = True, name='ExchangeDG'):
self.C = C
self.in_jacobian=in_jacobian
self.name = name
#@mtimed
def setup(self, DG3, m, Ms, unit_length=1.0):
self.DG3 = DG3
self.m = m
self.Ms = Ms
self.unit_length = unit_length
mesh = DG3.mesh()
self.mesh = mesh
DG = df.FunctionSpace(mesh, "DG", 0)
BDM = df.FunctionSpace(mesh, "BDM", 1)
#deal with three components simultaneously, each represents a vector
sigma = df.TrialFunction(BDM)
tau = df.TestFunction(BDM)
u = df.TrialFunction(DG)
v = df.TestFunction(DG)
# what we need is A x = K1 m
#a0 = (df.dot(sigma0, tau0) + df.dot(sigma1, tau1) + df.dot(sigma2, tau2)) * df.dx
a0 = df.dot(sigma, tau) * df.dx
self.A = df.assemble(a0)
a1 = - (df.div(tau) * u) * df.dx
self.K1 = df.assemble(a1)
C = sp.lil_matrix(self.K1.array())
self.KK1 = C.tocsr()
def boundary(x, on_boundary):
return on_boundary
# actually, we need to apply the Neumann boundary conditions.
zero = df.Constant((0,0,0))
self.bc = df.DirichletBC(BDM, zero, boundary)
#print 'before',self.A.array()
self.bc.apply(self.A)
#print 'after',self.A.array()
#AA = sp.lil_matrix(self.A.array())
AA = copy_petsc_to_csc(self.A)
self.solver = sp.linalg.factorized(AA.tocsc())
#LU = sp.linalg.spilu(AA)
#self.solver = LU.solve
a2 = (df.div(sigma) * v) * df.dx
self.K2 = df.assemble(a2)
self.L = df.assemble(v * df.dx).array()
self.mu0 = mu0
self.exchange_factor = 2.0 * self.C / (self.mu0 * Ms * self.unit_length**2)
self.coeff = self.exchange_factor/self.L
self.K2 = copy_petsc_to_csr(self.K2)
# b = K m
self.b = df.PETScVector()
# the vector in BDM space
self.sigma_v = df.PETScVector()
# to store the exchange fields
#self.H = df.PETScVector()
self.H_eff = m.vector().array()
self.m_x = df.PETScVector(self.m.vector().size()/3)
#@mtimed
def compute_field(self):
mm = self.m.vector().array()
mm.shape = (3,-1)
self.H_eff.shape=(3,-1)
for i in range(3):
self.m_x.set_local(mm[i])
self.K1.mult(self.m_x, self.b)
self.bc.apply(self.b)
H = self.solver(self.b.array())
#df.solve(self.A, self.sigma_v, self.b)
self.H_eff[i][:] = (self.K2*H)*self.coeff
mm.shape = (-1,)
self.H_eff.shape=(-1,)
return self.H_eff
def average_field(self):
"""
Compute the average field.
"""
return helpers.average_field(self.compute_field())
"""
Compute the exchange field in DG0 space with the help of BDM1 space.
"""
class ExchangeDG_bak(object):
def __init__(self, C, in_jacobian = False, name='ExchangeDG'):
self.C = C
self.in_jacobian=in_jacobian
self.name = name
#@mtimed
def setup(self, DG3, m, Ms, unit_length=1.0):
self.DG3 = DG3
self.m = m
self.Ms = Ms
self.unit_length = unit_length
mesh = DG3.mesh()
self.mesh = mesh
DG = df.FunctionSpace(mesh, "DG", 0)
BDM = df.FunctionSpace(mesh, "BDM", 1)
#deal with three components simultaneously, each represents a vector
W1 = df.MixedFunctionSpace([BDM, BDM, BDM])
(sigma0,sigma1,sigma2) = df.TrialFunctions(W1)
(tau0,tau1,tau2) = df.TestFunctions(W1)
W2 = df.MixedFunctionSpace([DG, DG, DG])
(u0,u1,u2) = df.TrialFunctions(W2)
(v0,v1,v2) = df.TestFunction(W2)
# what we need is A x = K1 m
a0 = (df.dot(sigma0, tau0) + df.dot(sigma1, tau1) + df.dot(sigma2, tau2)) * df.dx
self.A = df.assemble(a0)
a1 = - (df.div(tau0) * u0 + df.div(tau1) * u1 + df.div(tau2) * u2 ) * df.dx
self.K1 = df.assemble(a1)
def boundary(x, on_boundary):
return on_boundary
# actually, we need to apply the Neumann boundary conditions.
# we need a tensor here
zero = df.Constant((0,0,0,0,0,0,0,0,0))
self.bc = df.DirichletBC(W1, zero, boundary)
self.bc.apply(self.A)
a2 = (df.div(sigma0) * v0 + df.div(sigma1) * v1 + df.div(sigma2) * v2) * df.dx
self.K2 = df.assemble(a2)
self.L = df.assemble((v0 + v1 + v2) * df.dx).array()
self.mu0 = mu0
self.exchange_factor = 2.0 * self.C / (self.mu0 * Ms * self.unit_length**2)
self.coeff = self.exchange_factor/self.L
# b = K m
self.b = df.PETScVector()
# the vector in BDM space
self.sigma_v = df.PETScVector(self.K2.size(1))
# to store the exchange fields
self.H = df.PETScVector()
#@mtimed
def compute_field(self):
# b = K2 * m
self.K1.mult(self.m.vector(), self.b)
self.bc.apply(self.b)
df.solve(self.A, self.sigma_v, self.b)
self.K2.mult(self.sigma_v, self.H)
return self.H.array()*self.coeff
def average_field(self):
"""
Compute the average field.
"""
return helpers.average_field(self.compute_field())
| 15,900 | 25.996604 | 90 |
py
|
finmag
|
finmag-master/dev/sandbox/dg_sim/sim_test.py
|
import os
import dolfin as df
import numpy as np
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
from sim import Sim
from finmag.energies import Zeeman
from exchange import ExchangeDG as Exchange
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
def test_sim(do_plot=False):
mesh = df.BoxMesh(0, 0, 0, 2, 2, 2, 1, 1, 1)
sim = Sim(mesh, 8.6e5, unit_length=1e-9)
alpha=0.1
sim.alpha = alpha
sim.set_m((1, 0, 0))
sim.set_up_solver()
H0 = 1e5
sim.add(Zeeman((0, 0, H0)))
exchange = Exchange(13.0e-12)
sim.add(exchange)
dt = 1e-12; ts = np.linspace(0, 500 * dt, 100)
precession_coeff = sim.gamma / (1 + alpha ** 2)
mz_ref = []
mz = []
real_ts=[]
for t in ts:
sim.run_until(t)
real_ts.append(sim.t)
mz_ref.append(np.tanh(precession_coeff * alpha * H0 * sim.t))
mz.append(sim.m[-1]) # same as m_average for this macrospin problem
mz=np.array(mz)
if do_plot:
ts_ns = np.array(real_ts) * 1e9
plt.plot(ts_ns, mz, "b.", label="computed")
plt.plot(ts_ns, mz_ref, "r-", label="analytical")
plt.xlabel("time (ns)")
plt.ylabel("mz")
plt.title("integrating a macrospin")
plt.legend()
plt.savefig(os.path.join(MODULE_DIR, "test_sllg.png"))
print("Deviation = {}, total value={}".format(
np.max(np.abs(mz - mz_ref)),
mz_ref))
assert np.max(np.abs(mz - mz_ref)) < 8e-7
if __name__ == "__main__":
test_sim(do_plot=True)
| 1,596 | 22.144928 | 75 |
py
|
finmag
|
finmag-master/dev/sandbox/dg_sim/fk_demag.py
|
"""
A copy from the existing FK code.
This is not a real/pure DG method, I mean, the demagnetisation fields including the magnetic
potential are not totally computed by DG methods, such as IP method or
the mixed form using BDM and DG space. The idea is actually even we use DG space
to represent the effective field and magnetisation, we still can use CG space to compute
the magnetic potential -- this is the simplest way to extend, maybe we could try the
mixed form later.
"""
import numpy as np
import dolfin as df
from finmag.util.consts import mu0
from finmag.native.llg import compute_bem_fk
from finmag.util.meshes import nodal_volume
from finmag.util.timings import Timings, default_timer, timed, mtimed
from finmag.util import helpers
def prepared_timed(measurement_group, timer_to_use):
def new_timed(measurement_name):
return timed(measurement_name, measurement_group, timer_to_use)
return new_timed
fk_timer = Timings()
fk_timed = prepared_timed("FKDemag", fk_timer)
class FKDemagDG(object):
"""
Computation of the demagnetising field using the Fredkin-Koehler hybrid FEM/BEM technique.
Fredkin, D.R. and Koehler, T.R., "`Hybrid method for computing demagnetizing fields`_",
IEEE Transactions on Magnetics, vol.26, no.2, pp.415-417, Mar 1990.
.. _Hybrid method for computing demagnetizing fields: http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=106342
"""
def __init__(self, name='DemagDG'):
"""
Create a new FKDemag instance.
The attribute `parameters` is a dict that contains the settings for the solvers
for the Neumann (potential phi_1) and Laplace (potential phi_2) problems.
Setting the method used by the solvers:
Change the entries `phi_1_solver` and `phi_2_solver` to a value from
`df.list_krylov_solver_methods()`. Default is dolfin's default.
Setting the preconditioners:
Change the entries `phi_1_preconditioner` and `phi_2_preconditioner` to
a value from `df.list_krylov_solver_preconditioners()`. Default is dolfin's default.
Setting the tolerances:
Change the existing entries inside `phi_1` and `phi_2` which are themselves dicts.
You can add new entries to these dicts as well. Everything which is
understood by `df.KrylovSolver` is valid.
"""
self.name = name
self.in_jacobian = False
default_parameters = {
'absolute_tolerance': 1e-6,
'relative_tolerance': 1e-6,
'maximum_iterations': int(1e4)
}
self.parameters = {
'phi_1_solver': 'default',
'phi_1_preconditioner': 'default',
'phi_1': default_parameters,
'phi_2_solver': 'default',
'phi_2_preconditioner': 'default',
'phi_2': default_parameters.copy()
}
@mtimed(default_timer)
def setup(self, DG3, m, Ms, unit_length=1):
"""
Setup the FKDemag instance. Usually called automatically by the Simulation object.
*Arguments*
S3: dolfin.VectorFunctionSpace
The finite element space the magnetisation is defined on.
m: dolfin.Function on S3
The unit magnetisation.
Ms: float
The saturation magnetisation in A/m.
unit_length: float
The length (in m) represented by one unit on the mesh. Default 1.
"""
self.m = m
self.Ms = Ms
self.unit_length = unit_length
mesh = DG3.mesh()
self.S1 = df.FunctionSpace(mesh, "Lagrange", 1)
self.S3 = df.VectorFunctionSpace(mesh, "Lagrange", 1)
self.dim = mesh.topology().dim()
self.n = df.FacetNormal(mesh)
self.DG3 = DG3
self._test1 = df.TestFunction(self.S1)
self._trial1 = df.TrialFunction(self.S1)
self._test3 = df.TestFunction(self.S3)
self._trial3 = df.TrialFunction(self.S3)
self._test_dg3 = df.TestFunction(self.DG3)
self._trial_dg3 = df.TrialFunction(self.DG3)
# for computation of energy
self._nodal_volumes = nodal_volume(self.S1, unit_length)
self._H_func = df.Function(DG3) # we will copy field into this when we need the energy
self._E_integrand = -0.5 * mu0 * df.dot(self._H_func, self.m * self.Ms)
self._E = self._E_integrand * df.dx
self._nodal_E = df.dot(self._E_integrand, self._test1) * df.dx
self._nodal_E_func = df.Function(self.S1)
# for computation of field and scalar magnetic potential
self._poisson_matrix = self._poisson_matrix()
self._poisson_solver = df.KrylovSolver(self._poisson_matrix,
self.parameters['phi_1_solver'], self.parameters['phi_1_preconditioner'])
self._poisson_solver.parameters.update(self.parameters['phi_1'])
self._laplace_zeros = df.Function(self.S1).vector()
self._laplace_solver = df.KrylovSolver(
self.parameters['phi_2_solver'], self.parameters['phi_2_preconditioner'])
self._laplace_solver.parameters.update(self.parameters['phi_2'])
self._laplace_solver.parameters["preconditioner"]["same_nonzero_pattern"] = True
with fk_timed('compute BEM'):
if not hasattr(self, "_bem"):
self._bem, self._b2g_map = compute_bem_fk(df.BoundaryMesh(mesh, 'exterior', False))
self._phi_1 = df.Function(self.S1) # solution of inhomogeneous Neumann problem
self._phi_2 = df.Function(self.S1) # solution of Laplace equation inside domain
self._phi = df.Function(self.S1) # magnetic potential phi_1 + phi_2
# To be applied to the vector field m as first step of computation of _phi_1.
# This gives us div(M), which is equal to Laplace(_phi_1), equation
# which is then solved using _poisson_solver.
self._Ms_times_divergence = df.assemble(self.Ms * df.inner(self._trial_dg3, df.grad(self._test1)) * df.dx)
self._setup_gradient_computation()
@mtimed(default_timer)
def precomputed_bem(self, bem, b2g_map):
"""
If the BEM and a boundary to global vertices map are known, they can be
passed to the FKDemag object with this method so it will skip
re-computing them.
"""
self._bem, self._b2g_map = bem, b2g_map
@mtimed(default_timer)
def compute_potential(self):
"""
Compute the magnetic potential.
*Returns*
df.Function
The magnetic potential.
"""
self._compute_magnetic_potential()
return self._phi
@mtimed(default_timer)
def compute_field(self):
"""
Compute the demagnetising field.
*Returns*
numpy.ndarray
The demagnetising field.
"""
self._compute_magnetic_potential()
return self._compute_gradient()
def average_field(self):
"""
Compute the average demag field.
"""
return helpers.average_field(self.compute_field())
@mtimed(default_timer)
def compute_energy(self):
"""
Compute the total energy of the field.
.. math::
E_\\mathrm{d} = -\\frac12 \\mu_0 \\int_\\Omega
H_\\mathrm{d} \\cdot \\vec M \\mathrm{d}x
*Returns*
Float
The energy of the demagnetising field.
"""
self._H_func.vector()[:] = self.compute_field()
return df.assemble(self._E) * self.unit_length ** self.dim
@mtimed(default_timer)
def energy_density(self):
"""
Compute the energy density in the field.
.. math::
\\rho = \\frac{E_{\\mathrm{d}, i}}{V_i},
where V_i is the volume associated with the node i.
*Returns*
numpy.ndarray
The energy density of the demagnetising field.
"""
self._H_func.vector()[:] = self.compute_field()
nodal_E = df.assemble(self._nodal_E).array() * self.unit_length ** self.dim
return nodal_E / self._nodal_volumes
@mtimed(default_timer)
def energy_density_function(self):
"""
Returns the energy density in the field as a dolfin function to allow probing.
*Returns*
dolfin.Function
The energy density of the demagnetising field.
"""
self._nodal_E_func.vector()[:] = self.energy_density()
return self._nodal_E_func
@mtimed(fk_timer)
def _poisson_matrix(self):
A = df.dot(df.grad(self._trial1), df.grad(self._test1)) * df.dx
return df.assemble(A) # stiffness matrix for Poisson equation
def _compute_magnetic_potential(self):
# compute _phi_1 on the whole domain
g_1 = self._Ms_times_divergence * self.m.vector()
with fk_timed("first linear solve"):
self._poisson_solver.solve(self._phi_1.vector(), g_1)
# compute _phi_2 on the boundary using the Dirichlet boundary
# conditions we get from BEM * _phi_1 on the boundary.
with fk_timed("using boundary conditions"):
phi_1 = self._phi_1.vector()[self._b2g_map]
self._phi_2.vector()[self._b2g_map[:]] = np.dot(self._bem, phi_1.array())
boundary_condition = df.DirichletBC(self.S1, self._phi_2, df.DomainBoundary())
A = self._poisson_matrix.copy()
b = self._laplace_zeros
boundary_condition.apply(A, b)
# compute _phi_2 on the whole domain
with fk_timed("second linear solve"):
self._laplace_solver.solve(A, self._phi_2.vector(), b)
# add _phi_1 and _phi_2 to obtain magnetic potential
self._phi.vector()[:] = self._phi_1.vector() + self._phi_2.vector()
@mtimed(fk_timer)
def _setup_gradient_computation(self):
"""
Prepare the discretised gradient to use in :py:meth:`FKDemag._compute_gradient`.
We don't need the gradient field as a continuous field, we are only
interested in the values at specific points. It is thus a waste of
computational effort to use a projection of the gradient field, since
it performs the fairly large operation of assembling a matrix and
solving a linear system of equations.
"""
A = df.inner(self._test_dg3, - df.grad(self._trial1)) * df.dx
# This can be applied to scalar functions.
self._gradient = df.assemble(A)
# The `A` above is in fact not quite the gradient, since we integrated
# over the volume as well. We will divide by the volume later, after
# the multiplication of the scalar magnetic potential. Since the two
# operations are symmetric (multiplying by volume, dividing by volume)
# we don't have to care for the units, i.e. unit_length.
b = df.dot(self._test_dg3, df.Constant((1, 1, 1))) * df.dx
self._nodal_volumes_S3_no_units = df.assemble(b).array()
@mtimed(fk_timer)
def _compute_gradient(self):
"""
Get the demagnetising field from the magnetic scalar potential.
.. math::
\\vec{H}_{\\mathrm{d}} = - \\nabla \\phi (\\vec{r})
Using dolfin, we would translate this to
.. sourcecode::
H_d = df.project(- df.grad(self._phi), self.S3)
but the method used here is computationally less expensive.
"""
H = self._gradient * self._phi.vector()
return H.array() / self._nodal_volumes_S3_no_units
| 11,598 | 35.589905 | 117 |
py
|
finmag
|
finmag-master/dev/sandbox/dg_sim/exchange_test.py
|
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
import pytest
import numpy as np
import dolfin as df
from exchange import ExchangeDG
from finmag.energies.exchange import Exchange
from finmag.util.consts import mu0
from finmag.util.meshes import box
from finmag.field import Field
@pytest.fixture(scope = "module")
def fixt():
"""
Create an Exchange object that will be re-used during testing.
"""
mesh = df.UnitCubeMesh(10, 10, 10)
S3 = df.VectorFunctionSpace(mesh, "DG", 0)
Ms = 1
A = 1
m = df.Function(S3)
exch = ExchangeDG(A)
exch.setup(S3, m, Ms)
return {"exch": exch, "m": m, "A": A, "S3": S3, "Ms": Ms}
def test_interaction_accepts_name():
"""
Check that the interaction accepts a 'name' argument and has a 'name' attribute.
"""
exch = Exchange(13e-12, name='MyExchange')
assert hasattr(exch, 'name')
def test_there_should_be_no_exchange_for_uniform_m(fixt):
"""
Check that exchange field and energy are 0 for uniform magnetisation.
"""
TOLERANCE = 1e-6
fixt["m"].assign(df.Constant((1, 0, 0)))
H = fixt["exch"].compute_field()
print "Asserted zero exchange field for uniform m = (1, 0, 0), got H =\n{}.".format(H.reshape((3, -1)))
assert np.max(np.abs(H)) < TOLERANCE
def plot_m(mesh,xs,m_an,f_dg,f_cg,name='compare.pdf'):
fig=plt.figure()
plt.plot(xs,m_an,'--',label='Analytical')
dg=[]
cg=[]
for x in xs:
dg.append(f_dg(x,1.0,1.0)[2])
cg.append(f_cg(x,1.0,1.0)[2])
np.savetxt('xs.txt',np.array(xs))
np.savetxt('cg.txt', np.array(cg))
np.savetxt('dg.txt', np.array(dg))
np.savetxt('analytical.txt', np.array(m_an))
plt.plot(xs,dg,'.-',label='dg')
plt.plot(xs,cg,'^-',label='cg')
plt.xlabel('x')
plt.ylabel('Field')
plt.legend(loc=8)
fig.savefig(name)
def map_dg2cg(mesh, fun_dg):
CG = df.VectorFunctionSpace(mesh, 'CG', 1, dim=3)
DG = df.VectorFunctionSpace(mesh, 'DG', 0, dim=3)
fun_cg = df.Function(CG)
u = df.TrialFunction(DG)
v = df.TestFunction(CG)
L = df.assemble(df.dot(v, df.Constant([1,1,1]))*df.dx).array()
a = df.dot(u, v) * df.dx
A = df.assemble(a).array()
m = fun_dg.vector().array()
fun_cg.vector()[:]=np.dot(A,m)/L
return fun_cg
if __name__ == "__main__":
#mesh = df.IntervalMesh(10, 0, 2*np.pi)
#
#mesh = df.RectangleMesh(0,0,2*np.pi,1,10,1)
mesh = box(0,0,0,100,5,5, maxh=2.0)
#mesh = df.BoxMesh(0,0,0,100,5,5,50, 2, 2)
#mesh = box(0,0,0,2*np.pi,0.5,0.5, maxh=0.3)
df.plot(mesh)
df.interactive()
DG = df.VectorFunctionSpace(mesh, "DG", 0, dim=3)
C = 1.3
expr = df.Expression(('0', 'sin(2*pi*x[0]/100)','cos(2*pi*x[0]/100)'))
Ms = 8.6e5
m = df.interpolate(expr, DG)
exch = ExchangeDG(C)
exch.setup(DG, m, Ms, unit_length=1)
f = exch.compute_field()
xs=np.linspace(1,99,31)
m_an= -1.0*2*C/(mu0*Ms)*(2*np.pi/100)**2*np.cos(2*np.pi/100*xs)
field=df.Function(DG)
field.vector().set_local(f)
field=map_dg2cg(mesh, field)
S3 = df.VectorFunctionSpace(mesh, "CG", 1, dim=3)
S1 = df.FunctionSpace(mesh, "CG", 1)
m2 = Field(S3, expr)
exch = Exchange(C)
exch.setup(m2, Field(S1,Ms), unit_length=1)
f = exch.compute_field()
field2 = df.Function(S3)
field2.vector().set_local(f)
plot_m(mesh,xs,m_an,field,field2)
df.plot(field)
df.plot(field2)
df.interactive()
| 3,556 | 23.531034 | 107 |
py
|
finmag
|
finmag-master/dev/sandbox/dg_sim/__init__.py
| 0 | 0 | 0 |
py
|
|
finmag
|
finmag-master/dev/sandbox/dg_sim/experiment/compare_exch2.py
|
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
import finmag
import dolfin as df
import numpy as np
xs=np.linspace(0.5,2*np.pi-0.5,10)
def delta_cg(mesh,expr):
V = df.FunctionSpace(mesh, "CG", 1)
Vv = df.VectorFunctionSpace(mesh, "CG", 1)
u = df.interpolate(expr, Vv)
u1 = df.TrialFunction(Vv)
v1 = df.TestFunction(Vv)
K = df.assemble(df.inner(df.grad(u1), df.grad(v1)) * df.dx).array()
L = df.assemble(df.dot(v1, df.Constant([1,1,1])) * df.dx).array()
h=-np.dot(K,u.vector().array())/L
fun = df.Function(Vv)
fun.vector().set_local(h)
res = []
for x in xs:
res.append(fun(x,5,0.5)[0])
df.plot(fun)
return res
def delta_dg(mesh,expr):
CG = df.FunctionSpace(mesh, "CG", 1)
DG = df.FunctionSpace(mesh, "DG", 0)
CG3 = df.VectorFunctionSpace(mesh, "CG", 1)
DG3 = df.VectorFunctionSpace(mesh, "DG", 0)
m = df.interpolate(expr, DG3)
n = df.FacetNormal(mesh)
u_dg = df.TrialFunction(DG)
v_dg = df.TestFunction(DG)
u3 = df.TrialFunction(CG3)
v3 = df.TestFunction(CG3)
a = u_dg * df.inner(v3, n) * df.ds - u_dg * df.div(v3) * df.dx
mm = m.vector().array()
mm.shape = (3,-1)
K = df.assemble(a).array()
L3 = df.assemble(df.dot(v3, df.Constant([1,1,1])) * df.dx).array()
f = np.dot(K,mm[0])/L3
fun1 = df.Function(CG3)
fun1.vector().set_local(f)
df.plot(fun1)
a = df.div(u3) * v_dg * df.dx
A = df.assemble(a).array()
L = df.assemble(v_dg * df.dx).array()
h = np.dot(A,f)/L
fun = df.Function(DG)
fun.vector().set_local(h)
df.plot(fun)
res = []
for x in xs:
res.append(fun(x,5,0.5))
"""
fun2 =df.interpolate(fun, df.VectorFunctionSpace(mesh, "CG", 1))
file = df.File('field2.pvd')
file << fun2
"""
return res
def plot_m(mesh,expr,m_an,xs=xs,name='compare.pdf'):
fig=plt.figure()
plt.plot(xs,m_an,'--',label='Analytical')
cg = delta_cg(mesh,expr)
plt.plot(xs,cg,'.-',label='cg')
dg = delta_dg(mesh,expr)
plt.plot(xs,dg,'^--',label='dg')
plt.legend(loc=8)
fig.savefig(name)
if __name__ == "__main__":
mesh = df.BoxMesh(0,0,0,2*np.pi,10,1,100, 10, 1)
#mesh = df.IntervalMesh(10, 0, 2*np.pi)
expr = df.Expression('cos(x[0])')
expr = df.Expression(('cos(x[0])','0','0'))
m_an=-np.cos(xs)
plot_m(mesh, expr, m_an, name='cos_3d_2.pdf')
expr = df.Expression(('sin(x[0])','0','0'))
m_an=-np.sin(xs)
plot_m(mesh, expr, m_an, name='sin_3d_2.pdf')
expr = df.Expression(('x[0]*x[0]','0','0'))
m_an=2+1e-10*xs
plot_m(mesh, expr, m_an, name='x2_3d_2.pdf')
#df.interactive()
| 2,851 | 21.108527 | 71 |
py
|
finmag
|
finmag-master/dev/sandbox/dg_sim/experiment/compare_exch.py
|
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
import finmag
import dolfin as df
import numpy as np
xs=np.linspace(1e-10+0.5,2*np.pi-0.5,10)
def delta_cg(mesh,expr):
V = df.FunctionSpace(mesh, "CG", 1)
u = df.interpolate(expr, V)
u1 = df.TrialFunction(V)
v1 = df.TestFunction(V)
K = df.assemble(df.inner(df.grad(u1), df.grad(v1)) * df.dx).array()
L = df.assemble(v1 * df.dx).array()
h=-np.dot(K,u.vector().array())/L
fun = df.Function(V)
fun.vector().set_local(h)
dim = mesh.topology().dim()
res = []
if dim == 1:
for x in xs:
res.append(fun(x))
elif dim == 2:
df.plot(fun)
#df.interactive()
for x in xs:
res.append(fun(x,0.5))
elif dim == 3:
for x in xs:
res.append(fun(x,0.5,0.5))
return res
def printaa(expr,name):
print '='*100
print name
print np.max(np.abs(df.assemble(expr).array()))
print '-'*100
def delta_dg(mesh,expr):
V = df.FunctionSpace(mesh, "DG", 1)
m = df.interpolate(expr, V)
n = df.FacetNormal(mesh)
h = df.CellSize(mesh)
h_avg = (h('+') + h('-'))/2.0
alpha = 1.0
gamma = 0
u = df.TrialFunction(V)
v = df.TestFunction(V)
a = df.dot(df.grad(v), df.grad(u))*df.dx \
- df.dot(df.avg(df.grad(v)), df.jump(u, n))*df.dS \
- df.dot(df.jump(v, n), df.avg(df.grad(u)))*df.dS \
+ alpha/h_avg*df.dot(df.jump(v, n), df.jump(u, n))*df.dS
#- df.dot(df.grad(v), u*n)*df.ds \
#- df.dot(v*n, df.grad(u))*df.ds \
#+ gamma/h*v*u*df.ds
#a = 1.0/h_avg*df.dot(df.jump(v, n), df.jump(u, n))*df.dS
#- df.dot(df.grad(v), u*n)*df.ds \
#- df.dot(v*n, df.grad(u))*df.ds \
#+ gamma/h*v*u*df.ds
"""
a1 = df.dot(df.grad(v), df.grad(u))*df.dx
a2 = df.dot(df.avg(df.grad(v)), df.jump(u, n))*df.dS
a3 = df.dot(df.jump(v, n), df.avg(df.grad(u)))*df.dS
a4 = alpha/h_avg*df.dot(df.jump(v, n), df.jump(u, n))*df.dS
a5 = df.dot(df.grad(v), u*n)*df.ds
a6 = df.dot(v*n, df.grad(u))*df.ds
a7 = alpha/h*v*u*df.ds
printaa(a1,'a1')
printaa(a2,'a2')
printaa(a3,'a3')
printaa(a4,'a4')
printaa(a5,'a5')
printaa(a6,'a6')
printaa(a7,'a7')
"""
K = df.assemble(a).array()
L = df.assemble(v * df.dx).array()
h = -np.dot(K,m.vector().array())/L
fun = df.Function(V)
fun.vector().set_local(h)
DG1 = df.FunctionSpace(mesh, "DG", 1)
CG1 = df.FunctionSpace(mesh, "CG", 1)
#fun = df.interpolate(fun, DG1)
fun = df.project(fun, CG1)
dim = mesh.topology().dim()
res = []
if dim == 1:
for x in xs:
res.append(fun(x))
elif dim == 2:
df.plot(fun)
df.interactive()
for x in xs:
res.append(fun(x,0.5))
elif dim == 3:
for x in xs:
res.append(fun(x,0.5,0.5))
return res
def plot_m(mesh,expr,m_an,xs=xs,name='compare.pdf'):
fig=plt.figure()
plt.plot(xs,m_an,'--',label='Analytical')
cg = delta_cg(mesh,expr)
plt.plot(xs,cg,'.-',label='cg')
dg = delta_dg(mesh,expr)
plt.plot(xs,dg,'^--',label='dg')
plt.legend(loc=8)
fig.savefig(name)
if __name__ == "__main__":
expr = df.Expression('cos(x[0])')
m_an=-np.cos(xs)
mesh = df.IntervalMesh(100, 0, 2*np.pi)
plot_m(mesh, expr, m_an, name='cos_1d.pdf')
mesh = df.RectangleMesh(0,0,2*np.pi, 1, 20, 1)
plot_m(mesh, expr, m_an, name='cos_2d.pdf')
mesh = df.BoxMesh(0,0,0,2*np.pi,1,1,50, 1, 1)
plot_m(mesh, expr, m_an, name='cos_3d.pdf')
"""
expr = df.Expression('sin(x[0])')
m_an=-np.sin(xs)
plot_m(mesh, expr, m_an, name='sin_3d.pdf')
expr = df.Expression('x[0]*x[0]')
m_an=2+1e-10*xs
plot_m(mesh, expr, m_an, name='x2_3d.pdf')
"""
| 4,050 | 22.017045 | 71 |
py
|
finmag
|
finmag-master/dev/sandbox/dg_sim/experiment/cg2dg_fields.py
|
"""
The functions below are intend to test how to obtain the fields in DG0 space
for the case that the potential is stored in CG space.
"""
import dolfin as df
import numpy as np
df.parameters.reorder_dofs_serial = False
def compute_field1(mesh,phi):
V = df.FunctionSpace(mesh, 'CG', 1)
DG3 = df.VectorFunctionSpace(mesh, 'DG', 0)
u = df.TrialFunction(V)
v = df.TestFunction(DG3)
a = df.inner(df.grad(u), v) * df.dx
A = df.assemble(a)
L = df.assemble(df.dot(v, df.Constant([1,1])) * df.dx).array()
m = A*phi.vector()
f = df.Function(DG3)
f.vector().set_local(m.array()/L)
return f
def compute_field2(mesh,phi):
V = df.FunctionSpace(mesh, 'CG', 1)
DG3 = df.VectorFunctionSpace(mesh, 'DG', 0)
sig = df.TrialFunction(DG3)
v = df.TestFunction(DG3)
a = df.inner(sig, v) * df.dx
b = df.inner(df.grad(phi), v) * df.dx
f = df.Function(DG3)
df.solve(a == b, f)
return f
if __name__ == "__main__":
#mesh = df.UnitCubeMesh(32,32,1)
mesh = df.UnitSquareMesh(32,32)
S = df.FunctionSpace(mesh, "CG", 1)
expr = df.Expression("10*exp(-(pow(x[0] - 0.5, 2) + pow(x[1] - 0.5, 2)) / 0.2)")
phi = df.interpolate(expr, S)
m1=compute_field1(mesh,phi)
m2=compute_field2(mesh,phi)
diff = m1.vector()-m2.vector()
print 'max diff:',np.max(np.abs(diff.array()))
df.plot(m1)
df.plot(m2)
df.interactive()
| 1,522 | 18.525641 | 84 |
py
|
finmag
|
finmag-master/dev/sandbox/dg_sim/experiment/demag_test_dg.py
|
import dolfin as df
import numpy as np
df.parameters.reorder_dofs_serial = False
mu0=np.pi*4e-7
#import matplotlib as mpl
#mpl.use("Agg")
#import matplotlib.pyplot as plt
def compute_phi(mesh,m):
V = df.FunctionSpace(mesh, 'CG', 1)
W = df.VectorFunctionSpace(mesh, 'CG', 1)
w = df.TrialFunction(W)
v = df.TestFunction(V)
b = df.inner(w, df.grad(v))*df.dx
D = df.assemble(b)
n = df.FacetNormal(mesh)
print 'cg',df.assemble(df.dot(w,n)*v*df.ds).array()
h = D * m.vector()
f = df.Function(V)
f.vector().set_local(h.array())
return f
def compute_phi2(mesh,m):
V = df.FunctionSpace(mesh, 'CG', 1)
W = df.VectorFunctionSpace(mesh, 'CG', 1)
w = df.TrialFunction(W)
v = df.TestFunction(V)
n = df.FacetNormal(mesh)
b = -df.div(w)*v*df.dx+df.dot(w,n)*v*df.ds
D = df.assemble(b)
print '='*100,'CG:', np.max(df.assemble(df.div(w)*v*df.dx).array())
h = D * m.vector()
f = df.Function(V)
f.vector().set_local(h.array())
return f
def compute_phi_dg(mesh,m):
V = df.FunctionSpace(mesh, 'CG', 1)
W = df.VectorFunctionSpace(mesh, 'DG', 0)
w = df.TrialFunction(W)
v = df.TestFunction(V)
n = df.FacetNormal(mesh)
b = df.inner(w, df.grad(v))*df.dx
D = df.assemble(b)
h = D * m.vector()
f = df.Function(V)
f.vector().set_local(h.array())
return f
def compute_phi_dg2(mesh,m):
V = df.FunctionSpace(mesh, 'CG', 1)
W = df.VectorFunctionSpace(mesh, 'DG', 0)
w = df.TrialFunction(W)
v = df.TestFunction(V)
n = df.FacetNormal(mesh)
b = -df.div(w)*v*df.dx+df.dot(w,n)*v*df.ds
D = df.assemble(b)
print '='*100, np.max(df.assemble(df.div(w)*v*df.dx).array())
h = D * m.vector()
f = df.Function(V)
f.vector().set_local(h.array())
return f
def compute_phi_direct(mesh,m):
V = df.FunctionSpace(mesh, 'CG', 1)
n = df.FacetNormal(mesh)
v = df.TestFunction(V)
b = df.dot(n, m)*v*df.ds - df.div(m)*v*df.dx
h = df.assemble(b)
f = df.Function(V)
f.vector().set_local(h.array())
return f
def test_phi(mesh):
V = df.VectorFunctionSpace(mesh, "CG", 1)
Vd = df.VectorFunctionSpace(mesh, 'DG', 0)
expr = df.Expression(("sin(x[0])","cos(x[0])","0"))
m_cg = df.interpolate(expr, V)
m_dg = df.interpolate(expr, Vd)
p_cg=compute_phi(mesh,m_cg)
p_cg2=compute_phi2(mesh,m_cg)
p_cg3=compute_phi_direct(mesh,m_cg)
p_dg=compute_phi_dg(mesh,m_dg)
p_dg2=compute_phi_dg2(mesh,m_dg)
p_dg3=compute_phi_direct(mesh,m_dg)
d = p_dg.vector().array()-p_dg2.vector().array()
print 'dg max diff',np.max(abs(d))
d = p_dg2.vector().array()-p_dg3.vector().array()
print 'dg max2 diff',np.max(abs(d))
d = p_cg.vector().array()-p_cg2.vector().array()
print 'cg max diff',np.max(abs(d))
d = p_cg2.vector().array()-p_cg3.vector().array()
print 'cg max2 diff',np.max(abs(d))
df.plot(p_cg)
df.plot(p_cg2)
df.plot(p_dg)
df.plot(p_dg2)
def laplace(mesh,phi):
S1 = df.FunctionSpace(mesh, "CG", 1)
S3 = df.VectorFunctionSpace(mesh, "CG", 1)
u1 = df.TrialFunction(S1)
v1 = df.TestFunction(S1)
u3 = df.TrialFunction(S3)
v3 = df.TestFunction(S3)
K = df.assemble(df.inner(df.grad(u1), v3) * df.dx)
L = df.assemble(v1 * df.dx)
h = K*phi.vector()
f = df.Function(S3)
f.vector().set_local(h.array())
return f
def laplace_dg(mesh,phi):
S1 = df.FunctionSpace(mesh, "CG", 1)
S3 = df.VectorFunctionSpace(mesh, "DG", 0)
u1 = df.TrialFunction(S1)
v1 = df.TestFunction(S1)
u3 = df.TrialFunction(S3)
v3 = df.TestFunction(S3)
K = df.assemble(df.inner(df.grad(u1), v3) * df.dx)
L = df.assemble(v1 * df.dx)
h = K*phi.vector()
f = df.Function(S3)
f.vector().set_local(h.array())
return f
if __name__ == "__main__":
mesh = df.UnitCubeMesh(32,32,2)
S = df.FunctionSpace(mesh, "CG", 1)
expr = df.Expression("10*exp(-(pow(x[0] - 0.5, 2) + pow(x[1] - 0.5, 2)) / 0.2)")
phi = df.interpolate(expr, S)
#df.plot(phi)
m=laplace(mesh,phi)
m_dg=laplace_dg(mesh,phi)
#df.plot(m_dg)
test_phi(mesh)
#df.interactive()
| 4,295 | 22.347826 | 84 |
py
|
finmag
|
finmag-master/dev/sandbox/dg_sim/experiment/compare_exch_dg_cg.py
|
import dolfin as df
import numpy as np
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
def delta_cg(mesh,expr):
V = df.FunctionSpace(mesh, "CG", 1)
u = df.interpolate(expr, V)
u1 = df.TrialFunction(V)
v1 = df.TestFunction(V)
K = df.assemble(df.inner(df.grad(u1), df.grad(v1)) * df.dx).array()
L = df.assemble(v1 * df.dx).array()
h=-np.dot(K,u.vector().array())/L
return h
def delta_dg(mesh,expr):
V = df.FunctionSpace(mesh, "DG", 0)
m = df.interpolate(expr, V)
n = df.FacetNormal(mesh)
h = df.CellSize(mesh)
h_avg = (h('+') + h('-'))/2
alpha = 1.0
gamma = 0.0
u = df.TrialFunction(V)
v = df.TestFunction(V)
# for DG 0 case, only term contain alpha is nonzero
a = df.dot(df.grad(v), df.grad(u))*df.dx \
- df.dot(df.avg(df.grad(v)), df.jump(u, n))*df.dS \
- df.dot(df.jump(v, n), df.avg(df.grad(u)))*df.dS \
+ alpha/h_avg*df.dot(df.jump(v, n), df.jump(u, n))*df.dS \
- df.dot(df.grad(v), u*n)*df.ds \
- df.dot(v*n, df.grad(u))*df.ds \
+ gamma/h*v*u*df.ds
K = df.assemble(a).array()
L = df.assemble(v * df.dx).array()
h = -np.dot(K,m.vector().array())/(L)
xs=[]
for cell in df.cells(mesh):
xs.append(cell.midpoint().x())
print len(xs),len(h)
return xs,h
def plot_m(mesh,expr,m_an,name='compare.pdf'):
fig=plt.figure()
xs=mesh.coordinates().flatten()
plt.plot(xs,m_an,'--',label='Analytical')
cg = delta_cg(mesh,expr)
plt.plot(xs,cg,'.-',label='cg')
xs,dg = delta_dg(mesh,expr)
print xs,dg
plt.plot(xs,dg,'^--',label='dg')
plt.legend(loc=8)
fig.savefig(name)
if __name__ == "__main__":
mesh = df.UnitIntervalMesh(10)
xs=mesh.coordinates().flatten()
expr = df.Expression('cos(2*pi*x[0])')
m_an=-(2*np.pi)**2*np.cos(2*np.pi*xs)
plot_m(mesh, expr, m_an, name='cos.pdf')
expr = df.Expression('sin(2*pi*x[0])')
m_an=-(2*np.pi)**2*np.sin(2*np.pi*xs)
plot_m(mesh, expr, m_an, name='sin.pdf')
expr = df.Expression('x[0]*x[0]')
m_an=2+1e-10*xs
plot_m(mesh, expr, m_an, name='x2.pdf')
| 2,246 | 22.904255 | 71 |
py
|
finmag
|
finmag-master/dev/sandbox/crazy_spin/sim2.py
|
import dolfin as df
import numpy as np
import pylab as plt
from finmag import Simulation as Sim
from finmag.energies import Exchange, DMI, Zeeman
from finmag.energies.zeeman import TimeZeemanPython
from finmag.util.meshes import nanodisk
from finmag.util.consts import mu0
def skyrm_init(x):
r = (x[0]**2 + x[1]**2)**0.5
if r < 50e-9:
return (0, 0, -1)
else:
return (0, 0, 1)
def create_mesh():
d = 30 # nm
thickness = 5 # nm
hmax = 3 # nm
mesh = nanodisk(d, thickness, hmax, save_result=False)
#mesh =
#df.plot(mesh,interactive=True)
return mesh
def create_sim(mesh):
Ms = 3.84e5 # A/m
A = 8.78e-12 # J/m
D = 1.58e-3 # J/m**2
sim = Sim(mesh, Ms, unit_length=1e-9)
sim.set_m((0, 0, 1))
sim.set_tol(reltol=1e-10, abstol=1e-10)
sim.add(Exchange(A))
sim.add(DMI(D))
return sim
def relax():
mesh = create_mesh()
sim = create_sim(mesh)
sim.relax(stopping_dmdt=1e-3)
np.save('m0.npy', sim.m)
def dynamics():
t_exc = 0.5e-9
H_exc_max = 5e-3 / mu0
fc = 20e9
mesh = create_mesh()
sim = create_sim(mesh)
sim.set_m(np.load('m0.npy'))
sim.alpha = 1e-4
H0 = df.Expression(("0","0","1"))
def time_fun(t):
if t<t_exc:
return H_exc_max*np.sinc(2*np.pi*fc*(t-t_exc/2))
else:
return 0
zeeman = TimeZeemanPython(H0,time_fun)
sim.add(zeeman)
t_end = 5e-9
delta_t = 5e-12
t_array = np.arange(0, t_end, delta_t)
for t in t_array:
sim.run_until(t)
df.plot(sim.llg._m)
if __name__=='__main__':
#relax()
dynamics()
| 1,686 | 19.325301 | 60 |
py
|
finmag
|
finmag-master/dev/sandbox/crazy_spin/sim.py
|
import dolfin as df
import numpy as np
import pylab as plt
from finmag import Simulation as Sim
from finmag.energies import Exchange, DMI, Zeeman
from finmag.util.meshes import nanodisk
from finmag.util.consts import mu0
def skyrm_init(x):
r = (x[0]**2 + x[1]**2)**0.5
if r < 50e-9:
return (0, 0, -1)
else:
return (0, 0, 1)
d = 30 # nm
thickness = 5 # nm
hmax = 3 # nm
Ms = 3.84e5 # A/m
A = 8.78e-12 # J/m
D = 1.58e-3 # J/m**2
H = (0, 0, 0)
alpha = 1e-4
t_exc = 0.5e-9
n_exc = 201
H_exc_max = 5e-3 / mu0
fc = 20e9
t_end = 5e-9
delta_t = 5e-12
t_array = np.arange(0, t_end, delta_t)
filename = 'test.npz'
mesh_filename = 'mesh_test.xml'
mesh = nanodisk(d, thickness, hmax, save_result=False)
sim = Sim(mesh, Ms, unit_length=1e-9)
sim.set_m((0, 0, 1))
sim.set_tol(reltol=1e-10, abstol=1e-10)
sim.add(Exchange(A))
sim.add(DMI(D))
sim.add(Zeeman(H))
# Ground state simulation
sim.relax(stopping_dmdt=1e-5)
sim.reset_time(0)
n_nodes = mesh.num_vertices()
m_gnd = np.zeros(3*n_nodes)
m = np.zeros((len(t_array), 3*n_nodes))
m_gnd = sim.llg._m.vector().array()
# Excitation
t_excitation = np.linspace(0, t_exc, n_exc)
H_exc = H_exc_max * np.sinc(2*np.pi*fc*(t_excitation-t_exc/2))
#plt.plot(t_excitation, H_exc)
#plt.show()
sim.alpha = alpha
for i in xrange(len(t_excitation)):
sim.set_H_ext((0, 0, H_exc[i]))
sim.run_until(t_excitation[i])
sim.reset_time(0)
sim.set_H_ext(H)
# Dynamics
for i in xrange(len(t_array)):
sim.run_until(t_array[i])
df.plot(sim.llg._m)
m[i, :] = sim.llg._m.vector().array()
sim.save_vtk('vtk_file_' + str(i) + '.pvd', overwrite=True)
mesh_file = df.File(mesh_filename)
mesh_file << mesh
np.savez('test.npz', m_gnd=m_gnd, m=m, delta_t=np.array([delta_t]))
| 1,753 | 20.13253 | 67 |
py
|
finmag
|
finmag-master/dev/sandbox/repeatability/sundials_ode.py
|
import os
import numpy as np
from finmag.native import sundials
def call_back(t, y):
return y**2-y**3
class Test_Sundials(object):
def __init__(self, call_back, x0):
self.sim = call_back
self.x0 = x0
self.x = x0.copy()
self.ode_count = 0
self.create_integrator()
def create_integrator(self, reltol=1e-6, abstol=1e-6, nsteps=10000):
integrator = sundials.cvode(sundials.CV_BDF, sundials.CV_NEWTON)
integrator.init(self.sundials_rhs, 0, self.x0)
integrator.set_linear_solver_sp_gmr(sundials.PREC_NONE)
integrator.set_scalar_tolerances(reltol, abstol)
integrator.set_max_num_steps(nsteps)
self.integrator = integrator
self.t = 0
def sundials_rhs(self, t, y, ydot):
self.ode_count+=1
#The following line is very important!!!
ydot[:] = 0
ydot[:] = self.sim(t, y)
return 0
def advance_time(self, t):
if t > self.t:
self.integrator.advance_time(t, self.x)
self.t = t
def print_info(self):
print 'sim t=%0.15g'%self.t
print 'x=',self.x
print 'rhs=%d'%self.ode_count
| 1,295 | 22.142857 | 72 |
py
|
finmag
|
finmag-master/dev/sandbox/repeatability/repeatable.py
|
import os
import dolfin as df
import numpy as np
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
import finmag.util.consts as consts
from sundials_ode import Test_Sundials
MODULE_DIR = os.path.dirname(os.path.abspath(__file__))
alpha = 0.01
H0 = 1e5
Ms = 8.6e5
def call_back(t,y):
y.shape = (3,-1)
H = np.zeros(y.shape,dtype=np.double)
H[2,:] = H0
gamma = consts.gamma
alpha_L = alpha/(1 + alpha ** 2)
dm1 = -gamma * np.cross(y, H, axis=0)
dm2 = alpha_L * np.cross(y, dm1, axis=0)
c = 1e11
mm = y[0]*y[0] + y[1]*y[1] + y[2]*y[2]
dm3 = c*(1-mm)*y
dm = dm1+dm2+dm3
y.shape=(-1,)
dm.shape=(-1,)
return dm
def test_sim_ode(do_plot=False):
m0 = np.array([1.0,1.0,0,0,0,0])
sim = Test_Sundials(call_back, m0)
sim.create_integrator(reltol=1e-8, abstol=1e-8)
ts = np.linspace(0, 5e-9, 101)
precession_coeff = consts.gamma / (1 + alpha ** 2)
mz_ref = np.tanh(precession_coeff * alpha * H0 * ts)
mzs = []
length_error = []
for t in ts:
sim.advance_time(t)
mm = sim.x.copy()
print mm
mm.shape=(3,-1)
mx,my,mz = mm[:,-1] # same as m_average for this macrospin problem
mm.shape=(-1,)
mzs.append(mz)
length = np.sqrt(mx**2+my**2+mz**2)
length_error.append(abs(length-1.0))
if do_plot:
ts_ns = ts * 1e9
plt.plot(ts_ns, mzs, "b.", label="computed")
plt.plot(ts_ns, mz_ref, "r-", label="analytical")
plt.xlabel("time (ns)")
plt.ylabel("mz")
plt.title("integrating a macrospin")
plt.legend()
plt.savefig(os.path.join(MODULE_DIR, "test_sim_ode.png"))
print("max deviation = {}, last mz={} and last length error={}".format(
np.max(np.abs(mzs - mz_ref)),
mzs[-1],length_error[-1])
)
if __name__ == "__main__":
test_sim_ode(do_plot=True)
| 2,013 | 20.655914 | 75 |
py
|
finmag
|
finmag-master/dev/bin/ipynbdoctest.py
|
#!/usr/bin/env python
# IPython notebook testing script. This is based on the gist [1] (revision 5).
#
# Each cell is submitted to the kernel, and the outputs are compared
# with those stored in the notebook. If the output is an image this is
# currently ignored.
#
# https://gist.github.com/minrk/2620735
"""
IPython notebook testing script.
Usage: `ipnbdoctest.py foo.ipynb [bar.ipynb [...]]`
"""
import os
import re
import sys
import time
import base64
import string
import argparse
import textwrap
from collections import defaultdict
from Queue import Empty
try:
from IPython.kernel import KernelManager
except ImportError:
from IPython.zmq.blockingkernelmanager \
import BlockingKernelManager as KernelManager
from IPython.nbformat.current import reads, NotebookNode
CELL_EXECUTION_TIMEOUT = 200 # abort cell execution after this time (seconds)
# If any of the following patterns matches the output, the output will
# be discarded. If you don't want to discard the entire line but only
# bits of it, don't use "discard_patterns" but rather add an explicit
# replacement rule in the function 'sanitize()' below. Note that the
# pattern must match the output exactly (from start to finish).
#
# On the other hand, if a line may only occur in the output under
# certain circumstances (such as the matplotlib user warning), it must
# be added here instead of in sanitize(), because otherwise there may
# still be an empty line in the reference output which is not matched
# in the computed output, or vice versa.
DISCARD_PATTERNS_EXACT = \
[('stream', "LOGGING_TIMESTAMP DEBUG: Found unused display :[0-9]+"),
('stream', "LOGGING_TIMESTAMP DEBUG: The mesh '.*' already exists and is automatically returned."),
('stream', "LOGGING_TIMESTAMP DEBUG: Rendering Paraview scene on display :[0-9]+ using xpra."),
('stream', '(/[^/ ]+)+/matplotlib/figure.py:[0-9]+: UserWarning: This figure includes Axes that are not compatible with tight_layout, so its results might be incorrect.\n warnings.warn\("This figure includes Axes that are not "\n'),
('stream', '\n warnings.warn\("This figure includes Axes that are not "\n'),
('stream', "LOGGING_TIMESTAMP WARNING: Removing file '.*' and all associated .vtu files \(because overwrite=True\).\n"),
('stream', "LOGGING_TIMESTAMP WARNING: Warning: Ignoring netgen's output status of 34304."),
#('display_data', "<matplotlib.figure.Figure at 0x[0-9A-F]+>"),
]
DISCARD_PATTERNS_CONTAINED = []
for dep in ['Finmag', 'FinMag', 'Dolfin', 'Matplotlib', 'Numpy', 'Scipy', 'IPython',
'Python', 'Paraview', 'Sundials', 'Boost-Python', 'Linux']:
DISCARD_PATTERNS_CONTAINED.append(('stream', 'DEBUG: *{} *([0-9a-z:+-]+|<unknown>)'.format(dep)))
# This is used to remove coloring from error strings (which makes them unreadable in Jenkins)
ANSI_COLOR_REGEX = "\x1b\[(\d+)?(;\d+)*;?m"
def decolorize(string):
return re.sub(ANSI_COLOR_REGEX, "", string)
def indent(s, numSpaces):
"""
Indent all lines except the first one with numSpaces spaces.
"""
s = string.split(s, '\n')
s = s[:1] + [(numSpaces * ' ') + line for line in s[1:]]
s = string.join(s, '\n')
return s
class IPythonNotebookDoctestError(Exception):
pass
def compare_png(a64, b64):
"""
Compare two b64 PNGs (incomplete).
"""
try:
import Image
except ImportError:
pass
adata = base64.decodestring(a64)
bdata = base64.decodestring(b64)
return True
def keep_cell_output(out):
for output_type, pattern in DISCARD_PATTERNS_EXACT:
pattern = '^' + pattern + '$' # make sure we compare the whole string with the pattern
if out['output_type'] == output_type and re.match(pattern, out['text']):
return False
for output_type, pattern in DISCARD_PATTERNS_CONTAINED:
if out['output_type'] == output_type and re.search(pattern, out['text']):
return False
return True
def sanitize(s):
"""
Sanitize a string for comparison and return the sanitized string.
Fix universal newlines, strip trailing newlines, and normalize
likely random values (date stamps, memory addresses, UUIDs, etc.).
"""
# normalize newline:
s = s.replace('\r\n', '\n')
# ignore trailing newlines (but not space)
#s = s.rstrip('\n')
# normalize hex addresses:
s = re.sub(r'0x[a-f0-9]+', '0xFFFFFFFF', s)
# normalize UUIDs:
s = re.sub(r'[a-f0-9]{8}(\-[a-f0-9]{4}){3}\-[a-f0-9]{12}', 'U-U-I-D', s)
##
## Finmag-related stuff follows below
##
# Remove timestamps in logging output
s = re.sub(r'\[\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d\]', 'LOGGING_TIMESTAMP', s)
# Different kind of timestamp
s = re.sub('(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [ \d]\d \d\d:\d\d:\d\d \d\d\d\d', 'TIMESTAMP', s)
# Deal with temporary filenames
s = re.sub('/tmp/tmp\w{6}/', '/tmp/tmpXXXXXX/', s)
s = re.sub('Computing the eigenvalues and eigenvectors took [0-9]+\.[0-9]+ seconds', 'Computing the eigenvalues and eigenvectors took XXXX seconds', s)
# Ignore timings in Gmsh debugging messages
s = re.sub('Done meshing ([123])D \(\d+\.\d+ s\)', 'Done meshing \1D (XXXXXX s)', s)
# Ignore version information of external dependencies
#s = re.sub('^paraview version .*$', 'PARAVIEW_VERSION', s)
#for dep in ['Finmag', 'Dolfin', 'Matplotlib', 'Numpy', 'Scipy', 'IPython',
# 'Python', 'Paraview', 'Sundials', 'Boost-Python', 'Linux']:
# s = re.sub('DEBUG: *{}: .*'.format(dep), 'VERSION_{}'.format(dep), s)
# Ignore specific location of logging output file
s = re.sub("Finmag logging output will be.*", "FINMAG_LOGGING_OUTPUT", s)
# Ignore exact timing information
s = re.sub("saving took \d+\.\d+ seconds", "saving took XXX seconds", s)
s = re.sub("Saving the data took \d+\.\d+ seconds", "Saving the data took XXX seconds", s)
# Ignore datetime objects
s = re.sub(r'datetime.datetime\([0-9, ]*\)', 'DATETIME_OBJECT', s)
# Ignore filenames in Finmag debugging messages
s = re.sub('LOGGING_TIMESTAMP DEBUG: Loading restart data from (.*).',
'LOGGING_TIMESTAMP DEBUG: Loading restart data from FILENAME.',
s)
s = re.sub('LOGGING_TIMESTAMP INFO: Reloaded and set m (.*) and time=(.*) from .*\.',
'LOGGING_TIMESTAMP INFO: Reloaded and set m \g<1> and time=\g<2> from FILENAME.',
s)
return s
# def consolidate_outputs(outputs):
# """consolidate outputs into a summary dict (incomplete)"""
# data = defaultdict(list)
# data['stdout'] = ''
# data['stderr'] = ''
#
# for out in outputs:
# if out.type == 'stream':
# data[out.stream] += out.text
# elif out.type == 'pyerr':
# data['pyerr'] = dict(ename=out.ename, evalue=out.evalue)
# else:
# for key in ('png', 'svg', 'latex', 'html',
# 'javascript', 'text', 'jpeg'):
# if key in out:
# data[key].append(out[key])
# return data
def report_mismatch(key, test, ref, cell, message):
"""
See compare_outputs - this is just a helper function
to avoid re-writing code twice.
"""
output = "\n"
output += "{}\n".format(message)
output += "We were processing the following cell.input:\n"
output += "--- Cell input start\n"
output += "{}\n".format(cell.input)
output += "--- Cell input end\n"
if key in test and key in ref:
output += "----- Mismatch for key='{}': ---------------------------------------------------\n".format(key)
output += "{}\n".format(test[key])
output += "---------- != ----------"
output += "{}\n".format(ref[key])
output += "--------------------------------------------------------------------------------\n"
else:
output += "Failure with key='{}'\n".format(key)
if not key in test:
output += "key not in test output\n"
if not key in ref:
output += "key not in ref output\n"
assert False, "I think this should be impossible - is it? HF, Dec 2013"
output += "--- Test output, with keys -> values:\n"
for k, v in test.items():
if k == 'traceback':
v = indent('\n'.join(map(decolorize, v)), 41)
output += "\tTest output: {:10} -> {}\n".format(k, v)
output += "--- Reference output, with keys -> values:\n"
for k, v in ref.items():
if k == 'png':
v = '<PNG IMAGE>'
output += "\tReference output: {:10} -> {}\n".format(k, v)
output += "- " * 35 + "\n"
return output
def compare_outputs(test, ref, cell, skip_compare=('png', 'traceback',
'latex', 'prompt_number',
'metadata')):
"""
**Parameters**
``test`` is the output we got from executing the cell
``ref`` is the reference output we expected from the saved
notebook
``cell`` is the cell we are working on - useful to display the input
in case of a fail
``skip_compare`` a list of cell types we ignore
"""
if test.has_key('text'):
if 'LOGGING_TIMESTAMP ERROR: Could not render Paraview scene.' in test['text']:
print(textwrap.dedent("""
=======================================================
Paraview rendering error encountered! Ignoring...
=======================================================
"""))
# If a Paraview rendering error occurred, we simply ignore it and assume
# that the result would have been identical.
test = ref
for key in ref:
if key not in test:
# Note: One possibility for this branch is if an exception
# is raised in the notebook. Typical keys in the test notebook
# are ['evalue', 'traceback', 'ename']. Let's report some more
# detail in this case.
output = report_mismatch(key, test, ref, cell, "Something went wrong")
print(output)
# Now we have printed the failure. We should create a nice
# html snippet, the following is a hack to get going quickly.
# (HF, Dec 2013)
htmlSnippet = "Not HTML, just tracking error:<br><br>\n\n" + output
return False, htmlSnippet
elif (key not in skip_compare) and (test[key] != ref[key]):
output = report_mismatch(key, test, ref, cell, "In more detail:")
print(output)
try:
import diff_match_patch
dmp = diff_match_patch.diff_match_patch()
diffs = dmp.diff_main(ref[key], test[key])
dmp.diff_cleanupSemantic(diffs)
htmlSnippet = dmp.diff_prettyHtml(diffs)
except ImportError:
print("The library 'diff-match-patch' is not installed, thus "
"no diagnostic HTML output of the failed test could be "
"produced. Please consider installing it by saying "
"'sudo pip install diff-match-patch'")
return False, htmlSnippet
return True, ""
def run_cell(shell, iopub, cell):
# print cell.input
shell.execute(cell.input)
# wait for finish, abort if timeout is reached
shell.get_msg(timeout=CELL_EXECUTION_TIMEOUT)
outs = []
while True:
try:
msg = iopub.get_msg(timeout=0.2)
except Empty:
break
msg_type = msg['msg_type']
if msg_type in ('status', 'pyin'):
continue
elif msg_type == 'clear_output':
outs = []
continue
content = msg['content']
# print msg_type, content
out = NotebookNode(output_type=msg_type)
if msg_type == 'stream':
out.stream = content['name']
out.text = content['data']
elif msg_type in ('display_data', 'pyout'):
out['metadata'] = content['metadata']
for mime, data in content['data'].iteritems():
attr = mime.split('/')[-1].lower()
# this gets most right, but fix svg+html, plain
attr = attr.replace('+xml', '').replace('plain', 'text')
setattr(out, attr, data)
if msg_type == 'pyout':
out.prompt_number = content['execution_count']
elif msg_type == 'pyerr':
out.ename = content['ename']
out.evalue = content['evalue']
out.traceback = content['traceback']
else:
print "unhandled iopub msg:", msg_type
outs.append(out)
return outs
def merge_streams(outputs):
"""
Since the Finmag logger uses streams, output that logically
belongs together may be split up in the notebook source. Thus we
merge it here to be able to compare streamed output robustly.
This function also discards outputs matching any of the patterns
in DISCARD_PATTERNS.
"""
# Sanitize all outputs of the cell
for out in outputs:
if 'text' in out.keys():
out['text'] = sanitize(out['text'])
# Discard outputs that match any of the patterns in DISCARD_PATTERNS...
#import ipdb; ipdb.set_trace()
outputs = filter(keep_cell_output, outputs)
if outputs == []:
return []
res = outputs[:1]
for out in outputs[1:]:
prev_out = res[-1]
if (prev_out['output_type'] == 'stream' and
out['output_type'] == 'stream' and
prev_out['stream'] == out['stream']):
prev_out['text'] += out['text']
else:
res.append(out)
# XXX TODO: Remove outputs that are now empty!!!
return res
def test_notebook(nb, debug_failures=False):
km = KernelManager()
km.start_kernel(extra_arguments=['--pylab=inline'], stderr=open(os.devnull, 'w'))
try:
kc = km.client()
kc.start_channels()
iopub = kc.iopub_channel
except AttributeError:
# IPython 0.13
kc = km
kc.start_channels()
iopub = kc.sub_channel
shell = kc.shell_channel
# run %pylab inline, because some notebooks assume this
# even though they shouldn't
shell.execute("pass")
shell.get_msg()
while True:
try:
iopub.get_msg(timeout=1)
except Empty:
break
successes = 0
failures = 0
errors = 0
html_diffs_all = ""
skip_remainder = False
for ws in nb.worksheets:
for cell in ws.cells:
if skip_remainder:
continue
if cell.cell_type != 'code':
continue
# Extract the first line so that we can check for special tags such as IPYTHON_TEST_IGNORE_OUTPUT
first_line = cell['input'].splitlines()[0] if (cell['input'] != '') else ''
if re.search('^#\s*IPYTHON_TEST_SKIP_REMAINDER', first_line):
skip_remainder = True
continue
try:
outs = run_cell(shell, iopub, cell)
# Ignore output from cells tagged with IPYTHON_TEST_IGNORE_OUTPUT
if re.search('^#\s*IPYTHON_TEST_IGNORE_OUTPUT', first_line):
outs = []
except Exception as e:
print "failed to run cell:", repr(e)
print cell.input
errors += 1
continue
#import ipdb; ipdb.set_trace()
failed = False
outs_merged = merge_streams(outs)
cell_outputs_merged = merge_streams(cell.outputs)
for out, ref in zip(outs_merged, cell_outputs_merged):
cmp_result, html_diff = compare_outputs(out, ref, cell)
html_diffs_all += html_diff
if not cmp_result:
if debug_failures:
print(textwrap.dedent("""
==========================================================================
Entering debugger. You can print the reference output and computed output
with "print ref['text']" and "print out['text']", respectively.
==========================================================================
"""))
try:
import ipdb; ipdb.set_trace()
except ImportError:
try:
import pdb; pdb.set_trace()
except ImportError:
raise RuntimeError("Cannot start debugger. Please install pdb or ipdb.")
failed = True
if failed:
print "Failed to replicate cell with the following input: "
print "=== BEGIN INPUT ==================================="
print cell.input
print "=== END INPUT ====================================="
if failures == 0:
# This is the first cell that failed to replicate.
# Let's store its output for debugging.
first_failed_input = cell.input
first_failed_output = outs_merged
first_failed_output_expected = cell_outputs_merged
# For easier debugging, replace the (usually huge) binary
# data of any pngs appearing in the expected or computed
# output with a short string representing the image.
for node in first_failed_output_expected + first_failed_output:
try:
node['png'] = '<PNG IMAGE>'
except KeyError:
pass
failures += 1
else:
successes += 1
sys.stdout.write('.')
sys.stdout.flush()
if failures >= 1:
outfilename = 'ipynbtest_failed_test_differences.html'
with open(outfilename, 'w') as f:
f.write(html_diffs_all)
print("Diagnostic HTML output of the failed test has been "
"written to '{}'".format(outfilename))
print ""
print "tested notebook %s" % nb.metadata.name
print " %3i cells successfully replicated" % successes
if failures:
print " %3i cells mismatched output" % failures
if errors:
print " %3i cells failed to complete" % errors
kc.stop_channels()
km.shutdown_kernel()
del km
if failures or errors:
errmsg = ("The notebook {} failed to replicate successfully."
"".format(nb.metadata['name']))
if failures:
errmsg += \
("Input and output from first failed cell:\n"
"=== BEGIN INPUT ==================================\n"
"{}\n"
"=== BEGIN EXPECTED OUTPUT ========================\n"
"{}\n"
"=== BEGIN COMPUTED OUTPUT ========================\n"
"{}\n"
"==================================================\n"
"".format(first_failed_input,
first_failed_output_expected,
first_failed_output))
raise IPythonNotebookDoctestError(errmsg)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Execute one (or multiple) IPython notebooks cell-by-cell and compare the results of each computed result with the stored reference output..')
parser.add_argument('filenames', metavar='FILENAME', type=str, nargs='+',
help='filenames of the notebooks to be executed')
parser.add_argument('--debug-failures', action='store_true',
help='if a failure occurs, jump into an interactive debugging session (requires ipdb to be installed)')
args = parser.parse_args()
for ipynb in args.filenames:
print("Testing notebook '{}'".format(ipynb))
with open(ipynb) as f:
nb = reads(f.read(), 'json')
test_notebook(nb, debug_failures=args.debug_failures)
sys.stdout.flush()
| 20,556 | 37.640977 | 238 |
py
|
finmag
|
finmag-master/dev/logbooks/finmaglogs.py
|
"""
Using CherryPy to put together very basic webserver to display
today's discussions on the IRC channel.
Hans Fangohr, 6 September 2012
"""
import os
import time
import cherrypy
REFRESHCODE = """<META HTTP-EQUIV="REFRESH" CONTENT="60"> """
class HelloWorld:
def index(self):
# CherryPy will call this method for the root URI ("/") and send
# its return value to the client. Because this is tutorial
# lesson number 01, we'll just send something really simple.
# How about...
return """Go to
<ul>
<li> <a href="finmagirc">finmagirc</a> to see the
discussion today so far (updated every minute).<br>
</li>
<li><a href="finmagircupdate">finmagircupdate</a> to
see the discussions today so far (updated when the page is loaded)
</li>
</ul>"""
index.exposed=True
def finmagirc(self):
with open("/home/fangohr/www/ircdiff.txt","r") as f:
text = f.read()
return REFRESHCODE + text.replace('\n','<br>')
finmagirc.exposed = True
def finmagircupdate(self):
os.system("/bin/sh /home/fangohr/bin/finmag-update-todays-irc-diff.sh > /home/fangohr/www/ircdiff.txt")
return "Updating done ("+time.asctime()+")<br><br>"+\
self.finmagirc()
finmagircupdate.exposed = True
# CherryPy always starts with cherrypy.root when trying to map request URIs
# to objects, so we need to mount a request handler object here. A request
# to '/' will be mapped to cherrypy.root.index().
cherrypy.root = HelloWorld()
if __name__ == '__main__':
cherrypy.config.update('cherrypy.conf')
# Start the CherryPy server.
cherrypy.server.start()
| 1,743 | 31.296296 | 111 |
py
|
finmag
|
finmag-master/doc/generate_doc.py
|
import os
module_import_error = """
Unable to import the %s module
Error: %s
Did you forget to update your PYTHONPATH variable?"""
modules = open("modules.txt", "r").readlines()
for module in modules:
module = module.split()
name = ' '.join(module[:-1])
filename = '_'.join(module[:-1]) + '.rst'
module_name = module[-1]
try:
exec("import %s" % module_name)
except Exception as what:
raise ImportError(module_import_error % (module_name, what))
if not os.path.isdir("modules"):
os.mkdir("modules")
print "Writing modules/%s" % filename
outfile = open("modules/%s" % filename, "w")
outfile.write(name + "\n")
for characters in name:
outfile.write("=")
outfile.write("\n\n")
outfile.write(".. automodule:: %s\n" % module_name)
outfile.write("\t:members:\n")
outfile.write("\t:undoc-members:\n")
| 895 | 26.151515 | 68 |
py
|
finmag
|
finmag-master/doc/ipynb_sphinxext.py
|
'''
Sphinx/docutils extension to convert .ipynb files to .html files and
create links to the generated html in the source.
To use it, include something like the following in your .rst file:
:ipynb:`path/to/notebook.ipynb`
XXX TODO: Currently this only works for the 'html' builder (not for
singlehtml or latexpdf)
'''
import shutil
import os
import sys
import re
from IPython.nbformat import current as nbformat
def get_notebook_title(filename):
title = os.path.split(filename)[1]
with open(filename) as f:
nb = nbformat.read(f, 'json')
for worksheet in nb.worksheets:
for cell in worksheet.cells:
if (cell.cell_type == 'heading' or
(cell.cell_type == 'markdown' and re.match('^#+', cell.source))):
title = cell.source
if cell.cell_type != 'heading':
title = re.sub('^#+\s*', '', title) # strip leading '#' symbols
break
return title
def make_ipynb_link(name, rawtext, text, lineno, inliner,
options={}, content=[]):
from docutils import nodes, utils
ipynb_file = os.path.abspath(text)
ipynb_base = os.path.split(text)[1]
nb_title = get_notebook_title(ipynb_file)
## There is probably a less convoluted way to extract the sphinx_builder...
## XXX TODO: And it doesn't work yet anyway...
#sphinx_builder = inliner.document.settings.env.config.sphinx_builder
# TODO: The following should be rewritten once nbconvert is
# properly integrated into ipython and the API is stable.
try:
NBCONVERT = os.environ['NBCONVERT']
except KeyError:
print("Please set the environment variable NBCONVERT so that it points "
"to the location of the script nbconvert.py")
sys.exit(1)
nbconvert_path = os.path.dirname(NBCONVERT)
sys.path.append(nbconvert_path)
from nbconvert import ConverterHTML
build_dir = os.path.abspath(os.path.join('_build', 'html')) # XXX TODO: we should not hardcode the _build/html directory! How to get it from sphinx?
#print("[DDD] Converting .ipynb file to .html and putting it in target directory")
# Create the target directories for .ipynb and converted .html files
for subdir in ['ipynb', 'ipynb_html']:
if not os.path.exists(os.path.join(build_dir, subdir)):
os.mkdir(os.path.join(build_dir, subdir))
# Copy the .ipynb file into the target directory
shutil.copy(ipynb_file, os.path.join(build_dir, 'ipynb'))
# Convert the .ipynb file to .html
html_file = os.path.join('ipynb_html', re.sub('\.ipynb', '.html', ipynb_base))
c = ConverterHTML(ipynb_file, os.path.join(build_dir, html_file))
c.render()
# Create link in the rst tree
node = nodes.reference(rawtext, nb_title, refuri=html_file, **options)
nodes = [node]
sys_msgs = []
return nodes, sys_msgs
# Setup function to register the extension
def setup(app):
# app.add_config_value('sphinx_builder',
# app.builder,
# 'env')
app.add_role('ipynb', make_ipynb_link)
| 3,152 | 33.271739 | 153 |
py
|
finmag
|
finmag-master/doc/conf.py
|
# -*- coding: utf-8 -*-
#
# Finmag documentation build configuration file, created by
# sphinx-quickstart on Thu Feb 23 12:34:28 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('modules/'))
sys.path.insert(0, os.path.abspath('../src/finmag/'))
sys.path.insert(0, os.path.abspath('../src/finmag/sim/'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '1.1'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode',
'ipynb_sphinxext']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Finmag'
copyright = u'2012, Finmag-team'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.1'
# The full version, including alpha/beta/rc tags.
release = '0.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build', 'tailored_tutorials']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'finmag_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ['.']
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = 'A FEniCS based Micromagnetics Solver'
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = 'logo.jpeg'
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
html_show_sphinx = False
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'Finmagdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
'preamble': '',
}
# Add macros to LaTeX preamble.
# This will work with make latexpdf, but not make html.
# It is not possible to access the Mathjax configuration from sphynx.
with open("latex_macros.sty") as f:
for macro in f:
latex_elements["preamble"] += macro + "\n"
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'Finmag.tex', u'Finmag Documentation',
u'Finmag-team', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'finmag', u'Finmag Documentation',
[u'Finmag-team'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'Finmag', u'Finmag Documentation',
u'Finmag-team', 'Finmag', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
| 8,297 | 31.541176 | 80 |
py
|
finmag
|
finmag-master/doc/create_wrapper_for_ipynb_html_file.py
|
#!/usr/bin/env python
# This script takes a .ipynb file as input and generates a minimal
# .rst file that wraps the converted .html output of the ipython
# notebook using sphinx's :raw: directive. It also adds a title, which
# is extracted from the notebook cells if present (otherwise it just
# uses the input filename as title).
import re
import os
import sys
import json
import textwrap
import itertools
try:
infilename = sys.argv[1]
outfilename = sys.argv[2]
except IndexError:
print "Usage: {} INPUT.ipynb OUTPUT.rst".format(__file__)
sys.exit()
print("create_wrapper in:\n{}\n out: {}\n".format(infilename, outfilename))
def get_level(cell):
try:
level = cell['level']
except KeyError:
# Return the number of leading '#' as the level
m = re.search('^(#+)', cell['source'][0])
level = len(m.group(1))
return level
def extract_title(cell):
if cell['cell_type'] == 'markdown' and cell['source'][0].startswith('#'):
# Remove leading '#' signs
title = re.sub('^#+\s*', '', cell['source'][0])
print "[DDD] MARKDOWN: Using cell title: '{}'".format(title)
elif cell['cell_type'] == 'markdown':
if not isinstance(cell['source'], list):
raise ValueError("Cell source is not a list: '{}'. Please consider converting the notebook to an up-to-date format.".format(cell['source']))
# Remove leading '#' signs
title = re.sub('^#+\s*', '', cell['source'][0])
print "[DDD] MARKDOWN: Using cell title: '{}'".format(title)
else:
raise RuntimeError("Unknown cell type: '{}'".format(cell['cell_type']))
if title.strip() == '':
raise ValueError("Empty notebook title found: '{}' (cell contents: '{}'). This will cause sphinx to choke!".format(title, cell['source']))
return title
# Read JSON data
json_data = open(infilename).read()
data = json.loads(json_data)
# Extract all cells from all worksheets
# cells = list(itertools.chain(*ws['cells'] for ws in data['worksheets']]))
cells = list(itertools.chain(*[data['cells']]))
header_cells = sorted([c for c in cells if (c['cell_type'] == 'markdown' and c['source'][0].startswith('#'))], key=get_level)
if header_cells == []:
title = os.path.basename(infilename)
print "No header cells found. Using filename as title: '{}'".format(title)
else:
title = extract_title(header_cells[0])
print "Found some header cells. Using title from first highest-level one: '{}'".format(title)
with open(outfilename, 'w') as f:
outbasename, _ = os.path.splitext(os.path.basename(outfilename))
f.write(textwrap.dedent("""\
{}
{}
.. raw:: html
:file: {}
""".format(title, '=' * len(title), outbasename + '.html')))
| 2,775 | 33.7 | 152 |
py
|
finmag
|
finmag-master/doc/add_heading_if_needed.py
|
#!/usr/bin/env python
"""
Scan a given file 'FILENAME.rst' for header lines up to a certain
level. If no such lines are encountered, a header line of the
following form is added at the top of the file:
FILENAME.ipynb
==============
"""
import sys
import re
import os
# Heading symbols used by nbconvert, in descending order (from
# "heading 1" to "heading 6"). Note that the dash needs to be escaped!
heading_symbols = ["=", "\-", "`", "'", ".", "~"]
# Check command line arguments
try:
filename = sys.argv[1]
if not filename.endswith('.rst'):
raise ValueError("Filename must end in '.rst' "
"(got: '{}')".format(filename))
except IndexError:
print "Error: filename expected as first argument."
sys.exit(1)
try:
max_allowed_level = int(sys.argv[2])
except IndexError:
max_allowed_level = 1
print "Looking for header lines up to maximum level " + \
"'{}' in file '{}'".format(max_allowed_level, filename)
# Create a regexp which we can use to filter the lines in the file
heading_symbol_str = ''.join(heading_symbols[0:max_allowed_level])
heading_regexp = '^[{}]+$'.format(heading_symbol_str)
# Filter lines that only contain a repetition of one of the allowed
# symbols. Note that we read all lines into memory. Since notebooks
# usually shouldn't be very large, this is hopefully ok.
lines = open(filename).readlines()
num_heading_lines = len(filter(None, [re.match(heading_regexp, l.rstrip())
for l in lines]))
if num_heading_lines == 0:
print "No header lines found (up to maximum level {}). Adding a header " \
"line containing the filename at the beginning of the file.".format(
max_allowed_level)
# Write a title consisting of the filename at the beginning of the
# file, then dump the lines back that we read in earlier.
with open(filename, 'w') as f:
title_name = os.path.basename(filename)
f.write(title_name + '\n')
f.write('=' * len(title_name) + '\n\n')
for l in lines:
f.write(l)
else:
print "Found {} header line(s); not altering file.".format(num_heading_lines)
| 2,176 | 32.492308 | 81 |
py
|
finmag
|
finmag-master/doc/raw-notes/demag-Fredkin-Koehler-method-and-macro-geometry/script/demag_pbc_1d_ringdown.py
|
import numpy as np
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
import dolfin as df
from finmag import Simulation
from finmag.energies import Exchange, DMI, Demag, Zeeman, UniaxialAnisotropy
from finmag.energies.zeeman import TimeZeemanPython
import matplotlib.pyplot as plt
from finmag.util.fileio import Tablereader
mesh = df.BoxMesh(-5, -5, -5, 5, 5, 5, 5, 5, 5)
def ring_down(m0=(1,0.01,0), pbc=None):
n = 49
assert n>=1 and n%2==1
Ms = 8.6e5
sim = Simulation(mesh, Ms, unit_length=1e-9, name = 'dy', pbc='1d')
sim.alpha = 1e-3
sim.set_m(m0)
sim.set_tol(1e-8, 1e-8)
parameters = {
'absolute_tolerance': 1e-10,
'relative_tolerance': 1e-10,
'maximum_iterations': int(1e5)
}
Ts = []
for i in range(-n/2+1,n/2+1):
Ts.append((10.*i,0,0))
demag = Demag(Ts=Ts)
demag.parameters['phi_1'] = parameters
demag.parameters['phi_2'] = parameters
sim.add(demag)
sim.add(Exchange(1.3e-11))
sim.schedule('save_ndt', every=2e-12)
sim.run_until(4e-9)
def plot_mx(filename='dy.ndt'):
fig=plt.figure()
plt.plot(ts, data['E_total'], label='Total')
#plt.plot(ts, data['E_Demag'], label='Demag')
#plt.plot(ts, data['E_Exchange'], label='Exchange')
plt.xlabel('time (ns)')
plt.ylabel('energy')
plt.legend()
fig.savefig('energy.pdf')
def fft(mx, dt=5e-12):
n = len(mx)
freq = np.fft.fftfreq(n, dt)
ft_mx = np.fft.fft(mx)
ft_abs = np.abs(ft_mx)
ft_phase = np.angle(ft_mx)
return freq, ft_abs, ft_phase
def plot_average_fft():
data = Tablereader('dy.ndt')
ts = data['time']
my = data['m_y']
dt = ts[1]-ts[0]
freq, ft_abs, phase = fft(my, dt)
fig=plt.figure()
plt.subplot(2,1,1)
plt.plot(ts*1e9,my,label='Real')
plt.xlabel('Time (ns)')
plt.ylabel('m_y')
plt.subplot(2,1,2)
plt.plot(freq*1e-9,ft_abs,'.-',label='Real')
plt.xlabel('Frequency (GHz)')
plt.ylabel('FFT')
plt.xlim([10,20])
#plt.ylim([0,10])
fig.savefig('average_fft.pdf')
if __name__ == '__main__':
#ring_down()
plot_average_fft()
| 2,294 | 19.491071 | 76 |
py
|
finmag
|
finmag-master/doc/raw-notes/demag-Fredkin-Koehler-method-and-macro-geometry/script/demag_pbc_1d.py
|
import numpy as np
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
import dolfin as df
from finmag import Simulation
from finmag.energies import Exchange, DMI, Demag, Zeeman, UniaxialAnisotropy
from finmag.energies.zeeman import TimeZeemanPython
import matplotlib.pyplot as plt
from finmag.util.fileio import Tablereader
mesh = df.BoxMesh(-5, -5, -5, 5, 5, 5, 5, 5, 5)
def compute_field(n=1, m0=(1,0,0), pbc=None):
assert n>=1 and n%2==1
Ms = 1e6
sim = Simulation(mesh, Ms, unit_length=1e-9, name = 'dy', pbc=pbc)
sim.set_m(m0)
parameters = {
'absolute_tolerance': 1e-10,
'relative_tolerance': 1e-10,
'maximum_iterations': int(1e5)
}
Ts = []
for i in range(-n/2+1,n/2+1):
Ts.append((10.*i,0,0))
demag = Demag(Ts=Ts)
demag.parameters['phi_1'] = parameters
demag.parameters['phi_2'] = parameters
sim.add(demag)
sim.set_m((1,0,0))
field1 = sim.llg.effective_field.get_dolfin_function('Demag')
sim.set_m((0,0,1))
field2 = sim.llg.effective_field.get_dolfin_function('Demag')
return (field1(0,0,0)/Ms, field2(0,0,0)/Ms)
def plot_field():
ns = [1, 3, 5, 7, 11, 15, 21, 29, 59]
#ns = [1,3,5]
field1=[]
field2=[]
for n in ns:
f, g=compute_field(n=n)
field1.append(abs(f[0]))
field2.append(abs(g[2]))
#f2 = compute_field(n=n,m0=(1,0,0),pbc='1d')
#field_pbc.append(abs(f2[0]))
fig=plt.figure(figsize=(5, 5))
plt.subplot(2, 1, 1)
plt.plot(ns, field1, '.-')
plt.xlabel('Copies')
plt.ylabel('Field (Ms)')
plt.title('m aligned along x')
plt.subplot(2, 1, 2)
plt.plot(ns, field2, '.-')
plt.xlabel('Copies')
plt.ylabel('Field (Ms)')
plt.title('m aligned along z')
#plt.legend()
fig.savefig('fields.pdf')
if __name__ == '__main__':
plot_field()
| 1,995 | 21.942529 | 76 |
py
|
finmag
|
finmag-master/doc/ipython_notebooks_src/2D_square_sim.py
|
"""
Script to relax a skyrmion in the middle
of a 2D square system (trying to replicate a
Heisenberg model system)
IMPORTANT:
We are using the DMI expression from [1]
D(m_x * dm_z/dx - m_z * dm_x/dx) +
D(m_y * dm_z/dy - m_z * dm_y/dy) * df.dx
References:
[1] Rohart, S. and Thiaville A., Phys. Rev. B 88, 184422 (2013)
"""
# Material parameters from Rohart et al publication
# Ms = 1.1e6
# A = 16e-12
import os
import shutil
import argparse
# ARGUMENTS
parser = argparse.ArgumentParser(description='Relaxation of skyrmionic '
'textures for 2D square films '
'with interfacial DMI')
initial_state = parser.add_mutually_exclusive_group(required=True)
parser.add_argument('box_length', help='Length in nm',
type=float)
parser.add_argument('box_width', help='Width in nm',
type=float)
parser.add_argument('fd_max', help='Maximum edge length for the finite'
' elements', type=float)
parser.add_argument('--D', help='DMI constant in units of 1e-3 * J m^{-2}',
type=float)
parser.add_argument('--A', help='Exchange constant in units of J m^{-1}',
type=float, default=1e-12)
parser.add_argument('--Ms', help='Saturation magnetisationin units of A / m',
type=float, default=1.1e6)
parser.add_argument('--k_u', help='Anisotropy constant in units of Jm^-3',
type=float)
parser.add_argument('--B', help='External magnetic field perpendicular to the'
' square plane (z direction), in Tesla',
type=float)
# parser.add_argument('sk_initial_radius',
# help='Radius of the initial skyrmion to be relaxed ',
# type=float)
# parser.add_argument('--relax_time', help='Relaxation time after the SPPC '
# 'application, in ns ',
# type=float)
# parser.add_argument('initial_state',
# help='Path to initial state .npy file')
parser.add_argument('sim_name',
help='Simulation name')
parser.add_argument('--pin_borders',
help='Pin the magnetisation vectors at the box boundaries',
action='store_true')
parser.add_argument('--PBC_2D',
help='Two dimensional boundary condition',
action='store_true')
initial_state.add_argument('--initial_state_skyrmion_down',
help='This option puts a skyrmionic texture'
' in the centre of the'
' nanotrack, as initial m configuration. The'
' other spins are in the (0, 0, 1) direction',
type=float,
metavar=('SK_INITIAL_RADIUS')
# action='store_true'
)
initial_state.add_argument('--initial_state_skyrmion_up',
help='This option puts a skyrmionic texture'
' with its core pointing in the +z direction, '
'in the centre of the'
' nanotrack, as initial m configuration. The'
' other spins are in the (0, 0, 1) direction',
type=float,
metavar=('SK_INITIAL_RADIUS')
# action='store_true'
)
initial_state.add_argument('--initial_state_ferromagnetic_up',
help='This option sets the initial '
'm configuration as a ferromagnetic state'
' in the (0, 0, 1) direction',
action='store_true'
)
initial_state.add_argument('--initial_state_ferromagnetic_down',
help='This option sets the initial '
'm configuration as a ferromagnetic state'
' in the (0, 0, -1) direction',
action='store_true'
)
initial_state.add_argument('--initial_state_irregular',
help='This option sets the initial '
'm configuration as an irregular state'
' (TESTING)',
action='store_true')
parser.add_argument('--preview', help='Set to *yes* if a plot with m '
'being updated is shown instead of saving npy '
'and vtk files',
)
parser.add_argument('--alpha', help='Damping constant value',
type=float)
parser.add_argument('--save_files', help='Save vtk and npy files every x'
' nanoseconds',
type=float, default=False)
# Parser arguments
args = parser.parse_args()
import dolfin as df
import numpy as np
import finmag
from finmag import Simulation as Sim
from finmag.energies import Exchange, DMI, Zeeman, Demag, UniaxialAnisotropy
import textwrap
import subprocess
import mshr
# 2D Box specification
# The center of the box will be at (0, 0, 0)
mesh = df.RectangleMesh(-args.box_length * 0.5,
-args.box_width * 0.5,
args.box_length * 0.5,
args.box_width * 0.5,
int(args.box_length / args.fd_max),
int(args.box_width / args.fd_max),
)
# df.plot(mesh, interactive=True)
print finmag.util.meshes.mesh_quality(mesh)
print finmag.util.meshes.mesh_info(mesh)
# Generate simulation object with or without PBCs
if not args.PBC_2D:
sim = Sim(mesh, args.Ms, unit_length=1e-9,
name=args.sim_name)
else:
sim = Sim(mesh, args.Ms, unit_length=1e-9,
pbc='2d', name=args.sim_name)
# Add energies
sim.add(Exchange(args.A))
if args.D != 0:
sim.add(DMI(args.D * 1e-3, dmi_type='interfacial'))
# Zeeman field in the z direction (in Tesla)
# if it is not zero
if args.B != 0:
sim.add(Zeeman((0, 0, args.B / finmag.util.consts.mu0)))
if args.k_u:
sim.add(UniaxialAnisotropy(args.k_u,
(0, 0, 1), name='Ku'))
# No Demag in 2D
# sim.add(Demag())
# sim.llg.presession = False
if args.alpha:
sim.alpha = args.alpha
# Pin the magnetisation vectors at the borders if specified
if args.pin_borders:
def borders_pinning(pos):
x, y = pos[0], pos[1]
if (x < (-args.box_length * 0.5 + args.fd_max)
or (x > args.box_length * 0.5 - args.fd_max)):
return True
elif (y < (-args.box_width * 0.5 + args.fd_max)
or (y > args.box_width * 0.5 - args.fd_max)):
return True
else:
return False
# Pass the function to the 'pins' property of the simulation
sim.pins = borders_pinning
# Generate the skyrmion in the middle of the nanotrack
def generate_skyrmion_down(pos, sign):
"""
Sign will affect the chirality of the skyrmion
"""
# We will generate a skyrmion in the middle of the stripe
# (the origin is there) with the core pointing down
x, y = pos[0], pos[1]
if np.sqrt(x ** 2 + y ** 2) <= args.initial_state_skyrmion_down:
# Polar coordinates:
r = (x ** 2 + y ** 2) ** 0.5
phi = np.arctan2(y, x)
# This determines the profile we want for the
# skyrmion
# Single twisting: k = pi / R
k = np.pi / (args.initial_state_skyrmion_down)
# We define here a 'hedgehog' skyrmion pointing down
return (sign * np.sin(k * r) * np.cos(phi),
sign * np.sin(k * r) * np.sin(phi),
-np.cos(k * r))
else:
return (0, 0, 1)
def generate_skyrmion_up(pos, sign):
# We will generate a skyrmion in the middle of the stripe
# (the origin is there) with the core pointing down
x, y = pos[0], pos[1]
if np.sqrt(x ** 2 + y ** 2) <= args.initial_state_skyrmion_up:
# Polar coordinates:
r = (x ** 2 + y ** 2) ** 0.5
phi = np.arctan2(y, x)
# This determines the profile we want for the
# skyrmion
# Single twisting: k = pi / R
k = np.pi / (args.initial_state_skyrmion_up)
# We define here a 'hedgehog' skyrmion pointing down
return (sign * np.sin(k * r) * np.cos(phi),
sign * np.sin(k * r) * np.sin(phi),
np.cos(k * r))
else:
return (0, 0, -1)
def irregular_state(pos):
# We will generate a skyrmion in the middle of the stripe
# (the origin is there) with the core pointing down
x, y = pos[0], pos[1]
if x > 0:
return (0, 0, 1)
else:
return (0, 0, -1)
# Load magnetisation profile
# Change the skyrmion initial configuration according to the
# chirality of the system (give by the DMI constant)
if args.initial_state_skyrmion_down:
if args.D > 0:
sim.set_m(lambda x: generate_skyrmion_down(x, -1))
else:
sim.set_m(lambda x: generate_skyrmion_down(x, 1))
elif args.initial_state_skyrmion_up:
if args.D > 0:
sim.set_m(lambda x: generate_skyrmion_up(x, 1))
else:
sim.set_m(lambda x: generate_skyrmion_up(x, -1))
elif args.initial_state_ferromagnetic_up:
sim.set_m((0, 0, 1))
elif args.initial_state_ferromagnetic_down:
sim.set_m((0, 0, -1))
elif args.initial_state_irregular:
sim.set_m(irregular_state)
else:
raise Exception('Set one option for the initial state')
# DEBUG INFORMATION ##############################
print '\n\n'
print 'Running a {} nm x {} nm stripe'.format(args.box_length,
args.box_width,
)
print 'DMI constant', args.D, '* 1e-3 J m**-2'
# print 'Anisotropy constant', args.k_u, 'x 10 ** 4 Jm**-3'
print '\n\n'
# ################################################
# Save states if specified
if args.save_files:
sim.schedule('save_vtk', every=args.save_files * 1e-9,
filename='{}_.pvd'.format(args.sim_name),
overwrite=True)
sim.schedule('save_field', 'm', every=args.save_files * 1e-9,
filename='{}_.npy'.format(args.sim_name),
overwrite=True)
sim.overwrite_pvd_files = True
if args.preview:
# Save first state
sim.save_vtk('{}_initial.pvd'.format(args.sim_name), overwrite=True)
# Print a message with the avergae m and an updated plot
# with the magnetisation profile
times = np.linspace(0, 1 * 1e-9, 10000)
for t in times:
sim.run_until(t)
df.plot(sim.m_field.f, interactive=False)
print '##############################################'
print 'Energy: ', sim.compute_energy()
# print sim.llg.M_average
# print 'mz(0) = {}'.format(sim.llg._m_field.f(0, 0, 0)[2])
print '##############################################'
else:
# WE only need the LAST state (relaxed)
#
# We will save these options in case we need the transition
# in the future:::::::::::::
#
# Save the initial states
sim.save_vtk('{}_initial.pvd'.format(args.sim_name), overwrite=True)
np.save('{}_initial.npy'.format(args.sim_name), sim.m)
# Relax the system
sim.relax()
# Save the last relaxed state
sim.save_vtk('{}_final.pvd'.format(args.sim_name), overwrite=True)
np.save('{}_final.npy'.format(args.sim_name), sim.m)
# Save magnetic data from the simulations last step
sim.save_ndt()
# Save files
#
npy_dir = 'npys/'
vtk_dir = 'vtks/'
log_dir = 'logs/'
ndt_dir = 'ndts/'
def mkrootdir(s):
if not os.path.exists(s):
os.makedirs(s)
mkrootdir(npy_dir)
mkrootdir(vtk_dir)
mkrootdir(log_dir)
mkrootdir(ndt_dir)
files = os.listdir('.')
for f in files:
if ((f.endswith('vtu') or f.endswith('pvd'))
and f.startswith(args.sim_name)):
if os.path.exists(vtk_dir + f):
os.remove(vtk_dir + f)
shutil.move(f, vtk_dir)
elif (f.endswith('npy') and f.startswith(args.sim_name)):
if os.path.exists(npy_dir + f):
os.remove(npy_dir + f)
shutil.move(f, npy_dir)
elif (f.endswith('log') and f.startswith(args.sim_name)):
if os.path.exists(log_dir + f):
os.remove(log_dir + f)
shutil.move(f, log_dir)
elif (f.endswith('ndt') and f.startswith(args.sim_name)):
if os.path.exists(ndt_dir + f):
os.remove(ndt_dir + f)
shutil.move(f, ndt_dir)
| 12,781 | 31.524173 | 79 |
py
|
finmag
|
finmag-master/doc/tailored_tutorials/make-tailored-tutorial-tarball.py
|
#
## need to move these configuration details into a separate file
#tutorials = ['tutorial-example2','tutorial-saving-averages-demo','tutorial-use-of-logging']
#conf = {'nameshort':'Hesjedahl',
# 'names': ('Thorsten Hesjedahl','Shilei Zhang'),
# 'header':".. contents::\n\n",
# 'ipynbdir':"The raw ipython notebooks are `available here <ipynb>`__.\n\n" }
#
# library file starts
import logging
logging.basicConfig(level = logging.DEBUG)
import tempfile
import shutil
import os
import sys
import time
import subprocess
import textwrap
from argparse import ArgumentParser
def targetdirectoryname(conf):
use_build = True
if use_build == False:
tmpdirname = tempfile.mkdtemp()
else:
tmpdirname = '_build'
if not os.path.exists(tmpdirname): # if we don't use
os.mkdir(tmpdirname)
targetdirname = os.path.join(tmpdirname, 'finmag-tutorial-%s' % conf['nameshort'])
if os.path.exists(targetdirname):
assert use_build == True # otherwise this should be impossible
else:
os.mkdir(targetdirname)
return targetdirname
def create_index_html(conf):
"""
Create an index.html file which contains a title and links to all
the individual notebook html files.
"""
# XXX TODO: This is just a quick hack for proof-of-concept. The
# resulting html could be made much nicer using
# nbconvert's internal python functions directly, but it
# would probably need a bit of tweaking for that.
targetdirname = targetdirectoryname(conf)
partner_str = ", ".join(conf['names'])
logging.debug("[DDD] lst: {} (type: {})".format(conf['tutorials'], type(conf['tutorials'])))
contents_str = \
"<br>\n".join(map(lambda name: " <li><a href='{f}'>{f}</a></li>".format(f=name+'.html'),
list(conf['tutorials'])))
with open(os.path.join(targetdirname, 'index.html'), 'w') as f:
f.write(textwrap.dedent("""\
<h2>Finmag Manual for {partner_str}</h2>
<br>
Tutorial compiled on {date_str}.
<br><br>
Contents:<br>
<ul>
{contents_str}
</ul>
<br><br>
The raw ipython notebooks are <a href='ipynb/'>available here</a>
""".format(partner_str=partner_str,
date_str=time.asctime(),
contents_str=contents_str)))
def assemble_rst(conf):
rstrootfilenames = conf['tutorials']
targetdirname = targetdirectoryname(conf)
for fileroot in rstrootfilenames:
# copy all rst files (and where we have images also the corresponding _files directories)
# to the target location
shutil.copy("../ipython_notebooks_dest/%s.rst" % fileroot, os.path.join(targetdirname,fileroot+".rst"))
if os.path.exists("../ipython_notebooks_dest/%s_files" % fileroot):
targetdirnamefiles = os.path.join(targetdirname,fileroot+"_files")
if os.path.exiscompile_ipynb2htmlts(targetdirnamefiles):
shutil.rmtree(targetdirnamefiles)
shutil.copytree("../ipython_notebooks_dest/%s_files" % fileroot, targetdirnamefiles)
# also copy the raw ipynb files into the right directory
ipynbdir = os.path.join(targetdirname, 'ipynb')
if not os.path.exists(ipynbdir):
os.mkdir(ipynbdir)
shutil.copy("../ipython_notebooks_src/%s.ipynb" % fileroot, ipynbdir)
# Create index file
fout = open(os.path.join(targetdirname,'index.rst'),'w')
title = "Finmag Manual for %s" % (", ".join(conf['names']))
fout.write("%s\n" % title)
fout.write("=" * len(title) + '\n\n')
fout.write("Tutorial compiled at %s.\n\n" % time.asctime())
fout.write(conf['header'])
fout.write(conf['ipynbdir'])
# Assemble the index file
for fileroot in rstrootfilenames:
f = open(os.path.jocompile_ipynb2htmlin(targetdirname,fileroot + '.rst'),'r')
for line in f:
fout.write(line)
fout.write('\n\n') # need white space before next section to have valid rst
fout.close()
def compile_rst2html(conf):
targetdirname = targetdirectoryname(conf)
cmd = "cd %s; rst2html.py --stylesheet-path=../../../css/voidspace.css index.rst index.html" % targetdirname
logging.debug("Running cmd '%s'" % cmd)
output = subprocess.check_output(cmd, shell=True)
logging.debug("Output was %s" % output)
def compile_ipynb2html(conf):
#try:
# NBCONVERT = os.environ['NBCONVERT']
#except KeyError:
# print("Please set the environment variable NBCONVERT so that it "
# "points to the location of the script nbconvert.py.")
# sys.exit(1)
# XXX TODO: It would be much nicer to use the python functions in
# nbconvert directly rather than calling it via
# 'subprocess'. Once the --output-dest flag (or a
# similar one) has been adopted into the main repo we
# should revisit this.
targetdir = targetdirectoryname(conf)
ipynbdir = os.path.join(targetdir, 'ipynb')
if not os.path.exists(ipynbdir):
os.mkdir(ipynbdir)
for fileroot in conf['tutorials']:
shutil.copy("../ipython_notebooks_src/{}.ipynb".format(fileroot), ipynbdir)
NBCONVERT='NBCONVERT'
cmd = "cd {}/..; ipython nbconvert --to html ipynb/{}.ipynb".format(
ipynbdir, fileroot, fileroot)
logging.debug("Running cmd '%s'" % cmd)
output = subprocess.check_output(cmd, shell=True)
logging.debug("Output was %s" % output)
def assemble_tarballs(conf):
targetdirname = targetdirectoryname(conf)
cmd = "cd %s; tar cfvz finmag-tutorial-%s.tgz finmag-tutorial-%s" % \
(os.path.join(targetdirname, '..'), conf['nameshort'], conf['nameshort'])
logging.debug("Running cmd '%s'" % cmd)
output = subprocess.check_output(cmd, shell=True)
logging.debug("Output was %s" % output)
logging.info("Tarball %s.tgz is located in _build" % conf['nameshort'])
def remove_builddir(conf):
targetdirname = targetdirectoryname(conf)
cmd = shutil.rmtree(targetdirname)
logging.debug("Removing %s" % targetdirname)
if __name__ == '__main__':
#ArgumentParser
from argparse import ArgumentParser
parser=ArgumentParser(description="""Create tailored tutorial bundles""")
parser.add_argument('partner', type=str, nargs='+', \
help='partner[s] to process (names of subdirectories)')
parser.add_argument('--keepbuild', action='store_true', default=False, \
help='Keep directory in which tar ball is built (for debugging).')
parser.add_argument('--use-ipynb2html', action='store_true', default=True, \
help='Use nbconvert directly to convert .ipynb files to .html.')
args = vars(parser.parse_args())
if isinstance(args['partner'],list):
partners = args['partner']
logging.info("About to process %s" % ", ".join(partners))
else:
partners = [args['partner']]
for partner in partners:
if partner[-3:] == '.py':
partner = partner[:-3]
conffile = __import__(partner)
conf = conffile.conf
#add defaults
conf['header'] = ".. contents::\n\n"
conf['ipynbdir'] = "The raw ipython notebooks are `available here <ipynb>`__.\n\n"
# Do the work
if args['use_ipynb2html']:
logging.info("Creating index.html for %s" % partner)
create_index_html(conf)
logging.info("Converting .ipynb files to .html for %s" % partner)
compile_ipynb2html(conf)
else:
logging.info("Assembling rst file for %s" % partner)
assemble_rst(conf)
logging.info("Compiling rst file for %s" % partner)
compile_rst2html(conf)
logging.info("Creating tar ball for %s" % partner)
assemble_tarballs(conf)
if not args['keepbuild']:
remove_builddir(conf)
| 8,130 | 36.470046 | 112 |
py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.