Ejemplo n.º 1
0
def getthecoeffs(N=None, Re=None, scheme='CR',
                 inivp='Stokes', inifemp=None):
    femp, stokesmatsc, rhsmomcont \
        = dnsps.get_sysmats(problem='cylinderwake', N=N, Re=Re,
                            scheme=scheme, mergerhs=True)
    fp = rhsmomcont['fp']
    fv = rhsmomcont['fv']
    # stokesmatsc.update(rhsmomcont)

    J, MP = stokesmatsc['J'], stokesmatsc['MP']
    NV, NP = J.T.shape
    # Nv = J.shape[1]
    # Mpfac = spsla.splu(MP)

    if inivp is 'Stokes':
        inivp = lau.solve_sadpnt_smw(amat=stokesmatsc['A'], jmat=J,
                                     jmatT=-J.T, rhsv=fv, rhsp=fp)
        iniv = inivp[:NV]
        inip = snu.get_pfromv(v=iniv, V=femp['V'], M=stokesmatsc['M'],
                              A=stokesmatsc['A'], J=J, fv=fv, fp=fp,
                              diribcs=femp['diribcs'], invinds=femp['invinds'])
    else:
        inv, inp = dts.expand_vp_dolfunc(vp=inivp, **inifemp)
        # interpolate on new mesh and extract the invinds

    getconvvec = getconvvecfun(**femp)
    return dict(A=stokesmatsc['A'], M=stokesmatsc['M'], J=J, JT=J.T, MP=MP,
                fp=fp, fv=fv, getconvvec=getconvvec,
                iniv=iniv, inip=inip,
                V=femp['V'], Q=femp['Q'], invinds=femp['invinds'],
                diribcs=femp['diribcs'], ppin=femp['ppin'], femp=femp)
Ejemplo n.º 2
0
def compvperror(reffemp=None, vref=None, pref=None,
                curfemp=None, vcur=None, pcur=None):
    try:
        verf, perf = dts.expand_vp_dolfunc(vc=vref-vcur, pc=pref-pcur,
                                           zerodiribcs=True, **reffemp)
        verr = dolfin.norm(verf)
        perr = dolfin.norm(perf)
        # vreff, preff = dts.expand_vp_dolfunc(vc=vref, pc=pref, **reffemp)
        # vcurf, pcurf = dts.expand_vp_dolfunc(vc=vcur, pc=pcur, **curfemp)
        # verr = dolfin.norm(vreff - vcurf)
        # perr = dolfin.norm(preff - pcurf)
    except ValueError:  # obviously not the same FEM spaces
        vreff, preff = dts.expand_vp_dolfunc(vc=vref, pc=pref, **reffemp)
        vcurf, pcurf = dts.expand_vp_dolfunc(vc=vcur, pc=pcur, **curfemp)
        verr = dolfin.errornorm(vreff, vcurf)
        perr = dolfin.errornorm(preff, pcurf)
    return verr, perr
