public static int[] GetCellsOfOverlappingTestBlock(MultigridMapping map) { List <int> testcells = new List <int>(); //find block with 4 neighbours for (int iCell = 0; iCell < map.LocalNoOfBlocks; iCell++) { int[] NC = map.AggGrid.iLogicalCells.CellNeighbours[iCell]; if (NC.Length == 4) { foreach (int c in NC) { if (c >= map.LocalNoOfBlocks) { testcells.Add(c); } else if (!map.IsLocalBlock(map.FirstBlock + c)) { testcells.Add(c); } } if (testcells.Count > 0) { testcells.Add(iCell); break; } } } Debug.Assert(testcells.Count > 0); return(testcells.ToArray()); }
public static void Init() { //GridCommons grd = Grid2D.Cartesian2DGrid(RandomSpacing(), RandomSpacing()); //grid = new GridData(Grid2D.Cartesian2DGrid(GenericBlas.Linspace(-7, 7, 8), GenericBlas.Linspace(-1, 1, 2))); //grid = new GridData(Grid2D.Cartesian2DGrid(new double[] { -6, -4, -2, 2, 4, 6 }, GenericBlas.Linspace(-1, 1, 2))); //if (curved) //{ // grid = Grid2D.CurvedSquareGrid(GenericBlas.Linspace(1, 2, 5), GenericBlas.Linspace(0, 1, 17), CellType.Square_9, true).GridData; //} //else //{ // grid = (Grid2D.Cartesian2DGrid(GenericBlas.Linspace(-1.5, 1.5, 17), GenericBlas.Linspace(-1.5, 1.5, 17))).GridData; //} grid = (Grid2D.Cartesian2DGrid(GenericBlas.Linspace(-1.5, 1.5, 17), GenericBlas.Linspace(-1.5, 1.5, 17))).GridData; MgSeq = CoarseningAlgorithms.CreateSequence(grid); for (int p = 0; p <= 3; p++) // loop over polynomial degrees... { var uMapping = new UnsetteledCoordinateMapping(new Basis(grid, p)); var MgMapSeq = new MultigridMapping[MgSeq.Length]; var BasisSeq = AggregationGridBasis.CreateSequence(MgSeq, uMapping.BasisS); for (int iLevel = 0; iLevel < MgSeq.Length; iLevel++) { MgMapSeq[iLevel] = new MultigridMapping(uMapping, BasisSeq[iLevel], new int[] { p }); } MultigrigMap.Add(p, MgMapSeq); } }
public static int[] GetAllExtCellIdc(MultigridMapping map) { var extC = GetAllExternalCells(map); List <int> extIdcL = new List <int>(); foreach (int eC in extC) { Debug.Assert(eC < map.AggGrid.iLogicalCells.NoOfExternalCells + map.AggGrid.iLogicalCells.NoOfLocalUpdatedCells); Debug.Assert(eC >= map.AggGrid.iLogicalCells.NoOfLocalUpdatedCells); int[] Idc = GetIndcOfExtCell(map, eC); extIdcL.AddRange(Idc); } int[] extIdc = extIdcL.ToArray(); Array.Sort(extIdc); #if Debug int[] fields = map.NoOfVariables.ForLoop(i => i); int[] GlobalIdxMap_ext = map.GetSubvectorIndices_Ext(fields); Array.Sort(GlobalIdxMap_ext); Debug.Assert(extIdc.Length == GlobalIdxMap_ext.Length); for (int iCell = 0; iCell < extIdc.Length; iCell++) { Debug.Assert(extIdc[iCell] == GlobalIdxMap_ext[iCell]); } #endif return(extIdc); }
public static void Init() { bool dummy; ilPSP.Environment.Bootstrap( new string[0], BoSSS.Solution.Application.GetBoSSSInstallDir(), out dummy); //GridCommons grd = Grid2D.Cartesian2DGrid(RandomSpacing(), RandomSpacing()); //grid = new GridData(Grid2D.Cartesian2DGrid(GenericBlas.Linspace(-7, 7, 8), GenericBlas.Linspace(-1, 1, 2))); //grid = new GridData(Grid2D.Cartesian2DGrid(new double[] { -6, -4, -2, 2, 4, 6 }, GenericBlas.Linspace(-1, 1, 2))); grid = new GridData(Grid2D.Cartesian2DGrid(GenericBlas.Linspace(-1.5, 1.5, 17), GenericBlas.Linspace(-1.5, 1.5, 17))); MgSeq = CoarseningAlgorithms.CreateSequence(grid); for (int p = 0; p <= 3; p++) // loop over polynomial degrees... { var uMapping = new UnsetteledCoordinateMapping(new Basis(grid, p)); var MgMapSeq = new MultigridMapping[MgSeq.Length]; var BasisSeq = AggregationGridBasis.CreateSequence(MgSeq, uMapping.BasisS); for (int iLevel = 0; iLevel < MgSeq.Length; iLevel++) { MgMapSeq[iLevel] = new MultigridMapping(uMapping, BasisSeq[iLevel], new int[] { p }); } MultigrigMap.Add(p, MgMapSeq); } }
/// <summary> /// Restricts some solution vector down to a certain multigrid level and prolongates it back. /// </summary> /// <param name="i"> /// Multigrid level index; usually 0 at start of recursion. /// </param> /// <param name="iEnd"> /// End level index. /// </param> /// <param name="mgOp"></param> /// <param name="FineIn"> /// Input; solution vector which will be restricted down to level <paramref name="iEnd"/>. /// </param> /// <param name="FineOut"> /// Output; vector <paramref name="FineIn"/> restricted to level <paramref name="iEnd"/>, and prolongated back to level <paramref name="i"/>. /// </param> static void XDG_Recursive(int i, int iEnd, MultigridOperator mgOp, double[] FineIn, double[] FineOut) { MultigridMapping mgMap = mgOp.Mapping; int Lfin = mgMap.LocalLength; int Lcrs = mgOp.CoarserLevel.Mapping.LocalLength; Assert.IsTrue(FineIn.Length == Lfin); Assert.IsTrue(FineOut.Length == Lfin); double[] Coarse1 = new double[Lcrs]; double[] Coarse2 = new double[Lcrs]; mgOp.CoarserLevel.Restrict(FineIn, Coarse1); if (i == iEnd) { Coarse2.SetV(Coarse1); } else { XDG_Recursive(i + 1, iEnd, mgOp.CoarserLevel, Coarse1, Coarse2); } mgOp.CoarserLevel.Prolongate(1.0, FineOut, 0.0, Coarse2); }
public static int[] GetAllExternalCells(MultigridMapping map) { int NoOfExternalCells = map.AggGrid.iLogicalCells.NoOfExternalCells; int offset = map.AggGrid.iLogicalCells.NoOfLocalUpdatedCells; int[] extcells = NoOfExternalCells.ForLoop(i => i + offset); return(extcells); }
public static void GetExternalRowsTest( [Values(XDGusage.none, XDGusage.all)] XDGusage UseXdg, [Values(2)] int DGOrder, [Values(4)] int Res) { //Matlabaufruf --> gesamte Matrix nach Matlab schreiben //Teilmatritzen gemäß Globalid extrahieren //Mit ExternalRows vergleichen //Die große Frage: funktioniert der batchmode connector parallel? Beim rausschreiben beachten Utils.TestInit((int)UseXdg, DGOrder); Console.WriteLine("GetExternalRowsTest({0},{1})", UseXdg, DGOrder); //Arrange --- setup mgo and mask MultigridOperator mgo = Utils.CreateTestMGOperator(UseXdg, DGOrder, MatrixShape.laplace, Res); MultigridMapping map = mgo.Mapping; BlockMsrMatrix M = mgo.OperatorMatrix; //Delete this plz ... //M.SaveToTextFileSparse("M"); //int[] A = Utils.GimmeAllBlocksWithSpec(map, 9); //int[] B = Utils.GimmeAllBlocksWithSpec(map, 18); //if (map.MpiRank == 0) { // A.SaveToTextFileDebug("ACells"); // B.SaveToTextFileDebug("BCells"); //} var selector = new SubBlockSelector(map); var dummy = new BlockMsrMatrix(map); // we are only interested in getting indices, so a dummy is sufficient var mask = new BlockMask(selector, dummy); //Arrange --- get stuff to put into matlab int[] GlobalIdx_ext = Utils.GetAllExtCellIdc(map); double[] GlobIdx = GlobalIdx_ext.Length.ForLoop(i => (double)GlobalIdx_ext[i] + 1.0); //Arrange --- get external rows by mask BlockMsrMatrix extrows = BlockMask.GetAllExternalRows(mgo.Mapping, mgo.OperatorMatrix); //Assert --- idc and rows of extrows have to be the same Assert.IsTrue(GlobIdx.Length == extrows._RowPartitioning.LocalLength); //Arrange --- get external rows by matlab var infNorm = MultidimensionalArray.Create(1, 1); using (BatchmodeConnector matlab = new BatchmodeConnector()) { //note: BatchmodeCon maybe working on proc0 but savetotxt file, etc. (I/O) is full mpi parallel //so concider this as full mpi-parallel matlab.PutSparseMatrix(M, "M"); matlab.PutSparseMatrix(extrows, "M_test"); matlab.PutVector(GlobIdx, "Idx"); matlab.Cmd(String.Format("M_ext = M(Idx, :);")); matlab.Cmd("n=norm(M_test-M_ext,inf)"); matlab.GetMatrix(infNorm, "n"); matlab.Execute(); } //Assert --- test if we actually got the right Matrix corresponding to Index Assert.IsTrue(infNorm[0, 0] == 0.0); }
public static int[] GetIdcOfSubBlock(MultigridMapping map, int[] cells) { List <int> idc = new List <int>(); foreach (int c in cells) { idc.AddRange(GetIndcOfExtCell(map, c)); } return(idc.ToArray()); }
public static void SubSelection( [Values(XDGusage.none, XDGusage.all)] XDGusage UseXdg, [Values(2)] int DGOrder, [Values(MatrixShape.full_var_spec, MatrixShape.full_spec, MatrixShape.full_var, MatrixShape.full)] MatrixShape MShape, [Values(4)] int Res) { Utils.TestInit((int)UseXdg, DGOrder, (int)MShape, Res); Console.WriteLine("SubSelection({0},{1},{2},{3})", UseXdg, DGOrder, MShape, Res); //Arrange --- create test matrix, MG mapping MultigridOperator mgo = Utils.CreateTestMGOperator(UseXdg, DGOrder, MShape, Res); MultigridMapping map = mgo.Mapping; BlockMsrMatrix M = mgo.OperatorMatrix; //Arrange --- get mask int[] cells = Utils.GetCellsOfOverlappingTestBlock(map); Array.Sort(cells); var sbs = new SubBlockSelector(map); sbs.CellSelector(cells, false); BlockMsrMatrix M_ext = BlockMask.GetAllExternalRows(map, M); var mask = new BlockMask(sbs, M_ext); //Arrange --- get GlobalIdxList int[] idc = Utils.GetIdcOfSubBlock(map, cells); bool[] coup = Utils.SetCoupling(MShape); var M_sub = mask.GetSubBlockMatrix(M, false, coup[0], coup[1]); var infNorm = MultidimensionalArray.Create(4, 1); int rank = map.MpiRank; using (BatchmodeConnector matlab = new BatchmodeConnector()) { double[] GlobIdx = idc.Count().ForLoop(i => (double)idc[i] + 1.0); Assert.IsTrue(GlobIdx.Length == M_sub.NoOfRows); matlab.PutSparseMatrix(M, "M"); // note: M_sub lives on Comm_Self, therefore we have to distinguish between procs ... matlab.PutSparseMatrixRankExclusive(M_sub, "M_sub"); matlab.PutVectorRankExclusive(GlobIdx, "Idx"); matlab.Cmd("M_0 = full(M(Idx_0, Idx_0));"); matlab.Cmd("M_1 = full(M(Idx_1, Idx_1));"); matlab.Cmd("M_2 = full(M(Idx_2, Idx_2));"); matlab.Cmd("M_3 = full(M(Idx_3, Idx_3));"); matlab.Cmd("n=[0; 0; 0; 0];"); matlab.Cmd("n(1,1)=norm(M_0-M_sub_0,inf);"); matlab.Cmd("n(2,1)=norm(M_1-M_sub_1,inf);"); matlab.Cmd("n(3,1)=norm(M_2-M_sub_2,inf);"); matlab.Cmd("n(4,1)=norm(M_3-M_sub_3,inf);"); matlab.GetMatrix(infNorm, "n"); matlab.Execute(); } Assert.IsTrue(infNorm[rank, 0] == 0.0); }
public static Dictionary <int, int[]> GetDictOfAllExtCellIdc(MultigridMapping map) { int[] cells = GetAllExternalCells(map); Dictionary <int, int[]> extDict = new Dictionary <int, int[]>(); foreach (int eC in cells) { int[] idc = GetIndcOfExtCell(map, eC); extDict.Add(eC, idc); } return(extDict); }
public static void VectorSplitOperation( [Values(XDGusage.none, XDGusage.all)] XDGusage UseXdg, [Values(2)] int DGOrder, [Values(MatrixShape.full_var_spec, MatrixShape.full_spec, MatrixShape.full)] MatrixShape MShape, [Values(4)] int Res) { Utils.TestInit((int)UseXdg, DGOrder, (int)MShape, Res); Console.WriteLine("VectorSplitOperation({0},{1},{2},{3})", UseXdg, DGOrder, MShape, Res); //Arrange --- create test matrix, MG mapping MultigridOperator mgo = Utils.CreateTestMGOperator(UseXdg, DGOrder, MShape, Res); MultigridMapping map = mgo.Mapping; BlockMsrMatrix M = mgo.OperatorMatrix; BlockMsrMatrix M_ext = BlockMask.GetAllExternalRows(map, M); double[] Vec = Utils.GetRandomVector(M_ext.RowPartitioning.LocalLength); //Arrange --- setup masking SubBlockSelector sbsA = new SubBlockSelector(map); sbsA.SetDefaultSplitSelection(MShape, true, false); BlockMask maskA = new BlockMask(sbsA, M_ext); SubBlockSelector sbsB = new SubBlockSelector(map); sbsB.SetDefaultSplitSelection(MShape, false, false); BlockMask maskB = new BlockMask(sbsB, M_ext); double[] VecAB = new double[Vec.Length]; //Arrange --- some time measurement Stopwatch stw = new Stopwatch(); stw.Reset(); //Act --- stw.Start(); var VecA = maskA.GetSubVec(Vec, new double[0]); var VecB = maskB.GetSubVec(Vec, new double[0]); maskA.AccSubVec(VecA, VecAB, new double[0]); maskB.AccSubVec(VecB, VecAB, new double[0]); stw.Stop(); Debug.Assert(Vec.L2Norm() != 0); double fac = ((MShape == MatrixShape.full_var || MShape == MatrixShape.diagonal_var) && UseXdg == XDGusage.none) ? -2.0 : -1.0; VecAB.AccV(fac, Vec); //Assert --- are extracted blocks and Assert.IsTrue(VecAB.L2Norm() == 0.0, String.Format("L2Norm neq 0!")); }
public static int[] GetIndcOfExtCell(MultigridMapping map, int jCell) { int Jup = map.AggGrid.iLogicalCells.NoOfLocalUpdatedCells; int i0 = map.GlobalUniqueIndex(0, jCell, 0); int fld = map.NoOfVariables; int N = 0; for (int iF = 0; iF < fld; iF++) { N += map.AggBasis[iF].GetLength(jCell, map.DgDegree[iF]); } int[] ret = N.ForLoop(i => i + i0); return(ret); }
public static int GetIdxOfFirstBlockWith(MultigridMapping map, bool ZwoSpec) { int maxLen = Math.Max(map.GetSubblkLen(0)[0], map.GetSubblkLen(1)[0]); int minLen = Math.Min(map.GetSubblkLen(0)[0], map.GetSubblkLen(1)[0]); int crit = ZwoSpec ? maxLen : minLen; for (int iCell = 0; iCell < map.LocalNoOfBlocks; iCell++) { int iBlock = iCell + map.AggGrid.CellPartitioning.i0; if (map.GetBlockLen(iBlock) == crit) { return(iCell); } } return(-1); }
public static void Init() { grid = Grid2D.CurvedSquareGrid(GenericBlas.Linspace(1, 2, 17), GenericBlas.Linspace(0, 1, 17), CellType.Square_9, true).GridData; MgSeq = CoarseningAlgorithms.CreateSequence(grid); for (int p = 0; p <= 3; p++) { // loop over polynomial degrees... var uMapping = new UnsetteledCoordinateMapping(new Basis(grid, p)); var MgMapSeq = new MultigridMapping[MgSeq.Length]; var BasisSeq = AggregationGridBasis.CreateSequence(MgSeq, uMapping.BasisS); for (int iLevel = 0; iLevel < MgSeq.Length; iLevel++) { MgMapSeq[iLevel] = new MultigridMapping(uMapping, BasisSeq[iLevel], new int[] { p }); } MultigrigMap.Add(p, MgMapSeq); } }
public static void SubMatrixExtractionWithCoupling( [Values(XDGusage.none, XDGusage.all)] XDGusage UseXdg, [Values(2)] int DGOrder, [Values(MatrixShape.diagonal, MatrixShape.diagonal_var, MatrixShape.full_spec, MatrixShape.full_var_spec)] MatrixShape MShape ) { Utils.TestInit((int)UseXdg, DGOrder, (int)MShape); Console.WriteLine("ExtractSubMatrixAndIgnoreCoupling({0},{1},{2})", UseXdg, DGOrder, MShape); //Arrange --- get multigridoperator MultigridOperator MGOp = Utils.CreateTestMGOperator(UseXdg, DGOrder, MShape); BlockMsrMatrix M = MGOp.OperatorMatrix; MultigridMapping map = MGOp.Mapping; //Arrange --- setup masking SubBlockSelector SBS = new SubBlockSelector(map); BlockMask mask = new BlockMask(SBS, null); bool[] coup = Utils.SetCoupling(MShape); //Arrange --- some time measurement Stopwatch stw = new Stopwatch(); stw.Reset(); //Act --- establish submatrix stw.Start(); //var Ones = M.CloneAs(); //Ones.Clear(); //Ones.SetAll(1); //var extractOnes = mask.GetSubBlockMatrix(Ones, false, coup[0], coup[1]); var Mext = mask.GetSubBlockMatrix(M, false, coup[0], coup[1]); stw.Stop(); var Mquad = M.ConvertToQuadraticBMsr(mask.GlobalIList_Internal.ToArray(), true); Mext.Acc(-1.0, Mquad); //Assert --- Mext conains only diagonal blocks of M Assert.IsTrue(Mext.InfNorm() == 0); }
private void Setup() { MgSeq = CoarseningAlgorithms.CreateSequence(m_grid.iGridData); int p = m_DGorder; var uMapping = new UnsetteledCoordinateMapping(u1.Basis, u2.Basis); //var uMapping = new UnsetteledCoordinateMapping(u1.Basis); //var uMapping = new UnsetteledCoordinateMapping(new Basis(m_grid.iGridData, p)); XAggB = AggregationGridBasis.CreateSequence(MgSeq, uMapping.BasisS); var bla = LsTrk.SpeciesIdS.ToArray(); var agg = LsTrk.GetAgglomerator(bla, m_quadOrder, THRESHOLD, AgglomerateNewborn: false, AgglomerateDecased: false, ExceptionOnFailedAgglomeration: true); XAggB.UpdateXdgAggregationBasis(agg); var VarDegrees = uMapping.BasisS.Count.ForLoop(i => uMapping.BasisS[i].Degree); MG_Mapping = new MultigridMapping(uMapping, XAggB[0], VarDegrees); map = uMapping; }
public static int[] GimmeAllBlocksWithSpec(MultigridMapping map, int DOF) { int Bi0 = map.AggGrid.CellPartitioning.i0; List <int> hits = new List <int>(); for (int i = 0; i < map.LocalNoOfBlocks; i++) { int iBlock = Bi0 + i; int type = map.GetBlockType(iBlock); int BlockDOF = map.GetSubblkLen(type)[0]; if (BlockDOF == DOF) { hits.Add(iBlock); } } int[] recvcnt = hits.Count().MPIAllGather(); Debug.Assert(recvcnt.Length == map.MpiSize); int[] VecOfAllhits = hits.ToArray().MPIAllGatherv(recvcnt); return(VecOfAllhits); }
public static void RestrictionOfSystemOpTest() { Basis B1 = new Basis(grid, 0), B2 = new Basis(grid, 2); var Map = new UnsetteledCoordinateMapping(B1, B2); var Lev0Basis = new AggregationGridBasis(B2, TestProgram.MgSeq[0]); var Lev1Basis = new AggregationGridBasis(B2, TestProgram.MgSeq[1]); var Lev0 = new MultigridMapping(Map, new AggregationGridBasis[] { Lev0Basis, Lev0Basis }, new int[] { B1.Degree, B2.Degree }); var Lev1 = new MultigridMapping(Map, new AggregationGridBasis[] { Lev1Basis, Lev1Basis }, new int[] { B1.Degree, B2.Degree }); int[] I0col = Lev0.GetSubvectorIndices(new int[] { 0 }); int[] I1col = Lev0.GetSubvectorIndices(new int[] { 1 }); int[] I0row = Lev1.GetSubvectorIndices(new int[] { 0 }); int[] I1row = Lev1.GetSubvectorIndices(new int[] { 1 }); var RestMtx = Lev1.FromOtherLevelMatrix(Lev0); MsrMatrix Rest00 = new MsrMatrix(I0row.Length, I0col.Length, 1, 1); RestMtx.WriteSubMatrixTo(Rest00, I0row, default(int[]), I0col, default(int[])); MsrMatrix Rest01 = new MsrMatrix(I0row.Length, I1col.Length, 1, 1); RestMtx.WriteSubMatrixTo(Rest01, I0row, default(int[]), I1col, default(int[])); MsrMatrix Rest10 = new MsrMatrix(I1row.Length, I0col.Length, 1, 1); RestMtx.WriteSubMatrixTo(Rest10, I1row, default(int[]), I0col, default(int[])); MsrMatrix Rest11 = new MsrMatrix(I1row.Length, I1col.Length, 1, 1); RestMtx.WriteSubMatrixTo(Rest11, I1row, default(int[]), I1col, default(int[])); Debug.Assert(Rest10.InfNorm() == 0.0); Debug.Assert(Rest01.InfNorm() == 0.0); Debug.Assert(Rest00.InfNorm() != 0.0); Debug.Assert(Rest11.InfNorm() != 0.0); }
public static void RestrictionOfSystemOpTest() { Basis B1 = new Basis(grid, 0), B2 = new Basis(grid, 2); var Map = new UnsetteledCoordinateMapping(B1, B2); AggregationGridBasis[][] aB = AggregationGridBasis.CreateSequence(TestProgram.MgSeq.Take(2), new Basis[] { B1, B2 }); var Lev0 = new MultigridMapping(Map, aB[0], new int[] { B1.Degree, B2.Degree }); var Lev1 = new MultigridMapping(Map, aB[1], new int[] { B1.Degree, B2.Degree }); int[] I0col = Lev0.GetSubvectorIndices(new int[] { 0 }); int[] I1col = Lev0.GetSubvectorIndices(new int[] { 1 }); int[] I0row = Lev1.GetSubvectorIndices(new int[] { 0 }); int[] I1row = Lev1.GetSubvectorIndices(new int[] { 1 }); var RestMtx = Lev1.FromOtherLevelMatrix(Lev0); MsrMatrix Rest00 = new MsrMatrix(I0row.Length, I0col.Length, 1, 1); RestMtx.WriteSubMatrixTo(Rest00, I0row, default(int[]), I0col, default(int[])); MsrMatrix Rest01 = new MsrMatrix(I0row.Length, I1col.Length, 1, 1); RestMtx.WriteSubMatrixTo(Rest01, I0row, default(int[]), I1col, default(int[])); MsrMatrix Rest10 = new MsrMatrix(I1row.Length, I0col.Length, 1, 1); RestMtx.WriteSubMatrixTo(Rest10, I1row, default(int[]), I0col, default(int[])); MsrMatrix Rest11 = new MsrMatrix(I1row.Length, I1col.Length, 1, 1); RestMtx.WriteSubMatrixTo(Rest11, I1row, default(int[]), I1col, default(int[])); Assert.IsTrue(Rest10.InfNorm() == 0.0); Assert.IsTrue(Rest01.InfNorm() == 0.0); Assert.IsTrue(Rest00.InfNorm() != 0.0); Assert.IsTrue(Rest11.InfNorm() != 0.0); }
public static void SubBlockExtraction( [Values(XDGusage.none, XDGusage.all)] XDGusage UseXdg, [Values(2)] int DGOrder, [Values(MatrixShape.diagonal_var_spec, MatrixShape.diagonal_spec, MatrixShape.diagonal_var, MatrixShape.diagonal)] MatrixShape MShape, [Values(4)] int Res ) { Utils.TestInit((int)UseXdg, DGOrder, (int)MShape); Console.WriteLine("SubMatrixIgnoreCoupling({0},{1},{2})", UseXdg, DGOrder, MShape); //Arrange --- create test matrix and MG mapping MultigridOperator mgo = Utils.CreateTestMGOperator(UseXdg, DGOrder, MShape, Res); MultigridMapping map = mgo.Mapping; BlockMsrMatrix M = mgo.OperatorMatrix; //Arrange --- masking of all external cells var sbs = new SubBlockSelector(map); sbs.AllExternalCellsSelection(); var M_ext = BlockMask.GetAllExternalRows(map, M); var mask = new BlockMask(sbs, M_ext); //bool[] coup = Utils.SetCoupling(MShape); //Arrange --- get index dictonary of all external cell indices Dictionary <int, int[]> Didc = Utils.GetDictOfAllExtCellIdc(map); //Arrange --- stopwatch var stw = new Stopwatch(); stw.Reset(); //Act --- Extract subblocks stw.Start(); //var eblocks = mask.GetSubBlocks(M,coup[0],coup[1],coup[2]); var eblocks = mask.GetDiagonalBlocks(M, false, false); stw.Stop(); //Assert --- same number of blocks? Assert.IsTrue(eblocks.Length == M_ext._RowPartitioning.LocalNoOfBlocks); bool test = eblocks.Length.MPIEquals(); Debug.Assert(test); for (int iBlock = 0; iBlock < eblocks.Length; iBlock++) { var infNorm = MultidimensionalArray.Create(4, 1); int rank = map.MpiRank; int ExtBlockIdx = iBlock + map.AggGrid.iLogicalCells.NoOfLocalUpdatedCells; Didc.TryGetValue(ExtBlockIdx, out int[] idc); using (BatchmodeConnector matlab = new BatchmodeConnector()) { double[] GlobIdx = idc.Count().ForLoop(i => (double)idc[i] + 1.0); Assert.IsTrue(GlobIdx.Length == eblocks[iBlock].Lengths[0]); MsrMatrix M_sub = eblocks[iBlock].ConvertToMsr(); matlab.PutSparseMatrix(M, "M"); // note: M_sub lives on Comm_Self, therefore we have to distinguish between procs ... matlab.PutSparseMatrixRankExclusive(M_sub, "M_sub"); matlab.PutVectorRankExclusive(GlobIdx, "Idx"); matlab.Cmd("M_0 = full(M(Idx_0, Idx_0));"); matlab.Cmd("M_1 = full(M(Idx_1, Idx_1));"); matlab.Cmd("M_2 = full(M(Idx_2, Idx_2));"); matlab.Cmd("M_3 = full(M(Idx_3, Idx_3));"); matlab.Cmd("n=[0; 0; 0; 0];"); matlab.Cmd("n(1,1)=norm(M_0-M_sub_0,inf);"); matlab.Cmd("n(2,1)=norm(M_1-M_sub_1,inf);"); matlab.Cmd("n(3,1)=norm(M_2-M_sub_2,inf);"); matlab.Cmd("n(4,1)=norm(M_3-M_sub_3,inf);"); matlab.GetMatrix(infNorm, "n"); matlab.Execute(); } Assert.IsTrue(infNorm[rank, 0] == 0.0); // } }
public static void XDG_MatrixPolynomialRestAndPrlgTest( [Values(0, 1, 2, 3)] int p, [Values(0.0, 0.3)] double AggregationThreshold, [Values(0, 1)] int TrackerWidth) { XQuadFactoryHelper.MomentFittingVariants variant = XQuadFactoryHelper.MomentFittingVariants.OneStepGaussAndStokes; var xt = new XDGTestSetup(p, AggregationThreshold, TrackerWidth, MultigridOperator.Mode.Eye, variant); // test matrix version of the restriction operator // ----------------------------------------------- List <MultigridMapping> MultigridMaps = new List <MultigridMapping>(); for (var mgop = xt.XdgMultigridOp; mgop != null; mgop = mgop.CoarserLevel) { MultigridMaps.Add(mgop.Mapping); } for (int iLevel = 0; iLevel < MgSeq.Length; iLevel++) { MultigridMapping mgMap = MultigridMaps[iLevel]; var XAggBasis = mgMap.AggBasis[0]; // set the test field: XDGField Test = new XDGField(xt.XB, "Test"); Random rand = new Random(); for (int i = 0; i < Test.CoordinateVector.Count; i++) { Test.CoordinateVector[i] = rand.NextDouble(); } xt.agg.ClearAgglomerated(Test.CoordinateVector, Test.Mapping); // do restriction/prolongation (Reference) double[] RestVecRef = new double[XAggBasis.LocalDim]; XAggBasis.RestictFromFullGrid(Test.CoordinateVector, RestVecRef); // and now with the matrix: BlockMsrMatrix RestMtx = new BlockMsrMatrix(mgMap, mgMap.ProblemMapping); XAggBasis.GetRestrictionMatrix(RestMtx, mgMap, 0); double[] RestVec = new double[mgMap.LocalLength]; RestMtx.SpMV(1.0, Test.CoordinateVector, 0.0, RestVec); double[] X1 = new double[xt.XdgMultigridOp.Mapping.LocalLength]; XDGField X2 = new XDGField(Test.Basis); xt.XdgMultigridOp.TransformSolInto(Test.CoordinateVector, X1); xt.XdgMultigridOp.TransformSolFrom(X2.CoordinateVector, X1); //xt.agg.Extrapolate(X2.CoordinatesAsVector, X2.Mapping); var ERR2 = Test.CloneAs(); ERR2.Acc(-1.0, X2); double ERR2Norm = ERR2.L2Norm(); //Console.WriteLine("MultigridOperator TranformInto/FransformFrom mismatch: " + ERR2Norm); Assert.LessOrEqual(ERR2Norm, 1.0e-8); // compare double ERR = 0.0; int Nmax = XAggBasis.MaximalLength; for (int jAgg = 0; jAgg < mgMap.AggGrid.iLogicalCells.NoOfLocalUpdatedCells; jAgg++) { int i0Ref = jAgg * Nmax; int i0Tst = mgMap.LocalUniqueIndex(0, jAgg, 0); int N = mgMap.GetLength(jAgg); for (int n = 0; n < N; n++) { double dist = RestVecRef[i0Ref + n] - RestVec[i0Tst + n]; ERR += dist.Pow2(); } } Console.WriteLine("Restriction matrix test (iLevel = {0}): {1}", iLevel, ERR); Assert.LessOrEqual(ERR, 1.0e-8); // double[] PrlgVecA = new double[XAggBasis.LocalDim]; double[] PrlgVecB = new double[mgMap.LocalLength]; for (int jAgg = 0; jAgg < mgMap.AggGrid.iLogicalCells.NoOfLocalUpdatedCells; jAgg++) { int i0Ref = jAgg * Nmax; int i0Tst = mgMap.LocalUniqueIndex(0, jAgg, 0); int N = mgMap.GetLength(jAgg); for (int n = 0; n < N; n++) { double rndVal = rand.NextDouble(); PrlgVecA[i0Ref + n] = rndVal; PrlgVecB[i0Tst + n] = rndVal; } } XDGField QA = new XDGField(Test.Basis); XDGField QB = new XDGField(Test.Basis); XAggBasis.ProlongateToFullGrid(QA.CoordinateVector, PrlgVecA); var PrlgMtx = RestMtx.Transpose(); PrlgMtx.SpMV(1.0, PrlgVecB, 0.0, QB.CoordinateVector); XDGField ERR5 = QA.CloneAs(); ERR5.Acc(-1.0, QB); double ERR5_Norm = ERR5.L2Norm(); Console.WriteLine("Prolongation matrix test (iLevel = {0}): {1}", iLevel, ERR5_Norm); Assert.LessOrEqual(ERR5_Norm, 1.0e-8); } }
public static void VectorCellwiseOperation( [Values(XDGusage.none, XDGusage.all)] XDGusage UseXdg, [Values(2)] int DGOrder, [Values(MatrixShape.diagonal_var_spec, MatrixShape.diagonal_spec, MatrixShape.diagonal_var, MatrixShape.diagonal)] MatrixShape MShape, [Values(4)] int Res ) { Utils.TestInit((int)UseXdg, DGOrder, (int)MShape); Console.WriteLine("SubMatrixIgnoreCoupling({0},{1},{2})", UseXdg, DGOrder, MShape); //Arrange --- create test matrix, MG mapping MultigridOperator mgo = Utils.CreateTestMGOperator(UseXdg, DGOrder, MShape, Res); MultigridMapping map = mgo.Mapping; BlockMsrMatrix M = mgo.OperatorMatrix; //Arrange --- masking and subblock extraction of external cells var sbs = new SubBlockSelector(map); sbs.AllExternalCellsSelection(); var M_ext = BlockMask.GetAllExternalRows(map, M); var mask = new BlockMask(sbs, M_ext); var eblocks = mask.GetDiagonalBlocks(M, false, false); //Dictionary<int, int[]> Didc = Utils.GetDictOfAllExtCellIdc(map); //Arrange --- generate rnd vector and distribute it double[] vec = new double[map.LocalLength]; vec = Utils.GetRandomVector(map.LocalLength); var vec_ex = new MPIexchange <double[]>(map, vec); vec_ex.TransceiveStartImReturn(); vec_ex.TransceiveFinish(0.0); Debug.Assert(vec_ex.Vector_Ext.L2Norm() != 0); //Arrange --- stopwatch var stw = new Stopwatch(); stw.Reset(); //Arrange --- get extended (loc+external cells) vector double[] Vec_ext = new double[vec.Length + vec_ex.Vector_Ext.Length]; mask.AccSubVec(vec_ex.Vector_Ext, Vec_ext); bool test = eblocks.Length.MPIEquals(); Debug.Assert(test); //Act --- calculate blockwise result: M_i*vec_i=Res_i double[] Res_ext = new double[Vec_ext.Length]; stw.Start(); for (int i = 0; i < eblocks.Length; i++) { //int iBlock = i + map.AggGrid.iLogicalCells.NoOfLocalUpdatedCells; double[] vec_i = mask.GetSubVecOfCell(Vec_ext, i); double[] Res_i = new double[vec_i.Length]; eblocks[i].MatVecMul(1.0, vec_i, 0.0, Res_i); mask.AccSubVecOfCell(Res_i, i, Res_ext); if (map.MpiRank == 0) { eblocks[i].ConvertToMsr().SaveToTextFileSparseDebug(String.Format("block_{0}_{1}", i, map.MpiRank)); vec_i.SaveToTextFileDebug(String.Format("vec_{0}_{1}", i, map.MpiRank)); Res_i.SaveToTextFileDebug(String.Format("Res_{0}_{1}", i, map.MpiRank)); } } stw.Stop(); //Act --- project Res_i onto Res_g and Res_g=M_ext*vec_ext-Res_g double[] Res_g = mask.GetSubVec(Res_ext); var qM_ext = M_ext.ConvertToQuadraticBMsr(mask.GlobalIList_External.ToArray(), false); qM_ext.SpMV(1.0, vec_ex.Vector_Ext, -1.0, Res_g); if (map.MpiRank == 0) { vec_ex.Vector_Ext.SaveToTextFileDebug("vec_g"); Res_g.SaveToTextFileDebug("Res_g"); M_ext.SaveToTextFileSparseDebug("M_ext"); qM_ext.SaveToTextFileSparseDebug("qM_ext"); } //Assert --- |Res_g| should be at least near to zero Assert.IsTrue(Res_g.L2Norm() == 0.0); }
public static void FastSubMatrixExtraction( [Values(XDGusage.none, XDGusage.all)] XDGusage UseXdg, [Values(2)] int DGOrder, [Values(MatrixShape.laplace)] MatrixShape MShape, [Values(4)] int Res ) { Utils.TestInit((int)UseXdg, DGOrder, (int)MShape); Console.WriteLine("FastSubMatrixExtraction({0},{1},{2})", UseXdg, DGOrder, MShape); //Arrange --- MultigridOperator mgo = Utils.CreateTestMGOperator(UseXdg, DGOrder, MShape, Res); MultigridMapping map = mgo.Mapping; BlockMsrMatrix M = mgo.OperatorMatrix; var sbs = new SubBlockSelector(map); int[] extcells = sbs.AllExternalCellsSelection(); var M_ext = BlockMask.GetAllExternalRows(map, M); var mask = new BlockMask(sbs, M_ext); //Arrange --- get index list of all external cells int[] idc = Utils.GetAllExtCellIdc(map); double[] GlobIdx = idc.Count().ForLoop(i => (double)idc[i] + 1.0); //Arrange --- stopwatch var stw = new Stopwatch(); stw.Reset(); //Act --- Extract SubMatrix stw.Start(); BlockMsrMatrix subM = mask.GetSubBlockMatrix(M); stw.Stop(); //Arrange --- Extract Blocks in Matlab and substract var infNorm = MultidimensionalArray.Create(4, 1); int rank = map.MpiRank; using (BatchmodeConnector matlab = new BatchmodeConnector()) { matlab.PutSparseMatrix(M, "M"); // note: M_sub lives on Comm_Self, therefore we have to distinguish between procs ... matlab.PutSparseMatrixRankExclusive(subM, "M_sub"); matlab.PutVectorRankExclusive(GlobIdx, "Idx"); matlab.Cmd("M_0 = M(Idx_0, Idx_0);"); matlab.Cmd("M_1 = M(Idx_1, Idx_1);"); matlab.Cmd("M_2 = M(Idx_2, Idx_2);"); matlab.Cmd("M_3 = M(Idx_3, Idx_3);"); matlab.Cmd("n=[0; 0; 0; 0];"); matlab.Cmd("n(1,1)=norm(M_0-M_sub_0,inf);"); matlab.Cmd("n(2,1)=norm(M_1-M_sub_1,inf);"); matlab.Cmd("n(3,1)=norm(M_2-M_sub_2,inf);"); matlab.Cmd("n(4,1)=norm(M_3-M_sub_3,inf);"); matlab.GetMatrix(infNorm, "n"); matlab.Execute(); } //Assert --- mask blocks and extracted blocks are the same Assert.IsTrue(infNorm[rank, 0] == 0.0); }
public static void SubBlockExtractionWithCoupling( [Values(XDGusage.none, XDGusage.all)] XDGusage UseXdg, [Values(2)] int DGOrder, [Values(MatrixShape.diagonal, MatrixShape.diagonal_var, MatrixShape.diagonal_spec, MatrixShape.diagonal_var_spec)] MatrixShape MShape ) { Utils.TestInit((int)UseXdg, DGOrder, (int)MShape); Console.WriteLine("ExtractDiagonalBlocks({0},{1},{2})", UseXdg, DGOrder, MShape); //Arrange --- get multigridoperator MultigridOperator MGOp = Utils.CreateTestMGOperator(UseXdg, DGOrder, MShape); BlockMsrMatrix M = MGOp.OperatorMatrix; MultigridMapping map = MGOp.Mapping; //Arrange --- setup masking SubBlockSelector SBS = new SubBlockSelector(map); BlockMask mask = new BlockMask(SBS, null); bool[] coupling = Utils.SetCoupling(MShape); //Arrange --- some time measurement Stopwatch stw = new Stopwatch(); stw.Reset(); //Arrange --- setup auxiliary matrix //this will show us if more is extracted, than it should ... var Mprep = new BlockMsrMatrix(map); Mprep.Acc(1.0, M); //Act --- diagonal subblock extraction stw.Start(); var blocks = mask.GetDiagonalBlocks(Mprep, coupling[0], coupling[1]); stw.Stop(); //Assert --- all diagonal blocks are extracted Assert.IsTrue(blocks.Length == map.LocalNoOfBlocks); for (int i = 0; i < map.LocalNoOfBlocks; i++) { //Arrange --- get ith diagonal block of M: M_i int iBlock = i + map.AggGrid.CellPartitioning.i0; int L = map.GetBlockLen(iBlock); int i0 = map.GetBlockI0(iBlock); var Mblock = MultidimensionalArray.Create(L, L); M.ReadBlock(i0, i0, Mblock); //Act --- M_i-Mones_i Mblock.Acc(-1.0, blocks[i]); //Assert --- are extracted blocks and Assert.IsTrue(Mblock.InfNorm() == 0.0, String.Format("infNorm of block {0} neq 0!", i)); } //BlockMsrMatrix all1; //all1.SetAll(1); //Generate broken diagonal matrix, die zur Maske passt: M //M+all1=M_prep //Wende Extraction auf M_prep an, Man sollte nun M bekommen //Test: M_prep-extract(M_prep)=all1 //Test-crit: Result.SumEntries=DOF^2 oder Result.Max()==Result.Min()==1 //oder (besser) //Test: M-extract(M_prep)=zeros //Test-crit: Result.InfNorm()==0 //Der Test kann für ExtractSubMatrix mit ignore coupling wiederholt werden //eventuell: Testmatrix finden mit brauchbaren Nebendiagonalen für einen Fall //Was wird getestet: funktioniert ignorecoupling richtig? }