# Convergence order: CONVORDER = [] for ii in range(len(ERROR)-1): CONVORDER.append(np.log(ERROR[ii+1]/ERROR[ii])/np.log((1./NN[ii+1])/(1./NN[ii]))) print '\n\norder of convergence:', CONVORDER # Save plots: try: boolplot = int(sys.argv[1]) except: boolplot = 0 if boolplot > 0: filename, ext = splitext(sys.argv[0]) if isdir(filename + '/'): rmtree(filename + '/') myplot = PlotFenics(filename) myplot.set_varname('p') plotp = Function(V) for index, pp in enumerate(sol): plotp.vector()[:] = pp[0] myplot.plot_vtk(plotp, index) myplot.gather_vtkplots() fig = plt.figure() ax = fig.add_subplot(111) ax.loglog(1./NN, ERROR, '-o') ax.set_xlabel('h') ax.set_ylabel('error') fig.savefig(filename + '/convergence.eps')
print '\ntarget: min(c)={}, max(c)={}'.format(minct, maxct) print 'MAP: min(c)={}, max(c)={}'.format(minc, maxc) print 'med_misfit={:.4e}, err={:.1f}%'.format(norm_mmfc, errc) # WARNING: only makes sense if mpicomm_local == mpi_comm_self # otherwise, can't be restricted to PRINT processor only plotfolder = PARAM + '_k' + str(k) + '_e' + str(eps) myplot = PlotFenics(Outputfolder='output_transmission/plots/' + plotfolder, \ comm = mesh.mpi_comm()) waveobj._plotab( myplot, '-map_' + PARAM + '-VTV_' + amg + '_k' + str(k) + '_e' + str(eps)) myplot.set_varname('c-map_' + PARAM + '-VTV_' + amg + '_k' + str(k) + '_e' + str(eps)) myplot.plot_vtk(cf) """ # Test gradient and Hessian after several steps of Newton method waveobj.GN = False waveobj.regularization = ZeroRegularization(Vl) if ALL and (PARAM == 'a' or PARAM == 'b') and PRINT: print '*** Warning: Single inversion but changing both parameters' MPa = [ dl.Constant('1.0'), dl. Expression('sin(pi*x[0])*sin(pi*x[1])', degree=10), dl.Expression('x[0]', degree=10), dl.Expression('x[1]', degree=10), dl.Expression('sin(3*pi*x[0])*sin(3*pi*x[1])', degree=10)] MPb = [ dl.Constant('1.0'), dl. Expression('sin(pi*x[0])*sin(pi*x[1])', degree=10), dl.Expression('x[1]', degree=10), dl.Expression('x[0]', degree=10),
dl.interpolate(dl.Expression('log(10 - ' + '(pow(pow(x[0]-0.5,2)+pow(x[1]-0.5,2),0.5)<0.4) * (' + '8*(x[0]<=0.5) + 4*(x[0]>0.5) ))'), V), dl.interpolate(dl.Expression('log(10)'), V), dl.interpolate(dl.Expression('log(10 - ' + '(pow(pow(x[0]-0.5,2)+pow(x[1]-0.5,2),0.5)<0.2) * (' + '4*(x[0]<=0.5) + 8*(x[0]>0.5) ))'), V)] """ parameters={'solver':'lapack', 'problem_type':'hermitian'} ii=1 for a1, a2 in zip(a1true, a2true): if mpirank == 0: print 'Test ' + str(ii) plotfenics.set_varname('a1-case'+str(ii)) plotfenics.plot_vtk(a1) plotfenics.set_varname('a2-case'+str(ii)) plotfenics.plot_vtk(a2) cg.assemble_hessianab(a1.vector(), a2.vector()) ncg.assemble_hessianab(a1.vector(), a2.vector()) if mpirank == 0: print '\teigenvalues Hprecond' compute_eigfenics(cg.Hprecond, outdir + 'eig_cg_Hprecond-' + str(ii) + '.txt', parameters) compute_eigfenics(ncg.Hprecond, outdir + 'eig_ncg_Hprecond-' + str(ii) + '.txt', parameters) if mpirank == 0: print '\teigenvalues H' compute_eigfenics(cg.H, outdir + 'eig_cg_H-' + str(ii) + '.txt', parameters) compute_eigfenics(ncg.H,
wavepde.timestepper = 'backward' wavepde.lump = True wavepde.update({'a':a_target_fn, 'b':b_target_fn, \ 't0':t0, 'tf':tf, 'Dt':Dt, 'u0init':dl.Function(V), 'utinit':dl.Function(V)}) # parameters Vm = wavepde.Vm V = wavepde.V lenobspts = obsop.PtwiseObs.nbPts # set up plots: filename, ext = splitext(sys.argv[0]) if isdir(filename + '/'): rmtree(filename + '/') myplot = PlotFenics(filename + str(Nxy)) myplot.set_varname('a_target') myplot.plot_vtk(a_target_fn) # define objective function: regul = LaplacianPrior({ 'Vm': Vm, 'gamma': 5e-4, 'beta': 5e-4, 'm0': a_target_fn }) waveobj = ObjectiveAcoustic(wavepde, mysrc, 'a', regul) waveobj.obsop = obsop # noisy data print 'generate noisy data' waveobj.solvefwd() skip = 20
Waveex = AcousticWave({'V': Vex, 'Vm': Vl}) Waveex.timestepper = 'backward' Waveex.lump = True Waveex.update({'a':1.0, 'b':1.0, 't0':0.0, 'tf':tf, 'Dt':Dt,\ 'u0init':dl.Function(Vex), 'utinit':dl.Function(Vex)}) Waveex.ftime = mysrc sol, _ = Waveex.solve() Waveex.exact = dl.Function(Vex) normex = Waveex.computeabserror() # plot myplot.set_varname('u-q' + str(qq)) plotu = dl.Function(Vex) for index, uu in enumerate(sol): if index % boolplot == 0: setfct(plotu, uu[0]) myplot.plot_vtk(plotu, index) myplot.gather_vtkplots() print 'Check different spatial sampling' QQ = [4, 5, 6, 10] for qq in QQ: N = int(qq / cmin) h = 1. / N mesh = dl.UnitSquareMesh(N, N) Vl = dl.FunctionSpace(mesh, 'Lagrange', 1) V = dl.FunctionSpace(mesh, 'Lagrange', r) Pt = PointSources(V, [[.5, .5]]) mydelta = Pt[0].array() def mysrc(tt): return Ricker(tt) * mydelta
Wave.timestepper = 'centered' Wave.lump = True Wave.set_abc(mesh, AllFour(), True) Wave.exact = Function(V) Wave.update({'b':1.0, 'a':1.0, 't0':0.0, 'tf':tf, 'Dt':Dt,\ 'u0init':Function(V), 'utinit':Function(V)}) Wave.ftime = mysrc sol, error = Wave.solve() ERROR.append(error) if myrank == 0: print 'relative error = {:.5e}'.format(error) if not mycomm == None: MPI.barrier(mycomm) # Plots: try: boolplot = int(sys.argv[1]) except: boolplot = 0 if boolplot > 0: filename, ext = splitext(sys.argv[0]) if myrank == 0: if isdir(filename + '/'): rmtree(filename + '/') if not mycomm == None: MPI.barrier(mycomm) myplot = PlotFenics(filename) myplot.set_varname('p') plotp = Function(V) for index, pp in enumerate(sol): if index % boolplot == 0: plotp.vector()[:] = pp[0] myplot.plot_vtk(plotp, index) myplot.gather_vtkplots()
mtrue_exp = \ dl.Expression('1.0 + 7.0*(x[0]<=0.8)*(x[0]>=0.2)*(x[1]<=0.8)*(x[1]>=0.2)') mtrue = dl.interpolate(mtrue_exp, Vme) # target medium mtrueVm = dl.interpolate(mtrue_exp, Vm) # target medium f = dl.Expression("1.0") # source term # set up plots: if PLOT: filename, ext = splitext(sys.argv[0]) if mpirank == 0 and isdir(filename + '/'): rmtree(filename + '/') MPI.barrier(mpicomm) myplot = PlotFenics(filename) MPI.barrier(mpicomm) myplot.set_varname('m_target') myplot.plot_vtk(mtrue) myplot.set_varname('m_targetVm') myplot.plot_vtk(mtrueVm) else: myplot = None if mpirank == 0: print 'Compute noisy data' OPPS = 15 NB = OPPS + 1. Points = np.array([[[ii/NB,jj/NB] for ii in range(1,OPPS+1)]\ for jj in range(1,OPPS+1)]) Points.resize((OPPS * OPPS, 2)) ObsOp = ObsPointwise({'V': V, 'Points': Points}, mpicomm) ObsOp.noise = False goal = ObjFctalElliptic(V, Vme, bc, bc, [f], ObsOp, [], [], [], False, mpicomm) goal.update_m(mtrue)
import dolfin as dl from fenicstools.plotfenics import PlotFenics from fenicstools.miscfenics import setfct mesh = dl.UnitSquareMesh(40, 40) V = dl.FunctionSpace(mesh, 'Lagrange', 1) myplot = PlotFenics() myplot.set_varname('u') u = dl.Function(V) for ii in range(10): setfct(u, dl.interpolate(dl.Constant(ii), V)) myplot.plot_vtk(u, ii) myplot.gather_vtkplots()
# source: Ricker = RickerWavelet(fpeak, 1e-10) Pt = PointSources(V, [[0.5, 1.0]]) mydelta = Pt[0].array() def mysrc(tt): return Ricker(tt) * mydelta # target medium medformula = "A*A*(x[1]>=0.5) + 2.0*2.0*(x[1]<0.5)" TargetMedExpr = dl.Expression(medformula, A=1.5) TargetMed = dl.interpolate(TargetMedExpr, Vl) myplot.set_varname("target_medium") myplot.plot_vtk(TargetMed) # perturbation # PerturbationMedExpr = dl.Expression(medformula, A=1.0) # PerturbMed = dl.interpolate(PerturbationMedExpr, Vl) # myplot.set_varname('perturb_medium') # myplot.plot_vtk(PerturbMed) # observation operator: obspts = [[x / 10.0, 1.0] for x in range(1, 10)] obsop = TimeObsPtwise({"V": V, "Points": obspts}) # define pde operator: wavepde = AcousticWave({"V": V, "Vl": Vl, "Vr": Vl}) wavepde.timestepper = "backward" wavepde.lump = True wavepde.set_abc(mesh, ABC(), True) wavepde.update( {"lambda": TargetMed, "rho": 1.0, "t0": t0, "tf": tf, "Dt": Dt, "u0init": dl.Function(V), "utinit": dl.Function(V)}
def run_test(fpeak, lambdamin, lambdamax, Nxy, tfilterpts, r, Dt, skip): h = 1. / Nxy checkdt(Dt, h, r, np.sqrt(lambdamax), True) mesh = dl.UnitSquareMesh(Nxy, Nxy) Vl = dl.FunctionSpace(mesh, 'Lagrange', 1) V = dl.FunctionSpace(mesh, 'Lagrange', r) fctV = dl.Function(V) # set up plots: filename, ext = splitext(sys.argv[0]) if isdir(filename + '/'): rmtree(filename + '/') myplot = PlotFenics(filename) # source: Ricker = RickerWavelet(fpeak, 1e-10) Pt = PointSources(V, [[0.5, 0.5]]) mydelta = Pt[0].array() def mysrc(tt): return Ricker(tt) * mydelta # target medium: lambda_target = dl.Expression('lmin + x[0]*(lmax-lmin)', \ lmin=lambdamin, lmax=lambdamax) lambda_target_fn = dl.interpolate(lambda_target, Vl) myplot.set_varname('lambda_target') myplot.plot_vtk(lambda_target_fn) # initial medium: lambda_init = dl.Constant(lambdamin) lambda_init_fn = dl.interpolate(lambda_init, Vl) myplot.set_varname('lambda_init') myplot.plot_vtk(lambda_init_fn) # observation operator: #obspts = [[0.2, 0.5], [0.5, 0.2], [0.5, 0.8], [0.8, 0.5]] obspts = [[0.2, ii/10.] for ii in range(2,9)] + \ [[0.8, ii/10.] for ii in range(2,9)] + \ [[ii/10., 0.2] for ii in range(3,8)] + \ [[ii/10., 0.8] for ii in range(3,8)] obsop = TimeObsPtwise({'V': V, 'Points': obspts}, tfilterpts) # define pde operator: wavepde = AcousticWave({'V': V, 'Vl': Vl, 'Vr': Vl}) wavepde.timestepper = 'backward' wavepde.lump = True wavepde.set_abc(mesh, LeftRight(), True) wavepde.update({'lambda':lambda_target_fn, 'rho':1.0, \ 't0':t0, 'tf':tf, 'Dt':Dt, 'u0init':dl.Function(V), 'utinit':dl.Function(V)}) wavepde.ftime = mysrc # define objective function: waveobj = ObjectiveAcoustic(wavepde) waveobj.obsop = obsop # data print 'generate data' waveobj.solvefwd() myplot.plot_timeseries(waveobj.solfwd, 'pd', 0, skip, fctV) dd = waveobj.Bp.copy() # gradient print 'generate observations' waveobj.dd = dd waveobj.update_m(lambda_init_fn) waveobj.solvefwd_cost() cost1 = waveobj.misfit print 'misfit = {}'.format(waveobj.misfit) myplot.plot_timeseries(waveobj.solfwd, 'p', 0, skip, fctV) # Plot data and observations fig = plt.figure() if len(obspts) > 9: fig.set_size_inches(20., 15.) for ii in range(len(obspts)): if len(obspts) == 4: ax = fig.add_subplot(2, 2, ii + 1) else: ax = fig.add_subplot(4, 6, ii + 1) ax.plot(waveobj.PDE.times, waveobj.dd[ii, :], 'k--') ax.plot(waveobj.PDE.times, waveobj.Bp[ii, :], 'b') ax.set_title('Plot' + str(ii)) fig.savefig(filename + '/observations.eps') print 'compute gradient' waveobj.solveadj_constructgrad() myplot.plot_timeseries(waveobj.soladj, 'v', 0, skip, fctV) MG = waveobj.MGv.array().copy() myplot.set_varname('grad') myplot.plot_vtk(waveobj.Grad) """
for index, pp in enumerate(sol): setfct(solp, pp[0]) Bp[:, index] = myObs.obs(solp) mytimes[index] = pp[1] Bpf = Bp * mytf.evaluate(mytimes) # Plots: try: boolplot = int(sys.argv[1]) except: boolplot = 20 if boolplot > 0: filename, ext = splitext(sys.argv[0]) if myrank == 0: if isdir(filename + '/'): rmtree(filename + '/') if PARALLEL: MPI.barrier(mycomm) myplot = PlotFenics(filename) plotp = Function(V) myplot.plot_timeseries(sol, 'p', 0, boolplot, plotp) # Plot medium myplot.set_varname('lambda') myplot.plot_vtk(lambda_target_fn) # Plot observations fig = plt.figure() for ii in range(Bp.shape[0]): ax = fig.add_subplot(2, 2, ii + 1) ax.plot(mytimes, Bp[ii, :], 'b') ax.plot(mytimes, Bpf[ii, :], 'r--') ax.set_title('Plot' + str(ii)) fig.savefig(filename + '/observations_p' + str(myrank) + '.eps')
bc = DirichletBC(V, u0, u0_boundary) # Define target medium and rhs: mtrue_exp = Expression("1 + 7*(pow(pow(x[0] - 0.5,2) +" + " pow(x[1] - 0.5,2),0.5) > 0.2)") mtrue = interpolate(mtrue_exp, Vme) f = Expression("1.0") if myrank == 0: print "Compute target data".format(myrank) obspts = [[ii / 5.0, jj / 5.0] for ii in range(1, 5) for jj in range(1, 5)] noisepercent = 0.10 # e.g., 0.02 = 2% noise level ObsOp = ObsPointwise({"V": V, "Points": obspts, "noise": noisepercent}, mycomm) goal = ObjFctalElliptic(V, Vme, bc, bc, [f], ObsOp, [], [], [], False, mycomm) goal.update_m(mtrue) goal.solvefwd() UDnoise = goal.U if myrank == 0: print "Define prior and sample from prior" m0 = Function(Vm) m0.vector()[:] = 1.0 myprior = BilaplacianPrior({"Vm": Vm, "gamma": 10.0, "beta": 10.0, "m0": m0}) filename, ext = splitext(sys.argv[0]) if isdir(filename + "/"): rmtree(filename + "/") plotprior = PlotFenics(filename + "/Prior/") plotprior.set_varname("m_prior") for ii in range(10): mypriorsample = myprior.sample() plotprior.plot_vtk(mypriorsample, ii) plotprior.gather_vtkplots()
try: boolplot = int(sys.argv[1]) except: boolplot = 20 if boolplot > 0: filename, ext = splitext(sys.argv[0]) #filename = filename + '0' if myrank == 0: if isdir(filename + '/'): rmtree(filename + '/') if not mycomm == None: MPI.barrier(mycomm) myplot = PlotFenics(filename) plotp = Function(V) myplot.plot_timeseries(sol, 'p', 0, boolplot, plotp) # myplot.set_varname('p') # for index, pp in enumerate(sol): # if index%boolplot == 0: # setfct(plotp, pp[0]) # myplot.plot_vtk(plotp, index) # myplot.gather_vtkplots() # Plot medium myplot.set_varname('lambda') myplot.plot_vtk(lambda_target_fn) # Plot observations fig = plt.figure() for ii in range(Bp.shape[0]): ax = fig.add_subplot(2,2,ii+1) ax.plot(mytimes, Bp[ii,:], 'b') ax.plot(mytimes, Bpf[ii,:], 'r--') ax.set_title('Plot'+str(ii)) fig.savefig(filename + '/observations.eps')
Waveex = AcousticWave({'V':Vex, 'Vl':Vl, 'Vr':Vl}) Waveex.timestepper = 'backward' Waveex.lump = True Waveex.update({'lambda':1.0, 'rho':1.0, 't0':0.0, 'tf':tf, 'Dt':Dt,\ 'u0init':dl.Function(Vex), 'utinit':dl.Function(Vex)}) Waveex.ftime = mysrc sol,_ = Waveex.solve() Waveex.exact = dl.Function(Vex) normex = Waveex.computeabserror() # plot myplot.set_varname('u-q'+str(qq)) plotu = dl.Function(Vex) for index, uu in enumerate(sol): if index%boolplot == 0: setfct(plotu, uu[0]) myplot.plot_vtk(plotu, index) myplot.gather_vtkplots() print 'Check different spatial sampling' QQ = [4, 5, 6, 10] for qq in QQ: N = int(qq/cmin) h = 1./N mesh = dl.UnitSquareMesh(N,N) Vl = dl.FunctionSpace(mesh, 'Lagrange', 1) V = dl.FunctionSpace(mesh, 'Lagrange', r) Pt = PointSources(V, [[.5,.5]]) mydelta = Pt[0].array() def mysrc(tt): return Ricker(tt)*mydelta Wave = AcousticWave({'V':V, 'Vl':Vl, 'Vr':Vl})
wavepde.lump = True wavepde.update({'a':a_target_fn, 'b':b_target_fn, \ 't0':t0, 'tf':tf, 'Dt':Dt, 'u0init':dl.Function(V), 'utinit':dl.Function(V)}) # parameters Vm = wavepde.Vm V = wavepde.V lenobspts = obsop.PtwiseObs.nbPts # set up plots: filename, ext = splitext(sys.argv[0]) #if mpirank == 0 and isdir(filename + '/'): rmtree(filename + '/') #MPI.barrier(mpicomm) myplot = PlotFenics(filename + str(Nxy)) myplot.set_varname('b_target') myplot.plot_vtk(b_target_fn) # define objective function: regul = LaplacianPrior({ 'Vm': Vm, 'gamma': 5e-4, 'beta': 5e-4, 'm0': a_target_fn }) waveobj = ObjectiveAcoustic(wavepde, mysrc, 'b', regul) waveobj.obsop = obsop # noisy data #TODO: to be fixed for parallel computation if mpirank == 0: print 'generate noisy data' waveobj.solvefwd()
def run_test(fpeak, lambdamin, lambdamax, Nxy, tfilterpts, r, Dt, skip): h = 1./Nxy checkdt(Dt, h, r, np.sqrt(lambdamax), True) mesh = dl.UnitSquareMesh(Nxy, Nxy) Vl = dl.FunctionSpace(mesh, 'Lagrange', 1) V = dl.FunctionSpace(mesh, 'Lagrange', r) fctV = dl.Function(V) # set up plots: filename, ext = splitext(sys.argv[0]) if isdir(filename + '/'): rmtree(filename + '/') myplot = PlotFenics(filename) # source: Ricker = RickerWavelet(fpeak, 1e-10) Pt = PointSources(V, [[0.5,0.5]]) mydelta = Pt[0].array() def mysrc(tt): return Ricker(tt)*mydelta # target medium: lambda_target = dl.Expression('lmin + x[0]*(lmax-lmin)', \ lmin=lambdamin, lmax=lambdamax) lambda_target_fn = dl.interpolate(lambda_target, Vl) myplot.set_varname('lambda_target') myplot.plot_vtk(lambda_target_fn) # initial medium: lambda_init = dl.Constant(lambdamin) lambda_init_fn = dl.interpolate(lambda_init, Vl) myplot.set_varname('lambda_init') myplot.plot_vtk(lambda_init_fn) # observation operator: #obspts = [[0.2, 0.5], [0.5, 0.2], [0.5, 0.8], [0.8, 0.5]] obspts = [[0.2, ii/10.] for ii in range(2,9)] + \ [[0.8, ii/10.] for ii in range(2,9)] + \ [[ii/10., 0.2] for ii in range(3,8)] + \ [[ii/10., 0.8] for ii in range(3,8)] obsop = TimeObsPtwise({'V':V, 'Points':obspts}, tfilterpts) # define pde operator: wavepde = AcousticWave({'V':V, 'Vl':Vl, 'Vr':Vl}) wavepde.timestepper = 'centered' wavepde.lump = True wavepde.set_abc(mesh, LeftRight(), True) wavepde.update({'lambda':lambda_target_fn, 'rho':1.0, \ 't0':t0, 'tf':tf, 'Dt':Dt, 'u0init':dl.Function(V), 'utinit':dl.Function(V)}) wavepde.ftime = mysrc # define objective function: waveobj = ObjectiveAcoustic(wavepde) waveobj.obsop = obsop # data print 'generate noisy data' waveobj.solvefwd() myplot.plot_timeseries(waveobj.solfwd, 'pd', 0, skip, fctV) dd = waveobj.Bp.copy() nbobspt, dimsol = dd.shape noiselevel = 0.1 # = 10% sigmas = np.sqrt((dd**2).sum(axis=1)/dimsol)*noiselevel rndnoise = np.random.randn(nbobspt*dimsol).reshape((nbobspt, dimsol)) waveobj.dd = dd + sigmas.reshape((len(sigmas),1))*rndnoise # gradient print 'generate observations' waveobj.update_m(lambda_init_fn) waveobj.solvefwd_cost() cost1 = waveobj.misfit print 'misfit = {}'.format(waveobj.misfit) myplot.plot_timeseries(waveobj.solfwd, 'p', 0, skip, fctV) # Plot data and observations fig = plt.figure() if len(obspts) > 9: fig.set_size_inches(20., 15.) for ii in range(len(obspts)): if len(obspts) == 4: ax = fig.add_subplot(2,2,ii+1) else: ax = fig.add_subplot(4,6,ii+1) ax.plot(waveobj.PDE.times, waveobj.dd[ii,:], 'k--') ax.plot(waveobj.PDE.times, waveobj.Bp[ii,:], 'b') ax.set_title('Plot'+str(ii)) fig.savefig(filename + '/observations.eps') print 'compute gradient' waveobj.solveadj_constructgrad() myplot.plot_timeseries(waveobj.soladj, 'v', 0, skip, fctV) MG = waveobj.MGv.array().copy() myplot.set_varname('grad') myplot.plot_vtk(waveobj.Grad) print 'check gradient with FD' Medium = np.zeros((5, Vl.dim())) for ii in range(5): smoothperturb = dl.Expression('sin(n*pi*x[0])*sin(n*pi*x[1])', n=ii+1) smoothperturb_fn = dl.interpolate(smoothperturb, Vl) Medium[ii,:] = smoothperturb_fn.vector().array() checkgradfd_med(waveobj, Medium, 1e-6, [1e-5, 1e-4]) print 'check Hessian with FD' checkhessfd_med(waveobj, Medium, 1e-6, [1e-1, 1e-2, 1e-3, 1e-4, 1e-5], False)