Ejemplo n.º 3
0
 def plotit(vp, t):
     if plotplease:
         v, p = dts.expand_vp_dolfunc(vp=vp, **femp)
         v.rename('v', 'velocity')
         p.rename('p', 'pressure')
         vfile << v, t
         pfile << p, t
     else:
         return
    def test_expand_condense_vfuncs(self):
        """check the expansion of vectors to dolfin funcs

        """
        from dolfin_navier_scipy.dolfin_to_sparrays import expand_vp_dolfunc

        u = dolfin.Expression(('x[1]', '0'), element=self.V.ufl_element())
        ufun = dolfin.project(u, self.V, solver_type='lu')
        uvec = ufun.vector().get_local().reshape(len(ufun.vector()), 1)

        # Boundaries
        def top(x, on_boundary):
            return x[1] > 1.0 - dolfin.DOLFIN_EPS

        def leftbotright(x, on_boundary):
            return (x[0] > 1.0 - dolfin.DOLFIN_EPS
                    or x[1] < dolfin.DOLFIN_EPS
                    or x[0] < dolfin.DOLFIN_EPS)

        # No-slip boundary condition for velocity
        noslip = u
        bc0 = dolfin.DirichletBC(self.V, noslip, leftbotright)
        # Boundary condition for velocity at the lid
        lid = u
        bc1 = dolfin.DirichletBC(self.V, lid, top)
        # Collect boundary conditions
        diribcs = [bc0, bc1]
        bcinds = []
        for bc in diribcs:
            bcdict = bc.get_boundary_values()
            bcinds.extend(bcdict.keys())

        # indices of the innernodes
        innerinds = np.setdiff1d(range(self.V.dim()),
                                 bcinds).astype(np.int32)

        # take only the inner nodes
        uvec_condensed = uvec[innerinds, ]

        v, p = expand_vp_dolfunc(V=self.V, vc=uvec_condensed,
                                 invinds=innerinds, diribcs=diribcs)

        vvec = v.vector().get_local().reshape(len(v.vector()), 1)

        self.assertTrue(np.allclose(uvec, vvec))
    def test_expand_condense_vfuncs(self):
        """check the expansion of vectors to dolfin funcs

        """
        from dolfin_navier_scipy.dolfin_to_sparrays import expand_vp_dolfunc

        u = dolfin.Expression(('x[1]', '0'), element=self.V.ufl_element())
        ufun = dolfin.project(u, self.V, solver_type='lu')
        uvec = ufun.vector().get_local().reshape(len(ufun.vector()), 1)

        # Boundaries
        def top(x, on_boundary):
            return x[1] > 1.0 - dolfin.DOLFIN_EPS

        def leftbotright(x, on_boundary):
            return (x[0] > 1.0 - dolfin.DOLFIN_EPS or x[1] < dolfin.DOLFIN_EPS
                    or x[0] < dolfin.DOLFIN_EPS)

        # No-slip boundary condition for velocity
        noslip = u
        bc0 = dolfin.DirichletBC(self.V, noslip, leftbotright)
        # Boundary condition for velocity at the lid
        lid = u
        bc1 = dolfin.DirichletBC(self.V, lid, top)
        # Collect boundary conditions
        diribcs = [bc0, bc1]
        bcinds = []
        for bc in diribcs:
            bcdict = bc.get_boundary_values()
            bcinds.extend(bcdict.keys())

        # indices of the innernodes
        innerinds = np.setdiff1d(range(self.V.dim()), bcinds).astype(np.int32)

        # take only the inner nodes
        uvec_condensed = uvec[innerinds, ]

        v, p = expand_vp_dolfunc(V=self.V,
                                 vc=uvec_condensed,
                                 invinds=innerinds,
                                 diribcs=diribcs)

        vvec = v.vector().get_local().reshape(len(v.vector()), 1)

        self.assertTrue(np.allclose(uvec, vvec))
