Exemplo n.º 1
0
def decomp_leray(mmat, jmat, dataprfx='', testit=False):
    from spacetime_galerkin_pod.ldfnp_ext_cholmod import SparseFactorMassmat

    facmy = SparseFactorMassmat(mmat)
    Minv = facmy.solve_M

    pinsvddict = dict(jmat=jmat, Minv=Minv)
    thrthlstrl = [dataprfx+'_pithl', dataprfx+'_pithr']
    thl, thr = dou.load_or_comp(arraytype='dense', filestr=thrthlstrl,
                                numthings=2,
                                comprtn=_pinsvd, comprtnargs=pinsvddict)
    minvthr = Minv(thr)

    if testit:
        Np, Nv = jmat.shape
        print(np.allclose(np.eye(Nv-Np), thr.T.dot(thl)))
        minvjt = Minv(jmat.T).todense()
        S = jmat*minvjt
        Sinv = spla.inv(S)
        Pi = np.eye(Nv) - minvjt.dot(Sinv*jmat)
        print(np.allclose(Pi, thl.dot(thr.T)))

    return thl, thr, minvthr
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
mockUks = np.eye(Ns)
(M, A, rhs, nfunc, femp) = dbs.\
    burgers_spacedisc(N=Nq, nu=nu, retfemdict=True)
# +1 bc of boundary conditions that are eliminated
femp, ay, my = femp, A, M
tmesh = np.linspace(t0, tE, Nts)
iniv = np.r_[np.ones(((Nq - 1) / 2, 1)), np.zeros(((Nq) / 2, 1))]
# iniv = np.ones((Nq-1, 1))
datastr = 'burgv_contim_nu{1}_N{0}_Nts{2}'.format(Nq, nu, Nts)
if noconv:
    nfunc = None

simudict = dict(iniv=iniv, A=A, M=M, nfunc=nfunc, rhs=rhs, tmesh=tmesh)
vv = dou.load_or_comp(filestr='data/' + datastr,
                      comprtn=gpu.time_int_semil,
                      comprtnargs=simudict,
                      arraytype='dense',
                      debug=False)
