def test_rearrange_matrices(self):
        """check the algorithm rearranging for B2, solve the

        rearranged system and sort back the solution vector
        The rearr. is done by swapping columns in the coeff matrix,
        thus the resort is done by swapping the entries of the solution
        vector"""

        import dolfin
        import prob_defs as tts
        import dolfin_to_nparrays as dtn
        from smamin_utils import col_columns_atend, revert_sort_tob2
        import smamin_thcr_mesh

        N = 32
        mesh = smamin_thcr_mesh.getmake_mesh(N)

        V = dolfin.VectorFunctionSpace(mesh, "CG", 2)
        Q = dolfin.FunctionSpace(mesh, "CG", 1)

        velbcs = tts.setget_velbcs_zerosq(mesh, V)

        bcinds = []
        for bc in velbcs:
            bcdict = bc.get_boundary_values()
            bcinds.extend(bcdict.keys())

        # indices of the inner velocity nodes
        invinds = np.setdiff1d(range(V.dim()), bcinds)

        Ma, Aa, BTa, Ba, MPa = dtn.get_sysNSmats(V, Q)

        Mc = Ma[invinds, :][:, invinds]
        Bc = Ba[:, invinds]
        BTc = BTa[invinds, :]

        B2BubInds, _ = smamin_thcr_mesh.get_B2_bubbleinds(N, V, mesh)
        # we need the B2Bub indices in the reduced setting vc
        # this gives a masked array of boolean type
        B2BubBool = np.in1d(np.arange(V.dim())[invinds], B2BubInds)
        # B2BubInds = np.arange(len(B2BubIndsBool

        Nv = len(invinds)
        Np = Q.dim()
        dt = 1.0 / N

        # the complement of the bubble index in the inner nodes
        BubIndC = ~B2BubBool  # np.setdiff1d(np.arange(Nv),B2BubBool)
        # the bubbles as indices
        B2BI = np.arange(len(B2BubBool))[B2BubBool]

        # Reorder the matrices for smart min ext
        MSme = col_columns_atend(Mc, B2BI)
        BSme = col_columns_atend(Bc, B2BI)

        B1Sme = BSme[:, :Nv - (Np - 1)]
        B2Sme = BSme[:, Nv - (Np - 1):]

        M1Sme = MSme[:, :Nv - (Np - 1)]
        M2Sme = MSme[:, Nv - (Np - 1):]

        IterA1 = sps.hstack(
            [sps.hstack([M1Sme, dt*M2Sme]), -dt*BTc[:, 1:]])

        IterA2 = sps.hstack([sps.hstack([B1Sme[1:, :], dt*B2Sme[1:, :]]),
                             sps.csr_matrix((Np - 1, (Np - 1)))])
        # The rearranged coefficient matrix
        IterARa = sps.vstack([IterA1, IterA2])

        IterAqq = sps.hstack([Mc, -dt*BTc[:, 1:]])
        IterAp = sps.hstack([Bc[1:, :], sps.csr_matrix((Np-1, Np-1))])
        # The actual coefficient matrix
        IterA = sps.vstack([IterAqq, IterAp])

        rhs = np.random.random((Nv + Np - 1, 1))

        SolActu = spsla.spsolve(IterA, rhs)
        SolRa = spsla.spsolve(IterARa, rhs)

        # Sort it back
        # manually
        SortBack = np.zeros((Nv + Np - 1, 1))
        # q1
        SortBack[BubIndC, 0] = SolRa[:Nv - (Np - 1)]
        # tq2
        SortBack[B2BI, 0] = dt*SolRa[Nv - (Np - 1):Nv]
        SortBack[Nv:, 0] = SolRa[Nv:]

        SolRa = np.atleast_2d(SolRa).T

        # and by function
        SolRa[Nv - (Np - 1):Nv, 0] = dt*SolRa[Nv - (Np - 1):Nv, 0]
        SB2 = revert_sort_tob2(SolRa[:Nv, ], B2BI)
        SB2 = np.vstack([SB2, SolRa[Nv:, ]])
        # SB2v = np.atleast_2d(SB2)

        SolActu = np.atleast_2d(SolActu)
        SortBack = np.atleast_2d(SortBack).T

        self.assertTrue(np.allclose(SolActu, SortBack, atol=1e-6))
        self.assertTrue(np.allclose(SolActu, SB2.T, atol=1e-6))
    def test_eul_solution(self):
        from dolfin import project
        import prob_defs as tts
        import dolfin_to_nparrays as dtn
        from numpy import log

        nu = 0

        def get_funcexpr_as_vec(u, U, invinds=None, t=None):
            if t is not None:
                u.t = t
            if invinds is None:
                invinds = range(U.dim())
            ua = project(u, U)
            ua = ua.vector()
            ua = ua.array()
            return ua

        eoca = np.zeros(len(self.Nlist))
        eocc = np.zeros(len(self.Nlist))

        for k, N in enumerate(self.Nlist):
            PrP = tts.ProbParams(N, omega=8, nu=nu)
            # get system matrices as np.arrays
            Ma, Aa, BTa, Ba, MPa = dtn.get_sysNSmats(PrP.V, PrP.Q)

            tcur = self.tcur

            PrP.fv.t = tcur
            PrP.fv.nu = nu   # nu = 0, for Eulerian Flow - no diffusion

            fv, fp = dtn.setget_rhs(PrP.V, PrP.Q, PrP.fv, PrP.fp)

            Mc, Ac, BTc, Bc, fvbc, fpbc, bcinds, bcvals, invinds = \
                dtn.condense_sysmatsbybcs(Ma, Aa, BTa, Ba, fv, fp, PrP.velbcs)

            v, vdot, p = PrP.v, PrP.vdot, PrP.p

            vc = get_funcexpr_as_vec(v, PrP.V, t=tcur)
            pc = get_funcexpr_as_vec(p, PrP.Q, t=tcur)

            vdotc = get_funcexpr_as_vec(vdot, PrP.V, t=tcur)

            v.t = tcur
            vf = project(v, PrP.V)
            ConV = dtn.get_convvec(vf, PrP.V)

            resV = Ma*vdotc + nu*Aa*vc + ConV[:, 0] - BTa*pc - fv[:, 0]
            resVc = Mc*vdotc[invinds] + nu*Ac*vc[invinds] + ConV[invinds, 0] -\
                BTc*pc - fvbc[:, 0] - fv[invinds, 0]

            eoca[k] = np.sqrt(np.dot(np.atleast_2d(resV[invinds]),
                              Mc*np.atleast_2d(resV[invinds]).T))
            eocc[k] = np.sqrt(np.dot(np.atleast_2d(resVc),
                              Mc*np.atleast_2d(resVc).T))

        eocs = np.array([log(eoca[0] / eoca[1]),
                         log(eoca[1] / eoca[2]),
                         log(eocc[0] / eocc[1]),
                         log(eocc[1] / eocc[2])])

        OC = self.OC

        print eocs
        print np.array([OC*log(2)]*4)

        self.assertTrue((eocs > [np.array([OC*log(2)])]*4).all())