Ejemplo n.º 6
0
    def record_ldt(t, vel=None, p=None, memory={}, mode='abtwo'):

        rotval = 0.
        if mode == 'stokes':
            memory.update(dict(lastt=t))
            return rotval, memory

        if mode == 'init':
            memory.update(dict(lastt=t))
            return rotval, memory

        vfun, pfun = dts.expand_vp_dolfunc(vc=vel, pc=p, **femp)

        if mode == 'heunpred' or mode == 'heuncorr':
            curdt = t - memory['lastt']
            if mode == 'heunpred':
                memory.update(dict(lastv=vel))
                pass

            elif mode == 'heuncorr':
                lvfun = dts.expand_vp_dolfunc(vc=memory['lastv'],
                                              **femp)[0]
                trqe = euleres(vfun, pfun, curdt, lastvel=lvfun, phi=phitwo)
                lift = euleres(vfun, pfun, curdt, lastvel=lvfun, phi=poy)
                drag = euleres(vfun, pfun, curdt, lastvel=lvfun, phi=pox)
                memory.update(dict(lastt=t, lastdt=curdt, heunpred=vel))

                memory['trqs'].append(trqe)
                memory['lfts'].append(lift)
                memory['drgs'].append(drag)
                memory['tims'].append(t)

        elif mode == 'abtwo':

            lvfun = dts.expand_vp_dolfunc(vc=memory['lastv'], **femp)[0]
            curdt = t - memory['lastt']

            try:
                ovfn = dts.expand_vp_dolfunc(vc=memory['lastlastv'], **femp)[0]
                modres = abtwres
            except KeyError:  # no lastlastv yet -- we can check the Heun res
                ovfn = dts.expand_vp_dolfunc(vc=memory['heunpred'], **femp)[0]
                modres = heunres

            trqe = modres(vfun, pfun, curdt, lastvel=lvfun, othervel=ovfn,
                          phi=phitwo)
            lift = modres(vfun, pfun, curdt, lastvel=lvfun, othervel=ovfn,
                          phi=poy)
            drag = modres(vfun, pfun, curdt, lastvel=lvfun, othervel=ovfn,
                          phi=pox)

            memory.update(dict(lastlastv=np.copy(memory['lastv'])))
            memory.update(dict(lastv=vel))

            memory['trqs'].append(trqe)
            memory['lfts'].append(lift)
            memory['drgs'].append(drag)
            memory['tims'].append(t)
            memory.update(dict(lastt=t, lastdt=curdt))

        deltap = pfun(a_1) - pfun(a_2)
        memory['dtps'].append(deltap)
        return rotval, memory
    def test_residuals(self):
        femp, stokesmatsc, rhsd = \
            dnsps.get_sysmats(problem=self.problem, nu=self.nu,
                              bccontrol=False, charvel=self.charvel,
                              scheme=self.scheme, mergerhs=True,
                              meshparams=self.meshparams)

        # setting some parameters

        t0 = 0.0
        tE = .1
        Nts = 2
        tips = dict(t0=t0, tE=tE, Nts=Nts)

        soldict = stokesmatsc  # containing A, J, JT
        soldict.update(femp)  # adding V, Q, invinds, diribcs
        soldict.update(tips)  # adding time integration params
        soldict.update(fv=rhsd['fv'],
                       fp=rhsd['fp'],
                       treat_nonl_explct=True,
                       return_vp_dict=True,
                       no_data_caching=True,
                       start_ssstokes=True)

        vpdct = snu.solve_nse(**soldict)
        M, A, JT = stokesmatsc['M'], stokesmatsc['A'], stokesmatsc['JT']
        fv = rhsd['fv']
        V, invinds = femp['V'], femp['invinds']
        dt = (tE - t0) / Nts
        tm = (tE - t0) / 2

        reschkdict = dict(V=V,
                          nu=self.nu,
                          gradvsymmtrc=True,
                          outflowds=femp['outflowds'])
        euleres = get_imex_res(explscheme='eule', **reschkdict)
        heunres = get_imex_res(explscheme='heun', **reschkdict)
        crnires = get_imex_res(explscheme='abtw', **reschkdict)

        # the initial value
        inivwbcs = vpdct[t0]['v']
        iniv = inivwbcs[invinds]
        iniconvvec = dts.get_convvec(V=V, u0_vec=inivwbcs, invinds=invinds)
        inivelfun = dts.expand_vp_dolfunc(vc=inivwbcs, **femp)[0]

        # the Heun prediction step
        cneevwbcs = vpdct[(tm, 'heunpred')]['v']
        cneev = cneevwbcs[invinds]
        cneep = vpdct[(tm, 'heunpred')]['p']

        # the Heun step
        cnhevwbcs = vpdct[tm]['v']
        cnhev = cnhevwbcs[invinds]
        cnhep = vpdct[tm]['p']
        hpconvvec = dts.get_convvec(V=V, u0_vec=cneevwbcs, invinds=invinds)
        hpvelfun = dts.expand_vp_dolfunc(vc=cneevwbcs, **femp)[0]

        # the AB2 step
        cnabvwbcs = vpdct[tE]['v']
        cnabv = cnabvwbcs[invinds]
        cnabp = vpdct[tE]['p']
        hcconvvec = dts.get_convvec(V=V, u0_vec=cnhevwbcs, invinds=invinds)
        hcvelfun = dts.expand_vp_dolfunc(vc=cnhevwbcs, **femp)[0]

        print('Heun-Prediction: one step of Euler')
        resvec = (1. / dt * M * (cneev - iniv) + .5 * A * (iniv + cneev) +
                  iniconvvec - JT * cneep - fv)
        hpscres = np.linalg.norm(resvec)
        print('Scipy residual: ', hpscres)
        curv, curp = dts.expand_vp_dolfunc(vc=cneevwbcs, pc=cneep, **femp)
        res = euleres(curv, curp, dt, lastvel=inivelfun)
        hpfnres = np.linalg.norm(res.get_local()[invinds])
        print('dolfin residua: ', hpfnres)

        self.assertTrue(np.allclose(hpfnres, 0.))
        self.assertTrue(np.allclose(hpscres, 0.))

        print('\nHeun-Step:')
        heunrhs = M * iniv - .5 * dt * \
            (A * iniv + iniconvvec + hpconvvec) + dt * fv
        matvp = M * cnhev + .5 * dt * A * cnhev - dt * JT * cnhep
        hcscres = np.linalg.norm(matvp - heunrhs)
        print('Scipy residual: ', hcscres)
        # import ipdb; ipdb.set_trace()
        curv, curp = dts.expand_vp_dolfunc(vc=cnhevwbcs, pc=cnhep, **femp)
        heunres = heunres(curv, curp, dt, lastvel=inivelfun, othervel=hpvelfun)
        hcfnres = np.linalg.norm(heunres.get_local()[invinds])
        print('dolfin residua: ', hcfnres)

        self.assertTrue(np.allclose(hcfnres, 0.))
        self.assertTrue(np.allclose(hcscres, 0.))

        print('\nAB2-Step:')
        abtrhs = M * cnhev - .5 * dt * \
            (A * cnhev + -iniconvvec + 3. * hcconvvec) + dt * fv
        matvp = M * cnabv + .5 * dt * A * cnabv - dt * JT * cnabp
        abscres = np.linalg.norm(matvp - abtrhs)
        print('Scipy residual: ', abscres)

        # import ipdb; ipdb.set_trace()
        curv, curp = dts.expand_vp_dolfunc(vc=cnabvwbcs, pc=cnabp, **femp)
        crnires = crnires(curv, curp, dt, lastvel=hcvelfun, othervel=inivelfun)
        abfnres = np.linalg.norm(crnires.get_local()[invinds])
        print('dolfin residua: ', abfnres)

        self.assertTrue(np.allclose(abfnres, 0.))
        self.assertTrue(np.allclose(abscres, 0.))