# 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)
Exemplo n.º 4
0
def bfgs_opti(Nq=None,
              Nts=None,
              inivtype=None,
              dmndct=None,
              Ns=None,
              hq=None,
              hs=None,
              redrtol=None,
              redatol=None,
              spacebasscheme=None,
              nu=None,
              alpha=None,
              podstate=False,
              podadj=False,
              genpodcl=False,
              plotplease=None,
              tikzplease=False,
              tikzprefikz='',
              adjplotdict=None,
              bfgsiters=None,
              gtol=1e-5,
              target='inival',
              checkbwdtimings=False,
              onlytimings=False,
              **kwargs):

    dmndct.update(dict(plotplease=plotplease))

    t0, tE = dmndct['t0'], dmndct['tE']

    tmesh = np.linspace(t0, tE, Nts)
    # snapshottmesh = np.linspace(t0, tE, Ns)
    redtmesh = np.linspace(t0, tE, hs)
    # ### define the model

    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()

    x0, xE = dmndct['x0'], dmndct['xE']

    (My, A, rhs, nfunc, femp) = dbs.\
        burgers_spacedisc(N=Nq, nu=nu, x0=x0, xE=xE, retfemdict=True)
    iniv = dbs.burger_onedim_inival(Nq=Nq, inivtype=inivtype)

    # ### 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 = gpu.time_int_semil(**simudict)
        vv = dou.load_or_comp(filestr=datastr,
                              comprtn=gpu.time_int_semil,
                              arraytype='dense',
                              comprtnargs=simudict,
                              debug=debug)
    plotmat(vv, fignum=1234, **dmndct)

    (xms, Ms) = gpu.get_genmeasuremat(sol=vv.T, tmesh=tmesh, sdim=Ns)
    # ### compute the backward snapshots
    vfun = interp1d(tmesh, vv, axis=0, fill_value='extrapolate')
    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 adjplotdict is None:
        adjplotdict = dmndct
    plotmat(ll, fignum=1235, **adjplotdict)

    (Lms, _) = gpu.get_genmeasuremat(sol=ll.T, tmesh=tmesh, sdim=Ns)

    # ### compute the projection matrices, i.e. optimal bases
    (lyitUVy, lyUVy, lsitUVs, lsUVs, lyitULy, lyULy, lsitULs, lsULs) = gou.\
        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, liftVcoef, projVcoef =\
        gpu.get_spaprjredmod(M=My, A=A, nonl=nfunc, rhs=fwdrhs,
                             Uk=lyitUVy, prjUk=lyUVy)
    hiniv = projVcoef(iniv)
    # ## preassemble reduced nonlinearity as tensor
    print 'assembling the reduced tensor...'
    import burgers_genpod_utils as bgu
    datastr = 'data/fwd_iniv' + inivtype + '_tnsr_' + spacebasscheme + \
        '_target_' + target +\
        '_Nts{4}Nq{0}Ns{1}hq{2}nu{3}'.format(Nq, Ns, hq, nu, Nts)
    uvvdxl, _ = bgu.\
        get_burger_tensor(Uky=lyitUVy, Uks=lsitUVs, bwd=True, spaceonly=True,
                          # Vhdms=None, Vhms=None, Vhmy=MVk, Vhay=AVk,
                          # sdim=Ns, tmesh=tmesh,
                          datastr=datastr, debug=debug, **femp)

    def redfwdnln_tns(vvec, t):
        return bgu.eva_burger_spacecomp(uvvdxl=uvvdxl, svec=vvec).flatten()

    # ## the bwd projection scheme
    ALk, MLk, _, _, liftLcoef, projLcoef =\
        gpu.get_spaprjredmod(M=My, A=A, nonl=burger_bwd_nonl,
                             rhs=burger_bwd_rhs, Uk=lyitULy, prjUk=lyULy)
    htermiL = projLcoef(termiL)

    red_vdxop = gpu.get_redmatfunc(matfunc=vdxoperator,
                                   ULk=lyitULy,
                                   UVk=lyitUVy)

    print 'assembling the bwd reduced tensor...'
    datastr = 'data/bwdtnsr_iniv' + inivtype + '_' + spacebasscheme +\
        '_target_' + target +\
        '_Nts{4}Nq{0}Ns{1}hq{2}nu{3}'.format(Nq, Ns, hq, nu, Nts)
    Luvvdxl, _ = bgu.\
        get_burger_tensor(Uky=lyitULy, bwd=True, spaceonly=True,
                          Ukyconv=lyitUVy,
                          datastr=datastr, debug=debug,
                          **femp)

    # ## the mixed matrices
    VLhmy = np.dot(lyitUVy.T, My * lyitULy)
    LVhmy = np.dot(lyitULy.T, My * lyitUVy)

    redvstarvec = gou.functovec(vstar, redtmesh, projcoef=projVcoef)
    vstarvec = gou.functovec(vstar, tmesh)

    eva_redfwd = gou.get_eva_fwd(
        iniv=hiniv,
        MV=MVk,
        AV=AVk,
        MVU=VLhmy,
        rhs=rhs_red,
        nonlfunc=redfwdnln_tns,
        # nonlfunc=nonl_red,
        solvrtol=redrtol,
        solvatol=redatol,
        tmesh=redtmesh)

    eva_redbwd = gou.get_eva_bwd(vstarvec=redvstarvec,
                                 MLV=LVhmy,
                                 ML=MLk,
                                 AL=ALk,
                                 termiL=htermiL,
                                 tmesh=redtmesh,
                                 bwdvltens=Luvvdxl,
                                 solvrtol=redrtol,
                                 solvatol=redatol,
                                 vdxoperator=red_vdxop)
    if checkbwdtimings:
        rdvvec = eva_redfwd(np.zeros((hq, hs)))
        return eva_redbwd, rdvvec

    eva_liftufwd = gou.get_eva_fwd(iniv=iniv,
                                   MV=My,
                                   AV=A,
                                   MVU=My,
                                   rhs=fwdrhs,
                                   nonlfunc=nfunc,
                                   tmesh=tmesh,
                                   redtmesh=redtmesh,
                                   liftUcoef=liftLcoef)

    eva_redcostfun, eva_redcostgrad = \
        gou.get_eva_costfun(tmesh=redtmesh, MVs=MVk, MUs=alpha*MLk,
                            vstarvec=redvstarvec, getcompgrad=True,
                            eva_fwd=eva_redfwd, eva_bwd=eva_redbwd)

    eva_liftucostfun = \
        gou.get_eva_costfun(tmesh=tmesh, MVs=My,
                            utmesh=redtmesh, MUs=alpha*MLk,
                            vstarvec=vstarvec, eva_fwd=eva_liftufwd)

    checktest = True
    checktest = False
    if checktest:
        dmndct.update(dict(plotplease=True))
        rdvvec = eva_redfwd(np.zeros((hq, hs)))
        rdvv = gou.xvectoX(rdvvec, nq=hq, ns=hs)
        plotmat(np.dot(lyitUVy, rdvv).T, fignum=2135, **dmndct)

        rdlvec = eva_redbwd(rdvvec)
        rdll = gou.xvectoX(rdlvec, nq=hq, ns=hs)
        plotmat(np.dot(lyitULy, rdll).T, fignum=2136, **dmndct)

        plotmat(np.dot(lyitUVy, gou.xvectoX(redvstarvec, ns=hs, nq=hq)).T,
                fignum=324,
                **dmndct)
        checktestjaco = True
        checktestjaco = False
        if checktestjaco:
            import numdifftools as nd
            uk = gou.Xtoxvec(np.zeros((hq, hs)))
            myjaco = eva_redcostgrad(gou.Xtoxvec(uk).flatten())
            ndjaco = nd.Jacobian(eva_redcostfun)(gou.Xtoxvec(uk).flatten())
            print 'diffnorm of the analytical and the numerical jacobian' +\
                  ' `dJ={0}`'.format(np.linalg.norm(myjaco-ndjaco))

    uk = gou.Xtoxvec(np.zeros((hq, hs)))

    tfd = {}  # if timerecord else None
    print 'solving the reduced optimization problem'

    profileit = False
    if profileit:
        from pycallgraph import PyCallGraph
        from pycallgraph.output import GraphvizOutput
        with PyCallGraph(output=GraphvizOutput()):
            uopt, fopt, gopt, Bopt, nfc, ngc, wflag = \
                fmin_bfgs(eva_redcostfun, gou.Xtoxvec(uk), full_output=True,
                          fprime=eva_redcostgrad, maxiter=bfgsiters, gtol=gtol)
    with dou.Timer('bfgs optimization', timerinfo=tfd):
        uopt, fopt, gopt, Bopt, nfc, ngc, wflag = \
            fmin_bfgs(eva_redcostfun, gou.Xtoxvec(uk), full_output=True,
                      fprime=eva_redcostgrad, maxiter=bfgsiters, gtol=gtol)
        tfd.update(dict(nfc=nfc, ngc=ngc))

    if onlytimings:
        minfcallgcall = min(nfc, ngc)  # minimum of func/grad calls
        tfwdclt = []
        tfwdclo = []
        dumfwd = 0 * uk
        for k in range(3):
            ltfd = {}
            with dou.Timer('', verbose=False, timerinfo=ltfd):
                dumfwd = eva_redfwd(uopt)
            tfwdclo.append(ltfd['elt'])
            ltfd = {}
            with dou.Timer('', verbose=False, timerinfo=ltfd):
                dumfwd = eva_redfwd(gou.Xtoxvec(uk))
            tfwdclt.append(ltfd['elt'])
        dumfwd = 0 * dumfwd
        medfwdcall = 0.5 * (np.median(np.array(tfwdclo)) +
                            np.median(np.array(tfwdclt)))
        funccalloverhead = minfcallgcall * medfwdcall
        tfd.update(dict(overhead=funccalloverhead))

        return tfd

    else:
        print 'evaluating the full cost function'
        fulcostvpart, fulcostupart = eva_liftucostfun(uopt, retparts=True)

        if plotplease:
            vvecopt = eva_liftufwd(uopt)
            vopt = gou.xvectoX(vvecopt, nq=Nq - 1, ns=Nts)
            plotmat(vopt.T, fignum=3234, **dmndct)

        return dict(vterm=fulcostvpart,
                    uterm=fulcostupart,
                    value=fulcostupart + fulcostvpart,
                    unormsqrd=2 * 1. / alpha * fulcostupart), tfd
