def test_computeConservativeFlux_1d(self): NWorldCoarse = np.array([4]) NCoarseElement = np.array([2]) boundaryConditions = np.array([[0, 0]]) world = World(NWorldCoarse, NCoarseElement, boundaryConditions) fluxTF = np.array([[-1, 1], [-1, 1], [-1, 1], [-1, 1]]) conservativeFluxTF = transport.computeConservativeFlux(world, fluxTF) self.assertTrue(np.allclose(conservativeFluxTF, fluxTF)) fluxTF = np.array([[-1, 2], [-2, 1], [-1, 1], [-1, 1]]) conservativeFluxTF = transport.computeConservativeFlux(world, fluxTF) self.assertTrue(np.allclose(np.sum(conservativeFluxTF, axis=1), 0)) fluxTF = np.array([[-1, 2], [-2, 3], [-3, 2], [-1, 1]]) conservativeFluxTF = transport.computeConservativeFlux(world, fluxTF) self.assertTrue(np.allclose(np.sum(conservativeFluxTF, axis=1), 0))
def test_alive(self): NWorldCoarse = np.array([5, 5]) NCoarseElement = np.array([20, 20]) NFine = NWorldCoarse * NCoarseElement NtFine = np.prod(NFine) NpCoarse = np.prod(NWorldCoarse + 1) NpFine = np.prod(NWorldCoarse * NCoarseElement + 1) world = World(NWorldCoarse, NCoarseElement) IPatchGenerator = lambda i, N: interp.L2ProjectionPatchMatrix( i, N, NWorldCoarse, NCoarseElement) k = 5 pglod = pg.PetrovGalerkinLOD(world, k, IPatchGenerator, 0) aBase = np.ones(NtFine) pglod.updateCorrectors(coef.coefficientFine(NWorldCoarse, NCoarseElement, aBase), clearFineQuantities=False) K = pglod.assembleMsStiffnessMatrix() self.assertTrue(np.all(K.shape == NpCoarse)) basisCorrectors = pglod.assembleBasisCorrectors() self.assertTrue(np.all(basisCorrectors.shape == (NpFine, NpCoarse)))
def test_init(self): NWorldCoarse = np.array([4, 4]) NCoarseElement = np.array([2,2]) world = World(NWorldCoarse, NCoarseElement) k = 1 iElementWorldCoarse = np.array([0, 0]) ec = lod.elementCorrector(world, k, iElementWorldCoarse) self.assertTrue(np.all(ec.NPatchCoarse == [2, 2])) self.assertTrue(np.all(ec.iElementPatchCoarse == [0, 0])) self.assertTrue(np.all(ec.iPatchWorldCoarse == [0, 0])) iElementWorldCoarse = np.array([0, 3]) ec = lod.elementCorrector(world, k, iElementWorldCoarse) self.assertTrue(np.all(ec.NPatchCoarse == [2, 2])) self.assertTrue(np.all(ec.iElementPatchCoarse == [0, 1])) self.assertTrue(np.all(ec.iPatchWorldCoarse == [0, 2])) iElementWorldCoarse = np.array([0, 2]) ec = lod.elementCorrector(world, k, iElementWorldCoarse) self.assertTrue(np.all(ec.NPatchCoarse == [2, 3])) self.assertTrue(np.all(ec.iElementPatchCoarse == [0, 1])) self.assertTrue(np.all(ec.iPatchWorldCoarse == [0, 1])) iElementWorldCoarse = np.array([1, 2]) ec = lod.elementCorrector(world, k, iElementWorldCoarse) self.assertTrue(np.all(ec.NPatchCoarse == [3, 3])) self.assertTrue(np.all(ec.iElementPatchCoarse == [1, 1])) self.assertTrue(np.all(ec.iPatchWorldCoarse == [0, 1]))
def test_computeSingleT(self): NWorldCoarse = np.array([4, 5, 6]) NCoarseElement = np.array([5, 2, 3]) world = World(NWorldCoarse, NCoarseElement) d = np.size(NWorldCoarse) k = 1 iElementWorldCoarse = np.array([2, 1, 2]) ec = lod.elementCorrector(world, k, iElementWorldCoarse) IPatch = interp.nodalPatchMatrix(ec.iPatchWorldCoarse, ec.NPatchCoarse, NWorldCoarse, NCoarseElement) NtPatch = np.prod(ec.NPatchCoarse*NCoarseElement) coefficientPatch = coef.coefficientFine(ec.NPatchCoarse, NCoarseElement, np.ones(NtPatch)) ec.computeCorrectors(coefficientPatch, IPatch) correctorSum = reduce(np.add, ec.fsi.correctorsList) self.assertTrue(np.allclose(correctorSum, 0)) ec.computeCoarseQuantities() # Test that the matrices have the constants in their null space #self.assertTrue(np.allclose(np.sum(ec.csi.LTPrimeij, axis=1), 0)) #self.assertTrue(np.allclose(np.sum(ec.csi.LTPrimeij, axis=2), 0)) self.assertTrue(np.allclose(np.sum(ec.csi.Kij, axis=0), 0)) self.assertTrue(np.allclose(np.sum(ec.csi.Kij, axis=1), 0)) self.assertTrue(np.allclose(np.sum(ec.csi.Kmsij, axis=0), 0)) self.assertTrue(np.allclose(np.sum(ec.csi.Kmsij, axis=1), 0)) # I had difficulties come up with test cases here. This test # verifies that most "energy" is in the element T. elementTIndex = util.convertpCoordinateToIndex(ec.NPatchCoarse-1, ec.iElementPatchCoarse) self.assertTrue(np.all(ec.csi.muTPrime[elementTIndex] >= ec.csi.muTPrime)) self.assertTrue(not np.all(ec.csi.muTPrime[elementTIndex+1] >= ec.csi.muTPrime)) ec.clearFineQuantities()
def test_Patch(self): NWorldCoarse = np.array([4, 4]) NCoarseElement = np.array([2, 2]) world = World(NWorldCoarse, NCoarseElement) k = 1 TInd = 0 patch = Patch(world, k, TInd) self.assertTrue(np.all(patch.NPatchCoarse == [2, 2])) self.assertTrue(np.all(patch.iElementPatchCoarse == [0, 0])) self.assertTrue(np.all(patch.iPatchWorldCoarse == [0, 0])) TInd = 12 patch = Patch(world, k, TInd) self.assertTrue(np.all(patch.NPatchCoarse == [2, 2])) self.assertTrue(np.all(patch.iElementPatchCoarse == [0, 1])) self.assertTrue(np.all(patch.iPatchWorldCoarse == [0, 2])) TInd = 8 patch = Patch(world, k, TInd) self.assertTrue(np.all(patch.NPatchCoarse == [2, 3])) self.assertTrue(np.all(patch.iElementPatchCoarse == [0, 1])) self.assertTrue(np.all(patch.iPatchWorldCoarse == [0, 1])) TInd = 9 patch = Patch(world, k, TInd) self.assertTrue(np.all(patch.NPatchCoarse == [3, 3])) self.assertTrue(np.all(patch.iElementPatchCoarse == [1, 1])) self.assertTrue(np.all(patch.iPatchWorldCoarse == [0, 1]))
def test_trivial(self): NPatchCoarse = np.array([3,3]) NCoarseElement = np.array([2,2]) NPatchFine = NPatchCoarse*NCoarseElement Nt = np.prod(NPatchFine) Np = np.prod(NPatchFine+1) fixed = util.boundarypIndexMap(NPatchFine) world = World(NPatchCoarse, NCoarseElement) patch = Patch(world, 3, 0) aFlatPatchFine = np.ones(Nt) ALoc = fem.localStiffnessMatrix(NPatchFine) APatchFull = fem.assemblePatchMatrix(NPatchFine, ALoc, aFlatPatchFine) PPatch = fem.assembleProlongationMatrix(NPatchCoarse, NCoarseElement) IPatchNodal = interp.nodalPatchMatrix(patch) #IPatchuncL2 = interp.uncoupledL2ProjectionPatchMatrix(np.array([0, 0]), NPatchCoarse, NPatchCoarse, NCoarseElement) IPatchL2 = interp.L2ProjectionPatchMatrix(patch) for IPatch in [IPatchNodal, IPatchL2]: np.random.seed(0) bPatchFullList = [] self.assertTrue(not lod.ritzProjectionToFinePatch(patch, APatchFull, bPatchFullList, IPatch)) bPatchFullList = [np.zeros(Np)] projections = lod.ritzProjectionToFinePatch(patch, APatchFull, bPatchFullList, IPatch) self.assertEqual(len(projections), 1) self.assertTrue(np.allclose(projections[0], 0*projections[0])) bPatchFull = np.random.rand(Np) bPatchFullList = [bPatchFull] projections = lod.ritzProjectionToFinePatch(patch, APatchFull, bPatchFullList, IPatch) self.assertTrue(np.isclose(np.linalg.norm(IPatch*projections[0]), 0)) self.assertTrue(np.isclose(np.dot(projections[0], APatchFull*projections[0]), np.dot(projections[0], bPatchFullList[0]))) self.assertTrue(np.isclose(np.linalg.norm(projections[0][fixed]), 0)) bPatchFullList = [bPatchFull, -bPatchFull] projections = lod.ritzProjectionToFinePatch(patch, APatchFull, bPatchFullList, IPatch) self.assertTrue(np.allclose(projections[0], -projections[1])) bPatchFullList = [np.random.rand(Np), np.random.rand(Np)] projections = lod.ritzProjectionToFinePatch(patch, APatchFull, bPatchFullList, IPatch) self.assertTrue(np.isclose(np.dot(projections[1], APatchFull*projections[0]), np.dot(projections[1], bPatchFullList[0]))) bPatchFull = np.random.rand(Np) bPatchFullList = [bPatchFull] projectionCheckAgainst = lod.ritzProjectionToFinePatch(patch, APatchFull, bPatchFullList, IPatch)[0] for saddleSolver in [#lod.nullspaceOneLevelHierarchySolver(NPatchCoarse, NCoarseElement), lod.SchurComplementSolver()]: projection = lod.ritzProjectionToFinePatch(patch, APatchFull, bPatchFullList, IPatch, saddleSolver)[0] self.assertTrue(np.isclose(np.max(np.abs(projectionCheckAgainst-projection)), 0))
def test_computeFullDomain(self): NWorldCoarse = np.array([2, 3, 4], dtype='int64') NWorldCoarse = np.array([1, 1, 1], dtype='int64') NCoarseElement = np.array([4, 2, 3], dtype='int64') NWorldFine = NWorldCoarse*NCoarseElement NpWorldFine = np.prod(NWorldFine+1) NpWorldCoarse = np.prod(NWorldCoarse+1) NtWorldFine = np.prod(NWorldCoarse*NCoarseElement) np.random.seed(0) world = World(NWorldCoarse, NCoarseElement) d = np.size(NWorldCoarse) IWorld = interp.nodalPatchMatrix(0*NWorldCoarse, NWorldCoarse, NWorldCoarse, NCoarseElement) aWorld = np.exp(np.random.rand(NtWorldFine)) coefficientWorld = coef.coefficientFine(NWorldCoarse, NCoarseElement, aWorld) k = np.max(NWorldCoarse) elementpIndexMap = util.lowerLeftpIndexMap(np.ones_like(NWorldCoarse), NWorldCoarse) elementpIndexMapFine = util.lowerLeftpIndexMap(NCoarseElement, NWorldFine) coarsepBasis = util.linearpIndexBasis(NWorldCoarse) finepBasis = util.linearpIndexBasis(NWorldFine) correctors = np.zeros((NpWorldFine, NpWorldCoarse)) basis = np.zeros((NpWorldFine, NpWorldCoarse)) for iElementWorldCoarse in it.product(*[np.arange(n, dtype='int64') for n in NWorldCoarse]): iElementWorldCoarse = np.array(iElementWorldCoarse) ec = lod.elementCorrector(world, k, iElementWorldCoarse) ec.computeCorrectors(coefficientWorld, IWorld) worldpIndices = np.dot(coarsepBasis, iElementWorldCoarse) + elementpIndexMap correctors[:,worldpIndices] += np.column_stack(ec.fsi.correctorsList) worldpFineIndices = np.dot(finepBasis, iElementWorldCoarse*NCoarseElement) + elementpIndexMapFine basis[np.ix_(worldpFineIndices, worldpIndices)] = world.localBasis AGlob = fem.assemblePatchMatrix(NWorldFine, world.ALocFine, aWorld) alpha = np.random.rand(NpWorldCoarse) vH = np.dot(basis, alpha) QvH = np.dot(correctors, alpha) # Check norm inequality self.assertTrue(np.dot(QvH.T, AGlob*QvH) <= np.dot(vH.T, AGlob*vH)) # Check that correctors are really fine functions self.assertTrue(np.isclose(np.linalg.norm(IWorld*correctors, ord=np.inf), 0)) v = np.random.rand(NpWorldFine, NpWorldCoarse) v[util.boundarypIndexMap(NWorldFine)] = 0 # The chosen interpolation operator doesn't ruin the boundary conditions. vf = v-np.dot(basis, IWorld*v) vf = vf/np.sqrt(np.sum(vf*(AGlob*vf), axis=0)) # Check orthogonality self.assertTrue(np.isclose(np.linalg.norm(np.dot(vf.T, AGlob*(correctors - basis)), ord=np.inf), 0))
def test_testCsi_muTPrime(self): # 3D world NWorldCoarse = np.array([6, 5, 4]) NCoarseElement = np.array([5, 2, 3]) world = World(NWorldCoarse, NCoarseElement) # Full patch TInd = 0 k = 6 patch = Patch(world, k, TInd) # Let functions = [x1] def computeFunctions(): pc = util.pCoordinates(world.NWorldFine) x1 = pc[:,0] x2 = pc[:,1] return [x1] elementFinepIndexMap = util.extractElementFine(NWorldCoarse, NCoarseElement, 0*NCoarseElement, extractElements=False) elementFinetIndexMap = util.extractElementFine(NWorldCoarse, NCoarseElement, 0*NCoarseElement, extractElements=True) # Let lambdas = functions lambdasList = [f[elementFinepIndexMap] for f in computeFunctions()] ## Case # aPatch = 1 # Let corrector Q = functions # Expect: muTPrime for first element T is 0, the others 1 correctorsList = computeFunctions() aPatch = np.ones(world.NpFine) csi = lod.computeCoarseQuantities(patch, lambdasList, correctorsList, aPatch) self.assertAlmostEqual(np.sum(csi.muTPrime), 6*5*4-1) self.assertAlmostEqual(csi.muTPrime[0], 0) ## Case # aPatch = 1 # Let corrector Q = 2*functions # Expect: muTPrime is 1 for first element and 4 for all others correctorsList = [2*f for f in computeFunctions()] aPatch = np.ones(world.NpFine) csi = lod.computeCoarseQuantities(patch, lambdasList, correctorsList, aPatch) self.assertAlmostEqual(np.sum(csi.muTPrime), 4*(6*5*4-1)+1) self.assertAlmostEqual(csi.muTPrime[0], 1)
def test_computeConservativeFlux_2d_a(self): NWorldCoarse = np.array([2, 2]) NCoarseElement = np.array([1, 1]) boundaryConditions = np.array([[0, 0], [1, 1]]) world = World(NWorldCoarse, NCoarseElement, boundaryConditions) fluxTF = np.array([[-1., 2, 0, 0], [-2 , 2, 0, 0], [-2 , 3, 0, 0], [-3 , 2, 0, 0]]) conservativeFluxTF = transport.computeConservativeFlux(world, fluxTF) print conservativeFluxTF self.assertTrue(np.allclose(np.sum(conservativeFluxTF, axis=1), 0))
def test_nodalPatchMatrix(self): NWorldCoarse = np.array([1, 1, 1]) NCoarseElement = np.array([1, 1, 1]) patch = Patch(World(NWorldCoarse, NCoarseElement), 1, 0) INodalPatch = interp.nodalPatchMatrix(patch) self.assertTrue( sparse.linalg.onenormest(INodalPatch - sparse.eye(np.size(INodalPatch, 0))) == 0) NWorldCoarse = np.array([1, 1, 1]) NCoarseElement = np.array([2, 1, 1]) patch = Patch(World(NWorldCoarse, NCoarseElement), 1, 0) INodalPatch = interp.nodalPatchMatrix(patch) self.assertTrue( np.allclose( INodalPatch.todense(), np.array([[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]])))
def test_stiffessMatrix(self): # Compare stiffness matrix from PG object with the one # computed from correctors and fine stiffness matrix NWorldFine = np.array([10, 10]) NpFine = np.prod(NWorldFine + 1) NtFine = np.prod(NWorldFine) NWorldCoarse = np.array([2, 2]) NCoarseElement = NWorldFine / NWorldCoarse NtCoarse = np.prod(NWorldCoarse) NpCoarse = np.prod(NWorldCoarse + 1) world = World(NWorldCoarse, NCoarseElement) np.random.seed(0) aBase = np.random.rand(NtFine) aCoef = coef.coefficientFine(NWorldCoarse, NCoarseElement, aBase) IPatchGenerator = lambda i, N: interp.L2ProjectionPatchMatrix( i, N, NWorldCoarse, NCoarseElement) IWorld = IPatchGenerator(0 * NWorldCoarse, NWorldCoarse) k = 2 printLevel = 0 pglod = pg.PetrovGalerkinLOD(world, k, IPatchGenerator, 0, printLevel) pglod.updateCorrectors(aCoef, clearFineQuantities=False) KmsFull = pglod.assembleMsStiffnessMatrix() KFull = pglod.assembleStiffnessMatrix() basis = fem.assembleProlongationMatrix(NWorldCoarse, NCoarseElement) basisCorrectors = pglod.assembleBasisCorrectors() self.assertTrue( np.isclose(np.linalg.norm(IWorld * basisCorrectors.todense()), 0)) modifiedBasis = basis - basisCorrectors AFine = fem.assemblePatchMatrix(NWorldFine, world.ALocFine, aBase) KmsRef = np.dot(basis.T, AFine * modifiedBasis) KRef = np.dot(basis.T, AFine * basis) self.assertTrue( np.isclose(np.linalg.norm(KFull.todense() - KRef.todense()), 0)) self.assertTrue( np.isclose(np.linalg.norm(KmsFull.todense() - KmsRef.todense()), 0))
def standard_fem(world, N, fine, tau, tot_time_steps, aFine, bFine, f): # mesh parameters NWorldCoarse = np.array([N, N]) NFine = np.array([fine, fine]) NCoarseElement = NFine // NWorldCoarse NWorldFine = world.NWorldCoarse * world.NCoarseElement bc = world.boundaryConditions world = World(NWorldCoarse, NCoarseElement, bc) NpCoarse = np.prod(NWorldCoarse + 1) basis = fem.assembleProlongationMatrix(NWorldCoarse, NCoarseElement) Uo = np.zeros(NpCoarse) # coarse v^(-1) and v^0 V = [Uo] V.append(Uo) # compute ms matrices S = fem.assemblePatchMatrix(NWorldFine, world.ALocFine, aFine) K = fem.assemblePatchMatrix(NWorldFine, world.ALocFine, bFine) M = fem.assemblePatchMatrix(NWorldFine, world.MLocFine) free = util.interiorpIndexMap(NWorldCoarse) SmsFree = (basis.T * S * basis)[free][:, free] KmsFree = (basis.T * K * basis)[free][:, free] MmsFree = (basis.T * M * basis)[free][:, free] LmsFree = (basis.T * M * f)[free] for i in range(tot_time_steps): n = i + 1 # linear system A = (1. / (tau ** 2)) * MmsFree + (1. / tau) * SmsFree + KmsFree b = LmsFree + (1. / tau) * SmsFree * V[n][free] + (2. / (tau ** 2)) * MmsFree * V[n][free] \ - (1. / (tau ** 2)) * MmsFree * V[n - 1][free] # solve system VFree = linalg.linSolve(A, b) VFull = np.zeros(NpCoarse) VFull[free] = VFree # append solution for current time step V.append(VFull) return basis * V[-1]
def test_testCsi(self): NWorldCoarse = np.array([4, 5, 6]) NCoarseElement = np.array([5, 2, 3]) world = World(NWorldCoarse, NCoarseElement) d = np.size(NWorldCoarse) k = 1 iElementWorldCoarse = np.array([2, 1, 2]) ec = lod.elementCorrector(world, k, iElementWorldCoarse) IPatch = interp.L2ProjectionPatchMatrix(ec.iPatchWorldCoarse, ec.NPatchCoarse, NWorldCoarse, NCoarseElement) NtPatch = np.prod(ec.NPatchCoarse*NCoarseElement) np.random.seed(1) aPatch = np.random.rand(NtPatch) coefficientPatch = coef.coefficientFine(ec.NPatchCoarse, NCoarseElement, aPatch) ec.computeCorrectors(coefficientPatch, IPatch) ec.computeCoarseQuantities() TFinetIndexMap = util.extractElementFine(ec.NPatchCoarse, NCoarseElement, ec.iElementPatchCoarse, extractElements=True) TFinepIndexMap = util.extractElementFine(ec.NPatchCoarse, NCoarseElement, ec.iElementPatchCoarse, extractElements=False) TCoarsepIndexMap = util.extractElementFine(ec.NPatchCoarse, np.ones_like(NCoarseElement), ec.iElementPatchCoarse, extractElements=False) APatchFine = fem.assemblePatchMatrix(ec.NPatchCoarse*NCoarseElement, world.ALocFine, aPatch) AElementFine = fem.assemblePatchMatrix(NCoarseElement, world.ALocFine, aPatch[TFinetIndexMap]) basisPatch = fem.assembleProlongationMatrix(ec.NPatchCoarse, NCoarseElement) correctorsPatch = np.column_stack(ec.fsi.correctorsList) localBasis = world.localBasis KmsijShouldBe = -basisPatch.T*(APatchFine*(correctorsPatch)) KmsijShouldBe[TCoarsepIndexMap,:] += np.dot(localBasis.T, AElementFine*localBasis) self.assertTrue(np.isclose(np.max(np.abs(ec.csi.Kmsij-KmsijShouldBe)), 0))
def test_testCsi_Kmsij(self): NWorldCoarse = np.array([4, 5, 6]) NCoarseElement = np.array([5, 2, 3]) world = World(NWorldCoarse, NCoarseElement) d = np.size(NWorldCoarse) k = 1 iElementWorldCoarse = np.array([2, 1, 2]) TInd = util.convertpCoordIndexToLinearIndex(NWorldCoarse, iElementWorldCoarse) patch = Patch(world, k, TInd) IPatch = interp.L2ProjectionPatchMatrix(patch) NtPatch = patch.NtFine np.random.seed(1) aPatch = np.random.rand(NtPatch) basisCorrectorsList = lod.computeBasisCorrectors(patch, IPatch, aPatch) csi = lod.computeBasisCoarseQuantities(patch, basisCorrectorsList, aPatch) TFinetIndexMap = util.extractElementFine(patch.NPatchCoarse, NCoarseElement, patch.iElementPatchCoarse, extractElements=True) TFinepIndexMap = util.extractElementFine(patch.NPatchCoarse, NCoarseElement, patch.iElementPatchCoarse, extractElements=False) TCoarsepIndexMap = util.extractElementFine(patch.NPatchCoarse, np.ones_like(NCoarseElement), patch.iElementPatchCoarse, extractElements=False) APatchFine = fem.assemblePatchMatrix(patch.NPatchFine, world.ALocFine, aPatch) AElementFine = fem.assemblePatchMatrix(NCoarseElement, world.ALocFine, aPatch[TFinetIndexMap]) basisPatch = fem.assembleProlongationMatrix(patch.NPatchCoarse, NCoarseElement) correctorsPatch = np.column_stack(basisCorrectorsList) localBasis = world.localBasis KmsijShouldBe = -basisPatch.T*(APatchFine*(correctorsPatch)) KmsijShouldBe[TCoarsepIndexMap,:] += np.dot(localBasis.T, AElementFine*localBasis) self.assertTrue(np.isclose(np.max(np.abs(csi.Kmsij-KmsijShouldBe)), 0))
def test_fullPatch(self): NWorldCoarse = np.array([3,3]) NCoarseElement = np.array([2,2]) world = World(NWorldCoarse, NCoarseElement) k = 3 patchT = [Patch(world, k, TInd) for TInd in range(world.NtCoarse)] basisCorrectorsListT = [[np.zeros(world.NpFine), np.zeros(world.NpFine), np.zeros(world.NpFine), np.zeros(world.NpFine)] for i in range(world.NtCoarse)] # Set first and last corrector to constant 1 and 2 basisCorrectorsListT[0][0][:] = 1 basisCorrectorsListT[-1][-1][:] = 2 basisCorrectors = pglod.assembleBasisCorrectors(world, patchT, basisCorrectorsListT) self.assertTrue(np.allclose(basisCorrectors.todense()[:,0], 1)) self.assertTrue(np.allclose(basisCorrectors.todense()[:,-1], 2))
def computeAvgVelocitiesTF(NFluxElement): fluxWorld = World(NWorldFine / NFluxElement, NFluxElement, boundaryConditions) if True: avgFluxTF = transport.computeHarmonicMeanFaceFlux( fluxWorld.NWorldCoarse, fluxWorld.NWorldCoarse, NFluxElement, aBase, uFull) avgFluxTF = transport.computeAverageFaceFlux( fluxWorld.NWorldCoarse, avgFluxTF) conservativeFluxTF = transport.computeConservativeFlux( fluxWorld, avgFluxTF) if False: avgFluxTF = transport.computeElementFaceFlux( fluxWorld.NWorldCoarse, fluxWorld.NWorldCoarse, NFluxElement, aBase, uFull) avgFluxTF = transport.computeAverageFaceFlux( fluxWorld.NWorldCoarse, avgFluxTF) return avgFluxTF, conservativeFluxTF
def test_ritzProjectionToFinePatchBoundaryConditions(self): NPatchCoarse = np.array([4, 4]) NCoarseElement = np.array([10, 10]) world = World(NPatchCoarse, NCoarseElement) patch = Patch(world, 4, 0) NPatchFine = NPatchCoarse*NCoarseElement NpFine = np.prod(NPatchFine + 1) APatchFull = fem.assemblePatchMatrix(NPatchCoarse*NCoarseElement, world.ALocFine) bPatchFullList = [np.ones(NpFine)] fixed = util.boundarypIndexMap(NPatchFine) for IPatch in [interp.L2ProjectionPatchMatrix(patch), interp.nodalPatchMatrix(patch)]: schurComplementSolver = lod.SchurComplementSolver() schurComplementSolution = lod.ritzProjectionToFinePatch(patch, APatchFull, bPatchFullList, IPatch, schurComplementSolver)[0] self.assertTrue(np.isclose(np.max(np.abs(schurComplementSolution[fixed])), 0))
def test_smallPatch(self): NWorldCoarse = np.array([3,3]) NCoarseElement = np.array([2,2]) world = World(NWorldCoarse, NCoarseElement) k = 0 patchT = [Patch(world, k, TInd) for TInd in range(world.NtCoarse)] basisCorrectorsListT = [[np.zeros(patchT[0].NpFine), np.zeros(patchT[0].NpFine), np.zeros(patchT[0].NpFine), np.zeros(patchT[0].NpFine)] for i in range(world.NtCoarse)] # Set first and last corrector to constant 1 and 2 basisCorrectorsListT[0][0][:] = 1 basisCorrectorsListT[-1][-1][:] = 2 basisCorrectors = pglod.assembleBasisCorrectors(world, patchT, basisCorrectorsListT) firstBasisCorrectorShouldBe = np.array([1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) lastBasisCorrectorShouldBe = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0, 2, 2, 2, 0, 0, 0, 0, 2, 2, 2]) self.assertTrue(np.allclose(basisCorrectors.todense()[:,0].squeeze(), firstBasisCorrectorShouldBe)) self.assertTrue(np.allclose(basisCorrectors.todense()[:,-1].squeeze(), lastBasisCorrectorShouldBe))
def test_computeSingleT(self): NWorldCoarse = np.array([4, 5, 6]) NCoarseElement = np.array([5, 2, 3]) world = World(NWorldCoarse, NCoarseElement) d = np.size(NWorldCoarse) k = 1 iElementWorldCoarse = np.array([2, 1, 2]) TInd = util.convertpCoordIndexToLinearIndex(NWorldCoarse, iElementWorldCoarse) patch = Patch(world, k, TInd) IPatch = interp.L2ProjectionPatchMatrix(patch) NtPatch = patch.NtFine aPatch = np.ones(NtPatch) basisCorrectorsList = lod.computeBasisCorrectors(patch, IPatch, aPatch) correctorSum = reduce(np.add, basisCorrectorsList) self.assertTrue(np.allclose(correctorSum, 0)) csi = lod.computeBasisCoarseQuantities(patch, basisCorrectorsList, aPatch) # Test that the matrices have the constants in their null space #self.assertTrue(np.allclose(np.sum(ec.csi.LTPrimeij, axis=1), 0)) #self.assertTrue(np.allclose(np.sum(ec.csi.LTPrimeij, axis=2), 0)) self.assertTrue(np.allclose(np.sum(csi.Kij, axis=0), 0)) self.assertTrue(np.allclose(np.sum(csi.Kij, axis=1), 0)) self.assertTrue(np.allclose(np.sum(csi.Kmsij, axis=0), 0)) self.assertTrue(np.allclose(np.sum(csi.Kmsij, axis=1), 0)) # I had difficulties come up with test cases here. This test # verifies that most "energy" is in the element T. elementTIndex = util.convertpCoordIndexToLinearIndex(patch.NPatchCoarse-1, patch.iElementPatchCoarse) self.assertTrue(np.all(csi.muTPrime[elementTIndex] >= csi.muTPrime)) self.assertTrue(not np.all(csi.muTPrime[elementTIndex+1] >= csi.muTPrime))
def standard_method(world, N, fine, tau, tot_time_steps, k, aFine, bFine, f): # coarse mesh parameters NWorldCoarse = np.array([N, N]) NFine = np.array([fine, fine]) NpFine = np.prod(NFine + 1) NCoarseElement = NFine // NWorldCoarse NWorldFine = world.NWorldCoarse * world.NCoarseElement bc = world.boundaryConditions world = World(NWorldCoarse, NCoarseElement, bc) NpCoarse = np.prod(NWorldCoarse + 1) def IPatchGenerator(i, N): return interp.L2ProjectionPatchMatrix(i, N, NWorldCoarse, NCoarseElement, bc) b_coef = coef.coefficientFine(NWorldCoarse, NCoarseElement, bFine) a_coef = coef.coefficientFine(NWorldCoarse, NCoarseElement, aFine / tau) # compute basis correctors lod = lod_wave.LodWave(b_coef, world, k, IPatchGenerator, a_coef) lod.compute_basis_correctors() # compute ms basis basis = fem.assembleProlongationMatrix(NWorldCoarse, NCoarseElement) basis_correctors = lod.assembleBasisCorrectors() ms_basis = basis - basis_correctors # compute finescale solution correctors prev_fs_sol = ms_basis fs_solutions_new = [] for i in range(tot_time_steps): print('Calculating correction at N = %d, i = %d' % (N, i)) # solve localized system lod = lod_wave.LodWave(b_coef, world, k, IPatchGenerator, a_coef, prev_fs_sol) lod.solve_fs_system(localized=True) # store sparse solution prev_fs_sol = sparse.csc_matrix(np.array(np.column_stack(lod.fs_list))) fs_solutions_new.append(prev_fs_sol) # initial value Uo = np.zeros(NpCoarse) # coarse v^(-1) and v^0 V = [Uo] V.append(Uo) # compute ms matrices S = fem.assemblePatchMatrix(NWorldFine, world.ALocFine, aFine) K = fem.assemblePatchMatrix(NWorldFine, world.ALocFine, bFine) M = fem.assemblePatchMatrix(NWorldFine, world.MLocFine) free = util.interiorpIndexMap(NWorldCoarse) SmsFree = (ms_basis.T * S * ms_basis)[free][:, free] KmsFree = (ms_basis.T * K * ms_basis)[free][:, free] MmsFree = (ms_basis.T * M * ms_basis)[free][:, free] # load vector f = np.ones(NpFine) LmsFree = (ms_basis.T * M * f)[free] RmsFreeList = [] for i in range(tot_time_steps): n = i + 1 # linear system A = (1. / (tau ** 2)) * MmsFree + (1. / tau) * SmsFree + KmsFree b = LmsFree + (1. / tau) * SmsFree * V[n][free] + (2. / (tau ** 2)) * MmsFree * V[n][free] \ - (1. / (tau ** 2)) * MmsFree * V[n - 1][free] # store ms matrix R^{ms',h}_{H,i,k} RmsFull = ms_basis.T * S * sparse.csc_matrix(fs_solutions_new[i]) RmsFree = RmsFull[free][:, free] RmsFreeList.append(RmsFree) # add sum to linear system if i != 0: for j in range(i): b += (1. / tau) * RmsFreeList[j] * V[n - 1 - j][free] # solve system VFree = linalg.linSolve(A, b) VFull = np.zeros(NpCoarse) VFull[free] = VFree # append solution for current time step V.append(VFull) VFine = ms_basis * V[-1] WFine = 0 for j in range(tot_time_steps): WFine += sparse.csc_matrix(fs_solutions_new[j]) * V[n - j] return VFine + WFine, ms_basis * Uo
def standard_lod(world, N, fine, tau, tot_time_steps, k, aFine, bFine, f, damp_corr=False, both_coef=False): # mesh parameters NWorldCoarse = np.array([N, N]) NFine = np.array([fine, fine]) NCoarseElement = NFine // NWorldCoarse NWorldFine = world.NWorldCoarse * world.NCoarseElement bc = world.boundaryConditions world = World(NWorldCoarse, NCoarseElement, bc) def IPatchGenerator(i, N): return interp.L2ProjectionPatchMatrix(i, N, NWorldCoarse, NCoarseElement, bc) b_coef = coef.coefficientFine(NWorldCoarse, NCoarseElement, bFine) a_coef = coef.coefficientFine(NWorldCoarse, NCoarseElement, aFine / tau) NpCoarse = np.prod(NWorldCoarse + 1) basis = fem.assembleProlongationMatrix(NWorldCoarse, NCoarseElement) # compute basis correctors if damp_corr: b_coef = coef.coefficientFine(NWorldCoarse, NCoarseElement, np.zeros_like(bFine)) a_coef = coef.coefficientFine(NWorldCoarse, NCoarseElement, aFine / tau) elif both_coef: b_coef = coef.coefficientFine(NWorldCoarse, NCoarseElement, bFine) a_coef = coef.coefficientFine(NWorldCoarse, NCoarseElement, aFine) else: a_coef = coef.coefficientFine(NWorldCoarse, NCoarseElement, np.zeros_like(aFine)) b_coef = coef.coefficientFine(NWorldCoarse, NCoarseElement, bFine) lod = lod_wave.LodWave(b_coef, world, k, IPatchGenerator, a_coef) lod.compute_basis_correctors() # compute ms basis basis = fem.assembleProlongationMatrix(NWorldCoarse, NCoarseElement) basis_correctors = lod.assembleBasisCorrectors() mod_basis = basis - basis_correctors Uo = np.zeros(NpCoarse) # coarse v^(-1) and v^0 V = [Uo] V.append(Uo) # compute ms matrices S = fem.assemblePatchMatrix(NWorldFine, world.ALocFine, aFine) K = fem.assemblePatchMatrix(NWorldFine, world.ALocFine, bFine) M = fem.assemblePatchMatrix(NWorldFine, world.MLocFine) free = util.interiorpIndexMap(NWorldCoarse) SmsFree = (mod_basis.T * S * mod_basis)[free][:, free] KmsFree = (mod_basis.T * K * mod_basis)[free][:, free] MmsFree = (mod_basis.T * M * mod_basis)[free][:, free] LmsFree = (mod_basis.T * M * f)[free] for i in range(tot_time_steps): n = i + 1 # linear system A = (1. / (tau ** 2)) * MmsFree + (1. / tau) * SmsFree + KmsFree b = LmsFree + (1. / tau) * SmsFree * V[n][free] + (2. / (tau ** 2)) * MmsFree * V[n][free] \ - (1. / (tau ** 2)) * MmsFree * V[n - 1][free] # solve system VFree = linalg.linSolve(A, b) VFull = np.zeros(NpCoarse) VFull[free] = VFree # append solution for current time step V.append(VFull) return mod_basis * V[-1]
def test_pgtransport(self): NWorldCoarse = np.array([16, 16]) NCoarseElement = np.array([8, 8]) NWorldFine = NWorldCoarse * NCoarseElement boundaryConditions = np.array([[1, 1], [0, 0]]) d = 2 world = World(NWorldCoarse, NCoarseElement, boundaryConditions) # Load coefficient aLogBase = np.loadtxt( os.path.dirname(os.path.realpath(__file__)) + '/data/randomfield64x64') #aBase = np.loadtxt(os.path.dirname(os.path.realpath(__file__)) + '/data/upperness_x.txt') #aBase = aBase[:60*220] #aLogBase = np.random.rand(128*128) aBase = np.exp(3 * aLogBase) drawCoefficient(NWorldFine, aBase) plt.title('a') # Compute coordinates coordsFine = util.pCoordinates(NWorldFine) xFine = coordsFine[:, 0] yFine = coordsFine[:, 1] # Compute fixed and free dofs allDofs = np.arange(world.NpFine) fixed = util.boundarypIndexMap(NWorldFine, boundaryConditions == 0) free = np.setdiff1d(allDofs, fixed) # Compute matrices AFull = fem.assemblePatchMatrix(NWorldFine, world.ALocFine, aBase) A = AFull[free][:, free] # Compute rhs gFine = 1 - yFine bFull = -AFull * gFine b = bFull[free] # Solve fine system u0Free = sparse.linalg.spsolve(A, b) u0Full = np.zeros(world.NpFine) u0Full[free] = u0Free uFull = u0Full + gFine ## First, compute flux on fine mesh def computeAvgVelocitiesTF(NFluxElement): fluxWorld = World(NWorldFine / NFluxElement, NFluxElement, boundaryConditions) if True: avgFluxTF = transport.computeHarmonicMeanFaceFlux( fluxWorld.NWorldCoarse, fluxWorld.NWorldCoarse, NFluxElement, aBase, uFull) avgFluxTF = transport.computeAverageFaceFlux( fluxWorld.NWorldCoarse, avgFluxTF) conservativeFluxTF = transport.computeConservativeFlux( fluxWorld, avgFluxTF) if False: avgFluxTF = transport.computeElementFaceFlux( fluxWorld.NWorldCoarse, fluxWorld.NWorldCoarse, NFluxElement, aBase, uFull) avgFluxTF = transport.computeAverageFaceFlux( fluxWorld.NWorldCoarse, avgFluxTF) return avgFluxTF, conservativeFluxTF avgFluxTF, conservativeFluxTF = computeAvgVelocitiesTF(NCoarseElement) avgFluxtf, conservativeFluxtf = computeAvgVelocitiesTF( np.ones_like(NCoarseElement)) def fractionalFlow(s): return s**3 boundarys = np.array([[0, 0], [1, 0]]) sT = np.zeros(world.NtCoarse) st = np.zeros(world.NtFine) nTime = 1e5 endTime = 1 dTime = endTime / float(nTime) volt = np.prod(1. / world.NWorldFine) volT = np.prod(1. / world.NWorldCoarse) plt.figure() h1 = plt.gcf().number plt.figure() h2 = plt.gcf().number plt.figure() h3 = plt.gcf().number for timeStep in np.arange(nTime): def computeElementNetFluxT(NFluxElement, avgFluxTF, sT): fluxWorld = World(NWorldFine / NFluxElement, NFluxElement, boundaryConditions) netFluxT = transport.computeElementNetFlux( fluxWorld, avgFluxTF, sT, boundarys, fractionalFlow) return netFluxT netFluxT = computeElementNetFluxT(NCoarseElement, conservativeFluxTF, sT) netFluxt = computeElementNetFluxT(np.ones_like(NCoarseElement), conservativeFluxtf, st) sT = sT + dTime / volT * netFluxT #sT[sT > 1] = 1. #sT[sT < 0] = 0. st = st + dTime / volt * netFluxt #st[st > 1] = 1. #st[st < 0] = 0. if timeStep % 1000 == 0 or timeStep == nTime - 1: plt.figure(h1) drawSaturation(NWorldCoarse, sT) plt.title('sT') plt.gcf().canvas.draw() plt.figure(h2) drawSaturation(NWorldFine, st) plt.title('st') plt.gcf().canvas.draw() plt.figure(h3) stProjected = projectSaturation(NWorldCoarse, NCoarseElement, st) drawSaturation(NWorldCoarse, stProjected) plt.title('st projected') plt.gcf().canvas.draw() print np.sqrt(np.mean((stProjected - sT)**2)) plt.pause(0.0001) plt.show()
import numpy as np import scipy.sparse as sparse import matplotlib.pyplot as plt from gridlod import util, fem, coef, interp from gridlod.world import World import lod_wave # fine mesh parameters fine = 1024 NFine = np.array([fine]) NpFine = np.prod(NFine + 1) boundaryConditions = np.array([[0, 0]]) world = World(NFine, NFine // NFine, boundaryConditions) NWorldFine = world.NWorldCoarse * world.NCoarseElement # fine grid elements and nodes xt = util.tCoordinates(NFine).flatten() xp = util.pCoordinates(NFine).flatten() # time step parameters tau = 0.1 numTimeSteps = 10 # ms coefficients epsA = 2 ** (-4) epsB = 2 ** (-6) aFine = (2 - np.sin(2 * np.pi * xt / epsA)) ** (-1) bFine = (2 - np.cos(2 * np.pi * xt / epsB)) ** (-1) k_0 = np.inf k_1 = k_0
def test_computeCoarseErrorIndicatorFlux(self): NWorldCoarse = np.array([7, 7], dtype='int64') NCoarseElement = np.array([10, 10], dtype='int64') NWorldFine = NWorldCoarse * NCoarseElement NpWorldFine = np.prod(NWorldFine + 1) NpWorldCoarse = np.prod(NWorldCoarse + 1) NtWorldFine = np.prod(NWorldCoarse * NCoarseElement) NtWorldCoarse = np.prod(NWorldCoarse) np.random.seed(0) world = World(NWorldCoarse, NCoarseElement) d = np.size(NWorldCoarse) aBase = np.exp(np.random.rand(NtWorldFine)) k = np.max(NWorldCoarse) iElementWorldCoarse = np.array([3, 3]) rCoarseFirst = 1 + 3 * np.random.rand(NtWorldCoarse) coefFirst = coef.CoefficientCoarseFactor(NWorldCoarse, NCoarseElement, aBase, rCoarseFirst) IPatchGenerator = lambda i, N: interp.L2ProjectionPatchMatrix( i, N, NWorldCoarse, NCoarseElement) ec = lod_flux.CoarseBasisElementCorrectorFlux(world, k, iElementWorldCoarse, IPatchGenerator) ec.computeCorrectors(coefFirst) ec.computeCoarseQuantities() # If both rCoarseFirst and rCoarseSecond are equal, the error indicator should be zero rCoarseSecond = np.array(rCoarseFirst) self.assertTrue( np.isclose(ec.computeCoarseErrorIndicatorFlux(rCoarseSecond), 0)) coefSecond = coef.CoefficientCoarseFactor(NWorldCoarse, NCoarseElement, aBase, rCoarseSecond) self.assertTrue(np.isclose(ec.computeErrorIndicatorFine(coefSecond), 0)) # If rCoarseSecond is not rCoarseFirst, the error indicator should not be zero rCoarseSecond = 2 * np.array(rCoarseFirst) self.assertTrue( ec.computeCoarseErrorIndicatorFlux(rCoarseSecond) >= 0.1) coefSecond = coef.CoefficientCoarseFactor(NWorldCoarse, NCoarseElement, aBase, rCoarseSecond) self.assertTrue(ec.computeErrorIndicatorFine(coefSecond) >= 0.1) # Fine should be smaller than coarse estimate self.assertTrue( ec.computeErrorIndicatorFine(coefSecond) < ec.computeCoarseErrorIndicatorFlux(rCoarseSecond)) # If rCoarseSecond is different in the element itself, the error # indicator should be large elementCoarseIndex = util.convertpCoordIndexToLinearIndex( NWorldCoarse - 1, iElementWorldCoarse) rCoarseSecond = np.array(rCoarseFirst) rCoarseSecond[elementCoarseIndex] *= 2 saveForNextTest = ec.computeCoarseErrorIndicatorFlux(rCoarseSecond) self.assertTrue(saveForNextTest >= 0.1) coefSecond = coef.CoefficientCoarseFactor(NWorldCoarse, NCoarseElement, aBase, rCoarseSecond) fineResult = ec.computeErrorIndicatorFine(coefSecond) self.assertTrue(fineResult >= 0.1) self.assertTrue( ec.computeErrorIndicatorFine(coefSecond) < ec.computeCoarseErrorIndicatorFlux(rCoarseSecond)) # A difference in the perifery should be smaller than in the center rCoarseSecond = np.array(rCoarseFirst) rCoarseSecond[0] *= 2 self.assertTrue( saveForNextTest > ec.computeCoarseErrorIndicatorFlux(rCoarseSecond) ) # Again, but closer rCoarseSecond = np.array(rCoarseFirst) rCoarseSecond[elementCoarseIndex - 1] *= 2 self.assertTrue( saveForNextTest > ec.computeCoarseErrorIndicatorFlux(rCoarseSecond) )
import numpy as np import matplotlib.pyplot as plt from gridlod.world import World from math import log from methods import reference_sol, rb_method_sparse_stop # fine mesh set up fine = 256 NFine = np.array([fine, fine]) NpFine = np.prod(NFine + 1) boundaryConditions = np.array([[0, 0], [0, 0]]) world = World(NFine, NFine // NFine, boundaryConditions) # parameters tau = 0.02 Nlist = [64] tot_time_steps = 50 n = 2 no_rb_vecs = tot_time_steps np.random.seed(0) # ms coefficient A A = np.kron( np.random.rand(fine // n, fine // n) * 999.9 + 0.1, np.ones((n, n))) aFine = A.flatten() # ms coefficient B B = np.kron( np.random.rand(fine // n, fine // n) * 999.9 + 0.1, np.ones((n, n))) bFine = B.flatten()
def rb_method_sparse_stop(world, N, fine, tau, tot_time_steps, k, aFine, bFine, f, no_rb_vecs, TOL=None): # coarse mesh parameters NWorldCoarse = np.array([N, N]) NFine = np.array([fine, fine]) NpFine = np.prod(NFine + 1) NCoarseElement = NFine // NWorldCoarse NWorldFine = world.NWorldCoarse * world.NCoarseElement bc = world.boundaryConditions world = World(NWorldCoarse, NCoarseElement, bc) if TOL is None: TOL = 1e-6 NpCoarse = np.prod(NWorldCoarse + 1) def IPatchGenerator(i, N): return interp.L2ProjectionPatchMatrix(i, N, NWorldCoarse, NCoarseElement, bc) b_coef = coef.coefficientFine(NWorldCoarse, NCoarseElement, bFine) a_coef = coef.coefficientFine(NWorldCoarse, NCoarseElement, aFine / tau) # compute basis correctors lod = lod_wave.LodWave(b_coef, world, k, IPatchGenerator, a_coef) lod.compute_basis_correctors() # compute ms basis basis = fem.assembleProlongationMatrix(NWorldCoarse, NCoarseElement) basis_correctors = lod.assembleBasisCorrectors() ms_basis = basis - basis_correctors fs_solutions_new = [sparse.csc_matrix(np.zeros_like(ms_basis.toarray())) for i in range(tot_time_steps)] for node in range(NpCoarse): prev_fs_sol_new = ms_basis[:, node] snapshots = [] for time_step in range(no_rb_vecs): print('Calculating correction at N = %d, node = %d/%d, time_step = %d' % (N, node, NpCoarse, time_step)) node_index_arr = compute_2d_node(world.NWorldCoarse, node) ecT = lod_node.nodeCorrector(world, k, node_index_arr) b_patch = b_coef.localize(ecT.iPatchWorldCoarse, ecT.NPatchCoarse) a_patch = a_coef.localize(ecT.iPatchWorldCoarse, ecT.NPatchCoarse) IPatch = IPatchGenerator(ecT.iPatchWorldCoarse, ecT.NPatchCoarse) fs_list = ecT.compute_localized_node_correction_test(b_patch, a_patch, IPatch, prev_fs_sol_new, node) prev_fs_sol_new = sparse.csr_matrix(fs_list).T fs_solutions_new[time_step][:, node] = prev_fs_sol_new snapshots.append(fs_list) V = sparse.csc_matrix(gram_schmidt_rb(snapshots, TOL)) if V.get_shape()[0] == time_step: break for i in range(time_step + 1, tot_time_steps): fs_solutions_new[i][:, node] = sparse.csc_matrix(V.T * ecT.compute_rb_node_correction_test(b_patch, a_patch, IPatch, fs_solutions_new[i-1][:, node], V)).T # initial value Uo = np.zeros(NpCoarse) # coarse v^(-1) and v^0 V = [Uo] V.append(Uo) # compute ms matrices S = fem.assemblePatchMatrix(NWorldFine, world.ALocFine, aFine) K = fem.assemblePatchMatrix(NWorldFine, world.ALocFine, bFine) M = fem.assemblePatchMatrix(NWorldFine, world.MLocFine) free = util.interiorpIndexMap(NWorldCoarse) SmsFree = (ms_basis.T * S * ms_basis)[free][:, free] KmsFree = (ms_basis.T * K * ms_basis)[free][:, free] MmsFree = (ms_basis.T * M * ms_basis)[free][:, free] # load vector f = np.ones(NpFine) LmsFree = (ms_basis.T * M * f)[free] RmsFreeList = [] for i in range(tot_time_steps): n = i + 1 # linear system A = (1. / (tau ** 2)) * MmsFree + (1. / tau) * SmsFree + KmsFree b = LmsFree + (1. / tau) * SmsFree * V[n][free] + (2. / (tau ** 2)) * MmsFree * V[n][free] \ - (1. / (tau ** 2)) * MmsFree * V[n - 1][free] # store ms matrix R^{ms',h}_{H,i,k} RmsFull = ms_basis.T * S * sparse.csc_matrix(fs_solutions_new[i]) RmsFree = RmsFull[free][:, free] RmsFreeList.append(RmsFree) # add sum to linear system if i != 0: for j in range(i): b += (1. / tau) * RmsFreeList[j] * V[n - 1 - j][free] # solve system VFree = linalg.linSolve(A, b) VFull = np.zeros(NpCoarse) VFull[free] = VFree # append solution for current time step V.append(VFull) VFine = ms_basis * V[-1] WFine = 0 for j in range(tot_time_steps): WFine += sparse.csc_matrix(fs_solutions_new[j]) * V[n - j] return VFine + WFine, ms_basis * Uo
import scipy.sparse as sparse import matplotlib.pyplot as plt from gridlod import util, fem, coef, interp, linalg from gridlod.world import World import lod_wave ''' Settings ''' # fine mesh parameters fine = 256 NFine = np.array([fine]) NpFine = np.prod(NFine + 1) boundaryConditions = np.array([[0, 0]]) world = World(np.array([fine]), NFine / np.array([fine]), boundaryConditions) NWorldFine = world.NWorldCoarse * world.NCoarseElement # fine grid elements and nodes xt = util.tCoordinates(NFine).flatten() xp = util.pCoordinates(NFine).flatten() # time step parameters tau = 0.01 numTimeSteps = 100 # ms coefficients epsA = 2 ** (-5) epsB = 2 ** (-5) aFine = (2 - np.sin(2 * np.pi * xt / epsA)) ** (-1) bFine = (2 - np.cos(2 * np.pi * xt / epsB)) ** (-1)
def test_computeErrorIndicatorFine_zeroT(self): ## Setup # 2D, variables x0 and x1 NCoarse = np.array([4, 3]) NCoarseElement = np.array([2, 3]) world = World(NCoarse, NCoarseElement) patch = Patch(world, 4, 0) NFine = NCoarse*NCoarseElement # Let functions = [x1, 2*x2] def computeFunctions(): pc = util.pCoordinates(NFine) x1 = pc[:,0] x2 = pc[:,1] return [x1, 2*x2] # Mock corrector Q = functions correctorsList = computeFunctions() elementFinepIndexMap = util.extractElementFine(NCoarse, NCoarseElement, 0*NCoarseElement, extractElements=False) elementFinetIndexMap = util.extractElementFine(NCoarse, NCoarseElement, 0*NCoarseElement, extractElements=True) # Let lambdas = functions too lambdasList = [f[elementFinepIndexMap] for f in computeFunctions()] ## Case # AOld = ANew = scalar 1 # Expect: Error indicator should be zero aOld = np.ones(world.NtFine, dtype=np.float64) aNew = aOld self.assertEqual(lod.computeErrorIndicatorFine(patch, lambdasList, correctorsList, aOld, aNew), 0) ## Case # AOld = scalar 1 # ANew = scalar 10 # Expect: Error indicator is sqrt of integral over 11 elements with value (10-1)**2/10**2 aOld = np.ones(world.NtFine, dtype=np.float64) aNew = 10*aOld self.assertAlmostEqual(lod.computeErrorIndicatorFine(patch, lambdasList, correctorsList, aOld, aNew), np.sqrt(11*(10-1)**2/10**2)) ## Case # AOld = scalar 1 # ANew = scalar 10 except in T where ANew = 1000 # Expect: Error indicator is like in previous case, but /10 aOld = np.ones(world.NtFine, dtype=np.float64) aNew = 10*aOld aNew[elementFinetIndexMap] = 1000 self.assertAlmostEqual(lod.computeErrorIndicatorFine(patch, lambdasList, correctorsList, aOld, aNew), 0.1*np.sqrt(11*(10-1)**2/10**2))
#fine World NWorldFine = np.array([256, 256]) NpFine = np.prod(NWorldFine+1) #coarse World NWorldCoarse = np.array([16,16]) NpCoarse = np.prod(NWorldCoarse+1) #ratio between Fine and Coarse NCoarseElement = NWorldFine//NWorldCoarse boundaryConditions = np.array([[0, 0], [0, 0]]) world = World(NWorldCoarse, NCoarseElement, boundaryConditions) #righthandside f = np.ones(NpCoarse) #coefficient CoefClass = buildcoef2d.Coefficient2d(NWorldFine, bg = 0.05, val = 1, length = 8, thick = 8, space = 8, probfactor = 1, right = 1, down = 0, diagr1 = 0,
def test_computeErrorIndicatorCoarseFromCoefficients(self): ## Setup # 2D, variables x0 and x1 NCoarse = np.array([4, 3]) NCoarseElement = np.array([2, 3]) world = World(NCoarse, NCoarseElement) patch = Patch(world, 4, 0) NFine = NCoarse*NCoarseElement NtCoarse = world.NtCoarse # muTPrime = 1, ..., NtCoarse muTPrime = np.arange(NtCoarse) + 1 ## Case # aOld = aNew = 1 # Expect: 0 error indicator aOld = np.ones(world.NtFine, dtype=np.float64) aNew = aOld self.assertAlmostEqual(lod.computeErrorIndicatorCoarseFromCoefficients(patch, muTPrime, aOld, aNew), 0) #### Same test for Matrix valued #### Aeye = np.tile(np.eye(2), [np.prod(NFine), 1, 1]) aNew = np.einsum('tji, t -> tji', Aeye, aNew) self.assertAlmostEqual(lod.computeErrorIndicatorCoarseFromCoefficients(patch, muTPrime, aOld, aNew), 0) ## Case # aOld = 1 # aNew = 10 # Expect: sqrt(1/10 * 1/10*(10-1)**2*1 * (NtCoarse)*(NtCoarse+1)/2) aOld = np.ones(world.NtFine, dtype=np.float64) aNew = 10*aOld self.assertAlmostEqual(lod.computeErrorIndicatorCoarseFromCoefficients(patch, muTPrime, aOld, aNew), np.sqrt(1/10 * 1/10*(10-1)**2*1 * (NtCoarse)*(NtCoarse+1)/2)) #### Same test for Matrix valued #### aNew = np.einsum('tji, t -> tji', Aeye, aNew) aOld = np.einsum('tji, t-> tji', Aeye, aOld) self.assertAlmostEqual(lod.computeErrorIndicatorCoarseFromCoefficients(patch, muTPrime, aOld, aNew), np.sqrt(1/10 * 1/10*(10-1)**2*1 * (NtCoarse)*(NtCoarse+1)/2)) ## Case # aOld = 1 # aNew = 1 except in TInd=2 (where muTPrime == 3), where it is 10 # Expect: sqrt(1 * 1/10*(10-1)**2*1 * 3) aOld = np.ones(world.NtFine, dtype=np.float64) aNew = np.ones(world.NtFine, dtype=np.float64) elementFinetIndexMap = util.extractElementFine(NCoarse, NCoarseElement, np.array([2, 0]), extractElements=True) aNew[elementFinetIndexMap] = 10 self.assertAlmostEqual(lod.computeErrorIndicatorCoarseFromCoefficients(patch, muTPrime, aOld, aNew), np.sqrt(1 * 1/10*(10-1)**2*1 * 3)) #### Same test for Matrix valued #### aOld = np.einsum('tji, t-> tji', Aeye, aOld) self.assertAlmostEqual(lod.computeErrorIndicatorCoarseFromCoefficients(patch, muTPrime, aOld, aNew), np.sqrt(1 * 1/10*(10-1)**2*1 * 3))