problemname = 'cylinderwake'
N = 2
Nref = 3
Re = 10

femp, stokesmatsc, rhsd = dnsps.get_sysmats(problem=problemname, N=N, Re=Re,
                                            mergerhs=True)
soldict = stokesmatsc  # containing A, J, JT
soldict.update(femp)  # adding V, Q, invinds, diribcs
soldict.update(rhsd)  # adding the discrete rhs

v_ss_nse, list_norm_nwtnupd = snu.solve_steadystate_nse(N=N, **soldict)

vwbc = dts.append_bcs_vec(v_ss_nse, **femp)
vwbcf, _ = dts.expand_vp_dolfunc(vc=vwbc, V=femp['V'])

fempref, stokesmatsc, rhsd = dnsps.get_sysmats(problem=problemname, N=Nref,
                                               Re=Re, mergerhs=True)
Vref = fempref['V']


class ExtFunZero(dolfin.Expression):
    def __init__(self, vfun=None):
        self.vfun = vfun

    def eval(self, value, x):
        try:
            self.vfun.eval(value, x)
        except RuntimeError:
            value[0] = 0.0
def testit(problem=None, nu=None, charvel=None, Re=None,
           meshlvl=1,
           rho=1.,
           t0=0.0, tE=1.0, Nts=1e2+1, ParaviewOutput=False, scheme='TH'):

    meshfile = 'mesh/karman2D-rotcyl_lvl{0}.xml.gz'.format(meshlvl)
    physregs = 'mesh/karman2D-rotcyl_lvl{0}_facet_region.xml.gz'.\
        format(meshlvl)
    femp, stokesmatsc, rhsd = \
        dnsps.get_sysmats(problem='cylinder_rot', nu=nu, bccontrol=False,
                          charvel=charvel,
                          scheme=scheme, mergerhs=True,
                          meshparams=dict(strtomeshfile=meshfile,
                                          strtophysicalregions=physregs,
                                          strtobcsobs=geodata))
    ddir = 'data/'
    data_prfx = problem + '{4}_mesh{0}_Re{1}_Nts{2}_tE{3}'.\
        format(meshlvl, femp['Re'], Nts, tE, scheme)

    tips = dict(t0=t0, tE=tE, Nts=Nts)

    # ## Parameters for the benchmark values
    Um = charvel  # (we alread scale the inflow parabola accordingly)
    L = femp['charlen']  # characteristic length
    NP, NV = stokesmatsc['J'].shape
    print('NV + NP : {0} + {1} = {2}'.format(NV, NP, NV+NP))

    def rotcont(t, vel):
        return 0.

    dircntdict = dict(diricontbcinds=[femp['mvwbcinds']],
                      diricontbcvals=[femp['mvwbcvals']],
                      diricontfuncs=[rotcont])

    soldict = stokesmatsc  # containing A, J, JT
    soldict.update(femp)  # adding V, Q, invinds, diribcs
    soldict.update(tips)  # adding time integration params
    soldict.update(dircntdict)
    soldict.update(fv=rhsd['fv'], fp=rhsd['fp'],
                   N=meshlvl, nu=nu,
                   # start_ssstokes=True,
                   verbose=True,
                   return_vp=True,
                   iniv=0*rhsd['fv'],
                   get_datastring=None,
                   comp_nonl_semexp=True,
                   dbcinds=femp['dbcinds'], dbcvals=femp['dbcvals'],
                   data_prfx=ddir+data_prfx,
                   paraviewoutput=ParaviewOutput,
                   vfileprfx=proutdir+'vel_',
                   pfileprfx=proutdir+'p_')