Exemplo n.º 5
0
def space_genpod_burger(Nq=None,
                        Nts=None,
                        inivtype=None,
                        dmndct=None,
                        Ns=None,
                        hq=None,
                        hs=None,
                        spacebasscheme=None,
                        nu=None,
                        alpha=None,
                        plotplease=False,
                        tikzprefikz='',
                        adjplotdict=None,
                        onlytimings=False,
                        **kwargs):

    t0, tE = dmndct['t0'], dmndct['tE']

    tmesh = np.linspace(t0, tE, Nts)
    # snapshottmesh = np.linspace(t0, tE, Ns)
    redtmesh = np.linspace(t0, tE, hs)
    # ### 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)
    iniv = dbs.burger_onedim_inival(Nq=Nq, inivtype=inivtype)

    # ### 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 + \
            'Nq{0}Nts{1}nu{2}'.format(Nq, Nts, nu)
        # vv = gpu.time_int_semil(**simudict)
        vv = dou.load_or_comp(filestr=datastr,
                              comprtn=gpu.time_int_semil,
                              arraytype='dense',
                              comprtnargs=simudict,
                              debug=debug)
    plotmat(vv, fignum=1236, **dmndct)

    (xms, Ms) = gpu.get_genmeasuremat(sol=vv.T, tmesh=tmesh, sdim=Ns)

    # ### compute the backward snapshots
    vfun = interp1d(tmesh, vv, axis=0, fill_value='extrapolate')
    vdxoperator, fnctnl = dbs.\
        burgers_bwd_spacedisc(V=femp['V'], ininds=femp['ininds'],
                              diribc=femp['diribc'])
    te = tmesh[-1]

    def vstar(t):
        return iniv.flatten()

    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 + \
            '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 adjplotdict is None:
        adjplotdict = dmndct
    plotmat(ll, fignum=1235, **adjplotdict)

    (Lms, _) = gpu.get_genmeasuremat(sol=ll.T, tmesh=tmesh, sdim=Ns)

    # ### compute the projection matrices, i.e. optimal bases
    (lyitUVy, lyUVy, lsitUVs, lsUVs, lyitULy, lyULy, lsitULs, lsULs) = gou.\
        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, liftVcoef, projVcoef =\
        gpu.get_spaprjredmod(M=My, A=A, nonl=nfunc, rhs=fwdrhs,
                             Uk=lyitUVy, prjUk=lyUVy)
    hiniv = projVcoef(iniv)

    # ## the bwd projection scheme
    ALk, MLk, bwdl_red, bwdrhs_red, liftLcoef, projLcoef =\
        gpu.get_spaprjredmod(M=My, A=A, nonl=burger_bwd_nonl,
                             rhs=burger_bwd_rhs, Uk=lyitULy, prjUk=lyULy)
    htermiL = projLcoef(termiL)
    red_vdxop = gpu.get_redmatfunc(matfunc=vdxoperator,
                                   ULk=lyitULy,
                                   UVk=lyitUVy)

    # ## the mixed mats
    VLhmy = np.dot(lyitUVy.T, My * lyitULy)
    LVhmy = np.dot(lyitULy.T, My * lyitUVy)

    # ### the tests
    # ## reduced forward problem
    redsimudict = dict(iniv=hiniv,
                       A=AVk,
                       M=MVk,
                       nfunc=nonl_red,
                       rhs=rhs_red,
                       tmesh=redtmesh)
    with dou.Timer('redfwd'):
        print 'solving the reduced  problem (state)...'
        redvv = gpu.time_int_semil(**redsimudict)
    redvv = redvv.reshape((hs, hq))
    plotmat(np.dot(redvv, lyitUVy.T), fignum=1233, **dmndct)
    # ## the reduced fwd as a function
    eva_redfwd = gou.get_eva_fwd(iniv=hiniv,
                                 MV=MVk,
                                 AV=AVk,
                                 MVU=VLhmy,
                                 rhs=rhs_red,
                                 nonlfunc=nonl_red,
                                 tmesh=redtmesh)

    rdvvec = eva_redfwd(np.zeros((hq, hs)))
    rdvv = gou.xvectoX(rdvvec, nq=hq, ns=hs)
    plotmat(np.dot(rdvv.T, lyitUVy.T), fignum=1237, **dmndct)

    # ## the reduced bwd problem
    redbwdsimudict = dict(iniv=htermiL,
                          A=ALk,
                          M=MLk,
                          nfunc=bwdl_red,
                          rhs=bwdrhs_red,
                          tmesh=redtmesh)
    with dou.Timer('redbwd'):
        print 'solving the reduced  problem (adjoint)...'
        redll = gpu.time_int_semil(**redbwdsimudict)
    redll = np.flipud(redll)  # flip the to make it forward time
    redll = redll.reshape((hs, hq))
    plotmat(np.dot(redll, lyitULy.T), fignum=2232, **adjplotdict)

    # ## the reduced bwd problem with reduced fwd solution
    redvfun = interp1d(redtmesh, rdvv, axis=1, fill_value='extrapolate')

    def _liftredvfun(t):
        return np.dot(lyitUVy, redvfun(t))

    def _burger_bwd_rhs(t):
        # TODO: -----------------------------> here we need vstar
        return (-fnctnl(_liftredvfun(te - t)).flatten() +
                fnctnl(vstar(te - t)).flatten())

    def _burger_bwd_nonl(lvec, t):
        vdx = vdxoperator(_liftredvfun(te - t))
        return -(vdx * lvec).flatten()

    ALk, MLk, _bwdl_red, _bwdrhs_red, liftLcoef, projLcoef =\
        gpu.get_spaprjredmod(M=My, A=A, nonl=_burger_bwd_nonl,
                             rhs=_burger_bwd_rhs, Uk=lyitULy, prjUk=lyULy)

    _redbwdsimudict = dict(iniv=htermiL,
                           A=ALk,
                           M=MLk,
                           nfunc=_bwdl_red,
                           rhs=_bwdrhs_red,
                           tmesh=redtmesh)
    redll = gpu.time_int_semil(**_redbwdsimudict)
    redll = np.flipud(redll)  # flip the to make it forward time
    redll = redll.reshape((hs, hq))
    plotmat(np.dot(redll, lyitULy.T), fignum=2233, **adjplotdict)

    redvstarvec = gou.functovec(vstar, redtmesh, projcoef=projVcoef)
    redvstar = gou.xvectoX(redvstarvec, nq=hq, ns=hs)
    _redvstarfun = interp1d(redtmesh,
                            redvstar,
                            axis=1,
                            fill_value='extrapolate')

    # ## the reduced bwd problem with reduced fwd solution
    # ## and manual setup of the coeffs

    def redbvdxl(rlvec, t):
        rvdx = red_vdxop(redvfun(te - t))
        return -np.dot(rvdx, rlvec).flatten()

    def _bbwdrhs(t):
        # TODO: -----------------------------> here we need vstar
        return (-lau.mm_dnssps(LVhmy, redvfun(te - t)).flatten() +
                lau.mm_dnssps(LVhmy, _redvstarfun(t)).flatten())

    redbwdsimudict = dict(iniv=htermiL,
                          A=ALk,
                          M=MLk,
                          nfunc=redbvdxl,
                          rhs=_bbwdrhs,
                          tmesh=redtmesh)
    redll = gpu.time_int_semil(**redbwdsimudict)
    redll = np.flipud(redll)  # flip it to make it forward time
    redll = redll.reshape((hs, hq))
    plotmat(np.dot(redll, lyitULy.T), fignum=2234, **adjplotdict)

    eva_redbwd = gou.get_eva_bwd(vstarvec=redvstarvec,
                                 MLV=LVhmy,
                                 ML=MLk,
                                 AL=ALk,
                                 termiL=htermiL,
                                 tmesh=redtmesh,
                                 vdxoperator=red_vdxop)

    # ## the reduced bwd problem as function
    rdlvec = eva_redbwd(rdvvec)
    rdll = gou.xvectoX(rdlvec, nq=hq, ns=hs)
    plotmat(np.dot(rdll.T, lyitULy.T), fignum=2235, **adjplotdict)

    return None, None