def solve_stokesTimeDep(
    method=None,
    Omega=None,
    tE=None,
    Prec=None,
    N=None,
    NtsList=None,
    LinaTol=None,
    MaxIter=None,
    UsePreTStps=None,
    SaveTStps=None,
    SaveIniVal=None,
):
    # set parameters
    if N is None:
        N = 4  # 12
    if method is None:
        method = 1  # half explicit, our algorithm
    if Omega is None:
        Omega = 8
    methdict = {1: "HalfExpEulSmaMin", 2: "HalfExpEulInd2"}

    # instantiate object containing mesh, V, Q, rhs, velbcs, invinds
    PrP = ProbParams(N, Omega)
    # instantiate the Time Int Parameters
    TsP = TimestepParams(methdict[method], N)

    if NtsList is not None:
        TsP.Ntslist = NtsList
    if LinaTol is not None:
        TsP.linatol = LinaTol
    if MaxIter is not None:
        TsP.MaxIter = MaxIter
    if tE is not None:
        TsP.tE = tE
    if Omega is not None:
        TsP.Omega = Omega
    if SaveTStps is not None:
        TsP.SaveTStps = SaveTStps
    if UsePreTStps is not None:
        TsP.UsePreTStps = UsePreTStps
    if SaveIniVal is not None:
        TsP.SaveIniVal = SaveIniVal

    print "Mesh parameter N = %d" % N
    print "Time interval [%d,%1.2f]" % (TsP.t0, TsP.tE)
    print "Omega = %d" % TsP.Omega
    print "You have chosen %s for time integration" % methdict[method]
    print "The tolerance for the linear solver is %e" % TsP.linatol

    # get system matrices as np.arrays
    Ma, Aa, BTa, Ba, MPa = dtn.get_sysNSmats(PrP.V, PrP.Q)
    fv, fp = dtn.setget_rhs(PrP.V, PrP.Q, PrP.fv, PrP.fp)

    # condense the system by resolving the boundary values
    Mc, Ac, BTc, Bc, fvbc, fpbc, bcinds, bcvals, invinds = dtn.condense_sysmatsbybcs(
        Ma, Aa, BTa, Ba, fv, fp, PrP.velbcs
    )

    if method != 2:  # Wenn Minimal Extension
        # Rearrange the matrices and rhs
        from scipy.io import loadmat

        # AB HIER MUSS MAN ANPASSEN
        MSmeCL, BSme, B2Inds, B2BoolInv, B2BI = smartminex_CRmesh.get_smamin_rearrangement(N, PrP, Mc, Bc)

        FvbcSme = np.vstack([fvbc[~B2BoolInv,], fvbc[B2BoolInv,]])
        FpbcSme = fpbc

        PrP.Pdof = 0  # Thats how the smamin is constructed

        # inivalue
        dname = "IniValSmaMinN%s" % N
        try:
            IniV = loadmat(dname)
            qqpq_init = IniV["qqpq_old"]
            vp_init = None
        except IOError:
            qqpq_init = None

    # Output
    try:
        os.chdir("json")
    except OSError:
        raise Warning('need "json" subdirectory for storing the data')
    os.chdir("..")

    if TsP.ParaviewOutput:
        os.chdir("results/")
        for fname in glob.glob(TsP.method + "*"):
            os.remove(fname)
        os.chdir("..")

    ###
    # Time stepping
    ###
    # starting value
    dimredsys = len(fvbc) + len(fp) - 1
    vp_init = np.zeros((dimredsys, 1))

    for i, CurNTs in enumerate(TsP.Ntslist):
        TsP.Nts = CurNTs

        if method == 2:
            tis.halfexp_euler_nseind2(Mc, MPa, Ac, BTc, Bc, fvbc, fpbc, vp_init, PrP, TsP)
        elif method == 1:
            tis.halfexp_euler_smarminex(
                MSmeCL, BSme, MPa, FvbcSme, FpbcSme, B2BoolInv, PrP, TsP, vp_init, qqpq_init=qqpq_init
            )

        # Output only in first iteration!
        TsP.ParaviewOutput = False

    JsD = save_simu(TsP, PrP)

    return