#
# compute the uncontrolled steady state Navier-Stokes solution
#
    vp_ss_nse = snu.solve_steadystate_nse(**soldict)
    vss, dynpss = dts.expand_vp_dolfunc(vc=vp_ss_nse[0], pc=vp_ss_nse[1],
                                        **femp)
    realpss = rho*dynpss  # Um**2*rho*dynpss
    realvss = vss  # Um*vss
    getld = dnsps.LiftDragSurfForce(V=femp['V'], nu=nu,
                                    ldds=femp['liftdragds'])
    clift, cdrag = getld.evaliftdragforce(u=realvss, p=realpss)
    cdclfac = 2./(rho*L*Um**2)
    print('Cl: {0}'.format(cdclfac*clift))
    print('Cd: {0}'.format(cdclfac*cdrag))
    import dolfin
    a_1 = dolfin.Point(0.15, 0.2)
    a_2 = dolfin.Point(0.25, 0.2)
    pdiff = realpss(a_1) - realpss(a_2)
    print('Delta P: {0}'.format(pdiff))

    print('\n values from Schaefer/Turek as in')
    print('www.featflow.de/en/benchmarks/cfdbenchmarking/flow/' +
          'dfg_benchmark1_re20.html:')
    print('Cl: {0}'.format(0.010618948146))
    print('Cd: {0}'.format(5.57953523384))
    print('Delta P: {0}'.format(0.11752016697))