def check_the_sim(problem='cylinderwake', nswtchsl=[2], scheme='CR',
                  nu=None, Re=None, Nts=None, paraout=False, t0=None, tE=None,
                  plotit=False, dtstrdct={}, debug=False, Nref=3,
                  method=2, refmethod=2):
    trange = np.linspace(t0, tE, Nts+1)
    refdtstrdct = dict(prefix=ddir+problem+scheme,
                       method=refmethod, N=None, Nts=Nts, t0=t0, te=tE)
    refdatstr = get_dtstr(t=None, **refdtstrdct)
    compargs = dict(problem=problem, N=Nref, nu=nu, Re=Re, trange=trange,
                    scheme=scheme, data_prefix=refdatstr, debug=debug)
    refvdict, refpdict = dou.load_or_comp(filestr=[refdatstr+'_refvdict',
                                                   refdatstr+'_refpdict'],
                                          comprtn=gettheref,
                                          comprtnargs=compargs,
                                          debug=False, itsadict=True)

    viniv = dou.load_npa(refvdict['{0}'.format(t0)])
    piniv = dou.load_npa(refpdict['{0}'.format(t0)])

    # set up the list of the mesh parameters at every time step
    swl = Nts/len(nswtchsl)
    Nll = np.array([nswtchsl[0]]*(Nts+1))
    for k, N in enumerate(nswtchsl[1:]):
        Nll[(k+1)*swl+1:] = N
    Nll[0] = Nref
    Nll = Nll.tolist()
    nswtchstr = 'Nswitches' + ''.join(str(e) for e in nswtchsl)
    dtstrdct['prefix'] = dtstrdct['prefix'] + nswtchstr
    dtstrdct.update(t=None)
    cdatstr = get_dtstr(**dtstrdct)

    compvpdargs = dict(problem=problem, scheme=scheme, Re=Re, nu=nu,
                       t0=t0, tE=tE, Nts=Nts, viniv=viniv, piniv=piniv,
                       Nini=Nref, Nll=Nll, dtstrdct=dtstrdct, method=method)
    logger.info('try to load `' + cdatstr + '_vdict`, `' + cdatstr + '_pdict`')
    vdict, pdict = dou.load_or_comp(filestr=[cdatstr+'_vdict',
                                             cdatstr+'_pdict'],
                                    comprtn=rtu.rothe_time_int,
                                    comprtnargs=compvpdargs,
                                    debug=debug, itsadict=True)

    # vdict, pdict = rtu.rothe_ind2(problem=problem, scheme=scheme,
    #                               Re=Re, nu=nu,
    #                               t0=t0, tE=tE, Nts=Nts,
    #                               viniv=viniv, piniv=piniv, Nini=Nref,
    #                               Nll=Nll, dtstrdct=dtstrdct)

    compvperrargs = dict(problem=problem, scheme=scheme,
                         trange=trange.tolist(),
                         rvd=refvdict, rpd=refpdict, Nref=Nref,
                         cvd=vdict, cpd=pdict, Nll=Nll)

    errdict = dou.load_or_comp(filestr=[cdatstr+'_vperrdict'],
                               comprtn=compvperr, debug=debug,
                               comprtnargs=compvperrargs, itsadict=True)

    if plotit:
        rtu.plottimeerrs(trange=trange, perrl=[errdict['perrl']],
                         verrl=[errdict['verrl']], showplot=True)

    return (errdict['verrl'], errdict['perrl'],
            errdict['verrint'], errdict['perrint'], trange.tolist())