Example #4
0
def solve_stokesTimeDep(method=None, Omega=None, tE=None, Prec=None, N=None, NtsList=None, LinaTol=None, MaxIter=None, UsePreTStps=None, SaveTStps=None, SaveIniVal=None ):
	"""system to solve
	
  	 	 du\dt - lap u + grad p = fv
		         div u          = fp
	
	"""

	if N is None:
		N = 20 

	if method is None:
		method = 2
	
	if Omega is None:
		Omega = 3

	methdict = {
			1:'HalfExpEulSmaMin',
			2:'HalfExpEulInd2',
			3:'Heei2Ra'}

	# instantiate object containing mesh, V, Q, rhs, velbcs, invinds
	PrP = ProbParams(N,Omega)
	# instantiate the Time Int Parameters
	TsP = TimestepParams(methdict[method], N)

	if NtsList is not None:
		TsP.Ntslist = NtsList
	if LinaTol is not None:
		TsP.linatol = LinaTol
	if MaxIter is not None:
		TsP.MaxIter = MaxIter
	if tE is not None: 
		TsP.tE = tE
	if Omega is not None:
		TsP.Omega = Omega
	if SaveTStps is not None:
		TsP.SaveTStps = SaveTStps
	if UsePreTStps is not None:
		TsP.UsePreTStps = UsePreTStps
	if SaveIniVal is not None:
		TsP.SaveIniVal = SaveIniVal


	print 'Mesh parameter N = %d' % N
	print 'Time interval [%d,%1.2f]' % (TsP.t0, TsP.tE)
	print 'Omega = %d' % TsP.Omega
	print 'You have chosen %s for time integration' % methdict[method]
	print 'The tolerance for the linear solver is %e' %TsP.linatol

	# get system matrices as np.arrays
	Ma, Aa, BTa, Ba, MPa = dtn.get_sysNSmats(PrP.V, PrP.Q)
	fv, fp = dtn.setget_rhs(PrP.V, PrP.Q, PrP.fv, PrP.fp)

	# condense the system by resolving the boundary values
	Mc, Ac, BTc, Bc, fvbc, fpbc, bcinds, bcvals, invinds = \
			dtn.condense_sysmatsbybcs(Ma,Aa,BTa,Ba,fv,fp,PrP.velbcs)
	
	if method != 2:
		# Rearrange the matrices and rhs
		from smamin_utils import col_columns_atend
		from scipy.io import loadmat

		MSmeCL, BSme, B2Inds, B2BoolInv, B2BI = smartminex_tayhoomesh.get_smamin_rearrangement(N,PrP,Mc,Bc)

		FvbcSme = np.vstack([fvbc[~B2BoolInv,],fvbc[B2BoolInv,]])
		FpbcSme = fpbc

		PrP.Pdof = 0 # Thats how the smamin is constructed

		# inivalue 
		dname = 'IniValSmaMinN%s' % N
		try:
			IniV = loadmat(dname)
			qqpq_init = IniV['qqpq_old']
			vp_init = None
		except IOError:
			qqpq_init = None
	
	### Output
	try:
		os.chdir('json')
	except OSError:
		raise Warning('need "json" subdirectory for storing the data')
	os.chdir('..')

	if TsP.ParaviewOutput:
		os.chdir('results/')
		for fname in glob.glob(TsP.method + '*'):
			os.remove( fname )
		os.chdir('..')

	###
	# Time stepping
	###
	# starting value
	dimredsys = len(fvbc)+len(fp)-1
	vp_init   = np.zeros((dimredsys,1))
	
	for i, CurNTs in enumerate(TsP.Ntslist):
		TsP.Nts = CurNTs

		if method == 2:
			tis.halfexp_euler_nseind2(Mc,MPa,Ac,BTc,Bc,fvbc,fpbc,
					vp_init,PrP,TsP)
		elif method == 1:
			tis.halfexp_euler_smarminex(MSmeCL,BSme,MPa,FvbcSme,FpbcSme,
					B2BoolInv,PrP,TsP,vp_init,qqpq_init=qqpq_init)
		elif method == 3:
			tis.halfexp_euler_ind2ra(MSmeCL,BSme,MPa,FvbcSme,FpbcSme,
					vp_init,B2BoolInv,PrP,TsP)

		# Output only in first iteration!
		TsP.ParaviewOutput = False
	
	JsD = save_simu(TsP, PrP)
		
	return 
    # print 'NumOfNodes %3g and dimension %3g' % (PrP.mesh.num_vertices(),
    # len(u_array))
    print " ------------ "
    print "Mesh parameter N = %d" % PrP.N
    print "Number of Triangles  %4g" % (PrP.mesh.num_cells())
    print "Number of Nodes      %4g" % (PrP.mesh.num_vertices())
    print "Number of Edges      %4g" % (PrP.mesh.num_edges())
    print "Number of Facets     %4g" % (PrP.mesh.num_facets())
    print " ------------ "

    c4n = PrP.mesh.coordinates()
    n4e = PrP.mesh.cells()

    u_array = u.vector().array()
    p_array = p.vector().array()

    print "Dimensions: u has dim %3g and p has dim %3g" % (len(u_array), len(p_array))

    # compute matrices
    Ma, Aa, BTa, Ba, MPa = dtn.get_sysNSmats(PrP.V, PrP.Q)
    # delete row corresponding to pressure-DoF (T_0)
    Ba = Ba[1 : PrP.mesh.num_cells(), :]  # Bx.get_shape .toarray()
    # apply algorithm from Preprint
    dof_for_regular_B2 = get_SmartDoFs_CR(PrP.V, PrP.mesh, Ba)

    reg_B2_bloc = Ba[:, dof_for_regular_B2]

    print reg_B2_bloc.toarray()
    print "Die Determinante ist = %3g" % npla.det(reg_B2_bloc.toarray())