def testit(problem=None,
           nu=None,
           charvel=None,
           Re=None,
           meshlvl=1,
           gradvsymmtrc=True,
           rho=1.,
           ParaviewOutput=False,
           scheme='TH'):

    meshfile = 'mesh/karman2D-rotcyl_lvl{0}.xml.gz'.format(meshlvl)
    physregs = 'mesh/karman2D-rotcyl_lvl{0}_facet_region.xml.gz'.\
        format(meshlvl)
    femp, stokesmatsc, rhsd = \
        dnsps.get_sysmats(problem=problem, nu=nu,
                          charvel=charvel, gradvsymmtrc=gradvsymmtrc,
                          scheme=scheme, mergerhs=True,
                          meshparams=dict(strtomeshfile=meshfile,
                                          movingwallcntrl=False,
                                          strtophysicalregions=physregs,
                                          strtobcsobs=geodata))

    ddir = 'data/'
    data_prfx = problem + '{2}_mesh{0}_Re{1}'.format(meshlvl, femp['Re'],
                                                     scheme)

    # ## Parameters for the benchmark values
    Um = charvel  # (we alread scale the inflow parabola accordingly)
    L = femp['charlen']  # characteristic length
    NP, NV = stokesmatsc['J'].shape
    print('NV + NP : {0} + {1} = {2}'.format(NV, NP, NV + NP))

    soldict = stokesmatsc  # containing A, J, JT
    # soldict.update(femp)  # adding V, Q, invinds, diribcs
    soldict.update(invinds=femp['invinds'], V=femp['V'], Q=femp['Q'])
    soldict.update(fv=rhsd['fv'],
                   fp=rhsd['fp'],
                   N=meshlvl,
                   nu=nu,
                   verbose=True,
                   return_vp=True,
                   get_datastring=None,
                   dbcinds=femp['dbcinds'],
                   dbcvals=femp['dbcvals'],
                   data_prfx=ddir + data_prfx,
                   paraviewoutput=ParaviewOutput,
                   vfileprfx=proutdir + 'vel_',
                   pfileprfx=proutdir + 'p_')

    #
    # compute the uncontrolled steady state Navier-Stokes solution
    #
    vp_ss_nse = snu.solve_steadystate_nse(**soldict)
    vss, dynpss = dts.expand_vp_dolfunc(vc=vp_ss_nse[0],
                                        pc=vp_ss_nse[1],
                                        **femp)
    steady_state_res = \
        get_steady_state_res(V=femp['V'], gradvsymmtrc=True,
                             outflowds=femp['outflowds'], nu=nu)

    res = steady_state_res(vss, rho * dynpss)
    auxvec = np.zeros((femp['V'].dim(), ))
    invinds = femp['invinds']
    auxvec[invinds] = res.get_local()[invinds]
    print('two norm of the res: {0}'.format(np.linalg.norm(auxvec)))

    phionevec = np.zeros((femp['V'].dim(), 1))
    phionevec[femp['ldsbcinds'], :] = 1.
    phione = dolfin.Function(femp['V'])
    phione.vector().set_local(phionevec)
    pickx = dolfin.as_matrix([[1., 0.], [0., 0.]])
    picky = dolfin.as_matrix([[0., 0.], [0., 1.]])
    pox = pickx * phione
    poy = picky * phione
    drag = steady_state_res(vss, rho * dynpss, phi=pox)
    lift = steady_state_res(vss, rho * dynpss, phi=poy)
    cdclfac = 2. / (rho * L * Um**2)

    print('Computed via testing the residual: ')
    print('Cl: {0}'.format(cdclfac * lift))
    print('Cd: {0}'.format(cdclfac * drag))

    phionevec = np.zeros((femp['V'].dim(), 1))
    phionevec[femp['ldsbcinds'], :] = 1.
    phione = dolfin.Function(femp['V'])
    phione.vector().set_local(phionevec)
    # phionex = phione.sub(0)

    print('Computed via `dnsps.LiftDragSurfForce`:')
    realpss = rho * dynpss  # Um**2*rho*dynpss
    realvss = vss  # Um*vss
    getld = dnsps.LiftDragSurfForce(V=femp['V'],
                                    nu=nu,
                                    ldds=femp['liftdragds'],
                                    outflowds=femp['outflowds'],
                                    phione=phione)
    clift, cdrag = getld.evaliftdragforce(u=realvss, p=realpss)
    print('Cl: {0}'.format(cdclfac * clift))
    print('Cd: {0}'.format(cdclfac * cdrag))

    a_1 = dolfin.Point(0.15, 0.2)
    a_2 = dolfin.Point(0.25, 0.2)
    pdiff = realpss(a_1) - realpss(a_2)
    print('Delta P: {0}'.format(pdiff))

    print('\n values from Schaefer/Turek as in')
    print('www.featflow.de/en/benchmarks/cfdbenchmarking/flow/' +
          'dfg_benchmark1_re20.html:')
    print('Cl: {0}'.format(0.010618948146))
    print('Cd: {0}'.format(5.57953523384))
    print('Delta P: {0}'.format(0.11752016697))