Skip to content
Snippets Groups Projects
Commit 58322891 authored by hjsc's avatar hjsc
Browse files

Initial commit

parent 0e157ed2
No related branches found
No related tags found
No related merge requests found
Showing
with 2259 additions and 0 deletions
File added
from .cmap import *
File added
File added
This diff is collapsed.
from numpy import array, linspace, sqrt, linalg, where
from numpy import logical_not, logical_or, logical_and
import scipy.signal as signal
import scipy.io
import ufl
def sig(Vs):
""" Conductivity function """
# Initialization
xy = Vs.tabulate_dof_coordinates().reshape((-1,2))
N = xy[:,0].size
#Test case 1:
sig = 1 + np.exp(-5*(np.power(xy[:,0],2)+np.power(xy[:,1],2)))
#Test case 2:
#sig = 1 + np.exp(-20*(np.power(xy[:,0]+1/2,2)+np.power(xy[:,1],2))) + np.exp(-20*(np.power(xy[:,0],2)+np.power(xy[:,1]+1/2,2))) + np.exp(-50*(np.power(xy[:,0]-1/2,2)+np.power(xy[:,1]-1/2,2)))
#sigsqrt = np.sqrt(sig)
sigsqrt = np.sqrt(sig)
return sig,sigsqrt
if __name__ == '__main__':
import sys
# Initialize numpy, IO, matplotlib
import numpy as np
import scipy.io as io
import matplotlib.pyplot as plt
from matplotlib import ticker
plt.ion()
# Load
import cmap as cmap
from dolfin import __version__ as DOLFINversion
from dolfin import TrialFunction, TestFunction, FunctionSpace
from dolfin import project, Point, triangle
from dolfin import inner, dot, grad, dx, ds, VectorFunctionSpace, PETScLUSolver, as_backend_type
from dolfin import Function, assemble, Expression, parameters, VectorFunctionSpace
from dolfin import DirichletBC, as_matrix, interpolate, as_vector, UserExpression, errornorm, norm
from dolfin import MeshFunction, cells, solve, DOLFIN_EPS, near, Constant, FiniteElement
from mshr import generate_mesh, Circle
# Load dolfin plotting
from dolfin import plot as dolfinplot, File as dolfinFile
def plotVs(vec,**kwargs):
""" dolfin.plot-wrapper """
fn = Function(Vs,vec)
return dolfinplot(fn,**kwargs)
def plotVs1(vec,**kwargs):
""" dolfin.plot-wrapper """
fn = Function(Vs1,vec)
return dolfinplot(fn,**kwargs)
# Define Function spaces
def VsSpace(mesh, degree=1): # Corresponding to H^1
E1 = FiniteElement('CG', triangle, degree)
return FunctionSpace(mesh, E1)
def VqSpace(mesh, degree=1): # Used for the gradients
return VectorFunctionSpace(mesh, 'CG', degree)
def Vector(V):
return Function(V).vector()
# Define how to calculate the gradients
def Solver(Op):
s = PETScLUSolver(as_backend_type(Op),'mumps') # Constructs the linear operator Ks for the linear system Ks u = f using LU factorization, where the method 'numps' is used
return s
def GradientSolver(Vq,Vs): #Calculate derivatives on the quadrature points
"""
Based on:
https://fenicsproject.org/qa/1425/derivatives-at-the-quadrature-points/
"""
uq = TrialFunction(Vq)
vq = TestFunction(Vq)
M = assemble(inner(uq,vq)*dx)
femSolver = Solver(M)
u = TrialFunction(Vs)
P = assemble(inner(vq,grad(u))*dx)
def GradSolver(uvec):
gv = Vector(Vq)
g = P*uvec
femSolver.solve(gv, g)
dx = Vector(Vs)
dy = Vector(Vs)
dx[:] = gv[0::2].copy()
dy[:] = gv[1::2].copy()
return dx,dy
return GradSolver
# Define the mesh for the unit disk:
def UnitCircleMesh(n):
C = Circle(Point(0,0),1)
return generate_mesh(C,n)
cmaps = cmap.twilights()
# ------------------------------
# Setup mesh and FEM-spaces
parameters['allow_extrapolation'] = True
#Mesh to generate the power density data:
Ms = 150
#Ms = 200 #For N_{medium} as in Table 2
#Ms = 250 #For N_{large} as in Table 2
m = UnitCircleMesh(Ms)
Vs = VsSpace(m,1)
Vq = VqSpace(m,1)
#Mesh to solve the inverse problem:
Ms2 = 100
#Ms2 = 150 #For N_{medium} as in Table 2
#Ms2 = 200 #For N_{large} as in Table 2
m2 = UnitCircleMesh(Ms2)
Vs1 = VsSpace(m2,1)
Vq1 = VqSpace(m2,1)
# Gradient solver
GradSolver = GradientSolver(Vq,Vs)
GradSolver2 = GradientSolver(Vq1,Vs1)
xy = Vs.tabulate_dof_coordinates().reshape((-1,2))
xy2 = Vs1.tabulate_dof_coordinates().reshape((-1,2))
N = xy[:,0].size
print(N)
N2 = xy2[:,0].size
print(N2)
# ------------------------------
# Conductivity
sigt = Function(Vs1)
sigsqrtt = Vector(Vs1)
sig1 = Function(Vs)
sigsqrt1 = Function(Vs)
sigt1,sigsqrtt1 = sig(Vs)
sigt.vector()[:],sigsqrtt[:] = sig(Vs1)
sig1.vector().set_local(sigt1)
sigsqrt1.vector().set_local(sigsqrtt1)
# Plot
plot_settings = {
#'levels': np.linspace(-1,2,120),
#'levels': np.linspace(0,5,120),
'cmap': plt.set_cmap('bwr'),
}
# ------------------------------
# Boundary conditions
u_D1 = Expression('x[0]', degree=2)
u_D2 = Expression('x[1]', degree=1)
# Defining \Gamma
def boundary(x, on_boundary):
#\Gamma_{small}:
#return (on_boundary and (ufl.atan_2(x[1],x[0])<-(1.0/8.0)*np.pi and ufl.atan_2(x[1],x[0])>-(3.0/8.0)*np.pi) )
#\Gamma_{medium}:
return (on_boundary and (ufl.atan_2(x[1],x[0])<(1.0/4.0)*np.pi and ufl.atan_2(x[1],x[0])>-(3.0/4.0)*np.pi) )
#\Gamma_{large}:
#return (on_boundary and ((ufl.atan_2(x[1],x[0])<5.0/8.0*np.pi and ufl.atan_2(x[1],x[0])>-np.pi) or (ufl.atan_2(x[1],x[0])<np.pi and ufl.atan_2(x[1],x[0])>7.0/8.0*np.pi)))
def boundary2(x, on_boundary):
return on_boundary
bc1 = DirichletBC(Vs, u_D1, boundary)
bc2 = DirichletBC(Vs, u_D2, boundary)
u1 = Function(Vs)
v1 = TestFunction(Vs)
u2 = Function(Vs)
v2 = TestFunction(Vs)
#Defining and solving the variational equations
a1 = inner(sig1*grad(u1),grad(v1))*dx
a2 = inner(sig1*grad(u2),grad(v2))*dx
solve(a1 == 0,u1,bc1)
solve(a2 == 0,u2,bc2)
#Defining the gradients
dU1 = GradSolver(u1.vector())
dU2 = GradSolver(u2.vector())
H11t = Function(Vs)
H12t = Function(Vs)
H22t = Function(Vs)
#Compute the power density data
H11t.vector()[:] = sig1.vector()*(dU1[0]*dU1[0]+dU1[1]*dU1[1])
H12t.vector()[:] = sig1.vector()*(dU1[0]*dU2[0]+dU1[1]*dU2[1])
H22t.vector()[:] = sig1.vector()*(dU2[0]*dU2[0]+dU2[1]*dU2[1])
S11 = Function(Vs)
S12 = Function(Vs)
S21 = Function(Vs)
S22 = Function(Vs)
S11.vector()[:] = sigsqrt1.vector()*dU1[0]
S21.vector()[:] = sigsqrt1.vector()*dU1[1]
S12.vector()[:] = sigsqrt1.vector()*dU2[0]
S22.vector()[:] = sigsqrt1.vector()*dU2[1]
#Project the data to the mesh for solving the inverse problem
H11 = project(H11t,Vs1)
H12 = project(H12t,Vs1)
H22 = project(H22t,Vs1)
S11_1 = project(S11,Vs1)
S12_1 = project(S12,Vs1)
S21_1 = project(S21,Vs1)
S22_1 = project(S22,Vs1)
dt = H11.vector()*H22.vector()-H12.vector()*H12.vector()
lJac = Vector(Vs1)
lJac[:] = np.log(dt)
midet = np.amin(dt.get_local())
madet = np.amax(dt.get_local())
plot_settingsdet = {
'levels': np.linspace(midet,madet,250),
#'levels': np.linspace(0,5,120),
'cmap': plt.set_cmap('RdBu'),
}
mildet = np.amin(lJac.get_local())
maldet = np.amax(lJac.get_local())
plot_settingsldet = {
'levels': np.linspace(mildet,maldet,250),
#'levels': np.linspace(0,5,120),
#'cmap': plt.set_cmap('RdBu'),
'cmap': plt.get_cmap('bwr'),
}
miu1 = np.amin(u1.vector().get_local())
mau1 = np.amax(u1.vector().get_local())
plot_settingsu1 = {
'levels': np.linspace(miu1,mau1,250),
#'levels': np.linspace(0,5,120),
#'cmap': plt.set_cmap('RdBu'),
'cmap': plt.get_cmap('bwr'),
}
miu2 = np.amin(u2.vector().get_local())
mau2 = np.amax(u2.vector().get_local())
plot_settingsu2 = {
'levels': np.linspace(miu2,mau2,250),
#'levels': np.linspace(0,5,120),
#'cmap': plt.set_cmap('RdBu'),
'cmap': plt.get_cmap('bwr'),
}
#Illustrating the solutions u1 and u2
plt.figure(1).clear()
h = plotVs(u1.vector(),**plot_settingsu1) # dolfinplot
plt.gca().axis('off')
cb=plt.colorbar(h)
cb.ax.tick_params(labelsize=20)
tick_locator = ticker.MaxNLocator(nbins=6)
cb.locator = tick_locator
cb.update_ticks()
#plt.savefig('u1medc1')
plt.figure(2).clear()
h = plotVs(u2.vector(),**plot_settingsu2) # dolfinplot
plt.gca().axis('off')
cb=plt.colorbar(h)
cb.ax.tick_params(labelsize=20)
tick_locator = ticker.MaxNLocator(nbins=6)
cb.locator = tick_locator
cb.update_ticks()
#plt.savefig('u2medc1')
#Illustrating log(det(H)):
plt.figure(3).clear()
h = plotVs1(lJac,**plot_settingsldet) # dolfinplot
plt.gca().axis('off')
cb=plt.colorbar(h)
cb.ax.tick_params(labelsize=20)
tick_locator = ticker.MaxNLocator(nbins=6)
cb.locator = tick_locator
cb.update_ticks()
#plt.savefig('logDetMedc1')
dtest = H11.vector()*H22.vector()-H12.vector()*H12.vector()
print(min(dtest))
d = Vector(Vs1)
d[:] = np.sqrt(dtest)
#Compute the T matrix as in section 4.3
T11 = np.divide(1,np.sqrt(H11.vector()))
T12 = np.zeros(N2)
T21 = -np.divide(H12.vector(),np.multiply(np.sqrt(H11.vector()),d))
T22 = np.divide(np.sqrt(H11.vector()),d)
H1211 = Vector(Vs1)
H1211[:] = np.divide(H12.vector(),H11.vector())
dH1211 = GradSolver2(H1211)
#Compute the vector field V21 as in equation (4.7)
V210 = Vector(Vs1)
V211 = Vector(Vs1)
V210[:] = -np.multiply(np.divide(H11.vector(),d),dH1211[0])
V211[:] = -np.multiply(np.divide(H11.vector(),d),dH1211[1])
ld1 = Vector(Vs1)
ld1[:] = np.log(np.power(d,2))
dld1 = GradSolver2(ld1)
#Compute the right hand side \mathbf{F} for the Poisson equation (4.3)
dtheta0 = Function(Vs1)
dtheta1 = Function(Vs1)
dtheta0.vector()[:] = (1/2)*(-V210 + (1/2)*dld1[1])
dtheta1.vector()[:] = (1/2)*(-V211 - (1/2)*dld1[0])
#Compute the true R and theta
R11_1 = np.multiply(S11_1.vector(),T11) + np.multiply(S12_1.vector(),T12)
R21_1 = np.multiply(S21_1.vector(),T11) + np.multiply(S22_1.vector(),T12)
theta1t = Function(Vs1)
theta1t.vector()[:] = np.angle(R11_1+np.multiply(1j,R21_1))
theta1testfun = Function(Vs1)
theta1testfun.vector()[:] = theta1t.vector()
##The modification of \theta defined in equation (5.1) when using \Gamma_{small}:
#indBdr1tmp = np.where((np.arctan2(xy2[:,1],xy2[:,0])<-3.0*np.pi/8.0) & (np.arctan2(xy2[:,1],xy2[:,0])>-np.pi/2.0))
#indBdr1 = np.asarray(indBdr1tmp)
#indBdr1 = np.reshape(indBdr1,indBdr1.shape[1])
#theta1testfun.vector()[indBdr1] = theta1testfun.vector()[indBdr1] + 2*np.pi
#ThetFun = Function(Vs1,theta1t.vector())
#ThetFunMod = Function(Vs1,theta1testfun.vector())
##Illustration of the modification of \theta at the boundary:
#plt.figure(4)
#ax = plt.gca()
#Nt = 100
#ang = np.linspace(-np.pi,np.pi,Nt)
#r = 1
#bdryTf = [ThetFun(r*np.cos(t),r*np.sin(t)) for t in ang]
#bdryTfmod = [ThetFunMod(r*np.cos(t),r*np.sin(t)) for t in ang]
#ax.plot(ang, bdryTf,'b-',label=r'$\theta\vert_{\partial \Omega}(t)$')
#ax.plot(ang, bdryTfmod,'r--',label=r'$\tilde{\theta}\vert_{\partial \Omega}(t)$')
#ax.legend(loc=1,prop={'size': 16})
#plt.xticks([-np.pi,-np.pi/2,0,np.pi/2, np.pi],[r'-$\pi$',r'-$\frac{\pi}{2}$',0,r'$\frac{\pi}{2}$',r'$\pi$'])
#plt.yticks([-np.pi,-np.pi/2,0,np.pi/2, np.pi],[r'-$\pi$',r'-$\frac{\pi}{2}$',0,r'$\frac{\pi}{2}$',r'$\pi$'])
#plt.xlabel(r'$t$',fontsize=20)
#ax.tick_params(axis='both', which='major', labelsize=16)
#plt.grid(True)
##plt.savefig('ThetaBdry3', bbox_inches="tight")
plot_settingsT = {
'levels': np.linspace(-np.pi,np.pi,250),
#'levels': np.linspace(0,5,120),
'cmap': cmaps['twilight_shifted']
}
#plt.figure(5).clear()
#h = plotVs1(theta1t.vector(),**plot_settingsT) # dolfinplot
#plt.gca().axis('off')
#cb=plt.colorbar(h)
#cb.ax.tick_params(labelsize=20)
#tick_locator = ticker.MaxNLocator(nbins=6)
#cb.locator = tick_locator
#cb.update_ticks()
##plt.savefig('TrueThetaSmaMod')
bctheta1 = DirichletBC(Vs1, theta1testfun, boundary2)
theta1 = TrialFunction(Vs1)
vt1 = TestFunction(Vs1)
#Defining and solving the variational equation for the Poisson problem in (13)
a = inner(grad(theta1),grad(vt1))*dx
L = inner(as_vector([dtheta0,dtheta1]),grad(vt1))*dx
theta1 = Function(Vs1)
solve(a == L,theta1,bctheta1)
cos2 = Function(Vs1)
sin2 = Function(Vs1)
cos2t = Function(Vs1)
sin2t = Function(Vs1)
cos2.vector()[:] = np.cos(2*theta1.vector())
sin2.vector()[:] = np.sin(2*theta1.vector())
cos2t.vector()[:] = np.cos(2*theta1t.vector())
sin2t.vector()[:] = np.sin(2*theta1t.vector())
mis2 = np.amin(cos2.vector().get_local())
mas2 = np.amax(cos2.vector().get_local())
plot_settingssin2 = {
'levels': np.linspace(mis2,mas2,250),
'cmap': plt.get_cmap('bwr'),
}
#Illustrations of sin(2\theta) and its reconstructed version
plt.figure(6).clear()
h = plotVs1(sin2t.vector(),**plot_settingssin2) # dolfinplot
plt.gca().axis('off')
cb=plt.colorbar(h)
cb.ax.tick_params(labelsize=20)
tick_locator = ticker.MaxNLocator(nbins=6)
cb.locator = tick_locator
cb.update_ticks()
#plt.savefig('Truecos2ThetaMedc2')
plt.figure(7).clear()
h = plotVs1(sin2.vector(),**plot_settingssin2) # dolfinplot
plt.gca().axis('off')
cb=plt.colorbar(h)
cb.ax.tick_params(labelsize=20)
tick_locator = ticker.MaxNLocator(nbins=6)
cb.locator = tick_locator
cb.update_ticks()
#plt.savefig('Reccos2ThetaMedc2')
print((errornorm(cos2,cos2t,'L2')/norm(cos2t,'L2'))*100)
print((errornorm(sin2,sin2t,'L2')/norm(sin2t,'L2'))*100)
#Defining the vector fields V11 and V22 defined in equation (4.7)
V11in = Vector(Vs1)
V11in[:] = np.log(np.divide(1,np.sqrt(H11.vector())))
V11 = GradSolver2(V11in)
V22in = Vector(Vs1)
V22in[:] = np.log(np.divide(np.sqrt(H11.vector()),d))
V22 = GradSolver2(V22in)
V22min = np.amin(V22in.get_local())
V22max = np.amax(V22in.get_local())
plot_settingsV22 = {
'levels': np.linspace(V22min,V22max,250),
'cmap': plt.set_cmap('bwr'),
}
#Illustration of \log(\sqrt(H11)/D) as in figure 8
plt.figure(11).clear()
h = plotVs1(V22in,**plot_settingsV22) # dolfinplot
plt.gca().axis('off')
cb=plt.colorbar(h)
cb.ax.tick_params(labelsize=20)
tick_locator = ticker.MaxNLocator(nbins=6)
cb.locator = tick_locator
cb.update_ticks()
#Computing the vector field \mathbf{K} for the right hand side in equation (4.4)
Fc0 = V11[0] - V22[0] + V211
Fc1 = -V11[1] + V22[1] + V210
#Computing \mathbf{G} for the right hand side in (4.4)
dlogA0 = Function(Vs1)
dlogA1 = Function(Vs1)
dlogA0.vector()[:] = np.multiply(np.cos(2*theta1.vector()),Fc0) - np.multiply(np.sin(2*theta1.vector()),Fc1)
dlogA1.vector()[:] = np.multiply(np.cos(2*theta1.vector()),Fc1) + np.multiply(np.sin(2*theta1.vector()),Fc0)
logAt = Function(Vs1)
logAt.vector()[:] = np.log(sigt.vector())
bclogA = DirichletBC(Vs1, logAt, boundary2)
logA = TrialFunction(Vs1)
vA = TestFunction(Vs1)
#Defining and solving the variational formulation of the Poisson problem (4.5)
aA = inner(grad(logA),grad(vA))*dx
LA = inner(as_vector([dlogA0,dlogA1]),grad(vA))*dx
logA = Function(Vs1)
solve(aA == LA,logA,bclogA)
A = Function(Vs1)
A.vector()[:] = np.exp(logA.vector())
plot_settings4 = {
'levels': np.linspace(1.0,5.0,250),
'cmap': plt.set_cmap('bwr'),
}
plot_settings5 = {
'levels': np.linspace(1.0,2.0,250),
'cmap': plt.set_cmap('bwr'),
}
#Illustrating the true and reconstructed conductivity such as in figure 6
plt.figure(8).clear()
h = plotVs1(sigt.vector(),**plot_settings4) # dolfinplot
plt.gca().axis('off')
cb=plt.colorbar(h)
cb.ax.tick_params(labelsize=20)
tick_locator = ticker.MaxNLocator(nbins=6)
cb.locator = tick_locator
cb.update_ticks()
#plt.savefig('TrueSigmaCb2')
plt.figure(9).clear()
h = plotVs1(sigt.vector(),**plot_settings5) # dolfinplot
plt.gca().axis('off')
cb=plt.colorbar(h)
cb.ax.tick_params(labelsize=20)
tick_locator = ticker.MaxNLocator(nbins=6)
cb.locator = tick_locator
cb.update_ticks()
#plt.savefig('TrueSigma2')
plt.figure(10).clear()
h = plotVs1(A.vector(),**plot_settings4) # dolfinplot
plt.gca().axis('off')
cb=plt.colorbar(h)
cb.ax.tick_params(labelsize=20)
tick_locator = ticker.MaxNLocator(nbins=6)
cb.locator = tick_locator
cb.update_ticks()
#plt.savefig('RecSigmaLar2')
#Computing the relative L2-error
print((errornorm(A,sigt,'L2')/norm(sigt,'L2'))*100)
#!/bin/bash
# Load modules
#module load FEniCS/2017.2.0-with-petsc-and-slepc
module load FEniCS/2018.1.0-with-petsc-and-slepc-and-scotch-and-newmpi
module load scipy/0.19.1-python-3.6.2
module load matplotlib/2.0.2-python-3.6.2
#module load matplotlib/3.3.1-python-3.6.2
module load ffmpeg/3.4
module load numba/0.35.0-python-3.6.2
#!/bin/bash
# Load modules
#module load FEniCS/2017.2.0-with-petsc-and-slepc
module load FEniCS/2018.1.0-with-petsc-and-slepc-and-scotch-and-newmpi
module load scipy/0.19.1-python-3.6.2
module load matplotlib/2.0.2-python-3.6.2
module load ffmpeg/3.4
module load numba/0.35.0-python-3.6.2
File added
from .cmap import *
File added
File added
This diff is collapsed.
from numpy import array, linspace, sqrt, linalg, where
from numpy import logical_not, logical_or, logical_and
import scipy.signal as signal
import scipy.io
import ufl
def sig(Vs):
""" Conductivity function """
# Initialization
xy = Vs.tabulate_dof_coordinates().reshape((-1,2))
N = xy[:,0].size
#Test case 1:
#sig = 1 + np.exp(-5*(np.power(xy[:,0],2)+np.power(xy[:,1],2)))
#Test case 2:
sig = 1 + np.exp(-20*(np.power(xy[:,0]+1/2,2)+np.power(xy[:,1],2))) + np.exp(-20*(np.power(xy[:,0],2)+np.power(xy[:,1]+1/2,2))) + np.exp(-50*(np.power(xy[:,0]-1/2,2)+np.power(xy[:,1]-1/2,2)))
#sigsqrt = np.sqrt(sig)
sigsqrt = np.sqrt(sig)
return sig,sigsqrt
if __name__ == '__main__':
import sys
# Initialize numpy, IO, matplotlib
import numpy as np
import scipy.io as io
import matplotlib.pyplot as plt
from matplotlib import ticker
plt.ion()
# Load
import cmap as cmap
from dolfin import __version__ as DOLFINversion
from dolfin import TrialFunction, TestFunction, FunctionSpace
from dolfin import project, Point, triangle
from dolfin import inner, dot, grad, dx, ds, VectorFunctionSpace, PETScLUSolver, as_backend_type
from dolfin import Function, assemble, Expression, parameters, VectorFunctionSpace
from dolfin import DirichletBC, as_matrix, interpolate, as_vector, UserExpression, errornorm, norm
from dolfin import MeshFunction, cells, solve, DOLFIN_EPS, near, Constant, FiniteElement
from mshr import generate_mesh, Circle
# Load dolfin plotting
from dolfin import plot as dolfinplot, File as dolfinFile
def plotVs(vec,**kwargs):
""" dolfin.plot-wrapper """
fn = Function(Vs,vec)
return dolfinplot(fn,**kwargs)
def plotVs1(vec,**kwargs):
""" dolfin.plot-wrapper """
fn = Function(Vs1,vec)
return dolfinplot(fn,**kwargs)
# Define Function spaces
def VsSpace(mesh, degree=1): # Corresponding to H^1
E1 = FiniteElement('CG', triangle, degree)
return FunctionSpace(mesh, E1)
def VqSpace(mesh, degree=1): # Used for the gradients
return VectorFunctionSpace(mesh, 'CG', degree)
def Vector(V):
return Function(V).vector()
# Define how to calculate the gradients
def Solver(Op):
s = PETScLUSolver(as_backend_type(Op),'mumps') # Constructs the linear operator Ks for the linear system Ks u = f using LU factorization, where the method 'numps' is used
return s
def GradientSolver(Vq,Vs): #Calculate derivatives on the quadrature points
"""
Based on:
https://fenicsproject.org/qa/1425/derivatives-at-the-quadrature-points/
"""
uq = TrialFunction(Vq)
vq = TestFunction(Vq)
M = assemble(inner(uq,vq)*dx)
femSolver = Solver(M)
u = TrialFunction(Vs)
P = assemble(inner(vq,grad(u))*dx)
def GradSolver(uvec):
gv = Vector(Vq)
g = P*uvec
femSolver.solve(gv, g)
dx = Vector(Vs)
dy = Vector(Vs)
dx[:] = gv[0::2].copy()
dy[:] = gv[1::2].copy()
return dx,dy
return GradSolver
# Define the mesh for the unit disk:
def UnitCircleMesh(n):
C = Circle(Point(0,0),1)
return generate_mesh(C,n)
cmaps = cmap.twilights()
# ------------------------------
# Setup mesh and FEM-spaces
parameters['allow_extrapolation'] = True
#Mesh to generate the power density data:
Ms = 150
#Ms = 200 #For N_{medium} as in Table 2
#Ms = 250 #For N_{large} as in Table 2
m = UnitCircleMesh(Ms)
Vs = VsSpace(m,1)
Vq = VqSpace(m,1)
#Mesh to solve the inverse problem:
Ms2 = 100
#Ms2 = 150 #For N_{medium} as in Table 2
#Ms2 = 200 #For N_{large} as in Table 2
m2 = UnitCircleMesh(Ms2)
Vs1 = VsSpace(m2,1)
Vq1 = VqSpace(m2,1)
# Gradient solver
GradSolver = GradientSolver(Vq,Vs)
GradSolver2 = GradientSolver(Vq1,Vs1)
xy = Vs.tabulate_dof_coordinates().reshape((-1,2))
xy2 = Vs1.tabulate_dof_coordinates().reshape((-1,2))
N = xy[:,0].size
print(N)
N2 = xy2[:,0].size
print(N2)
# ------------------------------
# Conductivity
sigt = Function(Vs1)
sigsqrtt = Vector(Vs1)
sig1 = Function(Vs)
sigsqrt1 = Function(Vs)
sigt1,sigsqrtt1 = sig(Vs)
sigt.vector()[:],sigsqrtt[:] = sig(Vs1)
sig1.vector().set_local(sigt1)
sigsqrt1.vector().set_local(sigsqrtt1)
# Plot
plot_settings = {
#'levels': np.linspace(-1,2,120),
#'levels': np.linspace(0,5,120),
'cmap': plt.set_cmap('bwr'),
}
# ------------------------------
# Boundary conditions
u_D1 = Expression('x[0]', degree=2)
u_D2 = Expression('x[1]', degree=1)
# Defining \Gamma_{medium}
def boundary(x, on_boundary):
return (on_boundary and (ufl.atan_2(x[1],x[0])<(1.0/4.0)*np.pi and ufl.atan_2(x[1],x[0])>-(3.0/4.0)*np.pi) )
def boundary2(x, on_boundary):
return on_boundary
bc1 = DirichletBC(Vs, u_D1, boundary)
bc2 = DirichletBC(Vs, u_D2, boundary)
u1 = Function(Vs)
v1 = TestFunction(Vs)
u2 = Function(Vs)
v2 = TestFunction(Vs)
#Defining and solving the variational equations
a1 = inner(sig1*grad(u1),grad(v1))*dx
a2 = inner(sig1*grad(u2),grad(v2))*dx
solve(a1 == 0,u1,bc1)
solve(a2 == 0,u2,bc2)
#Defining the gradients
dU1 = GradSolver(u1.vector())
dU2 = GradSolver(u2.vector())
H11tmp = Vector(Vs)
H12tmp = Vector(Vs)
H22tmp = Vector(Vs)
#Compute the noise free power density data
H11tmp[:] = sig1.vector()*(dU1[0]*dU1[0]+dU1[1]*dU1[1])
H12tmp[:] = sig1.vector()*(dU1[0]*dU2[0]+dU1[1]*dU2[1])
H22tmp[:] = sig1.vector()*(dU2[0]*dU2[0]+dU2[1]*dU2[1])
H11t = Function(Vs)
H12t = Function(Vs)
H21t = Function(Vs)
H22t = Function(Vs)
#Add noise to the data by following the approach in section 5.4
np.random.seed(50)
e1 = Vector(Vs)
e2 = Vector(Vs)
e3 = Vector(Vs)
e4 = Vector(Vs)
e1[:]= np.random.randn(N)
e2[:]= np.random.randn(N)
e3[:]= np.random.randn(N)
e4[:]= np.random.randn(N)
#Define the noise level
alpha = 5
H11t.vector()[:] = H11tmp + alpha/100.0*(e1/norm(e1))*H11tmp
H12t.vector()[:] = H12tmp + alpha/100.0*(e2/norm(e2))*H12tmp
H21t.vector()[:] = H12tmp + alpha/100.0*(e3/norm(e3))*H12tmp
H22t.vector()[:] = H22tmp + alpha/100.0*(e4/norm(e4))*H22tmp
S11 = Function(Vs)
S12 = Function(Vs)
S21 = Function(Vs)
S22 = Function(Vs)
S11.vector()[:] = sigsqrt1.vector()*dU1[0]
S21.vector()[:] = sigsqrt1.vector()*dU1[1]
S12.vector()[:] = sigsqrt1.vector()*dU2[0]
S22.vector()[:] = sigsqrt1.vector()*dU2[1]
#Project the noisy data to the mesh for solving the inverse problem
H11tmp = project(H11t,Vs1)
H12tmp = project(H12t,Vs1)
H21tmp = project(H21t,Vs1)
H22tmp = project(H22t,Vs1)
H11 = Function(Vs1)
H12 = Function(Vs1)
H22 = Function(Vs1)
#Define a lower bound for the eigenvalues of \tilde{H}
lb = 1e-5
for i in range(N2):
H11mat = H11tmp.vector()[i]
H12mat = (1/2)*(H12tmp.vector()[i] + H21tmp.vector()[i])
H22mat = H22tmp.vector()[i]
Hmat = np.array([[H11mat,H12mat],[H12mat,H22mat]])
wh,vh = np.linalg.eig(Hmat)
H11.vector()[i] = np.maximum(wh[0],lb)*vh[0,0]*vh[0,0] + np.maximum(wh[1],lb)*vh[0,1]*vh[0,1]
H12.vector()[i] = np.maximum(wh[0],lb)*vh[0,0]*vh[1,0] + np.maximum(wh[1],lb)*vh[0,1]*vh[1,1]
H22.vector()[i] = np.maximum(wh[0],lb)*vh[1,0]*vh[1,0] + np.maximum(wh[1],lb)*vh[1,1]*vh[1,1]
S11_1 = project(S11,Vs1)
S12_1 = project(S12,Vs1)
S21_1 = project(S21,Vs1)
S22_1 = project(S22,Vs1)
dt = H11.vector()*H22.vector()-H12.vector()*H12.vector()
lJac = Vector(Vs1)
lJac[:] = np.log(dt)
midet = np.amin(dt.get_local())
madet = np.amax(dt.get_local())
plot_settingsdet = {
'levels': np.linspace(midet,madet,250),
#'levels': np.linspace(0,5,120),
'cmap': plt.set_cmap('RdBu'),
}
mildet = np.amin(lJac.get_local())
maldet = np.amax(lJac.get_local())
plot_settingsldet = {
'levels': np.linspace(mildet,maldet,250),
#'levels': np.linspace(0,5,120),
#'cmap': plt.set_cmap('RdBu'),
'cmap': plt.get_cmap('bwr'),
}
miu1 = np.amin(u1.vector().get_local())
mau1 = np.amax(u1.vector().get_local())
plot_settingsu1 = {
'levels': np.linspace(miu1,mau1,250),
#'levels': np.linspace(0,5,120),
#'cmap': plt.set_cmap('RdBu'),
'cmap': plt.get_cmap('bwr'),
}
miu2 = np.amin(u2.vector().get_local())
mau2 = np.amax(u2.vector().get_local())
plot_settingsu2 = {
'levels': np.linspace(miu2,mau2,250),
#'levels': np.linspace(0,5,120),
#'cmap': plt.set_cmap('RdBu'),
'cmap': plt.get_cmap('bwr'),
}
#Illustrating the solutions u1 and u2
plt.figure(1).clear()
h = plotVs(u1.vector(),**plot_settingsu1) # dolfinplot
plt.gca().axis('off')
cb=plt.colorbar(h)
cb.ax.tick_params(labelsize=20)
tick_locator = ticker.MaxNLocator(nbins=6)
cb.locator = tick_locator
cb.update_ticks()
#plt.savefig('u1medc1')
plt.figure(2).clear()
h = plotVs(u2.vector(),**plot_settingsu2) # dolfinplot
plt.gca().axis('off')
cb=plt.colorbar(h)
cb.ax.tick_params(labelsize=20)
tick_locator = ticker.MaxNLocator(nbins=6)
cb.locator = tick_locator
cb.update_ticks()
#plt.savefig('u2medc1')
#Illustrating log(det(H)):
plt.figure(3).clear()
h = plotVs1(lJac,**plot_settingsldet) # dolfinplot
plt.gca().axis('off')
cb=plt.colorbar(h)
cb.ax.tick_params(labelsize=20)
tick_locator = ticker.MaxNLocator(nbins=6)
cb.locator = tick_locator
cb.update_ticks()
#plt.savefig('logDetMedc1')
dtest = H11.vector()*H22.vector()-H12.vector()*H12.vector()
print(min(dtest))
d = Vector(Vs1)
d[:] = np.sqrt(dtest)
#Compute the T matrix as in section 4.3
T11 = np.divide(1,np.sqrt(H11.vector()))
T12 = np.zeros(N2)
T21 = -np.divide(H12.vector(),np.multiply(np.sqrt(H11.vector()),d))
T22 = np.divide(np.sqrt(H11.vector()),d)
H1211 = Vector(Vs1)
H1211[:] = np.divide(H12.vector(),H11.vector())
dH1211 = GradSolver2(H1211)
#Compute the vector field V21 as in equation (4.7)
V210 = Vector(Vs1)
V211 = Vector(Vs1)
V210[:] = -np.multiply(np.divide(H11.vector(),d),dH1211[0])
V211[:] = -np.multiply(np.divide(H11.vector(),d),dH1211[1])
ld1 = Vector(Vs1)
ld1[:] = np.log(np.power(d,2))
dld1 = GradSolver2(ld1)
#Compute the right hand side \mathbf{F} for the Poisson equation (4.3)
dtheta0 = Function(Vs1)
dtheta1 = Function(Vs1)
dtheta0.vector()[:] = (1/2)*(-V210 + (1/2)*dld1[1])
dtheta1.vector()[:] = (1/2)*(-V211 - (1/2)*dld1[0])
#Compute the true R and theta
R11_1 = np.multiply(S11_1.vector(),T11) + np.multiply(S12_1.vector(),T12)
R21_1 = np.multiply(S21_1.vector(),T11) + np.multiply(S22_1.vector(),T12)
theta1t = Function(Vs1)
theta1t.vector()[:] = np.angle(R11_1+np.multiply(1j,R21_1))
theta1testfun = Function(Vs1)
theta1testfun.vector()[:] = theta1t.vector()
bctheta1 = DirichletBC(Vs1, theta1t, boundary2)
theta1 = TrialFunction(Vs1)
vt1 = TestFunction(Vs1)
#Defining and solving the variational equation for the Poisson problem in (13)
a = inner(grad(theta1),grad(vt1))*dx
L = inner(as_vector([dtheta0,dtheta1]),grad(vt1))*dx
theta1 = Function(Vs1)
solve(a == L,theta1,bctheta1)
cos2 = Function(Vs1)
sin2 = Function(Vs1)
cos2t = Function(Vs1)
sin2t = Function(Vs1)
cos2.vector()[:] = np.cos(2*theta1.vector())
sin2.vector()[:] = np.sin(2*theta1.vector())
cos2t.vector()[:] = np.cos(2*theta1t.vector())
sin2t.vector()[:] = np.sin(2*theta1t.vector())
mis2 = np.amin(cos2.vector().get_local())
mas2 = np.amax(cos2.vector().get_local())
plot_settingssin2 = {
'levels': np.linspace(mis2,mas2,250),
'cmap': plt.get_cmap('bwr'),
}
#Illustrations of sin(2\theta) and its reconstructed version
plt.figure(6).clear()
h = plotVs1(sin2t.vector(),**plot_settingssin2) # dolfinplot
plt.gca().axis('off')
cb=plt.colorbar(h)
cb.ax.tick_params(labelsize=20)
tick_locator = ticker.MaxNLocator(nbins=6)
cb.locator = tick_locator
cb.update_ticks()
#plt.savefig('Truecos2ThetaMedc2')
plt.figure(7).clear()
h = plotVs1(sin2.vector(),**plot_settingssin2) # dolfinplot
plt.gca().axis('off')
cb=plt.colorbar(h)
cb.ax.tick_params(labelsize=20)
tick_locator = ticker.MaxNLocator(nbins=6)
cb.locator = tick_locator
cb.update_ticks()
#plt.savefig('Reccos2ThetaMedc2')
print((errornorm(cos2,cos2t,'L2')/norm(cos2t,'L2'))*100)
print((errornorm(sin2,sin2t,'L2')/norm(sin2t,'L2'))*100)
#Defining the vector fields V11 and V22 defined in equation (4.7)
V11in = Vector(Vs1)
V11in[:] = np.log(np.divide(1,np.sqrt(H11.vector())))
V11 = GradSolver2(V11in)
V22in = Vector(Vs1)
V22in[:] = np.log(np.divide(np.sqrt(H11.vector()),d))
V22 = GradSolver2(V22in)
V22min = np.amin(V22in.get_local())
V22max = np.amax(V22in.get_local())
plot_settingsV22 = {
'levels': np.linspace(V22min,V22max,250),
'cmap': plt.set_cmap('bwr'),
}
#Illustration of \log(\sqrt(H11)/D) as in figure 8
plt.figure(11).clear()
h = plotVs1(V22in,**plot_settingsV22) # dolfinplot
plt.gca().axis('off')
cb=plt.colorbar(h)
cb.ax.tick_params(labelsize=20)
tick_locator = ticker.MaxNLocator(nbins=6)
cb.locator = tick_locator
cb.update_ticks()
#Computing the vector field \mathbf{K} for the right hand side in equation (4.4)
Fc0 = V11[0] - V22[0] + V211
Fc1 = -V11[1] + V22[1] + V210
#Computing \mathbf{G} for the right hand side in (4.4)
dlogA0 = Function(Vs1)
dlogA1 = Function(Vs1)
dlogA0.vector()[:] = np.multiply(np.cos(2*theta1.vector()),Fc0) - np.multiply(np.sin(2*theta1.vector()),Fc1)
dlogA1.vector()[:] = np.multiply(np.cos(2*theta1.vector()),Fc1) + np.multiply(np.sin(2*theta1.vector()),Fc0)
logAt = Function(Vs1)
logAt.vector()[:] = np.log(sigt.vector())
bclogA = DirichletBC(Vs1, logAt, boundary2)
logA = TrialFunction(Vs1)
vA = TestFunction(Vs1)
#Defining and solving the variational formulation of the Poisson problem (4.5)
aA = inner(grad(logA),grad(vA))*dx
LA = inner(as_vector([dlogA0,dlogA1]),grad(vA))*dx
logA = Function(Vs1)
solve(aA == LA,logA,bclogA)
A = Function(Vs1)
A.vector()[:] = np.exp(logA.vector())
plot_settings4 = {
'levels': np.linspace(0,5.0,250),
'cmap': plt.set_cmap('bwr'),
}
plot_settings5 = {
'levels': np.linspace(1.0,2.0,250),
'cmap': plt.set_cmap('bwr'),
}
#Illustrating the true and reconstructed conductivity such as in figure 11
plt.figure(8).clear()
h = plotVs1(sigt.vector(),**plot_settings4) # dolfinplot
plt.gca().axis('off')
cb=plt.colorbar(h)
cb.ax.tick_params(labelsize=20)
tick_locator = ticker.MaxNLocator(nbins=6)
cb.locator = tick_locator
cb.update_ticks()
#plt.savefig('TrueSigmaCb2')
plt.figure(9).clear()
h = plotVs1(sigt.vector(),**plot_settings5) # dolfinplot
plt.gca().axis('off')
cb=plt.colorbar(h)
cb.ax.tick_params(labelsize=20)
tick_locator = ticker.MaxNLocator(nbins=6)
cb.locator = tick_locator
cb.update_ticks()
#plt.savefig('TrueSigma2')
plt.figure(10).clear()
h = plotVs1(A.vector(),**plot_settings4) # dolfinplot
plt.gca().axis('off')
cb=plt.colorbar(h)
cb.ax.tick_params(labelsize=20)
tick_locator = ticker.MaxNLocator(nbins=6)
cb.locator = tick_locator
cb.update_ticks()
#plt.savefig('RecSigmaLar2')
#Computing the relative L2-error
print((errornorm(A,sigt,'L2')/norm(sigt,'L2'))*100)
#!/bin/bash
# Load modules
#module load FEniCS/2017.2.0-with-petsc-and-slepc
module load FEniCS/2018.1.0-with-petsc-and-slepc-and-scotch-and-newmpi
module load scipy/0.19.1-python-3.6.2
module load matplotlib/2.0.2-python-3.6.2
#module load matplotlib/3.3.1-python-3.6.2
module load ffmpeg/3.4
module load numba/0.35.0-python-3.6.2
#!/bin/bash
# Load modules
#module load FEniCS/2017.2.0-with-petsc-and-slepc
module load FEniCS/2018.1.0-with-petsc-and-slepc-and-scotch-and-newmpi
module load scipy/0.19.1-python-3.6.2
module load matplotlib/2.0.2-python-3.6.2
module load ffmpeg/3.4
module load numba/0.35.0-python-3.6.2
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment