def test_spacetime_evals(self): """consistency tests of the space time discretization """ ay = self.ay my = self.my zsol = np.zeros((self.Nq, self.Nts)) contimsol = self.contimsol linspasol = self.linspasol dms = gpu.get_dms(sdim=self.Ns, tmesh=self.tmesh, basfuntype='pl') (msx, ms) = gpu.get_genmeasuremat(sol=zsol, tmesh=self.tmesh, sdim=self.Ns) self.assertTrue(np.allclose(ms, self.ms)) contimlinspa = np.kron(contimsol, linspasol) lintimlinspa = np.kron(self.lintimsol, linspasol) self.assertTrue(norm(contimlinspa) > 1e-8) self.assertTrue(np.allclose(0 * contimsol, np.dot(dms, contimsol))) # check the dtpart to be zero for const time funcs and nonzero for lin dtpart = spu.apply_time_space_kronprod(tvvec=contimlinspa, smat=dms, qmat=np.array(my.todense())) self.assertTrue(np.allclose(0 * contimlinspa, dtpart)) dtpart = spu.apply_time_space_kronprod(tvvec=lintimlinspa, smat=dms, qmat=np.array(my.todense())) self.assertTrue(norm(dtpart) > 1e-8) # check the a-part to be zero for lin (except from the boundary) # and nonzero for quad lintimlinspaqua = np.kron(self.lintimsol, linspasol * linspasol) dxxpart = spu.apply_time_space_kronprod(tvvec=lintimlinspa, smat=ms, qmat=np.array(ay.todense())) innernode = np.r_[0, np.ones((self.Nq - 2, )), 0] inds = np.tile(innernode, self.Ns).astype(bool) self.assertTrue(np.allclose(0 * contimlinspa[inds], dxxpart[inds])) dxxpart = spu.\ apply_time_space_kronprod(tvvec=lintimlinspaqua, smat=ms, qmat=np.array(ay.todense())) self.assertTrue(norm(dxxpart[1:-1]) > 1e-8)
def setUp(self): self.Nq = 50 # dimension of the spatial discretization self.Ns = 9 # dimension of the temporal discretization self.Nts = 60 # number of time sampling points self.nu = 1e-2 self.t0, self.tE = 0., 1. self.mockUky = np.eye(self.Nq) self.mockUks = np.eye(self.Ns) (M, A, rhs, nfunc, femp) = dbs.\ burgers_spacedisc(N=self.Nq+1, nu=self.nu, retfemdict=True) # +1 bc of boundary conditions that are eliminated self.femp, self.ay, self.my = femp, A, M self.tmesh = np.linspace(self.t0, self.tE, self.Nts) # constructing test solutions self.contimsol = np.ones((self.Ns, 1)) self.conspasol = np.ones((self.Nq, 1)) self.linspasol = np.linspace(0, 1, self.Nq).reshape((self.Nq, 1)) self.lintimsol = np.linspace(0, 1, self.Ns).reshape((self.Ns, 1)) self.dms = gpu.get_dms(sdim=self.Ns, tmesh=self.tmesh, basfuntype='pl') self.ms = gpu.get_ms(sdim=self.Ns, tmesh=self.tmesh, basfuntype='pl')
def testit(Nq=None, Nts=None, inivtype=None, dmndct=None, Ns=None, hq=None, hs=None, spacebasscheme=None, nu=None, alpha=None, genpodstate=False, genpodadj=False, genpodcl=False, plotplease=False, tikzplease=False, tikzprefikz='', adjplotdict=None, target='inival', onlytimings=False, **kwargs): t0, tE = dmndct['t0'], dmndct['tE'] # to tikz or not to tikz fullmodelv_tkzf, fullmodelL_tkzf, redoptiv_tkzf = None, None, None redmodelL_tkzf = None redmodelV_tkzf = None redoptlambda_tkzf, backcheck_tkzf = None, None if tikzplease: fullmodelv_tkzf = tikzprefikz + 'fullmodelV' fullmodelL_tkzf = tikzprefikz + 'fullmodelL' redmodelL_tkzf = tikzprefikz + 'redmodelL' redmodelV_tkzf = tikzprefikz + 'redmodelV' # redoptiv_tkzf = tikzprefikz + 'redoptiv' # redoptlambda_tkzf = tikzprefikz + 'redoptlambda' backcheck_tkzf = tikzprefikz + 'backcheck' tmesh = np.linspace(t0, tE, Nts) snapshottmesh = np.linspace(t0, tE, Ns) if target == 'inival': def vstar(t): return iniv.flatten() elif target == 'heart' or 'invheart': invertt = True if target == 'invheart' else False myheartfun = get_spcheartfun(NY=Nq - 1, invertt=invertt) def vstar(t): return myheartfun(t).flatten() # ### define the model x0, xE = dmndct['x0'], dmndct['xE'] (My, A, rhs, nfunc, femp) = dbs.\ burgers_spacedisc(N=Nq, nu=nu, x0=x0, xE=xE, retfemdict=True) # define the initial value if inivtype == 'smooth': xrng = np.linspace(0, 2 * np.pi, Nq - 1) iniv = 0.5 - 0.5 * np.sin(xrng + 0.5 * np.pi) iniv = 0.5 * iniv.reshape((Nq - 1, 1)) elif inivtype == 'step': # iniv = np.r_[np.ones(((Nq-1)/2, 1)), np.zeros(((Nq)/2, 1))] iniv = np.r_[np.zeros(((Nq) / 2, 1)), np.ones(((Nq - 1) / 2, 1))] elif inivtype == 'ramp': iniv = np.r_[np.linspace(0, 1, ((Nq - 1) / 2)).reshape( ((Nq - 1) / 2, 1)), np.zeros(((Nq) / 2, 1))] elif inivtype == 'zero': iniv = np.zeros((Nq - 1, 1)) # ### compute the forward snapshots def fwdrhs(t): return rhs simudict = dict(iniv=iniv, A=A, M=My, nfunc=nfunc, rhs=fwdrhs, tmesh=tmesh) with dou.Timer('fwd'): datastr = 'data/fwdsol_iniv' + inivtype + '_target_' + target +\ 'Nq{0}Nts{1}nu{2}'.format(Nq, Nts, nu) vv = dou.load_or_comp(filestr=datastr, comprtn=gpu.time_int_semil, arraytype='dense', comprtnargs=simudict, debug=debug) # vv = gpu.time_int_semil(**simudict) if plotplease: plotmat(vv, fignum=1234, tikzfile=fullmodelv_tkzf, **dmndct) (xms, Ms) = gpu.get_genmeasuremat(sol=vv.T, tmesh=tmesh, sdim=Ns) # ### compute the backward snapshots if genpodadj or genpodcl: _vfun = interp1d(tmesh, vv, axis=0) # , fill_value='extrapolate') def vfun(t): if t < tmesh[0]: return _vfun(tmesh[0]) elif t > tmesh[-1]: return _vfun(tmesh[-1]) else: return _vfun(t) vdxoperator, fnctnl = dbs.\ burgers_bwd_spacedisc(V=femp['V'], ininds=femp['ininds'], diribc=femp['diribc']) te = tmesh[-1] def burger_bwd_rhs(t): # TODO: -----------------------------> here we need vstar return -fnctnl(vfun(te - t)).flatten() + fnctnl( vstar(te - t)).flatten() def burger_bwd_nonl(lvec, t): vdx = vdxoperator(vfun(te - t)) return -(vdx * lvec).flatten() termiL = np.zeros((Nq - 1, 1)) bbwdsimudict = dict(iniv=termiL, A=A, M=My, nfunc=burger_bwd_nonl, rhs=burger_bwd_rhs, tmesh=tmesh) with dou.Timer('bwd'): datastr = 'data/bwdsol_iniv' + inivtype + '_target' + target +\ 'Nq{0}Nts{1}nu{2}'.format(Nq, Nts, nu) bwdll = dou.\ load_or_comp(filestr=datastr, comprtn=gpu.time_int_semil, arraytype='dense', comprtnargs=bbwdsimudict, debug=debug) # bwdll = gpu.time_int_semil(**bbwdsimudict) ll = np.flipud(bwdll) # flip the to make it forward time if plotplease: if adjplotdict is None: adjplotdict = dmndct plotmat(ll, fignum=1235, tikzfile=fullmodelL_tkzf, **adjplotdict) (Lms, _) = gpu.get_genmeasuremat(sol=ll.T, tmesh=tmesh, sdim=Ns) else: Lms = None # ### compute the projection matrices, i.e. optimal bases (lyitUVy, lyUVy, lsitUVs, lsUVs, lyitULy, lyULy, lsitULs, lsULs) = stateadjspatibas(xms=xms, lms=Lms, Ms=Ms, My=My, nspacevecs=hq, ntimevecs=hs, spacebasscheme=spacebasscheme) # ### the fwd projection scheme AVk, MVk, nonl_red, rhs_red, liftcoef, projcoef =\ gpu.get_spaprjredmod(M=My, A=A, nonl=nfunc, rhs=fwdrhs, Uk=lyitUVy, prjUk=lyUVy) hiniv = projcoef(iniv) Ms = sps.csc_matrix(gpu.get_ms(sdim=Ns, tmesh=tmesh)) dms = sps.csc_matrix(gpu.get_dms(sdim=Ns, tmesh=tmesh)) Vhms = np.dot(lsitUVs.T, Ms * lsitUVs) Vhdms = np.dot(lsitUVs.T, dms * lsitUVs) print 'assembling the reduced tensor...' datastr = 'data/fwd_iniv' + inivtype + '_tnsr_' + spacebasscheme + \ '_target_' + target +\ '_Nts{5}Nq{0}Ns{1}hq{2}hs{3}nu{4}'.format(Nq, Ns, hq, hs, nu, Nts) uvvdxl, htittl = bgu.\ get_burger_tensor(Uky=lyitUVy, Uks=lsitUVs, sdim=Ns, bwd=True, Vhdms=Vhdms, Vhms=Vhms, Vhmy=MVk, Vhay=AVk, tmesh=tmesh, datastr=datastr, debug=debug, **femp) vres, vresprime = \ bou.setup_burger_fwdres(Vhdms=Vhdms, Vhms=Vhms, Vhmy=MVk, Vhay=AVk, htittl=htittl, uvvdxl=uvvdxl, hiniv=hiniv) def ndvresprime(tvvec): ndjaco = nd.Jacobian(vres)(tvvec) return ndjaco # ### the bwd projection scheme if genpodadj or genpodcl: Lhms = np.dot(lsitULs.T, Ms * lsitULs) Lhdms = np.dot(lsitULs.T, dms * lsitULs) LVhms = np.dot(lsitULs.T, Ms * lsitUVs) LVhmy = np.dot(lyitULy.T, My * lyitUVy) Lhay, Lhmy, _, _, Lliftcoef, Lprojcoef =\ gpu.get_spaprjredmod(M=My, A=A, Uk=lyitULy, prjUk=lyULy) print 'assembling the bwd reduced tensor...' datastr = 'data/bwdtnsr_iniv' + inivtype + '_' + spacebasscheme +\ '_target_' + target +\ '_Nts{5}Nq{0}Ns{1}hq{2}hs{3}nu{4}'.format(Nq, Ns, hq, hs, nu, Nts) Luvvdxl, Lhtittl = bgu.\ get_burger_tensor(Uky=lyitULy, bwd=True, Uks=lsitULs, Ukyconv=lyitUVy, Uksconv=lsitUVs, sdim=Ns, tmesh=tmesh, datastr=datastr, debug=debug, **femp) tgtst = gou.xvectoX(gou.functovec(vstar, snapshottmesh), ns=Ns, nq=Nq - 1) htgst = np.dot(lyUVy.T, np.dot(tgtst, lsUVs)) htgstvec = Xtoxvec(htgst) hcurst = np.dot(lyUVy.T, np.dot(xms, lsitUVs)) hcurstvec = Xtoxvec(hcurst) htermiL = np.zeros((hq, 1)) lres, lresprime = bou.\ setup_burger_bwdres(Lhdms=Lhdms, Lhms=Lhms, Lhmy=Lhmy, Lhay=Lhay, LVhms=LVhms, LVhmy=LVhmy, Lhtittl=Lhtittl, Luvvdxl=Luvvdxl, hiniv=hiniv, htermiL=htermiL, tsVvec=hcurstvec[hq:, :], tsVtrgtvec=htgstvec) # ### the optimal cont problem VLhms = np.dot(lsitUVs.T, Ms * lsitULs) VLhmy = np.dot(lyitUVy.T, My * lyitULy) clres, clresprime = bou.\ setup_burger_clres(Vhdms=Vhdms, Vhms=Vhms, Vhmy=MVk, Vhay=AVk, VLhms=VLhms, VLhmy=VLhmy, alpha=alpha, htittl=htittl, uvvdxl=uvvdxl, tsVtrgtvec=htgstvec, Lhdms=Lhdms, Lhms=Lhms, Lhmy=Lhmy, Lhay=Lhay, LVhms=LVhms, LVhmy=LVhmy, Lhtittl=Lhtittl, Luvvdxl=Luvvdxl, hiniv=hiniv, htermiL=htermiL) # ### the tests # # forward problem if genpodstate: optiniV = np.tile(hiniv.T, hs - 1).T print 'solving the optimization problem (state)...' sol = spacetimesolve(func=vres, funcjaco=vresprime, inival=optiniV, message='fwd problem - analytical jacobian') optiV = np.r_[hiniv.flatten(), sol] optiV = optiV.reshape((hs, hq)) if plotplease: plotmat((np.dot(lyitUVy, np.dot(optiV.T, lsitUVs.T))).T, tikzfile=redmodelV_tkzf, fignum=1233, **dmndct) if genpodadj: optiniL = np.zeros((hq * (hs - 1), 1)) print 'solving the optimization problem (adjoint)...' sol = spacetimesolve(func=lres, funcjaco=lresprime, inival=optiniL, message='bwd problem - analytical jacobian') optiL = np.r_[sol, htermiL.flatten()] optiL = optiL.reshape((hs, hq)) if plotplease: plotmat((np.dot(lyitULy, np.dot(optiL.T, lsitULs.T))).T, fignum=124, tikzfile=redmodelL_tkzf, **adjplotdict) if genpodcl: print 'solving the optimization problem (fwdbwd)...' fwdbwdini = True if fwdbwdini: hcurst = np.dot(lyUVy.T, np.dot(xms, lsitUVs)) hcurstvec = gou.Xtoxvec(hcurst) # plotmat((np.dot(lyitUVy, # np.dot(gou.xvectoX(hcurstvec, nq=hq, ns=hs), # lsitUVs.T))).T, fignum=9999) optiniL = np.zeros((hq * (hs - 1), 1)) hcuradj = np.dot(lyULy.T, np.dot(Lms, lsitULs)) hcuradjvec = gou.Xtoxvec(hcuradj) # plotmat((np.dot(lyitULy, # np.dot(gou.xvectoX(hcuradjvec, nq=hq, ns=hs), # lsitULs.T))).T, fignum=9998) optiniV = hcurstvec[hq:, :] optiniL = hcuradjvec[:-hq, :] else: optiniV = np.zeros((hq * (hs - 1), 1)) optiniL = np.zeros((hq * (hs - 1), 1)) optiniVL = np.vstack([optiniV, optiniL]) sol, timingsdict = \ spacetimesolve(func=clres, funcjaco=clresprime, inival=optiniVL, message='optcont problem - analytical jacobian', timerecord=True) if onlytimings: return timingsdict optiV = np.r_[hiniv.flatten(), sol[:hq * (hs - 1)]] optiV = optiV.reshape((hs, hq)) optiL = np.r_[sol[-hq * (hs - 1):], htermiL.flatten()] optiL = optiL.reshape((hs, hq)) fulloptiL = (np.dot(lyitULy, np.dot(optiL.T, lsitULs.T))).T if plotplease: plotmat((np.dot(lyitUVy, np.dot(optiV.T, lsitUVs.T))).T, tikzfile=redoptiv_tkzf, fignum=123, **dmndct) plotmat(1. / alpha * fulloptiL, tikzfile=redoptlambda_tkzf, fignum=1241, **dmndct) plotmat(fulloptiL, tikzfile=redoptlambda_tkzf, fignum=12411, **dmndct) # ### SECTION: fwd problem with reduced costates redmodu = 1. / alpha * fulloptiL redmodufun = interp1d(snapshottmesh, redmodu, axis=0) def burger_contrl_rhs(t): if t > tE: # the integrator may require values outside [t0, tE] return fnctnl(redmodufun(tE)).flatten() else: return fnctnl(redmodufun(t)).flatten() simudict = dict(iniv=iniv, A=A, M=My, nfunc=nfunc, rhs=burger_contrl_rhs, tmesh=snapshottmesh) print 'back check...' with dou.Timer('check back'): vv = gpu.time_int_semil(**simudict) if plotplease: plotmat(vv, fignum=12341, tikzfile=backcheck_tkzf, **dmndct) vvd = vv - tgtst.T plotmat(vvd, fignum=12342, **dmndct) plotmat(tgtst.T, fignum=12343, tikzfile=tikzprefikz + 'zstar', **dmndct) valdict = eva_costfun(vopt=Xtoxvec(vv.T), uopt=Xtoxvec(redmodu), qmat=My, rmat=alpha * My, ms=Ms, vstar=vstar, tmesh=snapshottmesh) valdict.update(dict(unormsqrd=2 * 1. / alpha * valdict['uterm'])) logger.info('Value of the cost functional: {0}'.format( valdict['value'])) return valdict, timingsdict else: return None, None
# plotmat(vv) ared, mred, nonlred, rhsred, inired, Uky = gpu.\ get_podred_model(M=M, A=A, nonl=nfunc, rhs=rhs, sol=vv.T, tmesh=tmesh, verbose=True, poddim=hq, sdim=Ns, plotsvs=plotsvs, genpod=True, basfuntype='pl') inivred = np.dot(Uky.T, iniv) (msx, ms) = gpu.get_genmeasuremat(sol=vv.T, tmesh=tmesh, sdim=Ns) x = lau.apply_massinv(sps.csc_matrix(ms), msx.T).T sini = np.r_[1, np.zeros((Ns - 1, ))].reshape((Ns, 1)) xz = np.copy(x) xz[:, 0] = 0 # zero out nu0 - the ini condition needs extra treatment Uks = gpu.get_podmats(sol=xz.T, poddim=hs - 1, plotsvs=False, M=M) Uks = np.hstack([sini, Uks]) dms = gpu.get_dms(sdim=Ns, tmesh=tmesh, basfuntype='pl') hdms = np.dot(Uks.T, np.dot(dms, Uks)) hms = np.dot(Uks.T, np.dot(ms, Uks)) # nres, timespaceres = get_spacetimepodres(tvvec=hshysol, dms=hdms, ms=hms, # my=mred, ared=None, # nfunc=None, rhs=None) # trsrs = timespaceres.reshape((hq, hs)) # plotmat((np.dot(Uky, np.dot(trsrs, Uks.T))).T, fignum=121) def sollintimspasys(dms=None, ms=None, ay=None, my=None, iniv=None, opti=False):
linsimudict = dict(iniv=iniv, A=A, M=My, nfunc=None, rhs=rhs, tmesh=tmesh) vvl = dou.\ load_or_comp(filestr='data/lincase_'+datastr, comprtn=gpu.time_int_semil, comprtnargs=linsimudict, arraytype='dense', debug=True) if plotplease: plotmat(vvl, fignum=125) (msxlin, Ms) = gpu.get_genmeasuremat(sol=vvl.T, tmesh=tmesh, sdim=Ns) xlin = lau.apply_massinv(sps.csc_matrix(Ms), msxlin.T).T if not redmodel: Ukylin, Ukslin = np.eye(Nq-1), np.eye(Ns) hs, hq = Ns, Nq-1 Ms = gpu.get_ms(sdim=Ns, tmesh=tmesh, basfuntype='pl') dms = gpu.get_dms(sdim=Ns, tmesh=tmesh, basfuntype=timebasfuntype) rbd = dict(hmy=My.todense(), hay=A.todense(), hms=Ms, hdms=dms, inivred=iniv, hrhs=rhs, hnonl=nfunc) else: Ukylin, Ukslin = gpu.get_timspapar_podbas(hs=hs, hq=hq, plotsvs=plotplease, My=My, Ms=Ms, snapsl=[xlin]) rbd = get_podredmod_burger(Uky=Uky, Uks=Uks, Nq=Nq, nu=nu, iniv=iniv, nustr=nustr) dmsz = rbd['hdms'][1:, :1] # part of the mass matrix related to the ini value msz = rbd['hms'][1:, :1] dmsI = rbd['hdms'][1:, 1:] # mass matrices w/o ini values (test and trial) msI = rbd['hms'][1:, 1:]
def get_podredmod_burger(Uky=None, Uks=None, nu=None, iniv=None, Nq=None, plotsvs=False, Ns=None, tmesh=None, timebasfuntype=None, datastr=None): ''' get the coeffs of the space/time reduced Burgers model Parameters --- Uky : (Ny, hy) np.array containing the POD vectors in space dimension Uks : (Ns, hs) np.array containing the POD vectors in time dimension nu : float the considered viscosity iniv : (Ny, 1) np.array the initial value Returns --- redburgdict : dictionary a dictionary with the following keys coeffs of the reduced system: * `hmy`: space mass matrix * `hay`: space stiffness matrix * `hms`: time mass matrix * `hdms`: time derivative mass matrix * `inivred`: initial value * `uvvdxl`: the space component of the burger nonlinearity * `htittl`: the time component of the burger nonlinearity * `hnonl`: f(t, v) that returns the value of the nonlinearity * `hrhs`: right hand side * `nonlresjacobian`: f(v) that returns the Jacobian of the residual of the genpod burger approximation Examples --- redburgdict = get_podredmod_burger(Uky=x, Uks=x, Ms=x, curnu=1e-2, iniv=x) ''' retdict = {} # get the space full model for the considered `nu` (M, A, rhs, nfunc, femp) = dbs.\ burgers_spacedisc(N=Nq, nu=nu, retfemdict=True) # reducing the linear parts and the rhs ared, mred, _, rhsred, _, _ = gpu.\ get_podred_model(M=M, A=A, rhs=rhs, Uk=Uky) retdict.update( dict(hay=ared, hmy=mred, inivred=np.dot(Uky.T, iniv), hrhs=rhsred)) # the time reduced model # TODO: this should be synchronized with comp of Ms Ms = gpu.get_ms(sdim=Ns, tmesh=tmesh, basfuntype=timebasfuntype) dms = gpu.get_dms(sdim=Ns, tmesh=tmesh, basfuntype=timebasfuntype) hdms = np.dot(Uks.T, np.dot(dms, Uks)) hms = np.dot(Uks.T, np.dot(Ms, Uks)) retdict.update(dict(hdms=hdms, hms=hms)) uvvdxl, htittl = get_burger_tensor(Uky=Uky, Uks=Uks, datastr=datastr, sdim=Ns, tmesh=tmesh, **femp) retdict.update(dict(uvvdxl=uvvdxl, htittl=htittl)) def burger_rednonl(tvvec): return eva_burger_quadratic(tvvec=tvvec, htittl=htittl, uvvdxl=uvvdxl, iniv=None, retjacobian=False) hdmsI = hdms[1:, 1:] # mass matrices w/o ini values (test and trial) hmsI = hms[1:, 1:] solmat = np.kron(hdmsI, mred) + np.kron(hmsI, ared) def nlrprime(tsvec, curiniv=None): if curiniv is not None: try: tvvecini = np.vstack([curiniv, tsvec]) except ValueError: tvvecini = np.vstack([curiniv, tsvec.reshape((tsvec.size, 1))]) ebmat = eva_burger_quadratic(tvvec=tvvecini, htittl=htittl, uvvdxl=uvvdxl, retjacobian=True) ebmat = ebmat[curiniv.size:, curiniv.size:, ] return solmat + ebmat retdict.update(dict(hnonl=burger_rednonl, nonlresjacobian=nlrprime)) return retdict
from gen_pod_utils import hatfuncs, get_dms import matplotlib.pyplot as plt import numpy as np x0, xe, N = 0, 1, 100 n = 50 dhf, pts = hatfuncs(n=n, x0=x0, xe=xe, N=N, df=True) x = np.linspace(x0, xe, 4 * N + 1) dhfx = dhf(x) dmy = get_dms(sdim=10, tmesh=x) plt.plot(x, dhfx) plt.show()