From 78ca5aa1cb0a10b543416835cb453558cfbef116 Mon Sep 17 00:00:00 2001 From: Gustavo Batistela Date: Mon, 19 Apr 2021 17:10:51 -0300 Subject: [PATCH 001/187] Remove override keyword from Errors methods --- ErrorEstimation/Material/TPZMatLaplacianHybrid.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ErrorEstimation/Material/TPZMatLaplacianHybrid.h b/ErrorEstimation/Material/TPZMatLaplacianHybrid.h index fa23d7d2..2390f6e1 100644 --- a/ErrorEstimation/Material/TPZMatLaplacianHybrid.h +++ b/ErrorEstimation/Material/TPZMatLaplacianHybrid.h @@ -43,10 +43,10 @@ class TPZMatLaplacianHybrid : public TPZMatLaplacian virtual void Contribute(TPZVec &datavec, REAL weight, TPZFMatrix &ef) override; - virtual void ContributeBC(TPZVec &datavec, REAL weight, TPZFMatrix &ek,TPZFMatrix &ef,TPZBndCond &bc) override; + virtual void ContributeBC(TPZVec &datavec, REAL weight, TPZFMatrix &ek,TPZFMatrix &ef,TPZBndCond &bc); virtual void Solution(TPZVec &datavec, int var, TPZVec &Solout)override; - virtual void Errors(TPZVec &data, TPZVec &u_exact, TPZFMatrix &du_exact, TPZVec &errors)override; + virtual void Errors(TPZVec &data, TPZVec &u_exact, TPZFMatrix &du_exact, TPZVec &errors); virtual void Errors(TPZVec &data, TPZVec &errors)override; From 647028b41951b0800c6917d36e561660846db8aa Mon Sep 17 00:00:00 2001 From: Gustavo Batistela Date: Mon, 19 Apr 2021 17:11:07 -0300 Subject: [PATCH 002/187] Remove template from TPZBlock class --- ErrorEstimation/TPZMFSolutionTransfer.cpp | 16 ++++++++-------- ErrorEstimation/TPZMFSolutionTransfer.h | 2 +- Projects/ErrorEstimationH1/TPZPostProcessError.h | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/ErrorEstimation/TPZMFSolutionTransfer.cpp b/ErrorEstimation/TPZMFSolutionTransfer.cpp index 12ce2696..1664cb82 100644 --- a/ErrorEstimation/TPZMFSolutionTransfer.cpp +++ b/ErrorEstimation/TPZMFSolutionTransfer.cpp @@ -10,8 +10,8 @@ void TPZMFSolutionTransfer::Match::TransferFromMultiphysics(TPZCompMesh * cmesh){ - TPZBlock &blockMF = cmesh->Block(); - TPZBlock* blockAto = fblockTarget.first; + TPZBlock &blockMF = cmesh->Block(); + TPZBlock* blockAto = fblockTarget.first; int seqMF = fblockTarget.second; int seqAto = fblocknumber; int blocksizeAto = blockAto->Size(seqAto); @@ -43,8 +43,8 @@ void TPZMFSolutionTransfer::Match::TransferFromMultiphysics(TPZCompMesh * cmesh) } void TPZMFSolutionTransfer::Match::TransferToMultiphysics(TPZCompMesh * cmesh){ cmesh->InitializeBlock(); - TPZBlock &blockToTransfer = cmesh->Block(); - TPZBlock* blockAto = fblockTarget.first; + TPZBlock &blockToTransfer = cmesh->Block(); + TPZBlock* blockAto = fblockTarget.first; int seqtoTrans = fblockTarget.second; int seqAto = fblocknumber; @@ -142,8 +142,8 @@ void TPZMFSolutionTransfer::MeshTransferData::BuildTransferData(TPZCompMesh* cme int seqnumberMF = conectTarget.SequenceNumber(); Match currentmatch; currentmatch.fblocknumber = seqnumberAto; - TPZBlock *blockAto = &celfrom->Mesh()->Block(); - std::pair *, int> target = std::make_pair(blockAto,seqnumberMF); + TPZBlock *blockAto = &celfrom->Mesh()->Block(); + std::pair target = std::make_pair(blockAto,seqnumberMF); currentmatch.fblockTarget = target; fconnecttransfer.push_back(currentmatch); } @@ -216,8 +216,8 @@ void TPZMFSolutionTransfer::Match::Print(std::ostream &out, TPZCompMesh *cmesh) << " MeshB " << fblockTarget.first << " block " << fblocknumber << std::endl; int blnumA = fblockTarget.second; int blnumB = fblocknumber; - TPZBlock *blockA = &cmesh->Block(); - TPZBlock *blockB = fblockTarget.first; + TPZBlock *blockA = &cmesh->Block(); + TPZBlock *blockB = fblockTarget.first; int64_t nblA = cmesh->Block().NBlocks(); int64_t nblB = fblockTarget.first->NBlocks(); out << "BlockA pos " << blockA->Position(fblockTarget.second) diff --git a/ErrorEstimation/TPZMFSolutionTransfer.h b/ErrorEstimation/TPZMFSolutionTransfer.h index 1cbd40ec..7a4068f2 100644 --- a/ErrorEstimation/TPZMFSolutionTransfer.h +++ b/ErrorEstimation/TPZMFSolutionTransfer.h @@ -30,7 +30,7 @@ class TPZMFSolutionTransfer /** * @brief Pair that relates the origin block with the target block index. */ - std::pair *, int64_t> fblockTarget;// block target + std::pair fblockTarget;// block target /** * @brief Empty Constructor diff --git a/Projects/ErrorEstimationH1/TPZPostProcessError.h b/Projects/ErrorEstimationH1/TPZPostProcessError.h index 05cbb256..3d6327da 100644 --- a/Projects/ErrorEstimationH1/TPZPostProcessError.h +++ b/Projects/ErrorEstimationH1/TPZPostProcessError.h @@ -104,7 +104,7 @@ class TPZPostProcessError TPZFMatrix fSolution; // block corresponding to the original connect sequence numbers - TPZBlock fBlock; + TPZBlock fBlock; /// size of the connects in the multiphysics mesh TPZVec fConnectSizes; From 9b516699399d3da55d74a6404766f72c1cac1631 Mon Sep 17 00:00:00 2001 From: Gustavo Batistela Date: Fri, 23 Apr 2021 17:51:24 -0300 Subject: [PATCH 003/187] Fixed a few compiler errors due to change in TPZBlock interface --- .../ErrorEstimationH1/TPZPostProcessError.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/Projects/ErrorEstimationH1/TPZPostProcessError.cpp b/Projects/ErrorEstimationH1/TPZPostProcessError.cpp index 220a54c0..1c468a8e 100644 --- a/Projects/ErrorEstimationH1/TPZPostProcessError.cpp +++ b/Projects/ErrorEstimationH1/TPZPostProcessError.cpp @@ -267,8 +267,9 @@ void TPZPostProcessError::ComputeHDivSolution() TPZCompMesh *meshmixed = fMeshVector[1]; int64_t nval = fMeshVector[4]->Solution().Rows(); + TPZFMatrix &sol = fMeshVector[4]->Solution(); for (int64_t i=0; iSolution()(i,0) = 1.; + sol(i,0) = 1.; } int ModelDimension = meshmixed->Dimension(); @@ -371,11 +372,13 @@ void TPZPostProcessError::ComputeElementErrors(TPZVec &elementerrors) } } int64_t extseqcount = numintconnects; + TPZFMatrix &sol = meshweight->Solution(); for (int64_t patch=0; patchConnectVec()[partitionindex].SequenceNumber(); - meshweight->Block()(seqnum,0,0,0) = 1.; + std::pair ind = meshweight->Block().at(seqnum, 0, 0, 0); + sol.at(ind) = 1; } { int64_t nel = fVecVecPatches[color][patch].fElIndices.size(); @@ -491,16 +494,16 @@ void TPZPostProcessError::ComputeElementErrors(TPZVec &elementerrors) direct = 0; an.Assemble(); - - TPZAutoPointer > globmat = an.Solver().Matrix(); + + TPZMatrix &globmat = an.Mesh()->Solution(); for (int64_t p=0; pGetVal(firstlagrangeequation, firstlagrangeequation); + STATE diag = globmat.GetVal(firstlagrangeequation, firstlagrangeequation); diag += 1.; - globmat->Put(firstlagrangeequation, firstlagrangeequation, diag); + globmat.Put(firstlagrangeequation, firstlagrangeequation, diag); } } @@ -695,6 +698,7 @@ int64_t TPZPatch::FirstLagrangeEquation(TPZCompMesh *cmesh) const // Sum the solution stored in fSolution of the second mesh to the fSolution vector void TPZPostProcessError::TransferAndSumSolution(TPZCompMesh *cmesh) { + TPZFMatrix &sol = cmesh->Solution(); int64_t nconnect = cmesh->NConnects(); for (int64_t ic=0; icConnectVec()[ic]; @@ -714,7 +718,7 @@ void TPZPostProcessError::TransferAndSumSolution(TPZCompMesh *cmesh) for (int eq=0; eqSolution()(pos+eq,0); + fSolution(targetpos+eq,0) += sol(pos+eq,0); } } cmesh->Solution().Zero(); From fe9efbf39c69c7f1b9893cc1edc408e0bf31b192 Mon Sep 17 00:00:00 2001 From: Gustavo Batistela Date: Fri, 23 Apr 2021 17:53:15 -0300 Subject: [PATCH 004/187] Fix compilation error --- Projects/ErrorEstimationH1/TPZPostProcessError.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Projects/ErrorEstimationH1/TPZPostProcessError.cpp b/Projects/ErrorEstimationH1/TPZPostProcessError.cpp index 1c468a8e..e3cbf927 100644 --- a/Projects/ErrorEstimationH1/TPZPostProcessError.cpp +++ b/Projects/ErrorEstimationH1/TPZPostProcessError.cpp @@ -509,8 +509,8 @@ void TPZPostProcessError::ComputeElementErrors(TPZVec &elementerrors) an.Solve(); - TPZStepSolver &step = dynamic_cast &>(an.Solver()); - std::list singular = step.Singular(); + TPZStepSolver *step = dynamic_cast*>(an.Solver()); + std::list singular = step->Singular(); if (singular.size()) { From a05e86e7a6e8c4d3bf53c4cf85654f6878f7efcc Mon Sep 17 00:00:00 2001 From: Gustavo Batistela Date: Mon, 3 May 2021 16:02:44 -0300 Subject: [PATCH 005/187] [ongoing] Add function to print latex graphs --- Projects/ErrorEstimationMHM/main_Journal.cpp | 195 ++++++++++++++++--- 1 file changed, 173 insertions(+), 22 deletions(-) diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp index 21ae6494..bbc856ce 100644 --- a/Projects/ErrorEstimationMHM/main_Journal.cpp +++ b/Projects/ErrorEstimationMHM/main_Journal.cpp @@ -10,6 +10,34 @@ #include #include +struct ErrorResult { + ErrorResult(const std::string &s, const int nIntRef, const int nCoarseDiv, const int kOrder, const int nOrder, + const REAL estimatedError, const REAL exactError, const REAL ieff) { + problem_name = s; + n_internal_ref = nIntRef; + n_coarse_div = nCoarseDiv; + k_order = kOrder; + n_order = nOrder; + estimated_error = estimatedError; + exact_error = exactError; + effectivity_index = ieff; + } + std::string problem_name = "NULL"; + int n_internal_ref = -1; + int n_coarse_div = -1; + int k_order = -1; + int n_order = -1; + REAL estimated_error = -1.; + REAL exact_error = -1.; + REAL effectivity_index = -1.; +}; + +std::vector result_vec; + +const int porder = 1; +const int hdivmais = 3; +std::string dir_name = "Journal_k" + std::to_string(porder) + "n" + std::to_string(hdivmais); + void RunSmoothProblem(int nCoarseDiv, int nInternalRef); void RunNonConvexProblem(); void RunHighGradientProblem(int nCoarseDiv, int nInternalRef); @@ -35,22 +63,26 @@ void CreateMHMCompMeshPermFunction(TPZMHMixedMeshControl &mhm); void PeriodicPermeabilityFunction(const TPZVec &coord, TPZVec &res, TPZFMatrix &res_mat); void PeriodicProblemForcingFunction(const TPZVec &pt, TPZVec &result); +void PrintLatexGraphs(); + int main() { TPZLogger::InitializePZLOG(); gRefDBase.InitializeAllUniformRefPatterns(); const std::set nCoarseDiv = {3, 4, 5, 6}; - const std::set nInternalRef = {0, 1, 2, 3}; - for (const auto coarse_div : nCoarseDiv) { - for (const auto internal_ref : nInternalRef) { - RunSmoothProblem(coarse_div, internal_ref); - //RunInnerSingularityProblem(coarse_div, internal_ref); + const std::set nInternalRef = {1, 2}; + for (const auto internal_ref : nInternalRef) { + for (const auto coarse_div : nCoarseDiv) { + //RunSmoothProblem(coarse_div, internal_ref); + RunInnerSingularityProblem(coarse_div, internal_ref); //RunHighGradientProblem(coarse_div, internal_ref); //RunPeriodicPermProblem(coarse_div, internal_ref); } } - RunNonConvexProblem(); + PrintLatexGraphs(); + //RunNonConvexProblem(); + std::cout << "Bye!\n"; return 0; } @@ -60,9 +92,9 @@ void RunSmoothProblem(const int nCoarseDiv, const int nInternalRef) { config.exact = new TLaplaceExample1; config.exact.operator*().fExact = TLaplaceExample1::ESinSin; config.problemname = "Smooth"; - config.dir_name = "Journal"; - config.porder = 1; - config.hdivmais = 2; + config.dir_name = dir_name; + config.porder = porder; + config.hdivmais = hdivmais; config.materialids.insert(1); config.bcmaterialids.insert(-1); config.makepressurecontinuous = true; @@ -96,9 +128,9 @@ void RunHighGradientProblem(const int nCoarseDiv, const int nInternalRef) { config.exact = new TLaplaceExample1; config.exact.operator*().fExact = TLaplaceExample1::EBoundaryLayer; config.problemname = "HighGradient"; - config.dir_name = "Journal"; - config.porder = 1; - config.hdivmais = 2; + config.dir_name = dir_name; + config.porder = porder; + config.hdivmais = hdivmais; config.materialids.insert(1); config.bcmaterialids.insert(-1); config.makepressurecontinuous = true; @@ -132,9 +164,9 @@ void RunNonConvexProblem() { config.exact = new TLaplaceExample1; config.exact.operator*().fExact = TLaplaceExample1::ESinSin; config.problemname = "NonConvex"; - config.dir_name = "Journal"; - config.porder = 1; - config.hdivmais = 3; + config.dir_name = dir_name; + config.porder = porder; + config.hdivmais = hdivmais; config.materialids.insert(1); config.bcmaterialids.insert(-1); config.makepressurecontinuous = true; @@ -169,9 +201,9 @@ void RunInnerSingularityProblem(const int nCoarseDiv, const int nInternalRef) { config.exact = new TLaplaceExample1; config.exact.operator*().fExact = TLaplaceExample1::ESteklovNonConst; config.problemname = "InnerSingularity"; - config.dir_name = "Journal"; - config.porder = 1; - config.hdivmais = 2; + config.dir_name = dir_name; + config.porder = porder; + config.hdivmais = hdivmais; config.materialids = {1, 2}; config.bcmaterialids.insert(-1); config.makepressurecontinuous = true; @@ -229,6 +261,7 @@ void RunInnerSingularityProblem(const int nCoarseDiv, const int nInternalRef) { SolveMHMProblem(mhm, config); EstimateError(config, mhm); + } void RunPeriodicPermProblem(const int nCoarseDiv, const int nInternalRef) { @@ -238,9 +271,9 @@ void RunPeriodicPermProblem(const int nCoarseDiv, const int nInternalRef) { //config.exact = new TLaplaceExample1; //config.exact.operator*().fExact = TLaplaceExample1::EBoundaryLayer; config.problemname = "PeriodicPerm"; - config.dir_name = "Journal"; - config.porder = 1; - config.hdivmais = 2; + config.dir_name = dir_name; + config.porder = porder; + config.hdivmais = hdivmais; config.materialids.insert(1); config.bcmaterialids.insert(-1); config.makepressurecontinuous = true; @@ -445,7 +478,6 @@ void SolveMHMProblem(TPZMHMixedMeshControl *mhm, const ProblemConfig &config) { std::cout << "Finished\n"; an.LoadSolution(); // compute internal dofs - // TODO: Phil, this is the part that needs a fix! TPZMFSolutionTransfer transfer; transfer.BuildTransferData(cmesh.operator->()); transfer.TransferFromMultiphysics(); @@ -504,6 +536,16 @@ void EstimateError(ProblemConfig &config, TPZMHMixedMeshControl *mhm) { std::ofstream file(fileName, std::ios::app); Tools::PrintErrors(file, config, errors); } + + result_vec.emplace_back(config.problemname, + config.ninternalref, + config.ndivisions, + config.porder, + config.hdivmais, + errors[3], + errors[2], + sqrt(errors[4] + errors[3]) / sqrt(errors[2]) + ); } void InsertMaterialsInMHMMesh(TPZMHMixedMeshControl &control, const ProblemConfig &config) { @@ -664,3 +706,112 @@ void PeriodicPermeabilityFunction(const TPZVec &coord, TPZVec &res, } void PeriodicProblemForcingFunction(const TPZVec &pt, TPZVec &result) { result[0] = -1; } + +void PrintLatexGraphs() { + + std::stringstream latex_text; + if (result_vec.empty()) DebugStop(); + + auto it = result_vec.begin(); + std::string previous_problem = it->problem_name; + while (it != result_vec.end()) { + while(it->problem_name == previous_problem) { + if (!it.operator->()) DebugStop(); + + latex_text << "\\section{" << it->problem_name << "}\n"; + + int previous_k = it->k_order; + while (it->k_order == previous_k) { + int previous_n = it->n_order; + while (it->n_order == previous_n) { + latex_text << " \\subsection{k = " << it->k_order << ", n = " << it->n_order << "}\n"; + std::stringstream error_graph; + std::stringstream ieff_graph; + std::stringstream estimated_error_pts; + std::stringstream exact_error_pts; + std::stringstream estimated_error_legend; + std::stringstream exact_error_legend; + + error_graph << " \\begin{figure}[ht!]\n" + " \\centering\n" + " \\begin{tikzpicture}\n" + " \\begin{loglogaxis}[\n" + " width=0.6\\textwidth,\n" + " height=0.45\\textwidth,\n" + " xlabel={$h_{in}/h_{sk}$},\n" + " xtick scale label code/.code={},\n" + " legend pos=outer north east,\n" + " grid style=dashed,\n" + " cycle list name=mycycle,\n" + " ]\n"; + + ieff_graph << " \\begin{figure}[ht!]\n" + " \\centering\n" + " \\begin{tikzpicture}\n" + " \\begin{loglogaxis}[\n" + " width=0.6\\textwidth,\n" + " height=0.4\\textwidth,\n" + " xlabel={$h_{in}/h_{sk}$},\n" + " %ymin=1.0, ymax=1.1,\n" + " xtick scale label code/.code={},\n" + " legend pos=#2,\n" + " grid style=dashed,\n" + " cycle list name=mycycle,\n" + " y tick label style={\n" + " /pgf/number format/.cd,\n" + " fixed,\n" + " fixed zerofill,\n" + " precision=2,\n" + " /tikz/.cd\n" + " },\n" + " ]\n"; + int current_int_ref = it->n_internal_ref; + bool is_first = true; + while (it->n_internal_ref == current_int_ref) { + if (is_first) { + estimated_error_pts << " \\addplot\n \\coordinates{\n"; + exact_error_pts << " \\addplot\n \\coordinates{\n"; + ieff_graph << " \\addplot\n \\coordinates{\n"; + is_first = false; + } + estimated_error_legend << " $h_{in} = h_{sk}/" << std::to_string(2 ^ it->n_internal_ref) + << "$ (estimated),\n"; + exact_error_legend << " $h_{in} = h_{sk}/" << std::to_string(2 ^ it->n_internal_ref) + << "$ (exact),\n"; + + estimated_error_pts << " (1/" << it->n_coarse_div << ", " << it->estimated_error << ")\n"; + exact_error_pts << " (1/" << it->n_coarse_div << ", " << it->exact_error << ")\n"; + + ieff_graph << " (1/" << it->n_coarse_div << ", " << it->effectivity_index << ")\n"; + + if (it != result_vec.end()) { + it++; + } + } + estimated_error_pts << " };\n"; + exact_error_pts << " };\n"; + ieff_graph << " };\n"; + + error_graph << estimated_error_pts.str(); + error_graph << exact_error_pts.str(); + error_graph << " \\legend{\n" << estimated_error_legend.str() << exact_error_legend.str() + << " }\n" + " \\end{loglogaxis}\n" + " \\end{tikzpicture}\n" + " \\caption{#3}\n" + " \\end{figure}\n\n"; + + ieff_graph << " \\end{loglogaxis}\n" + " \\end{tikzpicture}\n" + " \\caption{#3}\n" + " \\end{figure}\n" + "}\n"; + + latex_text << error_graph.str(); + latex_text << ieff_graph.str(); + } + } + } + std::cout << latex_text.str(); + } +} From de5f32eb9794298480f80672e1636f81fa831f8a Mon Sep 17 00:00:00 2001 From: Gustavo Batistela Date: Fri, 7 May 2021 16:41:05 -0300 Subject: [PATCH 006/187] Finish latex graph printer --- Projects/ErrorEstimationMHM/main_Journal.cpp | 207 +++++++++++-------- 1 file changed, 117 insertions(+), 90 deletions(-) diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp index bbc856ce..13e65e01 100644 --- a/Projects/ErrorEstimationMHM/main_Journal.cpp +++ b/Projects/ErrorEstimationMHM/main_Journal.cpp @@ -38,10 +38,10 @@ const int porder = 1; const int hdivmais = 3; std::string dir_name = "Journal_k" + std::to_string(porder) + "n" + std::to_string(hdivmais); -void RunSmoothProblem(int nCoarseDiv, int nInternalRef); +void RunSmoothProblem(int nCoarseDiv, int nInternalRef, int k, int n); void RunNonConvexProblem(); void RunHighGradientProblem(int nCoarseDiv, int nInternalRef); -void RunInnerSingularityProblem(int nCoarseDiv, int nInternalRef); +void RunInnerSingularityProblem(int nCoarseDiv, int nInternalRef, int k, int n); void RunPeriodicPermProblem(int nCoarseDiv, int nInternalRef); TPZGeoMesh *CreateQuadGeoMesh(int nCoarseDiv, int nInternalRef); @@ -63,38 +63,53 @@ void CreateMHMCompMeshPermFunction(TPZMHMixedMeshControl &mhm); void PeriodicPermeabilityFunction(const TPZVec &coord, TPZVec &res, TPZFMatrix &res_mat); void PeriodicProblemForcingFunction(const TPZVec &pt, TPZVec &result); -void PrintLatexGraphs(); +void PrintLatexGraphs(std::ostream & out); int main() { TPZLogger::InitializePZLOG(); gRefDBase.InitializeAllUniformRefPatterns(); - const std::set nCoarseDiv = {3, 4, 5, 6}; - const std::set nInternalRef = {1, 2}; - for (const auto internal_ref : nInternalRef) { - for (const auto coarse_div : nCoarseDiv) { - //RunSmoothProblem(coarse_div, internal_ref); - RunInnerSingularityProblem(coarse_div, internal_ref); - //RunHighGradientProblem(coarse_div, internal_ref); - //RunPeriodicPermProblem(coarse_div, internal_ref); + const std::set nCoarseDiv = {3, 4, 5, 6, 7}; + const std::set nInternalRef = {1, 2, 3}; + const std::set kOrder = {1, 2}; + const std::set nOrder = {1, 2}; + + for (const auto k : kOrder) { + for (const auto n : nOrder) { + for (const auto internal_ref : nInternalRef) { + for (const auto coarse_div : nCoarseDiv) { + RunSmoothProblem(coarse_div, internal_ref, k, n); + } + } + } + } + + for (const auto k : kOrder) { + for (const auto n : nOrder) { + for (const auto internal_ref : nInternalRef) { + for (const auto coarse_div : nCoarseDiv) { + RunInnerSingularityProblem(coarse_div, internal_ref, k, n); + } + } } } - PrintLatexGraphs(); + std::ofstream out_latex("LatextGraphs.txt", std::ios::trunc); + PrintLatexGraphs(out_latex); //RunNonConvexProblem(); std::cout << "Bye!\n"; return 0; } -void RunSmoothProblem(const int nCoarseDiv, const int nInternalRef) { +void RunSmoothProblem(const int nCoarseDiv, const int nInternalRef, const int k, const int n) { ProblemConfig config; config.dimension = 2; config.exact = new TLaplaceExample1; config.exact.operator*().fExact = TLaplaceExample1::ESinSin; config.problemname = "Smooth"; config.dir_name = dir_name; - config.porder = porder; - config.hdivmais = hdivmais; + config.porder = k; + config.hdivmais = n; config.materialids.insert(1); config.bcmaterialids.insert(-1); config.makepressurecontinuous = true; @@ -195,15 +210,15 @@ void RunNonConvexProblem() { EstimateError(config, mhm); } -void RunInnerSingularityProblem(const int nCoarseDiv, const int nInternalRef) { +void RunInnerSingularityProblem(const int nCoarseDiv, const int nInternalRef, int k, int n) { ProblemConfig config; config.dimension = 2; config.exact = new TLaplaceExample1; config.exact.operator*().fExact = TLaplaceExample1::ESteklovNonConst; config.problemname = "InnerSingularity"; config.dir_name = dir_name; - config.porder = porder; - config.hdivmais = hdivmais; + config.porder = k; + config.hdivmais = n; config.materialids = {1, 2}; config.bcmaterialids.insert(-1); config.makepressurecontinuous = true; @@ -707,111 +722,123 @@ void PeriodicPermeabilityFunction(const TPZVec &coord, TPZVec &res, void PeriodicProblemForcingFunction(const TPZVec &pt, TPZVec &result) { result[0] = -1; } -void PrintLatexGraphs() { +void PrintLatexGraphs(std::ostream & out) { std::stringstream latex_text; if (result_vec.empty()) DebugStop(); auto it = result_vec.begin(); - std::string previous_problem = it->problem_name; while (it != result_vec.end()) { - while(it->problem_name == previous_problem) { - if (!it.operator->()) DebugStop(); - + std::string previous_problem = it->problem_name; + while (it->problem_name == previous_problem) { latex_text << "\\section{" << it->problem_name << "}\n"; int previous_k = it->k_order; while (it->k_order == previous_k) { int previous_n = it->n_order; while (it->n_order == previous_n) { - latex_text << " \\subsection{k = " << it->k_order << ", n = " << it->n_order << "}\n"; - std::stringstream error_graph; - std::stringstream ieff_graph; - std::stringstream estimated_error_pts; - std::stringstream exact_error_pts; - std::stringstream estimated_error_legend; - std::stringstream exact_error_legend; + latex_text << " \\subsection{$k = " << it->k_order << ", n = " << it->n_order << "$}\n"; + + std::stringstream error_graph, ieff_graph, estimated_error_pts, exact_error_pts, + estimated_error_legend, exact_error_legend, ieff_error_legend; error_graph << " \\begin{figure}[ht!]\n" - " \\centering\n" - " \\begin{tikzpicture}\n" - " \\begin{loglogaxis}[\n" - " width=0.6\\textwidth,\n" - " height=0.45\\textwidth,\n" - " xlabel={$h_{in}/h_{sk}$},\n" - " xtick scale label code/.code={},\n" - " legend pos=outer north east,\n" - " grid style=dashed,\n" - " cycle list name=mycycle,\n" - " ]\n"; + " \\centering\n" + " \\begin{tikzpicture}\n" + " \\begin{loglogaxis}[\n" + " width=0.6\\textwidth,\n" + " height=0.45\\textwidth,\n" + " xlabel={h_{sk}$},\n" + " xtick scale label code/.code={},\n" + " legend pos=outer north east,\n" + " grid style=dashed,\n" + " cycle list name=mycycle,\n" + " ]\n"; ieff_graph << " \\begin{figure}[ht!]\n" - " \\centering\n" - " \\begin{tikzpicture}\n" - " \\begin{loglogaxis}[\n" - " width=0.6\\textwidth,\n" - " height=0.4\\textwidth,\n" - " xlabel={$h_{in}/h_{sk}$},\n" - " %ymin=1.0, ymax=1.1,\n" - " xtick scale label code/.code={},\n" - " legend pos=#2,\n" - " grid style=dashed,\n" - " cycle list name=mycycle,\n" - " y tick label style={\n" - " /pgf/number format/.cd,\n" - " fixed,\n" - " fixed zerofill,\n" - " precision=2,\n" - " /tikz/.cd\n" - " },\n" - " ]\n"; + " \\centering\n" + " \\begin{tikzpicture}\n" + " \\begin{loglogaxis}[\n" + " width=0.6\\textwidth,\n" + " height=0.4\\textwidth,\n" + " xlabel={$h_{sk}$},\n" + " %ymin=1.0, ymax=1.1,\n" + " xtick scale label code/.code={},\n" + " legend pos=outer north east,\n" + " grid style=dashed,\n" + " cycle list name=mycycle,\n" + " y tick label style={\n" + " /pgf/number format/.cd,\n" + " fixed,\n" + " fixed zerofill,\n" + " precision=2,\n" + " /tikz/.cd\n" + " },\n" + " ]\n"; int current_int_ref = it->n_internal_ref; bool is_first = true; while (it->n_internal_ref == current_int_ref) { if (is_first) { - estimated_error_pts << " \\addplot\n \\coordinates{\n"; - exact_error_pts << " \\addplot\n \\coordinates{\n"; - ieff_graph << " \\addplot\n \\coordinates{\n"; + estimated_error_pts << " \\addplot\n \\coordinates{\n"; + exact_error_pts << " \\addplot\n \\coordinates{\n"; + ieff_graph << " \\addplot\n \\coordinates{\n"; is_first = false; + estimated_error_legend << " $h_{in} = h_{sk}/" + << std::to_string((int)pow(2, it->n_internal_ref)) + << "$ (estimated),\n"; + exact_error_legend << " $h_{in} = h_{sk}/" + << std::to_string((int)pow(2, it->n_internal_ref)) << "$ (exact),\n"; + ieff_error_legend << " $h_{in} = h_{sk}/" + << std::to_string((int)pow(2, it->n_internal_ref)) << "$,\n"; } - estimated_error_legend << " $h_{in} = h_{sk}/" << std::to_string(2 ^ it->n_internal_ref) - << "$ (estimated),\n"; - exact_error_legend << " $h_{in} = h_{sk}/" << std::to_string(2 ^ it->n_internal_ref) - << "$ (exact),\n"; - - estimated_error_pts << " (1/" << it->n_coarse_div << ", " << it->estimated_error << ")\n"; - exact_error_pts << " (1/" << it->n_coarse_div << ", " << it->exact_error << ")\n"; - ieff_graph << " (1/" << it->n_coarse_div << ", " << it->effectivity_index << ")\n"; + estimated_error_pts << " (1/" << it->n_coarse_div << ", " << it->estimated_error + << ")\n"; + exact_error_pts << " (1/" << it->n_coarse_div << ", " << it->exact_error << ")\n"; + ieff_graph << " (1/" << it->n_coarse_div << ", " << it->effectivity_index << ")\n"; + previous_n = it->n_order; + previous_k = it->k_order; + current_int_ref = it->n_internal_ref; + previous_problem = it->problem_name; if (it != result_vec.end()) { it++; + if (it->n_order == previous_n && it->k_order == previous_k && + it->n_internal_ref != current_int_ref) { + is_first = true; + current_int_ref = it->n_internal_ref; + } } } - estimated_error_pts << " };\n"; - exact_error_pts << " };\n"; - ieff_graph << " };\n"; + estimated_error_pts << " };\n"; + exact_error_pts << " };\n"; + ieff_graph << " };\n"; error_graph << estimated_error_pts.str(); error_graph << exact_error_pts.str(); - error_graph << " \\legend{\n" << estimated_error_legend.str() << exact_error_legend.str() - << " }\n" - " \\end{loglogaxis}\n" - " \\end{tikzpicture}\n" - " \\caption{#3}\n" - " \\end{figure}\n\n"; - - ieff_graph << " \\end{loglogaxis}\n" - " \\end{tikzpicture}\n" - " \\caption{#3}\n" - " \\end{figure}\n" - "}\n"; - - latex_text << error_graph.str(); - latex_text << ieff_graph.str(); + error_graph << " \\legend{\n" + << estimated_error_legend.str() << exact_error_legend.str() + << " }\n" + " \\end{loglogaxis}\n" + " \\end{tikzpicture}\n" + " \\caption{" + << "Estimated and exact errors, $k = " << previous_k << "$, $n = " << previous_n + << "$}\n \\end{figure}\n\n"; + + ieff_graph << " \\legend{\n" + << ieff_error_legend.str() + << " }\n" + " \\end{loglogaxis}\n" + " \\end{tikzpicture}\n" + " \\caption{" + "Effectivity index, $k = " << previous_k << "$, $n = " << previous_n + << "$}\n \\end{figure}\n\n"; + + latex_text << " % Error graph\n" << error_graph.str(); + latex_text << " % Ieff graph\n" << ieff_graph.str(); } } } - std::cout << latex_text.str(); + out << latex_text.str(); } } From c12052085bfff1e1c6efb284e7859b8378f1d6e3 Mon Sep 17 00:00:00 2001 From: Gustavo Batistela Date: Fri, 7 May 2021 18:16:22 -0300 Subject: [PATCH 007/187] Fix mistakes in atex graph printer function --- Projects/ErrorEstimationMHM/main_Journal.cpp | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp index 13e65e01..e17b0f6d 100644 --- a/Projects/ErrorEstimationMHM/main_Journal.cpp +++ b/Projects/ErrorEstimationMHM/main_Journal.cpp @@ -748,7 +748,7 @@ void PrintLatexGraphs(std::ostream & out) { " \\begin{loglogaxis}[\n" " width=0.6\\textwidth,\n" " height=0.45\\textwidth,\n" - " xlabel={h_{sk}$},\n" + " xlabel={$h_{sk}$},\n" " xtick scale label code/.code={},\n" " legend pos=outer north east,\n" " grid style=dashed,\n" @@ -758,7 +758,7 @@ void PrintLatexGraphs(std::ostream & out) { ieff_graph << " \\begin{figure}[ht!]\n" " \\centering\n" " \\begin{tikzpicture}\n" - " \\begin{loglogaxis}[\n" + " \\begin{semilogxaxis}[\n" " width=0.6\\textwidth,\n" " height=0.4\\textwidth,\n" " xlabel={$h_{sk}$},\n" @@ -779,9 +779,9 @@ void PrintLatexGraphs(std::ostream & out) { bool is_first = true; while (it->n_internal_ref == current_int_ref) { if (is_first) { - estimated_error_pts << " \\addplot\n \\coordinates{\n"; - exact_error_pts << " \\addplot\n \\coordinates{\n"; - ieff_graph << " \\addplot\n \\coordinates{\n"; + estimated_error_pts << " \\addplot\n coordinates{\n"; + exact_error_pts << " \\addplot\n coordinates{\n"; + ieff_graph << " \\addplot\n coordinates{\n"; is_first = false; estimated_error_legend << " $h_{in} = h_{sk}/" << std::to_string((int)pow(2, it->n_internal_ref)) @@ -807,6 +807,9 @@ void PrintLatexGraphs(std::ostream & out) { it->n_internal_ref != current_int_ref) { is_first = true; current_int_ref = it->n_internal_ref; + estimated_error_pts << " };\n"; + exact_error_pts << " };\n"; + ieff_graph << " };\n"; } } } @@ -828,7 +831,7 @@ void PrintLatexGraphs(std::ostream & out) { ieff_graph << " \\legend{\n" << ieff_error_legend.str() << " }\n" - " \\end{loglogaxis}\n" + " \\end{semilogxaxis}\n" " \\end{tikzpicture}\n" " \\caption{" "Effectivity index, $k = " << previous_k << "$, $n = " << previous_n @@ -836,6 +839,7 @@ void PrintLatexGraphs(std::ostream & out) { latex_text << " % Error graph\n" << error_graph.str(); latex_text << " % Ieff graph\n" << ieff_graph.str(); + latex_text << "\\clearpage\n"; } } } From 2a7485088cba44105bf4f252614f0e9310cb6815 Mon Sep 17 00:00:00 2001 From: Gustavo Batistela Date: Wed, 12 May 2021 11:21:52 -0300 Subject: [PATCH 008/187] Fix graph printing once more --- Projects/ErrorEstimationMHM/main_Journal.cpp | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp index e17b0f6d..7100a1ee 100644 --- a/Projects/ErrorEstimationMHM/main_Journal.cpp +++ b/Projects/ErrorEstimationMHM/main_Journal.cpp @@ -69,8 +69,8 @@ int main() { TPZLogger::InitializePZLOG(); gRefDBase.InitializeAllUniformRefPatterns(); - const std::set nCoarseDiv = {3, 4, 5, 6, 7}; - const std::set nInternalRef = {1, 2, 3}; + const std::set nCoarseDiv = {3, 4, 5};//, 6, 7}; + const std::set nInternalRef = {1, 2};//, 3}; const std::set kOrder = {1, 2}; const std::set nOrder = {1, 2}; @@ -94,7 +94,7 @@ int main() { } } - std::ofstream out_latex("LatextGraphs.txt", std::ios::trunc); + std::ofstream out_latex("LatexGraphs.txt", std::ios::trunc); PrintLatexGraphs(out_latex); //RunNonConvexProblem(); std::cout << "Bye!\n"; @@ -729,9 +729,9 @@ void PrintLatexGraphs(std::ostream & out) { auto it = result_vec.begin(); while (it != result_vec.end()) { - std::string previous_problem = it->problem_name; - while (it->problem_name == previous_problem) { - latex_text << "\\section{" << it->problem_name << "}\n"; + std::string current_problem = it->problem_name; + latex_text << "\\section{" << it->problem_name << "}\n"; + while (it->problem_name == current_problem) { int previous_k = it->k_order; while (it->k_order == previous_k) { @@ -800,7 +800,7 @@ void PrintLatexGraphs(std::ostream & out) { previous_n = it->n_order; previous_k = it->k_order; current_int_ref = it->n_internal_ref; - previous_problem = it->problem_name; + current_problem = it->problem_name; if (it != result_vec.end()) { it++; if (it->n_order == previous_n && it->k_order == previous_k && @@ -843,6 +843,7 @@ void PrintLatexGraphs(std::ostream & out) { } } } - out << latex_text.str(); } + out << latex_text.str(); + std::cout << latex_text.str(); } From ff5c2b1299a6878d6835fe77159834ae2e757837 Mon Sep 17 00:00:00 2001 From: Gustavo Batistela Date: Mon, 17 May 2021 19:02:29 -0300 Subject: [PATCH 009/187] Work on adaptivity problem --- Projects/ErrorEstimationMHM/main_Journal.cpp | 252 +++++++++++++++++-- 1 file changed, 236 insertions(+), 16 deletions(-) diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp index 7100a1ee..feea0b05 100644 --- a/Projects/ErrorEstimationMHM/main_Journal.cpp +++ b/Projects/ErrorEstimationMHM/main_Journal.cpp @@ -1,7 +1,6 @@ // // Created by Gustavo Batistela on 3/31/21. // - #include "pzgmesh.h" #include
 #include 
@@ -43,6 +42,7 @@ void RunNonConvexProblem();
 void RunHighGradientProblem(int nCoarseDiv, int nInternalRef);
 void RunInnerSingularityProblem(int nCoarseDiv, int nInternalRef, int k, int n);
 void RunPeriodicPermProblem(int nCoarseDiv, int nInternalRef);
+void RunHighGradientAdaptivityProblem(int n_steps);
 
 TPZGeoMesh *CreateQuadGeoMesh(int nCoarseDiv, int nInternalRef);
 TPZGeoMesh *CreateLShapeGeoMesh(int nCoarseRef, int nInternalRef, TPZStack &mhmIndexes);
@@ -56,8 +56,10 @@ void CreateMHMCompMeshHeteroPerm(TPZMHMixedMeshControl *mhm, const ProblemConfig
 void SolveMHMProblem(TPZMHMixedMeshControl *mhm, const ProblemConfig &config);
 
 void EstimateError(ProblemConfig &config, TPZMHMixedMeshControl *mhm);
+void EstimateError(ProblemConfig &config, TPZMHMixedMeshControl *mhm, TPZMHMHDivErrorEstimator &estimator);
 
-void MHMAdaptivity(TPZMHMixedMeshControl *mhm, TPZGeoMesh* gmeshToRefine, ProblemConfig& config);
+void MHMAdaptivity(TPZMHMixedMeshControl *mhm, TPZGeoMesh *gmeshToRefine, ProblemConfig &config,
+                   TPZCompMesh *postProcMesh);
 
 void CreateMHMCompMeshPermFunction(TPZMHMixedMeshControl &mhm);
 void PeriodicPermeabilityFunction(const TPZVec &coord, TPZVec &res, TPZFMatrix &res_mat);
@@ -65,40 +67,57 @@ void PeriodicProblemForcingFunction(const TPZVec  &pt, TPZVec  &res
 
 void PrintLatexGraphs(std::ostream & out);
 
+void RunSmoothProblemSuite(const std::set &nCoarseDiv, const std::set &nInternalRef,
+                           const std::set &kOrder, const std::set &nOrder);
+void RunInnerSingularityProblemSuite(const std::set &nCoarseDiv, const std::set &nInternalRef,
+                                     const std::set &kOrder, const std::set &nOrder);
+
+
+
 int main() {
     TPZLogger::InitializePZLOG();
     gRefDBase.InitializeAllUniformRefPatterns();
 
-    const std::set nCoarseDiv = {3, 4, 5};//, 6, 7};
-    const std::set nInternalRef = {1, 2};//, 3};
+    const std::set nCoarseDiv = {2, 4, 6, 8};
+    const std::set nInternalRef = {0, 1, 2, 3};
     const std::set kOrder = {1, 2};
     const std::set nOrder = {1, 2};
 
+    //RunSmoothProblemSuite(nCoarseDiv, nInternalRef, kOrder, nOrder);
+
+    //RunInnerSingularityProblemSuite(nCoarseDiv, nInternalRef, kOrder, nOrder);
+
+    RunHighGradientAdaptivityProblem(5);
+
+    //RunNonConvexProblem();
+    //std::ofstream out_latex("LatexGraphs.txt", std::ios::trunc);
+    //PrintLatexGraphs(out_latex);
+
+    return 0;
+}
+void RunInnerSingularityProblemSuite(const std::set &nCoarseDiv, const std::set &nInternalRef,
+                                     const std::set &kOrder, const std::set &nOrder) {
     for (const auto k : kOrder) {
         for (const auto n : nOrder) {
             for (const auto internal_ref : nInternalRef) {
                 for (const auto coarse_div : nCoarseDiv) {
-                    RunSmoothProblem(coarse_div, internal_ref, k, n);
+                    RunInnerSingularityProblem(coarse_div, internal_ref, k, n);
                 }
             }
         }
     }
-
+}
+void RunSmoothProblemSuite(const std::set &nCoarseDiv, const std::set &nInternalRef,
+                           const std::set &kOrder, const std::set &nOrder) {
     for (const auto k : kOrder) {
         for (const auto n : nOrder) {
             for (const auto internal_ref : nInternalRef) {
                 for (const auto coarse_div : nCoarseDiv) {
-                    RunInnerSingularityProblem(coarse_div, internal_ref, k, n);
+                    RunSmoothProblem(coarse_div, internal_ref, k, n);
                 }
             }
         }
     }
-
-    std::ofstream out_latex("LatexGraphs.txt", std::ios::trunc);
-    PrintLatexGraphs(out_latex);
-    //RunNonConvexProblem();
-    std::cout << "Bye!\n";
-    return 0;
 }
 
 void RunSmoothProblem(const int nCoarseDiv, const int nInternalRef, const int k, const int n) {
@@ -134,6 +153,7 @@ void RunSmoothProblem(const int nCoarseDiv, const int nInternalRef, const int k,
     CreateMHMCompMesh(mhm, config, nInternalRef, definePartitionByCoarseIndexes, coarseIndexes);
 
     SolveMHMProblem(mhm, config);
+    TPZCompMesh *cmesh = nullptr;
     EstimateError(config, mhm);
 }
 
@@ -207,6 +227,7 @@ void RunNonConvexProblem() {
     CreateMHMCompMesh(mhm, config, nInternalRef, definePartitionByCoarseIndexes, coarseIndexes);
 
     SolveMHMProblem(mhm, config);
+    TPZCompMesh *cmesh = nullptr;
     EstimateError(config, mhm);
 }
 
@@ -275,6 +296,7 @@ void RunInnerSingularityProblem(const int nCoarseDiv, const int nInternalRef, in
     CreateMHMCompMeshHeteroPerm(mhm, config, nInternalRef, definePartitionByCoarseIndexes, coarseIndexes);
 
     SolveMHMProblem(mhm, config);
+    TPZCompMesh *cmesh = nullptr;
     EstimateError(config, mhm);
 
 }
@@ -569,7 +591,7 @@ void InsertMaterialsInMHMMesh(TPZMHMixedMeshControl &control, const ProblemConfi
     int dim = control.GMesh()->Dimension();
     cmesh.SetDimModel(dim);
 
-    TPZMixedPoisson *mat = new TPZMixedPoisson(1, dim);
+    auto *mat = new TPZMixedPoisson(1, dim);
 
     TPZFMatrix K(3, 3, 0), invK(3, 3, 0);
     K.Identity();
@@ -609,7 +631,7 @@ void CreateMHMCompMeshHeteroPerm(TPZMHMixedMeshControl *mhm, const ProblemConfig
     int dim = mhm->GMesh()->Dimension();
     cmesh.SetDimModel(dim);
 
-    TPZMixedPoisson *mat = new TPZMixedPoisson(1, dim);
+    auto *mat = new TPZMixedPoisson(1, dim);
 
     TPZFMatrix K(3, 3, 0), invK(3, 3, 0);
     K.Identity();
@@ -623,7 +645,7 @@ void CreateMHMCompMeshHeteroPerm(TPZMHMixedMeshControl *mhm, const ProblemConfig
 
     cmesh.InsertMaterialObject(mat);
 
-    TPZMixedPoisson *mat2 = new TPZMixedPoisson(2, dim);
+    auto *mat2 = new TPZMixedPoisson(2, dim);
 
     TPZFMatrix K2(3, 3, 0), invK2(3, 3, 0);
     K2.Identity();
@@ -847,3 +869,201 @@ void PrintLatexGraphs(std::ostream & out) {
     out << latex_text.str();
     std::cout << latex_text.str();
 }
+
+void RunHighGradientAdaptivityProblem(const int n_steps){
+
+    ProblemConfig config;
+    config.dimension = 2;
+    config.exact = new TLaplaceExample1;
+    config.exact.operator*().fExact = TLaplaceExample1::EBoundaryLayer;
+    config.problemname = "EBoundaryLayer";
+    config.dir_name = "Adaptivity";
+    config.porder = 2;
+    config.hdivmais = 3;
+    config.materialids.insert(1);
+    config.bcmaterialids.insert(-1);
+    config.makepressurecontinuous = true;
+
+    int nCoarseRef = 5;
+    int nInternalRef = 1;
+
+    config.ndivisions = nCoarseRef;
+    config.gmesh = CreateQuadGeoMesh(nCoarseRef, nInternalRef);
+
+    std::string command = "mkdir -p " + config.dir_name;
+    system(command.c_str());
+
+    {
+        std::string fileName = config.dir_name + "/" + config.problemname + "GeoMesh.vtk";
+        std::ofstream file(fileName);
+        TPZVTKGeoMesh::PrintGMeshVTK(config.gmesh, file);
+    }
+
+    auto *mhm = new TPZMHMixedMeshControl(config.gmesh);
+    TPZManVector coarseIndexes;
+    ComputeCoarseIndices(config.gmesh, coarseIndexes);
+    bool definePartitionByCoarseIndexes = true;
+    CreateMHMCompMesh(mhm, config, nInternalRef, definePartitionByCoarseIndexes, coarseIndexes);
+
+    {
+        std::string fileName = config.dir_name + "/" + config.problemname + "GeoMeshAfterPartition.vtk";
+        std::ofstream file(fileName);
+        TPZVTKGeoMesh::PrintGMeshVTK(config.gmesh, file);
+    }
+
+    SolveMHMProblem(mhm, config);
+
+    bool postProcWithHDiv = false;
+    TPZMultiphysicsCompMesh *originalMesh = dynamic_cast(mhm->CMesh().operator->());
+    if (!originalMesh) DebugStop();
+    TPZMHMHDivErrorEstimator estimator(*originalMesh, mhm, postProcWithHDiv);
+    EstimateError(config, mhm, estimator);
+
+    auto *postprocmesh = estimator.PostProcMesh();
+    if (!postprocmesh) DebugStop();
+
+    const auto sol = postprocmesh->ElementSolution();
+    int64_t nelem = sol.Rows();
+
+    MHMAdaptivity(mhm, config.gmesh, config, postprocmesh);
+    //for (int iSteps = 0; iSteps < n_steps; iSteps++) {
+
+    //    {
+    //        std::string fileName = config.dir_name + "/" + config.problemname + "GeoMeshAdapt.vtk";
+    //        std::ofstream file(fileName);
+    //        TPZVTKGeoMesh::PrintGMeshVTK(config.gmesh, file);
+    //    }
+
+    //    config.adaptivityStep = iSteps;
+
+    //    mhm = new TPZMHMixedMeshControl(config.gmesh);
+    //    ComputeCoarseIndices(config.gmesh, coarseIndexes);
+    //    definePartitionByCoarseIndexes = true;
+    //    CreateMHMCompMesh(mhm, config, nInternalRef, definePartitionByCoarseIndexes, coarseIndexes);
+
+    //    SolveMHMProblem(mhm, config);
+    //    EstimateError(config, mhm);
+
+    //}
+}
+
+void MHMAdaptivity(TPZMHMixedMeshControl *mhm, TPZGeoMesh *gmeshToRefine, ProblemConfig &config,
+                   TPZCompMesh *postProcMesh) {
+
+    // Column of the flux error estimate on the element solution matrix
+    const int fluxErrorEstimateCol = 3;
+
+    TPZMultiphysicsCompMesh *cmesh = dynamic_cast(mhm->CMesh().operator->());
+    if (!cmesh) DebugStop();
+
+    TPZFMatrix &sol = cmesh->Solution();
+    TPZSolutionMatrix &elsol = cmesh->ElementSolution();
+    int64_t nelem = elsol.Rows();
+    int64_t nelem2 = sol.Rows();
+
+    //postProcessMesh->ElementSolution().Print("ElSolutionForAdaptivity",std::cout);
+
+    // Iterates through element errors to get the maximum value
+    REAL maxError = 0.;
+    for (int64_t iel = 0; iel < nelem; iel++) {
+        TPZCompEl* cel = cmesh->ElementVec()[iel];
+        if (!cel) continue;
+        if (cel->Dimension() != cmesh->Dimension()) continue;
+        REAL elementError = 0;//elsol(iel, fluxErrorEstimateCol);
+
+
+        if (elementError > maxError) {
+            maxError = elementError;
+        }
+    }
+
+    std::cout << "max error " << maxError << "\n";
+
+    // Refines elements which error are bigger than 30% of the maximum error
+    REAL threshold = 0.2 * maxError;
+
+    for (int64_t iel = 0; iel < nelem; iel++) {
+        TPZCompEl* cel = cmesh->ElementVec()[iel];
+        if (!cel) continue;
+        if (cel->Dimension() != cmesh->Dimension()) continue;
+
+        REAL elementError = 0;//elsol(iel, fluxErrorEstimateCol);
+        //prefinement
+        if (elementError > threshold) {
+
+            std::cout << "element error " << elementError << "el " << iel << "\n";
+            TPZGeoEl* gel = cel->Reference();
+            int iel = gel->Id();
+
+            TPZVec sons;
+            TPZGeoEl* gelToRefine = gmeshToRefine->ElementVec()[iel];
+            if (gelToRefine && !gelToRefine->HasSubElement()) {
+                gelToRefine->Divide(sons);
+#ifdef LOG4CXX2
+                int nsides = gelToRefine->NSides();
+                TPZVec loccenter(gelToRefine->Dimension());
+                TPZVec center(3);
+                gelToRefine->CenterPoint(nsides - 1, loccenter);
+
+                gelToRefine->X(loccenter, center);
+                static LoggerPtr logger(Logger::getLogger("HDivErrorEstimator"));
+                if (logger->isDebugEnabled()) {
+                    std::stringstream sout;
+                    sout << "\nCenter coord: = " << center[0] << " " << center[1] << "\n";
+                    sout << "Error = " << elementError << "\n\n";
+                    LOGPZ_DEBUG(logger, sout.str())
+                }
+#endif
+            }
+        } else {
+            std::cout << "como refinar em p? " << "\n";
+//            TPZInterpolationSpace *sp = dynamic_cast(cel);
+//            if(!sp) continue;
+//            int level = sp->Reference()->Level();
+//            int ordem = config.porder + (config.adaptivityStep -1 ) + (level);
+//            std::cout<<"level "<< level<<" ordem "<PRefine(ordem);
+
+        }
+    }
+    Tools::DivideLowerDimensionalElements(gmeshToRefine);
+}
+
+void EstimateError(ProblemConfig &config, TPZMHMixedMeshControl *mhm, TPZMHMHDivErrorEstimator& estimator) {
+
+    std::cout << "\nError Estimation processing for MHM-Hdiv problem " << std::endl;
+
+    // Error estimation
+    TPZMultiphysicsCompMesh *originalMesh = dynamic_cast(mhm->CMesh().operator->());
+    if (!originalMesh) DebugStop();
+
+    estimator.SetAnalyticSolution(config.exact);
+    estimator.PotentialReconstruction();
+
+    std::string command = "mkdir -p " + config.dir_name;
+    system(command.c_str());
+
+    TPZManVector errors;
+    TPZManVector elementerrors;
+    std::stringstream outVTK;
+    outVTK << config.dir_name << "/" << config.problemname << "-" << config.ndivisions << "-" << config.ninternalref
+           << "-Errors.vtk";
+    std::string outVTKstring = outVTK.str();
+    estimator.ComputeErrors(errors, elementerrors, outVTKstring);
+
+    {
+        std::string fileName = config.dir_name + "/" + config.problemname + "-GlobalErrors.txt";
+        std::ofstream file(fileName, std::ios::app);
+        Tools::PrintErrors(file, config, errors);
+    }
+
+    result_vec.emplace_back(config.problemname,
+                            config.ninternalref,
+                            config.ndivisions,
+                            config.porder,
+                            config.hdivmais,
+                            errors[3],
+                            errors[2],
+                            sqrt(errors[4] + errors[3]) / sqrt(errors[2])
+    );
+}

From 1b672c9e49674c48e1ffe40d4f4ae1c55270cf7c Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Mon, 17 May 2021 19:03:07 -0300
Subject: [PATCH 010/187] Move element solution out of loop

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 69071863..0d4d5cb6 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -112,12 +112,13 @@ void TPZHDivErrorEstimator::ComputeErrors(TPZVec&errorVec, TPZVec& e
     for (REAL & elementerror : elementErrors) {
         elementerror = 0;
     }
+
+    TPZFMatrix &elsol = fPostProcMesh.ElementSolution();
     for (int64_t i = 0; i < nelem; i++) {
         TPZCompEl *cel = fPostProcMesh.Element(i);
         if (!cel) continue;
         TPZGeoEl* gel = fPostProcMesh.Element(i)->Reference();
         if (!gel) continue;
-        TPZFMatrix &elsol = fPostProcMesh.ElementSolution();
         elementErrors[gel->Index()] = elsol(i, 3);
     }
     

From 41ec93bace6608813e76826c754de1f34bcba709 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Mon, 17 May 2021 19:03:27 -0300
Subject: [PATCH 011/187] Make CopmuteEffectivityIndices method static

---
 ErrorEstimation/TPZHDivErrorEstimator.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.h b/ErrorEstimation/TPZHDivErrorEstimator.h
index c97009d3..0df0c339 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.h
+++ b/ErrorEstimation/TPZHDivErrorEstimator.h
@@ -161,7 +161,7 @@ class TPZHDivErrorEstimator {
     void ComputeEffectivityIndices();
 
     /// compute the effectivity indices of the pressure error and flux error and store in the element solution
-    void ComputeEffectivityIndices(TPZSubCompMesh *subcmesh);
+    static void ComputeEffectivityIndices(TPZSubCompMesh *subcmesh);
 
     /// returns true if the material associated with the element is a boundary condition
     /// and if the boundary condition is dirichlet type

From 53859a054e207f8f2d1fe8920f398d090fdcdedc Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 27 May 2021 18:06:06 -0300
Subject: [PATCH 012/187] Templatized material data in function declarations

---
 .../Material/TPZHDivErrorEstimateMaterial.h           | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
index ed1a84c3..386175cf 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
@@ -29,14 +29,17 @@ class TPZHDivErrorEstimateMaterial : public TPZMixedPoisson {
     
     TPZHDivErrorEstimateMaterial &operator=(const TPZHDivErrorEstimateMaterial ©);
 
-    virtual void Contribute(TPZVec &datavec, REAL weight, TPZFMatrix &ek,
+    virtual void Contribute(TPZVec> &datavec, REAL weight, TPZFMatrix &ek,
                             TPZFMatrix &ef) override;
 
-    virtual void ContributeBC(TPZVec &datavec, REAL weight, TPZFMatrix &ek,
+    virtual void ContributeBC(TPZVec> &datavec, REAL weight, TPZFMatrix &ek,
                               TPZFMatrix &ef, TPZBndCond &bc) override;
 
-    virtual void FillDataRequirements(TPZVec &datavec) override;
-    virtual void FillBoundaryConditionDataRequirement(int type, TPZVec &datavec) override;
+    // TODO add doc
+    void FillDataRequirements(TPZVec > &datavec) const override;
+
+    // TODO add doc
+    void FillBoundaryConditionDataRequirements(int type, TPZVec > &datavec) const override;
 
     bool fNeumannLocalProblem = false;
 

From cc7d1064a676874d46bb598b2d26ced01b786fd3 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 27 May 2021 18:06:59 -0300
Subject: [PATCH 013/187] Use override instead of virtual in function
 declarations

---
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
index 386175cf..2c4af51d 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
@@ -25,7 +25,7 @@ class TPZHDivErrorEstimateMaterial : public TPZMixedPoisson {
     
     TPZHDivErrorEstimateMaterial(const TPZMixedPoisson ©);
     
-    virtual ~TPZHDivErrorEstimateMaterial();
+    ~TPZHDivErrorEstimateMaterial() override;
     
     TPZHDivErrorEstimateMaterial &operator=(const TPZHDivErrorEstimateMaterial ©);
 
@@ -47,7 +47,7 @@ class TPZHDivErrorEstimateMaterial : public TPZMixedPoisson {
         fNeumannLocalProblem = neumannProblem;
     }
 
-    virtual int NEvalErrors() override { return 5; } // erro de oscilacao de dados tbem
+    int NEvalErrors() override { return 5; }
 
     /// Compute the error and error estimate
     // error[0] - error computed with exact pressure

From 7e74b69e7eab8fcdce93cf0dab7d2a42f7c8f609 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 27 May 2021 18:07:34 -0300
Subject: [PATCH 014/187] Update to TPZMixedDarcyFlow material and use
 non-deprecated header

---
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
index 2c4af51d..f830baca 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
@@ -11,10 +11,10 @@
 #ifndef TPZHDivErrorEstimateMaterial_hpp
 #define TPZHDivErrorEstimateMaterial_hpp
 
-#include 
-#include "mixedpoisson.h"
+#include 
+#include "DarcyFlow/TPZMixedDarcyFlow.h"
 
-class TPZHDivErrorEstimateMaterial : public TPZMixedPoisson {
+class TPZHDivErrorEstimateMaterial : public TPZMixedDarcyFlow {
 
 public:
     TPZHDivErrorEstimateMaterial(int matid, int dim);
@@ -23,7 +23,7 @@ class TPZHDivErrorEstimateMaterial : public TPZMixedPoisson {
     
     TPZHDivErrorEstimateMaterial(const TPZHDivErrorEstimateMaterial ©);
     
-    TPZHDivErrorEstimateMaterial(const TPZMixedPoisson ©);
+    TPZHDivErrorEstimateMaterial(const TPZMixedDarcyFlow ©);
     
     ~TPZHDivErrorEstimateMaterial() override;
     

From b95e3ab8a8471cb9fd3fba21ce41831d6826f5b6 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 27 May 2021 18:14:17 -0300
Subject: [PATCH 015/187] Indented code

Sorry, I had to do it
---
 .../Material/TPZHDivErrorEstimateMaterial.cpp | 547 +++++++++---------
 1 file changed, 260 insertions(+), 287 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index 1acd756b..e5a10ba4 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -8,52 +8,37 @@
 #include "TPZHDivErrorEstimateMaterial.h"
 #include "pzaxestools.h"
 #include "TPZAnalyticSolution.h"
-#include "pzbndcond.h"
+#include "TPZBndCond.h"
 
 
 #ifdef LOG4CXX
 static LoggerPtr logger(Logger::getLogger("pz.errorestimation.hdiv"));
 #endif
 
-TPZHDivErrorEstimateMaterial::TPZHDivErrorEstimateMaterial(int matid, int dim) : TPZMixedPoisson(matid,dim)
-{
-    
-}
+TPZHDivErrorEstimateMaterial::TPZHDivErrorEstimateMaterial(int matid, int dim) : TPZMixedDarcyFlow(matid, dim) {}
 
-TPZHDivErrorEstimateMaterial::TPZHDivErrorEstimateMaterial() : TPZMixedPoisson()
-{
-    
-}
+TPZHDivErrorEstimateMaterial::TPZHDivErrorEstimateMaterial() : TPZMixedDarcyFlow() {}
 
-TPZHDivErrorEstimateMaterial::TPZHDivErrorEstimateMaterial(const TPZMixedPoisson ©) : TPZMixedPoisson(copy)
-{
-    
-}
+TPZHDivErrorEstimateMaterial::TPZHDivErrorEstimateMaterial(const TPZMixedDarcyFlow ©) : TPZMixedDarcyFlow(copy) {}
 
-TPZHDivErrorEstimateMaterial::TPZHDivErrorEstimateMaterial(const TPZHDivErrorEstimateMaterial ©) : TPZMixedPoisson(copy)
-{
-    
-}
+TPZHDivErrorEstimateMaterial::TPZHDivErrorEstimateMaterial(const TPZHDivErrorEstimateMaterial ©)
+        : TPZMixedDarcyFlow(copy) {}
 
-TPZHDivErrorEstimateMaterial::~TPZHDivErrorEstimateMaterial()
-{
-    
-}
+TPZHDivErrorEstimateMaterial::~TPZHDivErrorEstimateMaterial() {}
 
-TPZHDivErrorEstimateMaterial &TPZHDivErrorEstimateMaterial::operator=(const TPZHDivErrorEstimateMaterial ©)
-{
-    TPZMixedPoisson::operator=(copy);
+TPZHDivErrorEstimateMaterial &TPZHDivErrorEstimateMaterial::operator=(const TPZHDivErrorEstimateMaterial ©) {
+    TPZMixedDarcyFlow::operator=(copy);
     return *this;
 }
 
-int TPZHDivErrorEstimateMaterial::FirstNonNullApproxSpaceIndex(TPZVec &datavec){
+int TPZHDivErrorEstimateMaterial::FirstNonNullApproxSpaceIndex(TPZVec &datavec) {
 
     int nvec = datavec.NElements();
     int firstNoNullposition = -1;
 
-    for(int ivec = 0; ivec < nvec ; ivec++){
+    for (int ivec = 0; ivec < nvec; ivec++) {
         TPZMaterialData::MShapeFunctionType shapetype = datavec[ivec].fShapeType;
-        if(shapetype != TPZMaterialData::EEmpty){
+        if (shapetype != TPZMaterialData::EEmpty) {
             firstNoNullposition = ivec;
             return firstNoNullposition;
         }
@@ -62,8 +47,8 @@ int TPZHDivErrorEstimateMaterial::FirstNonNullApproxSpaceIndex(TPZVec &datavec, REAL weight, TPZFMatrix &ek, TPZFMatrix &ef)
-{
+void TPZHDivErrorEstimateMaterial::Contribute(const TPZVec> &datavec, REAL weight,
+                                              TPZFMatrix &ek, TPZFMatrix &ef) {
     /**
    
      datavec[0] H1 mesh, local uk/grad v for Mark reconstruction and Empty for H1 reconstruction
@@ -80,98 +65,95 @@ void TPZHDivErrorEstimateMaterial::Contribute(TPZVec &datavec,
      uk = int_K ukfem dx
    
      **/
-    
+
     int H1functionposition = 0;
     H1functionposition = FirstNonNullApproxSpaceIndex(datavec);
-    
+
     int dim = datavec[H1functionposition].axes.Rows();
     //defining test functions
     // Setting the phis
     TPZFMatrix &phiuk = datavec[H1functionposition].phi;
     TPZFMatrix &dphiukaxes = datavec[H1functionposition].dphix;
-    TPZFNMatrix<9,REAL> dphiuk(3,dphiukaxes.Cols());
+    TPZFNMatrix<9, REAL> dphiuk(3, dphiukaxes.Cols());
     TPZAxesTools::Axes2XYZ(dphiukaxes, dphiuk, datavec[H1functionposition].axes);
-    
-    
+
+
     int nphiuk = phiuk.Rows();
-    
-    TPZFMatrix solsigmafem(3,nphiuk),solukfem(1,1);
+
+    TPZFMatrix solsigmafem(3, nphiuk), solukfem(1, 1);
     solsigmafem.Zero();
     solukfem.Zero();
-    
-    
 
 
-        //potetial fem
-        solukfem(0,0) = datavec[3].sol[0][0];
-        //flux fem
-        for (int ip = 0; ip<3; ip++){
 
-            solsigmafem(ip,0) = datavec[2].sol[0][ip];
-        }
 
-    
-    
-    TPZFNMatrix<9,REAL> PermTensor;
-    TPZFNMatrix<9,REAL> InvPermTensor;
-    
+    //potetial fem
+    solukfem(0, 0) = datavec[3].sol[0][0];
+    //flux fem
+    for (int ip = 0; ip < 3; ip++) {
+
+        solsigmafem(ip, 0) = datavec[2].sol[0][ip];
+    }
+
+
+    TPZFNMatrix<9, REAL> PermTensor;
+    TPZFNMatrix<9, REAL> InvPermTensor;
+
     GetPermeabilities(datavec[1].x, PermTensor, InvPermTensor);
-    
-    
-    TPZFMatrix kgraduk(3,nphiuk,0.);
-    
-        
-    for(int irow=0 ; irow kgraduk(3, nphiuk, 0.);
+
+
+    for (int irow = 0; irow < nphiuk; irow++) {
+
         //K graduk
-        for(int id=0; id< dim; id++){
-            
-            for(int jd=0; jd< dim;jd++){
-                
-                kgraduk(id,irow) += PermTensor(id,jd)*dphiuk(jd,irow);
-                
+        for (int id = 0; id < dim; id++) {
+
+            for (int jd = 0; jd < dim; jd++) {
+
+                kgraduk(id, irow) += PermTensor(id, jd) * dphiuk(jd, irow);
+
             }
             //bk = (-1)*int_k sigmaukfem.grad phi_i,here dphiuk is multiplied by axes
             //the minus sign is necessary because we are working with sigma_h = - K grad u, Mark works with sigma_h = K grad u
-            
-            ef(irow,0)+=(-1.)*weight*dphiuk(id,irow)*solsigmafem(id,0);
+
+            ef(irow, 0) += (-1.) * weight * dphiuk(id, irow) * solsigmafem(id, 0);
         }
-        
+
         //matrix Sk= int_{K} K graduk.gradv
-        for(int jcol=0; jcol &datavec, REAL weight, TPZFMatrix &ek,
@@ -254,30 +236,29 @@ void TPZHDivErrorEstimateMaterial::ContributeBC(TPZVec &datavec
     }
 }
 
-void TPZHDivErrorEstimateMaterial::FillDataRequirements(TPZVec &datavec) {
+void TPZHDivErrorEstimateMaterial::FillDataRequirements(TPZVec &datavec) {
+
+    //fem solution for flux and potential
+    datavec[2].SetAllRequirements(false);
+    datavec[2].fNeedsSol = true;
+    datavec[2].fNeedsNormal = true;
+
+    datavec[3].SetAllRequirements(false);
+    datavec[3].fNeedsSol = true;
 
-        //fem solution for flux and potential
-        datavec[2].SetAllRequirements(false);
-        datavec[2].fNeedsSol = true;
-        datavec[2].fNeedsNormal = true;
-        
-        datavec[3].SetAllRequirements(false);
-        datavec[3].fNeedsSol = true;
-  
 
 }
 
-void TPZHDivErrorEstimateMaterial::FillBoundaryConditionDataRequirement(int type,TPZVec &datavec){
+void TPZHDivErrorEstimateMaterial::FillBoundaryConditionDataRequirement(int type, TPZVec &datavec) {
 
     datavec[2].SetAllRequirements(false);
     datavec[2].fNeedsSol = true;
     datavec[2].fNeedsNormal = true;
-        
-    
+
+
 }
 
-void TPZHDivErrorEstimateMaterial::Errors(TPZVec &data, TPZVec &errors)
-{    
+void TPZHDivErrorEstimateMaterial::Errors(TPZVec &data, TPZVec &errors) {
     /**
      datavec[0] H1 mesh, uh_reconstructed
      datavec[1] L2 mesh,
@@ -290,113 +271,114 @@ void TPZHDivErrorEstimateMaterial::Errors(TPZVec &data, TPZVec<
       error[3] - energy error computed with reconstructed solution
       error[4] - oscilatory data error
      **/
-    
+
     errors.Resize(NEvalErrors());
     errors.Fill(0.0);
-    
-    
-    TPZManVector fluxfem(3);
+
+
+    TPZManVector fluxfem(3);
     STATE divsigmafem, pressurefem, pressurereconstructed;
     divsigmafem = 0.;
     pressurefem = 0.;
     pressurereconstructed = 0.;
-    
-    
-    TPZFNMatrix<3,REAL> fluxreconstructed(3,1), fluxreconstructed2(3,1);
-    
+
+
+    TPZFNMatrix<3, REAL> fluxreconstructed(3, 1), fluxreconstructed2(3, 1);
+
 
     fluxfem = data[2].sol[0];
-    
 
-    divsigmafem= data[2].divsol[0][0];
-    
-    STATE divtest=0.;
-    for (int j=0; j divsigma(1);
-    divsigma[0]=0.;
+    divsigma[0] = 0.;
 
     TPZManVector u_exact(1);
     TPZFNMatrix<9, STATE> du_exact(3, 3);
-    if(this->fExactSol){
-        
-        this->fExactSol->Execute(data[H1functionposition].x,u_exact,du_exact);
-    
-        this->fForcingFunction->Execute(data[H1functionposition].x,divsigma);
+    if (this->fExactSol) {
+
+        this->fExactSol->Execute(data[H1functionposition].x, u_exact, du_exact);
+
+        this->fForcingFunction->Execute(data[H1functionposition].x, divsigma);
     }
-    
+
     REAL residual = 0.;
 
-    residual = (divsigma[0] - divsigmafem)*(divsigma[0] - divsigmafem);
-   
-    
+    residual = (divsigma[0] - divsigmafem) * (divsigma[0] - divsigmafem);
+
+
     pressurereconstructed = data[H1functionposition].sol[0][0];
-  
- 
-        pressurefem = data[3].sol[0][0];
-    
-    TPZFNMatrix<9,REAL> PermTensor;
-    TPZFNMatrix<9,REAL> InvPermTensor;
-    
+
+
+    pressurefem = data[3].sol[0][0];
+
+    TPZFNMatrix<9, REAL> PermTensor;
+    TPZFNMatrix<9, REAL> InvPermTensor;
+
     GetPermeabilities(data[2].x, PermTensor, InvPermTensor);
-    
-    TPZFNMatrix<3,REAL> fluxexactneg;
-    
+
+    TPZFNMatrix<3, REAL> fluxexactneg;
+
     //sigmarec = -K grad(urec)
     //  sigmak = -K graduk
-    
+
     {
-        TPZFNMatrix<9,REAL> gradpressure(3,1);
-        for (int i=0; i<3; i++) {
-            gradpressure(i,0) = du_exact[i];
+        TPZFNMatrix<9, REAL> gradpressure(3, 1);
+        for (int i = 0; i < 3; i++) {
+            gradpressure(i, 0) = du_exact[i];
         }
-        PermTensor.Multiply(gradpressure,fluxexactneg);
+        PermTensor.Multiply(gradpressure, fluxexactneg);
     }
-    
-    
-    
+
+
     TPZFMatrix &dsolaxes = data[H1functionposition].dsol[0];
-    TPZFNMatrix<9,REAL> fluxrec(3,0);
+    TPZFNMatrix<9, REAL> fluxrec(3, 0);
     TPZAxesTools::Axes2XYZ(dsolaxes, fluxrec, data[H1functionposition].axes);
-    
-    for(int id=0 ; id<3; id++) {
-        fluxreconstructed2(id,0) = (-1.)*fluxrec(id,0);
+
+    for (int id = 0; id < 3; id++) {
+        fluxreconstructed2(id, 0) = (-1.) * fluxrec(id, 0);
     }
-    
-     PermTensor.Multiply(fluxreconstructed2,fluxreconstructed);
-    
-    
+
+    PermTensor.Multiply(fluxreconstructed2, fluxreconstructed);
+
+
     REAL innerexact = 0.;
     REAL innerestimate = 0.;
-    
-    
-    
+
+
 #ifdef PZDEBUG2
     std::cout<<"flux fem "< &data, TPZVec<
 #endif
 }
 
-int TPZHDivErrorEstimateMaterial::VariableIndex(const std::string &name)
-{
-    if(name == "FluxFem") return 40;
-    if(name == "FluxReconstructed") return 41;
-    if(name == "FluxExact") return 42;
-    if(name == "PressureFem") return 43;
-    if(name == "PressureReconstructed") return 44;
-    if(name == "PressureExact") return 45;
-    if(name == "PressureErrorExact") return 100;
-    if(name == "PressureErrorEstimate") return 101;
-    if(name == "EnergyErrorExact") return 102;
-    if(name == "EnergyErrorEstimate") return 103;
-    if(name == "ResidualError") return 104;
-    if(name == "PressureEffectivityIndex") return 105;
-    if(name == "EnergyEffectivityIndex") return 106;
-    if(name == "POrder") return 46;
-     
+int TPZHDivErrorEstimateMaterial::VariableIndex(const std::string &name) {
+    if (name == "FluxFem") return 40;
+    if (name == "FluxReconstructed") return 41;
+    if (name == "FluxExact") return 42;
+    if (name == "PressureFem") return 43;
+    if (name == "PressureReconstructed") return 44;
+    if (name == "PressureExact") return 45;
+    if (name == "PressureErrorExact") return 100;
+    if (name == "PressureErrorEstimate") return 101;
+    if (name == "EnergyErrorExact") return 102;
+    if (name == "EnergyErrorEstimate") return 103;
+    if (name == "ResidualError") return 104;
+    if (name == "PressureEffectivityIndex") return 105;
+    if (name == "EnergyEffectivityIndex") return 106;
+    if (name == "POrder") return 46;
+
     return -1;
 }
 
 
-int TPZHDivErrorEstimateMaterial::NSolutionVariables(int var)
-{
+int TPZHDivErrorEstimateMaterial::NSolutionVariables(int var) {
     switch (var) {
         case 40:
         case 41:
@@ -471,8 +451,7 @@ int TPZHDivErrorEstimateMaterial::NSolutionVariables(int var)
  * @param Solout [out] is the solution vector
  */
 
-void TPZHDivErrorEstimateMaterial::Solution(TPZVec &datavec, int var, TPZVec &Solout)
-{
+void TPZHDivErrorEstimateMaterial::Solution(TPZVec &datavec, int var, TPZVec &Solout) {
 
     /**
      datavec[0] H1 mesh, uh_reconstructed for Mark reconstruction and Empty for H1 reconstruction
@@ -480,56 +459,54 @@ void TPZHDivErrorEstimateMaterial::Solution(TPZVec &datavec, in
      datavec[2] Hdiv fem mesh, sigma_h
      datavec[3] L2 mesh fem, u_h
      **/
-    
+
     int H1functionposition = 0;
     H1functionposition = FirstNonNullApproxSpaceIndex(datavec);
-    
-    TPZFNMatrix<9,REAL> PermTensor;
-    TPZFNMatrix<9,REAL> InvPermTensor;
-    
+
+    TPZFNMatrix<9, REAL> PermTensor;
+    TPZFNMatrix<9, REAL> InvPermTensor;
+
     GetPermeabilities(datavec[2].x, PermTensor, InvPermTensor);
-    
-    
-    TPZManVector pressexact(1,0.);
-    TPZFNMatrix<9,STATE> gradu(3,1,0.), fluxinv(3,1);
-    
-    if(fExactSol)
-    {
-        this->fExactSol->Execute(datavec[H1functionposition].x, pressexact,gradu);
-       
+
+
+    TPZManVector pressexact(1, 0.);
+    TPZFNMatrix<9, STATE> gradu(3, 1, 0.), fluxinv(3, 1);
+
+    if (fExactSol) {
+        this->fExactSol->Execute(datavec[H1functionposition].x, pressexact, gradu);
+
     }
-    
+
     PermTensor.Multiply(gradu, fluxinv);
-    
-    int dim=this->fDim;
-    switch (var)
-    {
+
+    int dim = this->fDim;
+    switch (var) {
         case 40://FluxFem
-  
-            for(int i=0; i<3; i++) Solout[i] = datavec[2].sol[0][i];
+
+            for (int i = 0; i < 3; i++) Solout[i] = datavec[2].sol[0][i];
 
             break;
-        case 41:{//FluxReconstructed is grad U
+        case 41: {//FluxReconstructed is grad U
             TPZFMatrix &dsolaxes = datavec[H1functionposition].dsol[0];
-            TPZFNMatrix<9,REAL> dsol(3,0);
-             TPZFNMatrix<9,REAL> KGradsol(3,0);
+            TPZFNMatrix<9, REAL> dsol(3, 0);
+            TPZFNMatrix<9, REAL> KGradsol(3, 0);
             TPZAxesTools::Axes2XYZ(dsolaxes, dsol, datavec[H1functionposition].axes);
-            
-            PermTensor.Multiply(dsol,KGradsol);
-            
-            for(int id=0 ; id &datavec, in
     }
 }
 
-void TPZHDivErrorEstimateMaterial:: ErrorsBC(TPZVec &data, TPZVec &u_exact, TPZFMatrix &du_exact, TPZVec &errors,TPZBndCond &bc){
-    
-    if(bc.Type()== 4){
-    
+void TPZHDivErrorEstimateMaterial::ErrorsBC(TPZVec &data, TPZVec &u_exact,
+                                            TPZFMatrix &du_exact, TPZVec &errors, TPZBndCond &bc) {
 
-    errors.Resize(NEvalErrors());
-    errors.Fill(0.0);
-    
-    
-    TPZFNMatrix<3,REAL> fluxreconstructed(3,1), fluxreconstructed2(3,1);
-    TPZManVector fluxfem(3);
-        
-    int H1functionposition = 0;
-    H1functionposition = FirstNonNullApproxSpaceIndex(data);
+    if (bc.Type() == 4) {
 
-    REAL normalsigmafem = 0.,normalsigmarec = 0.,urec=0.;;
-    normalsigmafem = data[2].sol[0][0];// sigma.n
-    urec = data[H1functionposition].sol[0][0];
 
+        errors.Resize(NEvalErrors());
+        errors.Fill(0.0);
 
-    
-    REAL u_D = 0.,g = 0.;
-    REAL normflux = 0.;
-        
-        TPZManVector fluxrec(fDim);
-        this->Solution(data,VariableIndex("FluxReconstructed"), fluxrec);
-        
-  //      std::cout<<"flux_rec "< PermTensor, InvPermTensor;
-    TPZManVector res(3);
-    TPZFNMatrix<9, STATE> gradu(this->Dimension(), 1);
 
-    if (bc.HasForcingFunction()) {
+        TPZFNMatrix<3, REAL> fluxreconstructed(3, 1), fluxreconstructed2(3, 1);
+        TPZManVector fluxfem(3);
+
+        int H1functionposition = 0;
+        H1functionposition = FirstNonNullApproxSpaceIndex(data);
+
+        REAL normalsigmafem = 0., normalsigmarec = 0., urec = 0.;;
+        normalsigmafem = data[2].sol[0][0];// sigma.n
+        urec = data[H1functionposition].sol[0][0];
+
+
+        REAL u_D = 0., g = 0.;
+        REAL normflux = 0.;
+
+        TPZManVector fluxrec(fDim);
+        this->Solution(data, VariableIndex("FluxReconstructed"), fluxrec);
+
+        //      std::cout<<"flux_rec "< PermTensor, InvPermTensor;
+        TPZManVector res(3);
+        TPZFNMatrix<9, STATE> gradu(this->Dimension(), 1);
+
+        if (bc.HasForcingFunction()) {
             bc.ForcingFunction()->Execute(data[H1functionposition].x, res, gradu);
             GetPermeabilities(data[0].x, PermTensor, InvPermTensor);
-        u_D = res[0];
-        
-            
+            u_D = res[0];
+
+
         } else {
             // usualmente updatebc coloca o valor exato no val2
             u_D = bc.Val2()(0, 0);
         }
-        
-        
-        for(int i=0; i<3; i++)
-        {
-            for(int j=0; j<3; j++)
-            {
-                
-                normflux += data[2].normal[i]*PermTensor(i,j)*gradu(j,0);
-            
+
+
+        for (int i = 0; i < 3; i++) {
+            for (int j = 0; j < 3; j++) {
+
+                normflux += data[2].normal[i] * PermTensor(i, j) * gradu(j, 0);
+
             }
         }
-        g = (-1)*normflux;
-        
- //       std::cout<<"n_0 "<
Date: Thu, 27 May 2021 18:38:51 -0300
Subject: [PATCH 016/187] [ongoing] Update signatures of basic material methods

---
 .../Material/TPZHDivErrorEstimateMaterial.cpp | 22 +++++++++----------
 .../Material/TPZHDivErrorEstimateMaterial.h   | 20 +++++++++--------
 2 files changed, 22 insertions(+), 20 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index e5a10ba4..fc15044f 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -156,8 +156,8 @@ void TPZHDivErrorEstimateMaterial::Contribute(const TPZVec &datavec, REAL weight, TPZFMatrix &ek,
-                                                TPZFMatrix &ef, TPZBndCond &bc) {
+void TPZHDivErrorEstimateMaterial::ContributeBC(const TPZVec> &datavec, REAL weight,
+                                                TPZFMatrix &ek, TPZFMatrix &ef, TPZBndCondT &bc) {
 
     /*
      Add Robin boundary condition for local problem
@@ -236,7 +236,7 @@ void TPZHDivErrorEstimateMaterial::ContributeBC(TPZVec &datavec
     }
 }
 
-void TPZHDivErrorEstimateMaterial::FillDataRequirements(TPZVec &datavec) {
+void TPZHDivErrorEstimateMaterial::FillDataRequirements(TPZVec> &datavec) const {
 
     //fem solution for flux and potential
     datavec[2].SetAllRequirements(false);
@@ -249,16 +249,15 @@ void TPZHDivErrorEstimateMaterial::FillDataRequirements(TPZVec
 
 }
 
-void TPZHDivErrorEstimateMaterial::FillBoundaryConditionDataRequirement(int type, TPZVec &datavec) {
-
+void
+TPZHDivErrorEstimateMaterial::FillBoundaryConditionDataRequirements(int type,
+                                                                    TPZVec> &datavec) const {
     datavec[2].SetAllRequirements(false);
     datavec[2].fNeedsSol = true;
     datavec[2].fNeedsNormal = true;
-
-
 }
 
-void TPZHDivErrorEstimateMaterial::Errors(TPZVec &data, TPZVec &errors) {
+void TPZHDivErrorEstimateMaterial::Errors(const TPZVec> &data, TPZVec &errors) {
     /**
      datavec[0] H1 mesh, uh_reconstructed
      datavec[1] L2 mesh,
@@ -396,7 +395,7 @@ void TPZHDivErrorEstimateMaterial::Errors(TPZVec &data, TPZVec<
 #endif
 }
 
-int TPZHDivErrorEstimateMaterial::VariableIndex(const std::string &name) {
+int TPZHDivErrorEstimateMaterial::VariableIndex(const std::string &name) const {
     if (name == "FluxFem") return 40;
     if (name == "FluxReconstructed") return 41;
     if (name == "FluxExact") return 42;
@@ -416,7 +415,7 @@ int TPZHDivErrorEstimateMaterial::VariableIndex(const std::string &name) {
 }
 
 
-int TPZHDivErrorEstimateMaterial::NSolutionVariables(int var) {
+int TPZHDivErrorEstimateMaterial::NSolutionVariables(int var) const {
     switch (var) {
         case 40:
         case 41:
@@ -451,7 +450,8 @@ int TPZHDivErrorEstimateMaterial::NSolutionVariables(int var) {
  * @param Solout [out] is the solution vector
  */
 
-void TPZHDivErrorEstimateMaterial::Solution(TPZVec &datavec, int var, TPZVec &Solout) {
+void
+TPZHDivErrorEstimateMaterial::Solution(const TPZVec> &datavec, int var, TPZVec &Solout) {
 
     /**
      datavec[0] H1 mesh, uh_reconstructed for Mark reconstruction and Empty for H1 reconstruction
diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
index f830baca..e39a89a8 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
@@ -13,6 +13,7 @@
 
 #include 
 #include "DarcyFlow/TPZMixedDarcyFlow.h"
+#include "TPZMaterialDataT.h"
 
 class TPZHDivErrorEstimateMaterial : public TPZMixedDarcyFlow {
 
@@ -29,11 +30,11 @@ class TPZHDivErrorEstimateMaterial : public TPZMixedDarcyFlow {
     
     TPZHDivErrorEstimateMaterial &operator=(const TPZHDivErrorEstimateMaterial ©);
 
-    virtual void Contribute(TPZVec> &datavec, REAL weight, TPZFMatrix &ek,
+    void Contribute(const TPZVec> &datavec, REAL weight, TPZFMatrix &ek,
                             TPZFMatrix &ef) override;
 
-    virtual void ContributeBC(TPZVec> &datavec, REAL weight, TPZFMatrix &ek,
-                              TPZFMatrix &ef, TPZBndCond &bc) override;
+    void ContributeBC(const TPZVec> &datavec, REAL weight, TPZFMatrix &ek,
+                      TPZFMatrix &ef, TPZBndCondT &bc) override;
 
     // TODO add doc
     void FillDataRequirements(TPZVec > &datavec) const override;
@@ -54,14 +55,15 @@ class TPZHDivErrorEstimateMaterial : public TPZMixedDarcyFlow {
     // error[1] - error computed with reconstructed pressure
     // error[2] - energy error computed with exact solution
     // error[3] - energy error computed with reconstructed solution
-    virtual void Errors(TPZVec &data, TPZVec &errors) override;
+    void Errors(const TPZVec> &data, TPZVec &errors) override;
 
-    void ErrorsBC(TPZVec &data, TPZVec &u_exact, TPZFMatrix &du_exact,
-                  TPZVec &errors, TPZBndCond &bc) override;
+    void ErrorsBC(const TPZVec> &data, TPZVec &u_exact, TPZFMatrix &du_exact,
+                  TPZVec &errors, TPZBndCond &bc);
 
-    virtual int VariableIndex(const std::string &name) override;
-    virtual int NSolutionVariables(int var) override;
-    virtual void Solution(TPZVec &datavec, int var, TPZVec &Solout) override;
+    [[nodiscard]] int VariableIndex(const std::string &name) const override;
+    [[nodiscard]] int NSolutionVariables(int var) const override;
+
+    void Solution(const TPZVec> &datavec, int var, TPZVec &Solout) override;
 
     // Returns the first non-null approximation space index, which will be the
     // H1 reconstruction space

From 84dc61599d9697b9585bddd41153eb085ee7bc94 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 27 May 2021 18:54:07 -0300
Subject: [PATCH 017/187] Templatize material data in FirstNonNullSpace method

---
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp | 3 +--
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h   | 2 +-
 2 files changed, 2 insertions(+), 3 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index fc15044f..fc04554d 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -31,7 +31,7 @@ TPZHDivErrorEstimateMaterial &TPZHDivErrorEstimateMaterial::operator=(const TPZH
     return *this;
 }
 
-int TPZHDivErrorEstimateMaterial::FirstNonNullApproxSpaceIndex(TPZVec &datavec) {
+int TPZHDivErrorEstimateMaterial::FirstNonNullApproxSpaceIndex(TPZVec> &datavec) {
 
     int nvec = datavec.NElements();
     int firstNoNullposition = -1;
@@ -474,7 +474,6 @@ TPZHDivErrorEstimateMaterial::Solution(const TPZVec> &da
 
     if (fExactSol) {
         this->fExactSol->Execute(datavec[H1functionposition].x, pressexact, gradu);
-
     }
 
     PermTensor.Multiply(gradu, fluxinv);
diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
index e39a89a8..dc7b6570 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
@@ -67,7 +67,7 @@ class TPZHDivErrorEstimateMaterial : public TPZMixedDarcyFlow {
 
     // Returns the first non-null approximation space index, which will be the
     // H1 reconstruction space
-    int FirstNonNullApproxSpaceIndex(TPZVec &datavec);
+    int FirstNonNullApproxSpaceIndex(TPZVec> &datavec);
 };
 
 #endif /* TPZHDivErrorEstimateMaterial_hpp */

From 9aae150e3ff02316418d186bcaaa7ef494058e20 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 27 May 2021 18:55:40 -0300
Subject: [PATCH 018/187] Change declaration of FirstNonNullApproxSpaceIndex
 method

---
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp | 2 +-
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h   | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index fc04554d..5e64bd11 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -31,7 +31,7 @@ TPZHDivErrorEstimateMaterial &TPZHDivErrorEstimateMaterial::operator=(const TPZH
     return *this;
 }
 
-int TPZHDivErrorEstimateMaterial::FirstNonNullApproxSpaceIndex(TPZVec> &datavec) {
+int TPZHDivErrorEstimateMaterial::FirstNonNullApproxSpaceIndex(const TPZVec> &datavec) {
 
     int nvec = datavec.NElements();
     int firstNoNullposition = -1;
diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
index dc7b6570..eabbf5c6 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
@@ -67,7 +67,7 @@ class TPZHDivErrorEstimateMaterial : public TPZMixedDarcyFlow {
 
     // Returns the first non-null approximation space index, which will be the
     // H1 reconstruction space
-    int FirstNonNullApproxSpaceIndex(TPZVec> &datavec);
+    static int FirstNonNullApproxSpaceIndex(const TPZVec> &datavec);
 };
 
 #endif /* TPZHDivErrorEstimateMaterial_hpp */

From 6c6c6d04c33e33c00d6c256882db1d5c3c4a8b3c Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 27 May 2021 18:57:57 -0300
Subject: [PATCH 019/187] Fix forcing function and exact sol calls

---
 .../Material/TPZHDivErrorEstimateMaterial.cpp          | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index 5e64bd11..ae3d4d5e 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -181,10 +181,10 @@ void TPZHDivErrorEstimateMaterial::ContributeBC(const TPZVec res(3);
         TPZFNMatrix<9, STATE> gradu(dim, 1);
-        bc.ForcingFunction()->Execute(datavec[H1functionposition].x, res, gradu);
+        bc.ForcingFunctionBC()(datavec[H1functionposition].x, res, gradu);
         u_D = res[0];
 
         TPZFNMatrix<9, REAL> PermTensor, InvPermTensor;
@@ -306,9 +306,9 @@ void TPZHDivErrorEstimateMaterial::Errors(const TPZVec>
     TPZFNMatrix<9, STATE> du_exact(3, 3);
     if (this->fExactSol) {
 
-        this->fExactSol->Execute(data[H1functionposition].x, u_exact, du_exact);
+        this->fExactSol(data[H1functionposition].x, u_exact, du_exact);
 
-        this->fForcingFunction->Execute(data[H1functionposition].x, divsigma);
+        this->fForcingFunction(data[H1functionposition].x, divsigma);
     }
 
     REAL residual = 0.;
@@ -473,7 +473,7 @@ TPZHDivErrorEstimateMaterial::Solution(const TPZVec> &da
     TPZFNMatrix<9, STATE> gradu(3, 1, 0.), fluxinv(3, 1);
 
     if (fExactSol) {
-        this->fExactSol->Execute(datavec[H1functionposition].x, pressexact, gradu);
+        this->fExactSol(datavec[H1functionposition].x, pressexact, gradu);
     }
 
     PermTensor.Multiply(gradu, fluxinv);

From 4ce6a5348624875ebcd7f09ea8510536ad436039 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 27 May 2021 18:58:16 -0300
Subject: [PATCH 020/187] Fix call to Val2

---
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index ae3d4d5e..d0b22274 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -200,7 +200,7 @@ void TPZHDivErrorEstimateMaterial::ContributeBC(const TPZVec
Date: Thu, 27 May 2021 19:00:55 -0300
Subject: [PATCH 021/187] Update bignumber variable

---
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index d0b22274..e9beaeb9 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -221,9 +221,9 @@ void TPZHDivErrorEstimateMaterial::ContributeBC(const TPZVec
Date: Thu, 27 May 2021 19:06:28 -0300
Subject: [PATCH 022/187] Fix analysis header

---
 ErrorEstimation/TPZHDivErrorEstimator.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.h b/ErrorEstimation/TPZHDivErrorEstimator.h
index 0df0c339..7b8d3a5d 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.h
+++ b/ErrorEstimation/TPZHDivErrorEstimator.h
@@ -13,7 +13,7 @@
 #include "TPZMultiphysicsCompMesh.h"
 #include "TPZAnalyticSolution.h"
 #include "ProblemConfig.h"
-#include "pzanalysis.h"
+#include "TPZAnalysis.h"
 #include "pzsubcmesh.h"
 
 /// this class will compute the estimated value of the energy error of the input mesh

From 06c5da83ba96be7b9f78f96cd41cb611ea00289a Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 27 May 2021 19:07:14 -0300
Subject: [PATCH 023/187] Fix a few headers

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 0d4d5cb6..fe0f74ce 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -12,9 +12,9 @@
 #include "TPZInterfaceEl.h"
 #include "TPZMixedHdivErrorEstimate.h"
 #include "TPZNullMaterial.h"
-#include "mixedpoisson.h"
-#include "pzanalysis.h"
-#include "pzbndcond.h"
+#include "DarcyFlow/TPZMixedDarcyFlow.h"
+#include "TPZAnalysis.h"
+#include "TPZBndCond.h"
 #include "pzbuildmultiphysicsmesh.h"
 #include "pzcmesh.h"
 #include "pzcompel.h"
@@ -22,7 +22,7 @@
 #include "pzelementgroup.h"
 #include "pzelmat.h"
 #include "pzintel.h"
-#include "pzmat1dlin.h"
+//#include "pzmat1dlin.h"
 #include "pzsubcmesh.h"
 #include "pzstepsolver.h"
 #include "TPZVTKGeoMesh.h"

From ec94551b211fcca0580e8371593dcb3ddd3d48e4 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 27 May 2021 19:07:43 -0300
Subject: [PATCH 024/187] Fix material types according to new templates and
 interfaces

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index fe0f74ce..e7341062 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -68,7 +68,7 @@ TPZHDivErrorEstimator::~TPZHDivErrorEstimator() {
 /// compute the element errors comparing the reconstructed solution based on average pressures
 /// with the original solution
 void TPZHDivErrorEstimator::ComputeErrors(TPZVec&errorVec, TPZVec& elementErrors, std::string& vtkPath) {
-    TPZAnalysis an(&fPostProcMesh, false);
+    TPZLinearAnalysis an(&fPostProcMesh, false);
     
     if (fExact) {
         an.SetExact(fExact->ExactSolution());
@@ -199,16 +199,16 @@ TPZCompMesh *TPZHDivErrorEstimator::CreatePressureMesh() {
         std::set bcMatIDs = GetBCMatIDs(&fPostProcMesh);
         for (auto bcID : bcMatIDs) {
             TPZMaterial *mat = mult->FindMaterial(bcID);
-            TPZBndCond *bc = dynamic_cast(mat);
+            TPZBndCondT *bc = dynamic_cast *>(mat);
             if (!bc) DebugStop();
 
             int volumetricMatId = bc->Material()->Id();
-            TPZMaterial *pressuremat = pressureMesh->FindMaterial(volumetricMatId);
+            TPZMatBase *pressuremat = dynamic_cast*>(pressureMesh->FindMaterial(volumetricMatId));
             if (!pressuremat) DebugStop();
 
-            TPZMaterial *newbc = pressuremat->CreateBC(pressuremat, bc->Id(), bc->Type(), bc->Val1(), bc->Val2());
-            if (bc->HasForcingFunction()) {
-                newbc->SetForcingFunction(bc->ForcingFunction());
+            TPZBndCondT *newbc = pressuremat->CreateBC(pressuremat, bc->Id(), bc->Type(), bc->Val1(), bc->Val2());
+            if (bc->HasForcingFunctionBC()) {
+                newbc->SetForcingFunctionBC(bc->ForcingFunctionBC());
             }
             pressureMesh->InsertMaterialObject(newbc);
         }

From fe82a601a63a9dfb40018940f80f0f644a1c7cb2 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 27 May 2021 19:22:13 -0300
Subject: [PATCH 025/187] Fix material types and templates

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 20 +++++++++++---------
 1 file changed, 11 insertions(+), 9 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index e7341062..000ec767 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -6,6 +6,8 @@
 //  Created by Philippe Devloo on 10/06/18.
 //
 
+#include 
+#include "TPZElementMatrixT.h"
 #include "TPZHDivErrorEstimator.h"
 #include "TPZGeoElSideAncestors.h"
 #include "TPZGeoElSidePartition.h"
@@ -523,7 +525,7 @@ void TPZHDivErrorEstimator::CreateEdgeSkeletonMesh(TPZCompMesh *pressuremesh) {
     if (pressuremesh->MaterialVec().find(fPressureSkeletonMatId) != pressuremesh->MaterialVec().end()) {
         DebugStop();
     }
-    TPZNullMaterial *nullmat = new TPZNullMaterial(fPressureSkeletonMatId);
+    TPZNullMaterial *nullmat = new TPZNullMaterial(fPressureSkeletonMatId);
     pressuremesh->InsertMaterialObject(nullmat);
     int dim = fPostProcMesh.Dimension();
     int64_t nel = pressuremesh->NElements();
@@ -836,7 +838,7 @@ void TPZHDivErrorEstimator::ComputeBoundaryL2Projection(int target_dim){
     
     TPZAdmChunkVector &elementvec = pressuremesh->ElementVec();
     
-    TPZElementMatrix ekbc, efbc;
+    TPZElementMatrixT ekbc, efbc;
     TPZFMatrix &mesh_sol = pressuremesh->Solution();
     for (int iel = 0; iel < nel; iel++) {
         TPZCompEl *cel = elementvec[iel];
@@ -1775,7 +1777,7 @@ void TPZHDivErrorEstimator::PlotPressureSkeleton(const std::string &filename, bo
         scalnames.Push("State");
     }
 
-    TPZAnalysis an(pressure, false);
+    TPZLinearAnalysis an(pressure, false);
 
     {
         int dim = pressure->Reference()->Dimension() - 1;
@@ -1802,7 +1804,7 @@ void TPZHDivErrorEstimator::PlotInterfaceFluxes(const std::string &filename, boo
     TPZStack scalnames, vecnames;
     scalnames.Push("State");
 
-    TPZAnalysis an(flux_mesh, false);
+    TPZLinearAnalysis an(flux_mesh, false);
 
     {
         int dim = flux_mesh->Reference()->Dimension() - 1;
@@ -1821,11 +1823,11 @@ void TPZHDivErrorEstimator::PlotInterfaceFluxes(const std::string &filename, boo
 void TPZHDivErrorEstimator::SwitchMaterialObjects() {
 
     for (auto mat : fPostProcMesh.MaterialVec()) {
-        TPZMixedPoisson *mixpoisson = dynamic_cast(mat.second);
+        TPZMixedDarcyFlow *mixpoisson = dynamic_cast(mat.second);
         if (mixpoisson) {
-            TPZMaterial *newmat;
+            TPZMixedDarcyFlow *newmat;
             if (fPostProcesswithHDiv) {
-                newmat = new TPZMixedHDivErrorEstimate(*mixpoisson);
+                newmat = new TPZMixedHDivErrorEstimate(*mixpoisson);
             } else {
                 newmat = new TPZHDivErrorEstimateMaterial(*mixpoisson);
             }
@@ -1834,7 +1836,7 @@ void TPZHDivErrorEstimator::SwitchMaterialObjects() {
                 newmat->SetForcingFunction(mixpoisson->ForcingFunction());
             }
             if (mixpoisson->HasExactSol()) {
-                newmat->SetExactSol(mixpoisson->GetExactSol());
+                newmat->SetExactSol(mixpoisson->ExactSol(), mixpoisson->PolynomialOrderExact());
             }
 
             for (auto bcmat : fPostProcMesh.MaterialVec()) {
@@ -2199,7 +2201,7 @@ void TPZHDivErrorEstimator::ComputePressureWeights() {
                     DebugStop();
             }
         } else {
-            TPZMixedPoisson *mixpoisson = dynamic_cast(mat);
+            auto *mixpoisson = dynamic_cast(mat);
             if (!mixpoisson) DebugStop();
 
             REAL perm;

From cc59bf3543d331967fc63c463e3a77b874492e13 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Fri, 28 May 2021 11:02:38 -0300
Subject: [PATCH 026/187] Fix includes in TPZMixedHdivErrorEstimate material

---
 ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
index ac05582d..afa8e8b9 100644
--- a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
+++ b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
@@ -8,7 +8,8 @@
 #ifndef TPZMixedErrorEstimate_hpp
 #define TPZMixedErrorEstimate_hpp
 
-#include 
+#include 
+#include 
 #include "pzreal.h"
 
 template

From 425331d6d8cbf8b7d29dddd78226d06a768854c4 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Fri, 28 May 2021 11:03:20 -0300
Subject: [PATCH 027/187] Add template parameters to materials

---
 .../TPZCreateMultiphysicsSpace.cpp            | 26 +++++++++----------
 1 file changed, 13 insertions(+), 13 deletions(-)

diff --git a/ErrorEstimation/TPZCreateMultiphysicsSpace.cpp b/ErrorEstimation/TPZCreateMultiphysicsSpace.cpp
index e7238f7d..ab9c5af5 100644
--- a/ErrorEstimation/TPZCreateMultiphysicsSpace.cpp
+++ b/ErrorEstimation/TPZCreateMultiphysicsSpace.cpp
@@ -312,7 +312,7 @@ void TPZCreateMultiphysicsSpace::CreatePressureBoundaryElements(TPZCompMesh *pre
 void TPZCreateMultiphysicsSpace::InsertPressureMaterialIds(TPZCompMesh *pressure)
 {
     for (auto matid:fMaterialIds) {
-        TPZNullMaterial *nullmat = new TPZNullMaterial(matid);
+        auto *nullmat = new TPZNullMaterial(matid);
         nullmat->SetDimension(fDimension);
         nullmat->SetNStateVariables(1);
         pressure->InsertMaterialObject(nullmat);
@@ -320,21 +320,21 @@ void TPZCreateMultiphysicsSpace::InsertPressureMaterialIds(TPZCompMesh *pressure
     if((fH1Hybrid.fHybridizeBCLevel == 2) || (fH1Hybrid.fHybridizeBCLevel == 0))
     {
         for (auto matid:fBCMaterialIds) {
-            TPZNullMaterial *nullmat = new TPZNullMaterial(matid);
+            auto *nullmat = new TPZNullMaterial(matid);
             nullmat->SetDimension(fDimension);
             nullmat->SetNStateVariables(1);
             pressure->InsertMaterialObject(nullmat);
         }
     }
     {
-        TPZNullMaterial *nullmat = new TPZNullMaterial(fH1Hybrid.fMatWrapId);
+        auto *nullmat = new TPZNullMaterial(fH1Hybrid.fMatWrapId);
         nullmat->SetDimension(fDimension);
         nullmat->SetNStateVariables(1);
         pressure->InsertMaterialObject(nullmat);
     }
     if(fSpaceType == EH1HybridSquared)
     {
-        TPZNullMaterial *nullmat = new TPZNullMaterial(fH1Hybrid.fInterfacePressure);
+        auto *nullmat = new TPZNullMaterial(fH1Hybrid.fInterfacePressure);
         nullmat->SetDimension(fDimension);
         nullmat->SetNStateVariables(1);
         pressure->InsertMaterialObject(nullmat);
@@ -347,7 +347,7 @@ void TPZCreateMultiphysicsSpace::InsertFluxMaterialIds(TPZCompMesh *fluxmesh)
 {
     if (fSpaceType == EH1Hybrid || fSpaceType == EH1HybridSquared) {
         int matid = fH1Hybrid.fFluxMatId;
-        TPZNullMaterial *nullmat = new TPZNullMaterial(matid);
+        auto *nullmat = new TPZNullMaterial(matid);
         nullmat->SetDimension(fDimension-1);
         nullmat->SetNStateVariables(1);
         fluxmesh->InsertMaterialObject(nullmat);
@@ -358,7 +358,7 @@ void TPZCreateMultiphysicsSpace::InsertFluxMaterialIds(TPZCompMesh *fluxmesh)
     if(fH1Hybrid.fHybridizeBCLevel == 1)
     {
         for (auto matid:fBCMaterialIds) {
-            TPZNullMaterial *nullmat = new TPZNullMaterial(matid);
+            auto *nullmat = new TPZNullMaterial(matid);
             nullmat->SetDimension(fDimension);
             nullmat->SetNStateVariables(1);
             fluxmesh->InsertMaterialObject(nullmat);
@@ -370,7 +370,7 @@ void TPZCreateMultiphysicsSpace::InsertFluxMaterialIds(TPZCompMesh *fluxmesh)
 void TPZCreateMultiphysicsSpace::InsertNullSpaceMaterialIds(TPZCompMesh *nullspace)
 {
     for (auto matid:fMaterialIds) {
-        TPZNullMaterial *nullmat = new TPZNullMaterial(matid);
+        auto *nullmat = new TPZNullMaterial(matid);
         nullmat->SetDimension(fDimension);
         nullmat->SetNStateVariables(1);
         nullspace->InsertMaterialObject(nullmat);
@@ -659,7 +659,7 @@ TPZCompEl *TPZCreateMultiphysicsSpace::FindFluxElement(TPZCompEl *wrapelement)
             }
         }
     }
-    return NULL;
+    return nullptr;
 }
 
 /// Compute Periferal Material ids
@@ -691,7 +691,7 @@ static void InsertNullMaterial(int matid, int dim, int nstate, TPZCompMesh *cmes
 {
     TPZMaterial *mat = cmesh->FindMaterial(matid);
     if(mat) return;
-    TPZNullMaterial *nullmat = new TPZNullMaterial(matid);
+    auto *nullmat = new TPZNullMaterial(matid);
     nullmat->SetDimension(dim);
     nullmat->SetNStateVariables(nstate);
     cmesh->InsertMaterialObject(nullmat);
@@ -720,16 +720,16 @@ void TPZCreateMultiphysicsSpace::InsertLagranceMaterialObjects(TPZMultiphysicsCo
 {
     if(fSpaceType == EH1Hybrid)
     {
-        TPZLagrangeMultiplier *lag1 = new TPZLagrangeMultiplier(fH1Hybrid.fLagrangeMatid.first, fDimension-1, 1);
+        auto *lag1 = new TPZLagrangeMultiplier(fH1Hybrid.fLagrangeMatid.first, fDimension-1, 1);
         mphys->InsertMaterialObject(lag1);
-        TPZLagrangeMultiplier *lag2 = new TPZLagrangeMultiplier(fH1Hybrid.fLagrangeMatid.second, fDimension-1, 1);
+        auto *lag2 = new TPZLagrangeMultiplier(fH1Hybrid.fLagrangeMatid.second, fDimension-1, 1);
         lag2->SetMultiplier(-1.);
         mphys->InsertMaterialObject(lag2);
     }
     else if (fSpaceType == EH1HybridSquared) {
-        TPZLagrangeMultiplier *lag1 = new TPZLagrangeMultiplier(fH1Hybrid.fLagrangeMatid.first, fDimension-1, 1);
+        auto *lag1 = new TPZLagrangeMultiplier(fH1Hybrid.fLagrangeMatid.first, fDimension-1, 1);
         mphys->InsertMaterialObject(lag1);
-        TPZLagrangeMultiplier *lag2 = new TPZLagrangeMultiplier(fH1Hybrid.fSecondLagrangeMatid, fDimension-1, 1);
+        auto *lag2 = new TPZLagrangeMultiplier(fH1Hybrid.fSecondLagrangeMatid, fDimension-1, 1);
         lag2->SetMultiplier(-1.);
         mphys->InsertMaterialObject(lag2);
     }

From 1124322e8ed401b9368f8783a6a4a6b06848121c Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:22:43 -0300
Subject: [PATCH 028/187] Remove obsolete includes from Tools lib

---
 Projects/Tools/Tools.h    |  5 -----
 Projects/Tools/ToolsMHM.h | 16 +---------------
 2 files changed, 1 insertion(+), 20 deletions(-)

diff --git a/Projects/Tools/Tools.h b/Projects/Tools/Tools.h
index 024d8673..5e480beb 100644
--- a/Projects/Tools/Tools.h
+++ b/Projects/Tools/Tools.h
@@ -14,10 +14,6 @@
 #include "TPZVTKGeoMesh.h"
 #include "ProblemConfig.h"
 
-#include "mixedpoisson.h"
-#include "TPZVecL2.h"
-#include "pzbndcond.h"
-
 #include "pzintel.h"
 
 #include "pzbuildmultiphysicsmesh.h"
@@ -25,7 +21,6 @@
 #include "TPZMultiphysicsInterfaceEl.h"
 #include "TPZHybridizeHDiv.h"
 
-#include "pzanalysis.h"
 #include "pzstepsolver.h"
 #include "TPZSSpStructMatrix.h"
 #include "TPZParFrontStructMatrix.h"
diff --git a/Projects/Tools/ToolsMHM.h b/Projects/Tools/ToolsMHM.h
index e22c10a2..303eeca4 100644
--- a/Projects/Tools/ToolsMHM.h
+++ b/Projects/Tools/ToolsMHM.h
@@ -35,18 +35,13 @@
 
 #include "TPZRefPattern.h"
 #include "tpzgeoelrefpattern.h"
-#include "tpzcompmeshreferred.h"
 #include "tpzautopointer.h"
-#include "pzbndcond.h"
-#include "pzanalysis.h"
 
 #include "TPZSSpStructMatrix.h"
 #include "pzstepsolver.h"
-#include "pzstrmatrix.h"
 #include "pzfstrmatrix.h"
 #include "TPZFrontNonSym.h"
 #include "TPZFrontSym.h"
-#include "TPBSpStructMatrix.h"
 #include "TPZSpStructMatrix.h"
 #include "pzbstrmatrix.h"
 
@@ -54,15 +49,7 @@
 #include "tpzgeoblend.h"
 #include "TPZGeoLinear.h"
 
-#include "pzpoisson3d.h"
-//#include "pzhybridpoisson.h"
-#include "pzpoisson3dreferred.h"
-#include "mixedpoisson.h"
-#include "pzelasmat.h"
-#include "pzelasthybrid.h"
-#include "pzmat1dlin.h"
-#include "TPZVecL2.h"
-#include "TPZMatLaplacianHybrid.h"
+//#include "TPZMatLaplacianHybrid.h"
 #include "TPZLagrangeMultiplier.h"
 
 #include "pzbuildmultiphysicsmesh.h"
@@ -95,7 +82,6 @@
 #include 
 #include 
 #include 
-#include "pzsolve.h"
 
 #include "TPZPersistenceManager.h"
 

From 8e0d262822cc8d71a233157c8cec09a89aa01dca Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:23:35 -0300
Subject: [PATCH 029/187] Pass parameter as const reference

---
 Projects/Tools/Tools.cpp | 2 +-
 Projects/Tools/Tools.h   | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/Projects/Tools/Tools.cpp b/Projects/Tools/Tools.cpp
index 769c0db3..be4ba01f 100644
--- a/Projects/Tools/Tools.cpp
+++ b/Projects/Tools/Tools.cpp
@@ -645,7 +645,7 @@ void Tools::DivideLowerDimensionalElements(TPZGeoMesh* gmesh) {
 }
 
 
-TPZCompMesh* Tools::CMeshH1(ProblemConfig problem) {
+TPZCompMesh* Tools::CMeshH1(const ProblemConfig& problem) {
 
     TPZCompMesh* cmesh = new TPZCompMesh(problem.gmesh);
     TPZMaterial* mat = 0;
diff --git a/Projects/Tools/Tools.h b/Projects/Tools/Tools.h
index 5e480beb..1e0c58da 100644
--- a/Projects/Tools/Tools.h
+++ b/Projects/Tools/Tools.h
@@ -79,7 +79,7 @@ namespace Tools {
 
     void SolveMixedProblem(TPZCompMesh *cmesh_HDiv, const ProblemConfig &config);
 
-    TPZCompMesh *CMeshH1(ProblemConfig problem);
+    TPZCompMesh *CMeshH1(const ProblemConfig& problem);
 
     void hAdaptivity(TPZCompMesh *postProcessMesh, TPZGeoMesh *gmeshToRefine, ProblemConfig &config);
 

From 9585640eba0af531606e122af4aa9a223d6a8422 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:27:50 -0300
Subject: [PATCH 030/187] Change parameter to const reference

---
 Projects/Tools/ToolsMHM.cpp | 2 +-
 Projects/Tools/ToolsMHM.h   | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/Projects/Tools/ToolsMHM.cpp b/Projects/Tools/ToolsMHM.cpp
index 7be80cde..e07ae6e1 100644
--- a/Projects/Tools/ToolsMHM.cpp
+++ b/Projects/Tools/ToolsMHM.cpp
@@ -402,7 +402,7 @@ TPZGeoMesh *CreateLMHMMesh(int nDiv, TPZVec& coarseIndexes) {
     return gmesh;
 }
 
-void SolveProblem(TPZAutoPointer cmesh, const TPZVec> &compmeshes,
+void SolveProblem(const TPZAutoPointer& cmesh, const TPZVec> &compmeshes,
                   TPZAnalyticSolution *analytic, const std::string &prefix, TRunConfig config) {
     //calculo solution
     bool shouldrenumber = true;
diff --git a/Projects/Tools/ToolsMHM.h b/Projects/Tools/ToolsMHM.h
index 303eeca4..eab7765c 100644
--- a/Projects/Tools/ToolsMHM.h
+++ b/Projects/Tools/ToolsMHM.h
@@ -156,4 +156,4 @@ void ComputeCoarseIndices(TPZGeoMesh *gmesh, TPZVec &coarseindices);
 TPZGeoMesh *CreateLMHMMesh(int nDiv, TPZVec& coarseIndexes);
 
 /// Solve the problem composed of a multiphysics mesh composed of compmeshes - applies to MHM and MHM-H(div)
-void SolveProblem(TPZAutoPointer cmesh, const TPZVec >& compmeshes, TPZAnalyticSolution *analytic, const std::string& prefix, TRunConfig config);
+void SolveProblem(const TPZAutoPointer& cmesh, const TPZVec >& compmeshes, TPZAnalyticSolution *analytic, const std::string& prefix, TRunConfig config);

From 680df7cbbc146c7771af99569b917af1e0fc13bb Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:28:31 -0300
Subject: [PATCH 031/187] Update includes of pz headers

---
 Projects/Tools/ToolsMHM.cpp | 9 +++------
 1 file changed, 3 insertions(+), 6 deletions(-)

diff --git a/Projects/Tools/ToolsMHM.cpp b/Projects/Tools/ToolsMHM.cpp
index e07ae6e1..30a36493 100644
--- a/Projects/Tools/ToolsMHM.cpp
+++ b/Projects/Tools/ToolsMHM.cpp
@@ -17,19 +17,16 @@
 #include "pzgeoelside.h"
 #include "tpzgeoelrefpattern.h"
 #include "tpzautopointer.h"
-#include "pzbndcond.h"
-#include "pzanalysis.h"
+#include "TPZBndCond.h"
+#include "TPZNullMaterial.h"
 
 #include "TPZSSpStructMatrix.h"
 #include "pzstepsolver.h"
-#include "pzstrmatrix.h"
+#include "TPZStructMatrix.h"
 
 #include "tpzarc3d.h"
 #include "tpzgeoblend.h"
 
-#include "mixedpoisson.h"
-#include "TPZVecL2.h"
-
 #include "pzbuildmultiphysicsmesh.h"
 #include "TPZCompMeshTools.h"
 

From 743c7c93346dc463d1590947989ee85909114d58 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:30:46 -0300
Subject: [PATCH 032/187] Update includes of pz headers

---
 ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp | 1 -
 ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h   | 1 +
 Projects/ErrorEstimationMHM/main_Journal.cpp           | 1 +
 Projects/Tools/Tools.cpp                               | 4 ++++
 4 files changed, 6 insertions(+), 1 deletion(-)

diff --git a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
index c0333f1d..78c9feb0 100644
--- a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
+++ b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
@@ -6,7 +6,6 @@
 //
 
 #include "TPZMixedHdivErrorEstimate.h"
-#include "mixedpoisson.h"
 #include "pzaxestools.h"
 
 
diff --git a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
index afa8e8b9..ee9fbc1e 100644
--- a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
+++ b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
@@ -10,6 +10,7 @@
 
 #include 
 #include 
+#include 
 #include "pzreal.h"
 
 template
diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp
index feea0b05..44fadfc2 100644
--- a/Projects/ErrorEstimationMHM/main_Journal.cpp
+++ b/Projects/ErrorEstimationMHM/main_Journal.cpp
@@ -8,6 +8,7 @@
 //#include 
 #include 
 #include 
+#include 
 
 struct ErrorResult {
     ErrorResult(const std::string &s, const int nIntRef, const int nCoarseDiv, const int kOrder, const int nOrder,
diff --git a/Projects/Tools/Tools.cpp b/Projects/Tools/Tools.cpp
index be4ba01f..1a12dc04 100644
--- a/Projects/Tools/Tools.cpp
+++ b/Projects/Tools/Tools.cpp
@@ -13,8 +13,12 @@
 #include 
 #include 
 #include 
+#include 
+#include 
+#include 
 #include "DataStructure.h"
 
+
 #include "pzelementgroup.h"
 
 void Tools::PrintGeometry(TPZGeoMesh *gmesh, const std::string &file_name, bool printTXT, bool printVTK) {

From e3a25bb4e868d54367862ab4da5a4f5c8830e878 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:32:25 -0300
Subject: [PATCH 033/187] Update analysis and struct matrix types

---
 Projects/ErrorEstimationMHM/main_Journal.cpp | 6 +++---
 Projects/Tools/Tools.cpp                     | 8 ++++----
 Projects/Tools/ToolsMHM.cpp                  | 4 ++--
 3 files changed, 9 insertions(+), 9 deletions(-)

diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp
index 44fadfc2..9ea7b7ed 100644
--- a/Projects/ErrorEstimationMHM/main_Journal.cpp
+++ b/Projects/ErrorEstimationMHM/main_Journal.cpp
@@ -494,11 +494,11 @@ void SolveMHMProblem(TPZMHMixedMeshControl *mhm, const ProblemConfig &config) {
     TPZAutoPointer cmesh = mhm->CMesh();
 
     bool shouldrenumber = true;
-    TPZAnalysis an(cmesh, shouldrenumber);
+    TPZLinearAnalysis an(cmesh, shouldrenumber);
 
 #ifdef PZ_USING_MKL
-    TPZSymetricSpStructMatrix strmat(cmesh.operator->());
-    strmat.SetNumThreads(8);
+    TPZSSpStructMatrix strmat(cmesh.operator->());
+    strmat.SetNumThreads(4);
 #else
     TPZSkylineStructMatrix strmat(cmesh.operator->());
     strmat.SetNumThreads(0);
diff --git a/Projects/Tools/Tools.cpp b/Projects/Tools/Tools.cpp
index 1a12dc04..06c1874d 100644
--- a/Projects/Tools/Tools.cpp
+++ b/Projects/Tools/Tools.cpp
@@ -408,10 +408,10 @@ void Tools::Prefinamento(TPZCompMesh* cmesh, int ndiv, int porder) {
 void Tools::SolveHybridProblem(TPZCompMesh *Hybridmesh, std::pair InterfaceMatId, const ProblemConfig &problem,
                    bool PostProcessingFEM) {
 
-    TPZAnalysis an(Hybridmesh);
+    TPZLinearAnalysis an(Hybridmesh);
 
 #ifdef PZ_USING_MKL
-    TPZSymetricSpStructMatrix strmat(Hybridmesh);
+    TPZSSpStructMatrix strmat(Hybridmesh);
     strmat.SetNumThreads(0);
     //        strmat.SetDecomposeType(ELDLt);
 #else
@@ -521,10 +521,10 @@ void Tools::SolveMixedProblem(TPZCompMesh* cmesh_HDiv, const ProblemConfig& conf
 #endif
 
 
-    TPZAnalysis an(cmesh_HDiv, false);
+    TPZLinearAnalysis an(cmesh_HDiv, false);
 
 
-    TPZSymetricSpStructMatrix strmat(cmesh_HDiv);
+    TPZSSpStructMatrix strmat(cmesh_HDiv);
     strmat.SetNumThreads(0);
     an.SetStructuralMatrix(strmat);
 
diff --git a/Projects/Tools/ToolsMHM.cpp b/Projects/Tools/ToolsMHM.cpp
index 30a36493..885e4b52 100644
--- a/Projects/Tools/ToolsMHM.cpp
+++ b/Projects/Tools/ToolsMHM.cpp
@@ -403,9 +403,9 @@ void SolveProblem(const TPZAutoPointer& cmesh, const TPZVec());
+    TPZSSpStructMatrix strmat(cmesh.operator->());
     strmat.SetNumThreads(0/*config.n_threads*/);
 #else
     TPZSkylineStructMatrix strmat(cmesh.operator->());

From 5a1d9c3d9d0bed26f83c404adfc824ff56a830ab Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:37:53 -0300
Subject: [PATCH 034/187] Update estimator materials to pz interfaces

---
 .../Material/TPZHDivErrorEstimateMaterial.h      |  3 ++-
 .../Material/TPZMixedHdivErrorEstimate.h         | 16 +++-------------
 2 files changed, 5 insertions(+), 14 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
index eabbf5c6..7915e021 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
@@ -15,7 +15,8 @@
 #include "DarcyFlow/TPZMixedDarcyFlow.h"
 #include "TPZMaterialDataT.h"
 
-class TPZHDivErrorEstimateMaterial : public TPZMixedDarcyFlow {
+class TPZHDivErrorEstimateMaterial: public virtual TPZMatBase,
+        TPZMatErrorCombinedSpaces, TPZDarcyFlowInterface>, public TPZMixedDarcyFlow {
 
 public:
     TPZHDivErrorEstimateMaterial(int matid, int dim);
diff --git a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
index ee9fbc1e..f8666965 100644
--- a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
+++ b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
@@ -13,20 +13,10 @@
 #include 
 #include "pzreal.h"
 
-template
-class TPZFMatrix;
 
-class TPZMaterial;
-class TPZMaterialData;
+class TPZMixedHDivErrorEstimate : public virtual TPZMatBase,
+        TPZMatErrorCombinedSpaces, TPZDarcyFlowInterface>, public TPZMixedDarcyFlow {
 
-template
-class TPZVec;
-
-template
-class TPZMixedHDivErrorEstimate : public MixedMat
-{
-    
-    
 public:
     
     TPZMixedHDivErrorEstimate();
@@ -35,7 +25,7 @@ class TPZMixedHDivErrorEstimate : public MixedMat
     
     virtual ~TPZMixedHDivErrorEstimate();
     
-    TPZMixedHDivErrorEstimate(const MixedMat &cp);
+    TPZMixedHDivErrorEstimate(const TPZMixedDarcyFlow &cp);
     
     TPZMixedHDivErrorEstimate(const TPZMixedHDivErrorEstimate &cp);
     

From 5cd7413aee0aec263e0eb5c42386d9847cca0647 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:39:41 -0300
Subject: [PATCH 035/187] Improve keywords in function signatures

---
 .../Material/TPZMixedHdivErrorEstimate.cpp    | 23 ++++++-------------
 .../Material/TPZMixedHdivErrorEstimate.h      |  8 +++----
 2 files changed, 10 insertions(+), 21 deletions(-)

diff --git a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
index 78c9feb0..d96c3638 100644
--- a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
+++ b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
@@ -46,21 +46,14 @@ TPZMixedHDivErrorEstimate &TPZMixedHDivErrorEstimate::operat
     return *this;
 }
 
-template
-void TPZMixedHDivErrorEstimate::FillDataRequirements(TPZVec &datavec)
-{
-    MixedMat::FillDataRequirements(datavec);
-    {
-        int i = 1;
-        datavec[i].SetAllRequirements(false);
-        //datavec[0].fNeedsSol = true;
-        datavec[i].fNeedsSol = true;
-    }
-    
+void TPZMixedHDivErrorEstimate::FillDataRequirements(TPZVec> &datavec) const {
+    TPZMixedDarcyFlow::FillDataRequirements(datavec);
+    int i = 1;
+    datavec[i].SetAllRequirements(false);
+    datavec[i].fNeedsSol = true;
 }
 
-template
-int TPZMixedHDivErrorEstimate::VariableIndex(const std::string &name)
+int TPZMixedHDivErrorEstimate::VariableIndex(const std::string &name) const
 {
     if(name == "FluxFem") return 40;
     if(name == "FluxReconstructed") return 41;
@@ -80,9 +73,7 @@ int TPZMixedHDivErrorEstimate::VariableIndex(const std::string &name)
     return -1;
 }
 
-template
-int TPZMixedHDivErrorEstimate::NSolutionVariables(int var)
-{
+int TPZMixedHDivErrorEstimate::NSolutionVariables(int var) const {
     switch (var) {
         case 40:
         case 41:
diff --git a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
index f8666965..5281691c 100644
--- a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
+++ b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
@@ -23,7 +23,7 @@ class TPZMixedHDivErrorEstimate : public virtual TPZMatBase
Date: Tue, 1 Jun 2021 13:40:25 -0300
Subject: [PATCH 036/187] Fix material ctors and dtors

---
 .../Material/TPZMixedHdivErrorEstimate.cpp    | 21 +++++++------------
 1 file changed, 7 insertions(+), 14 deletions(-)

diff --git a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
index d96c3638..05bc5ec9 100644
--- a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
+++ b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
@@ -8,41 +8,34 @@
 #include "TPZMixedHdivErrorEstimate.h"
 #include "pzaxestools.h"
 
-
-template
-TPZMixedHDivErrorEstimate::TPZMixedHDivErrorEstimate() : MixedMat()
+TPZMixedHDivErrorEstimate::TPZMixedHDivErrorEstimate() : TPZMixedDarcyFlow()
 {
     
 }
 
-template
-TPZMixedHDivErrorEstimate::TPZMixedHDivErrorEstimate(int matid, int dim) : MixedMat(matid,dim)
+TPZMixedHDivErrorEstimate::TPZMixedHDivErrorEstimate(int matid, int dim) : TPZMixedDarcyFlow(matid,dim)
 {
     
 }
 
-template
-TPZMixedHDivErrorEstimate::TPZMixedHDivErrorEstimate(const MixedMat ©) : MixedMat(copy)
+TPZMixedHDivErrorEstimate::TPZMixedHDivErrorEstimate(const TPZMixedDarcyFlow ©) : TPZMixedDarcyFlow(copy)
 {
     
 }
 
-template
-TPZMixedHDivErrorEstimate::~TPZMixedHDivErrorEstimate()
+TPZMixedHDivErrorEstimate::~TPZMixedHDivErrorEstimate()
 {
     
 }
 
-template
-TPZMixedHDivErrorEstimate::TPZMixedHDivErrorEstimate(const TPZMixedHDivErrorEstimate &cp) : MixedMat(cp)
+TPZMixedHDivErrorEstimate::TPZMixedHDivErrorEstimate(const TPZMixedHDivErrorEstimate &cp) : TPZMixedDarcyFlow(cp)
 {
     
 }
 
-template
-TPZMixedHDivErrorEstimate &TPZMixedHDivErrorEstimate::operator=(const TPZMixedHDivErrorEstimate ©)
+TPZMixedHDivErrorEstimate &TPZMixedHDivErrorEstimate::operator=(const TPZMixedHDivErrorEstimate ©)
 {
-    MixedMat::operator=(copy);
+    TPZMixedDarcyFlow::operator=(copy);
     return *this;
 }
 

From 7ab4924af62ae414d6fac4aa55483464a6afc3b3 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:40:50 -0300
Subject: [PATCH 037/187] Remove unreachable code

---
 ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp | 2 --
 1 file changed, 2 deletions(-)

diff --git a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
index 05bc5ec9..119b9ca8 100644
--- a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
+++ b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
@@ -72,7 +72,6 @@ int TPZMixedHDivErrorEstimate::NSolutionVariables(int var) const {
         case 41:
         case 42:
             return 3;
-            break;
         case 43:
         case 44:
         case 45:
@@ -85,7 +84,6 @@ int TPZMixedHDivErrorEstimate::NSolutionVariables(int var) const {
         case 105:
         case 106:
             return 1;
-            break;
         default:
             DebugStop();
             break;

From c466ac4f7e24d270137fec02602293c6f17fdbd1 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:42:05 -0300
Subject: [PATCH 038/187] Update material data type in function signatures

---
 .../Material/TPZMixedHdivErrorEstimate.cpp          | 11 ++++-------
 .../Material/TPZMixedHdivErrorEstimate.h            | 13 ++++++-------
 2 files changed, 10 insertions(+), 14 deletions(-)

diff --git a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
index 119b9ca8..9960356f 100644
--- a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
+++ b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
@@ -97,9 +97,8 @@ int TPZMixedHDivErrorEstimate::NSolutionVariables(int var) const {
  * @param var [in] number of solution variables. See  NSolutionVariables() method
  * @param Solout [out] is the solution vector
  */
-template
-void TPZMixedHDivErrorEstimate::Solution(TPZVec &datavec, int var, TPZVec &Solout)
-{
+void
+TPZMixedHDivErrorEstimate::Solution(const TPZVec> &datavec, int var, TPZVec &Solout) {
     /**
      datavec[0]= Hdiv Resconstructed
      datavec[1]= Pressure Resconstructed
@@ -174,10 +173,8 @@ void TPZMixedHDivErrorEstimate::Solution(TPZVec &data
 
 
 /// make a contribution to the error computation
-template
-void TPZMixedHDivErrorEstimate::Errors(TPZVec &data, TPZVec &errors)
-{
-    
+void TPZMixedHDivErrorEstimate::Errors(const TPZVec> &data, TPZVec &errors) {
+
     /**
      datavec[0]= Hdiv Reconstructed
      datavec[1]= Pressure Reconstructed
diff --git a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
index 5281691c..09362397 100644
--- a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
+++ b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
@@ -36,15 +36,14 @@ class TPZMixedHDivErrorEstimate : public virtual TPZMatBase &datavec) override;
+    void FillDataRequirements(TPZVec> &datavec) const override;
     
     /// make a contribution to the error computation
-    virtual void Errors(TPZVec &data, TPZVec &errors) override;
+    void Errors(const TPZVec> &data, TPZVec &errors) override;
+
+    int NEvalErrors() override { return 5; }
     
-    virtual int NEvalErrors() override {
-        return 5;
-        
-    }
+    [[nodiscard]] int VariableIndex(const std::string &name) const override;
     
     [[nodiscard]] int NSolutionVariables(int var) const override;
     
@@ -54,7 +53,7 @@ class TPZMixedHDivErrorEstimate : public virtual TPZMatBase &datavec, int var, TPZVec &Solout) override;
+    void Solution(const TPZVec> &datavec, int var, TPZVec &Solout) override;
 
     /// whether the post processing mesh will be H(div) or H1
     bool fPostProcesswithHDiv = true;

From 3dd57bbeae828bd585b8089dc8d1c29f09ca00ba Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:45:18 -0300
Subject: [PATCH 039/187] Comment ErrorsBC definition for now

---
 .../Material/TPZHDivErrorEstimateMaterial.cpp | 162 +++++++++---------
 1 file changed, 81 insertions(+), 81 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index e9beaeb9..ba7df81d 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -523,85 +523,85 @@ TPZHDivErrorEstimateMaterial::Solution(const TPZVec> &da
     }
 }
 
-void TPZHDivErrorEstimateMaterial::ErrorsBC(TPZVec &data, TPZVec &u_exact,
-                                            TPZFMatrix &du_exact, TPZVec &errors, TPZBndCond &bc) {
-
-    if (bc.Type() == 4) {
-
-
-        errors.Resize(NEvalErrors());
-        errors.Fill(0.0);
-
-
-        TPZFNMatrix<3, REAL> fluxreconstructed(3, 1), fluxreconstructed2(3, 1);
-        TPZManVector fluxfem(3);
-
-        int H1functionposition = 0;
-        H1functionposition = FirstNonNullApproxSpaceIndex(data);
-
-        REAL normalsigmafem = 0., normalsigmarec = 0., urec = 0.;;
-        normalsigmafem = data[2].sol[0][0];// sigma.n
-        urec = data[H1functionposition].sol[0][0];
-
-
-        REAL u_D = 0., g = 0.;
-        REAL normflux = 0.;
-
-        TPZManVector fluxrec(fDim);
-        this->Solution(data, VariableIndex("FluxReconstructed"), fluxrec);
-
-        //      std::cout<<"flux_rec "< PermTensor, InvPermTensor;
-        TPZManVector res(3);
-        TPZFNMatrix<9, STATE> gradu(this->Dimension(), 1);
-
-        if (bc.HasForcingFunction()) {
-            bc.ForcingFunction()->Execute(data[H1functionposition].x, res, gradu);
-            GetPermeabilities(data[0].x, PermTensor, InvPermTensor);
-            u_D = res[0];
-
-
-        } else {
-            // usualmente updatebc coloca o valor exato no val2
-            u_D = bc.Val2()(0, 0);
-        }
-
-
-        for (int i = 0; i < 3; i++) {
-            for (int j = 0; j < 3; j++) {
-
-                normflux += data[2].normal[i] * PermTensor(i, j) * gradu(j, 0);
-
-            }
-        }
-        g = (-1) * normflux;
-
-        //       std::cout<<"n_0 "< &data, TPZVec &u_exact,
+//                                            TPZFMatrix &du_exact, TPZVec &errors, TPZBndCond &bc) {
+//
+//    if (bc.Type() == 4) {
+//
+//
+//        errors.Resize(NEvalErrors());
+//        errors.Fill(0.0);
+//
+//
+//        TPZFNMatrix<3, REAL> fluxreconstructed(3, 1), fluxreconstructed2(3, 1);
+//        TPZManVector fluxfem(3);
+//
+//        int H1functionposition = 0;
+//        H1functionposition = FirstNonNullApproxSpaceIndex(data);
+//
+//        REAL normalsigmafem = 0., normalsigmarec = 0., urec = 0.;;
+//        normalsigmafem = data[2].sol[0][0];// sigma.n
+//        urec = data[H1functionposition].sol[0][0];
+//
+//
+//        REAL u_D = 0., g = 0.;
+//        REAL normflux = 0.;
+//
+//        TPZManVector fluxrec(fDim);
+//        this->Solution(data, VariableIndex("FluxReconstructed"), fluxrec);
+//
+//        //      std::cout<<"flux_rec "< PermTensor, InvPermTensor;
+//        TPZManVector res(3);
+//        TPZFNMatrix<9, STATE> gradu(this->Dimension(), 1);
+//
+//        if (bc.HasForcingFunction()) {
+//            bc.ForcingFunction()->Execute(data[H1functionposition].x, res, gradu);
+//            GetPermeabilities(data[0].x, PermTensor, InvPermTensor);
+//            u_D = res[0];
+//
+//
+//        } else {
+//            // usualmente updatebc coloca o valor exato no val2
+//            u_D = bc.Val2()(0, 0);
+//        }
+//
+//
+//        for (int i = 0; i < 3; i++) {
+//            for (int j = 0; j < 3; j++) {
+//
+//                normflux += data[2].normal[i] * PermTensor(i, j) * gradu(j, 0);
+//
+//            }
+//        }
+//        g = (-1) * normflux;
+//
+//        //       std::cout<<"n_0 "<
Date: Tue, 1 Jun 2021 13:46:50 -0300
Subject: [PATCH 040/187] Update usage of permeability in material methods

---
 .../Material/TPZMixedHdivErrorEstimate.cpp    | 47 ++++++++-----------
 1 file changed, 20 insertions(+), 27 deletions(-)

diff --git a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
index 9960356f..16bb4b01 100644
--- a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
+++ b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
@@ -106,29 +106,23 @@ TPZMixedHDivErrorEstimate::Solution(const TPZVec> &datav
      datavec[3]= Pressure FEM
     
      **/
-    
+
     TPZFNMatrix<9,REAL> PermTensor;
     TPZFNMatrix<9,REAL> InvPermTensor;
-    
-    MixedMat::GetPermeabilities(datavec[1].x, PermTensor, InvPermTensor);
 
-    int dim = MixedMat::fDim;
+    TPZMixedDarcyFlow::GetPermeabilities(datavec[1].x, PermTensor, InvPermTensor);
+
+    int dim = TPZMixedDarcyFlow::fDim;
 
-    if (MixedMat::fPermeabilityFunction) {
+    if (TPZMixedDarcyFlow::fPermeabilityFunction) {
         PermTensor.Redim(dim, dim);
         InvPermTensor.Redim(dim, dim);
-        TPZFNMatrix<18, STATE> resultMat(2 * dim, dim, 0.);
-        TPZManVector res;
-        MixedMat::fPermeabilityFunction->Execute(datavec[1].x, res, resultMat);
-
-        for (int id = 0; id < dim; id++) {
-            for (int jd = 0; jd < dim; jd++) {
-                PermTensor(id, jd) = resultMat(id, jd);
-                InvPermTensor(id, jd) = resultMat(id + dim, jd);
-            }
-        }
+        TPZFNMatrix<1, STATE> K(1, 1, 0);
+        TPZFNMatrix<1, STATE> InvK(1, 1, 0);
+        TPZMixedDarcyFlow::fPermeabilityFunction(datavec[1].x, K, InvK);
     }
 
+
     STATE pressureexact = 0.;
     TPZManVector pressvec(1,0.);
     TPZFNMatrix<9, STATE> gradu(dim, 1, 0.), fluxinv(dim, 1);
@@ -217,20 +211,19 @@ void TPZMixedHDivErrorEstimate::Errors(const TPZVec> &da
     
     TPZFNMatrix<9,REAL> PermTensor;
     TPZFNMatrix<9,REAL> InvPermTensor;
-    
-    MixedMat::GetPermeabilities(data[1].x, PermTensor, InvPermTensor);
-    
-    
-    if(MixedMat::fPermeabilityFunction){
+
+    TPZMixedDarcyFlow::GetPermeabilities(data[1].x, PermTensor, InvPermTensor);
+
+    if(this->fPermeabilityFunction){
         PermTensor.Redim(dim, dim);
         InvPermTensor.Redim(dim, dim);
-        TPZFNMatrix<18, STATE> resultMat(2 * dim, dim, 0.);
-        TPZManVector res;
-        MixedMat::fPermeabilityFunction->Execute(data[1].x,res,resultMat);
+        TPZFNMatrix<1, STATE> K(1, 1, 0);
+        TPZFNMatrix<1, STATE> InvK(1, 1, 0);
+        this->fPermeabilityFunction(data[1].x, K, InvK);
         for(int id=0; id> &da
         }
         PermTensor.Multiply(gradpressure,fluxexactneg);
     }
-    
-    
+
+
     REAL innerexact = 0.;
     REAL innerestimate = 0.;
     for (int i=0; i
Date: Tue, 1 Jun 2021 13:48:33 -0300
Subject: [PATCH 041/187] Update usage of exact sol and dimension in material

---
 ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp | 8 +++-----
 1 file changed, 3 insertions(+), 5 deletions(-)

diff --git a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
index 16bb4b01..f81dc32d 100644
--- a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
+++ b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
@@ -127,10 +127,8 @@ TPZMixedHDivErrorEstimate::Solution(const TPZVec> &datav
     TPZManVector pressvec(1,0.);
     TPZFNMatrix<9, STATE> gradu(dim, 1, 0.), fluxinv(dim, 1);
 
-    if(MixedMat::fExactSol)
-    {
-
-        MixedMat::fExactSol->Execute(datavec[0].x, pressvec,gradu);
+    if(TPZMixedDarcyFlow::fExactSol) {
+        TPZMixedDarcyFlow::fExactSol(datavec[0].x, pressvec,gradu);
         gradu.Resize(3, 1);
         //gradu(2,0) = 0.;
     }
@@ -179,7 +177,7 @@ void TPZMixedHDivErrorEstimate::Errors(const TPZVec> &da
     errors.Resize(NEvalErrors());
     errors.Fill(0.0);
 
-    const int dim = MixedMat::fDim;
+    const int dim = this->fDim;
 
     TPZManVector fluxfem(3), fluxreconstructed(3), pressurefem(1), pressurereconstructed(1);
 

From 3fb1680151f66962ebccbeef020f09bbb7dc4b04 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:49:27 -0300
Subject: [PATCH 042/187] Remove obsolete template class instantiation

---
 ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp | 6 ------
 1 file changed, 6 deletions(-)

diff --git a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
index f81dc32d..0c3bc93b 100644
--- a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
+++ b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
@@ -256,9 +256,3 @@ void TPZMixedHDivErrorEstimate::Errors(const TPZVec> &da
         if(std::isnan(errors[i])) DebugStop();
     }
 }
-
-
-
-
-
-template class TPZMixedHDivErrorEstimate;

From b267f11b2af47e33dbf8ce28e4c5efb38811c573 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:49:51 -0300
Subject: [PATCH 043/187] Indent code

---
 .../Material/TPZMixedHdivErrorEstimate.cpp    | 26 ++++++++-----------
 1 file changed, 11 insertions(+), 15 deletions(-)

diff --git a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
index 0c3bc93b..59132066 100644
--- a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
+++ b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
@@ -132,7 +132,7 @@ TPZMixedHDivErrorEstimate::Solution(const TPZVec> &datav
         gradu.Resize(3, 1);
         //gradu(2,0) = 0.;
     }
-    
+
     PermTensor.Multiply(gradu, fluxinv);
     pressureexact = pressvec[0];
     switch (var)
@@ -173,7 +173,7 @@ void TPZMixedHDivErrorEstimate::Errors(const TPZVec> &da
      datavec[2]= Hdiv FEM
      datavec[3]= Pressure FEM
      **/
-    
+
     errors.Resize(NEvalErrors());
     errors.Fill(0.0);
 
@@ -181,32 +181,28 @@ void TPZMixedHDivErrorEstimate::Errors(const TPZVec> &da
 
     TPZManVector fluxfem(3), fluxreconstructed(3), pressurefem(1), pressurereconstructed(1);
 
-    
+
     fluxreconstructed = data[0].sol[0];
     fluxfem = data[2].sol[0];
     STATE divsigmafem=data[2].divsol[0][0];
-    
-    
+
+
     TPZVec divsigma(1,0.);
 
     TPZManVector u_exact(1);
     TPZFNMatrix<9, STATE> du_exact(3, 3);
     if(this->fExactSol){
-        this->fExactSol->Execute(data[0].x,u_exact,du_exact);
-        this->fForcingFunction->Execute(data[0].x,divsigma);
+        this->fExactSol(data[0].x,u_exact,du_exact);
+        this->fForcingFunction(data[0].x,divsigma);
     }
-    
 
-    
     REAL residual = 0.;
-//    std::cout<<" divsigma "< PermTensor;
     TPZFNMatrix<9,REAL> InvPermTensor;
 
@@ -225,7 +221,7 @@ void TPZMixedHDivErrorEstimate::Errors(const TPZVec> &da
             }
         }
     }
-    
+
     TPZFNMatrix<3,REAL> fluxexactneg;
 
     //sigma=-K grad(u)

From dbee37c14705ae0ca4992ca05c37f9debf35dd74 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:52:01 -0300
Subject: [PATCH 044/187] Update type of bc val2 to a vector

---
 Projects/ErrorEstimationMHM/main_Journal.cpp | 9 ++++++---
 Projects/Tools/Tools.cpp                     | 9 ++++++---
 Projects/Tools/ToolsMHM.cpp                  | 3 ++-
 3 files changed, 14 insertions(+), 7 deletions(-)

diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp
index 9ea7b7ed..de90f874 100644
--- a/Projects/ErrorEstimationMHM/main_Journal.cpp
+++ b/Projects/ErrorEstimationMHM/main_Journal.cpp
@@ -605,7 +605,8 @@ void InsertMaterialsInMHMMesh(TPZMHMixedMeshControl &control, const ProblemConfi
     cmesh.InsertMaterialObject(mat);
 
     for (auto matid : config.bcmaterialids) {
-        TPZFNMatrix<1, REAL> val1(1, 1, 0.), val2(1, 1, 0.);
+        TPZFNMatrix<1, REAL> val1(1, 1, 0.);
+        TPZManVector val2(1, 0.);
         int bctype = 0;
         TPZBndCond *bc = mat->CreateBC(mat, matid, bctype, val1, val2);
         bc->TPZMaterial::SetForcingFunction(config.exact.operator*().Exact());
@@ -661,7 +662,8 @@ void CreateMHMCompMeshHeteroPerm(TPZMHMixedMeshControl *mhm, const ProblemConfig
     cmesh.InsertMaterialObject(mat2);
 
     for (auto matid : config.bcmaterialids) {
-        TPZFNMatrix<1, REAL> val1(1, 1, 0.), val2(1, 1, 0.);
+        TPZFNMatrix<1, REAL> val1(1, 1, 0.);
+        TPZManVector val2(1, 0.);
         int bctype = 0;
         TPZBndCond *bc = mat->CreateBC(mat, matid, bctype, val1, val2);
         bc->TPZMaterial::SetForcingFunction(config.exact.operator*().Exact());
@@ -704,7 +706,8 @@ void CreateMHMCompMeshPermFunction(TPZMHMixedMeshControl &mhm) {
     mix->SetPermeabilityFunction(perm_function);
     mix->SetForcingFunction(PeriodicProblemForcingFunction, 1);
 
-    TPZFNMatrix<1, REAL> val1(1, 1, 0.), val2(1, 1, 0.);
+    TPZFNMatrix<1, REAL> val1(1, 1, 0.);
+    TPZManVector val2(1, 0.);
     constexpr int dirichlet_bc = 0;
     TPZBndCond *pressure_left = mix->CreateBC(mix, -1, dirichlet_bc, val1, val2);
 
diff --git a/Projects/Tools/Tools.cpp b/Projects/Tools/Tools.cpp
index 06c1874d..01797568 100644
--- a/Projects/Tools/Tools.cpp
+++ b/Projects/Tools/Tools.cpp
@@ -75,7 +75,8 @@ TPZCompMesh* Tools::CreateFluxHDivMesh(const ProblemConfig& problem) {
         cmesh->InsertMaterialObject(mix);
     }
     for (auto matid : problem.bcmaterialids) {
-        TPZFNMatrix<1, REAL> val1(1, 1, 0.), val2(1, 1, 1.);
+        TPZFNMatrix<1, REAL> val1(1, 1, 0.);
+        TPZManVector val2(1, 1.);
         int bctype;
         if (matid == -1 || matid == 2) {
             bctype = 0;
@@ -142,7 +143,8 @@ TPZMultiphysicsCompMesh* Tools::CreateHDivMesh(const ProblemConfig& problem) {
         
     
     for (auto matid : problem.bcmaterialids) {
-        TPZFNMatrix<1, REAL> val1(1, 1, 0.), val2(1, 1, 0.);
+        TPZFNMatrix<1, REAL> val1(1, 1, 0.);
+        TPZManVector val2(1, 0.);
         int bctype;
     
         switch (matid) {
@@ -665,7 +667,8 @@ TPZCompMesh* Tools::CMeshH1(const ProblemConfig& problem) {
     }
 
     for (auto matid : problem.bcmaterialids) {
-        TPZFNMatrix<1, REAL> val1(1, 1, 0.), val2(1, 1, 0.);
+        TPZFNMatrix<1, REAL> val1(1, 1, 0.);
+        TPZManVector val2(1, 0.);
         int bctype = 0;
         val2.Zero();
         TPZBndCond *bc = mat->CreateBC(mat, matid, bctype, val1, val2);
diff --git a/Projects/Tools/ToolsMHM.cpp b/Projects/Tools/ToolsMHM.cpp
index 885e4b52..2d5fde98 100644
--- a/Projects/Tools/ToolsMHM.cpp
+++ b/Projects/Tools/ToolsMHM.cpp
@@ -69,7 +69,8 @@ TPZCompMesh *CMeshFlux(TPZGeoMesh * gmesh,int pOrder){
     
     int type_D = 0;
     int type_N = 1;
-    TPZFMatrix val1(1, 1, 0.), val2(1, 1, 0.);
+    TPZFMatrix val1(1, 1, 0.);
+    TPZManVector val2(1, 0.);
     
     // Insert boundary conditions
     //Neumann boundary conditions (flux = 0)

From cd6a4dad5ac0335fcbbe8c1686cc4fac3785a8b0 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:52:55 -0300
Subject: [PATCH 045/187] Update permeability access from material

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 000ec767..52dc8680 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -2209,8 +2209,10 @@ void TPZHDivErrorEstimator::ComputePressureWeights() {
             gel->CenterPoint(gel->NSides() - 1, xi);
             TPZVec x(3, 0.);
             gel->X(xi, x);
-            mixpoisson->GetMaxPermeability(perm, x);
 
+            TPZFNMatrix<1, STATE> K(1, 1, 0.), InvK(1, 1, 0.);
+            mixpoisson->GetPermeabilities(x, K, InvK);
+            perm = K(0, 0);
             if (IsZero(perm)) DebugStop();
             this->fPressureweights[el] = perm;
             fMatid_weights[matid] = perm;

From 1037ccb0482f40208d95eed714d53664e756e388 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:53:41 -0300
Subject: [PATCH 046/187] Update includes in estimator classes

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp    | 3 +--
 ErrorEstimation/TPZMHMHDivErrorEstimator.cpp | 4 +++-
 2 files changed, 4 insertions(+), 3 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 52dc8680..bf7a65da 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -7,12 +7,12 @@
 //
 
 #include 
+#include 
 #include "TPZElementMatrixT.h"
 #include "TPZHDivErrorEstimator.h"
 #include "TPZGeoElSideAncestors.h"
 #include "TPZGeoElSidePartition.h"
 #include "TPZInterfaceEl.h"
-#include "TPZMixedHdivErrorEstimate.h"
 #include "TPZNullMaterial.h"
 #include "DarcyFlow/TPZMixedDarcyFlow.h"
 #include "TPZAnalysis.h"
@@ -29,7 +29,6 @@
 #include "pzstepsolver.h"
 #include "TPZVTKGeoMesh.h"
 #include "pzmultiphysicscompel.h"
-#include "TPZHDivErrorEstimateMaterial.h"
 #include "TPZCompMeshTools.h"
 
 #ifdef LOG4CXX
diff --git a/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp b/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
index e7fcb806..9a33ad25 100644
--- a/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
@@ -1,8 +1,9 @@
 
 #include "TPZMHMHDivErrorEstimator.h"
 #include "TPZNullMaterial.h"
+#include "TPZLagrangeMultiplierCS.h"
 #include "TPZVTKGeoMesh.h"
-#include "pzbndcond.h"
+#include "TPZBndCond.h"
 #include "pzintel.h"
 #include "pzsubcmesh.h"
 #include 
@@ -11,6 +12,7 @@
 #include 
 #include 
 
+
 #ifdef LOG4CXX
 static LoggerPtr logger(Logger::getLogger("HDivErrorEstimator"));
 #endif

From b10e3927889438085379007e8992ce6b5038b67d Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:55:17 -0300
Subject: [PATCH 047/187] Update types of inserted material

---
 Projects/Tools/ToolsMHM.cpp | 19 +++++++++----------
 1 file changed, 9 insertions(+), 10 deletions(-)

diff --git a/Projects/Tools/ToolsMHM.cpp b/Projects/Tools/ToolsMHM.cpp
index 2d5fde98..612baf4a 100644
--- a/Projects/Tools/ToolsMHM.cpp
+++ b/Projects/Tools/ToolsMHM.cpp
@@ -57,8 +57,8 @@ TPZCompMesh *CMeshFlux(TPZGeoMesh * gmesh,int pOrder){
     
     //Definition of the approximation space:
     
-    TPZVecL2 *mat_0 = new TPZVecL2(impervious_mat);
-    TPZVecL2 *mat_1 = new TPZVecL2(permeable_mat);
+    auto *mat_0 = new TPZNullMaterial(impervious_mat);
+    auto *mat_1 = new TPZNullMaterial(permeable_mat);
     
     //  inserting volumetric materials objects
     cmesh->InsertMaterialObject(mat_0);
@@ -75,29 +75,28 @@ TPZCompMesh *CMeshFlux(TPZGeoMesh * gmesh,int pOrder){
     // Insert boundary conditions
     //Neumann boundary conditions (flux = 0)
     int right_bc_id = -2;
-    TPZMaterial * right_bc = mat_0->CreateBC(mat_0, right_bc_id, type_N, val1, val2);
+    auto * right_bc = mat_0->CreateBC(mat_0, right_bc_id, type_N, val1, val2);
     cmesh->InsertMaterialObject(right_bc);
     
     int left_bc_id = -4;
-    TPZMaterial * left_bc = mat_0->CreateBC(mat_0, left_bc_id, type_N, val1, val2);
+    auto * left_bc = mat_0->CreateBC(mat_0, left_bc_id, type_N, val1, val2);
     cmesh->InsertMaterialObject(left_bc);
     
     int bottom_bc_1id = -1;
-    TPZMaterial * bottom_bc_1 = mat_0->CreateBC(mat_0, bottom_bc_1id, type_N, val1, val2);
+    auto * bottom_bc_1 = mat_0->CreateBC(mat_0, bottom_bc_1id, type_N, val1, val2);
     cmesh->InsertMaterialObject(bottom_bc_1);
     
     int top_bc_1id = -3;
-    TPZMaterial * top_bc_1 = mat_0->CreateBC(mat_0, top_bc_1id, type_N, val1, val2);
+    auto * top_bc_1 = mat_0->CreateBC(mat_0, top_bc_1id, type_N, val1, val2);
     cmesh->InsertMaterialObject(top_bc_1);
-    
-    
+
     //Dirichlet Conditions (p=1 in, p=0 out)
     int bottom_bc_id = -5;
-    TPZMaterial * bottom_bc = mat_0->CreateBC(mat_0, bottom_bc_id, type_D, val1, val2);
+    auto * bottom_bc = mat_0->CreateBC(mat_0, bottom_bc_id, type_D, val1, val2);
     cmesh->InsertMaterialObject(bottom_bc);
     
     int top_bc_id = -6;
-    TPZMaterial * top_bc = mat_0->CreateBC(mat_0, top_bc_id, type_D, val1, val2);
+    auto * top_bc = mat_0->CreateBC(mat_0, top_bc_id, type_D, val1, val2);
     cmesh->InsertMaterialObject(top_bc);
     
     cmesh->SetName("LaberintoTest");

From 81ad26d616ee79a53ed2c09bd1d906a3f8ebfc57 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:55:45 -0300
Subject: [PATCH 048/187] Update analysis type

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index bf7a65da..212aea6f 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -2226,7 +2226,7 @@ void TPZHDivErrorEstimator::PlotState(const std::string& filename, int targetDim
     cmesh->Print(outTXT);
     
     {
-        TPZAnalysis an(cmesh, false);
+        TPZLinearAnalysis an(cmesh, false);
         TPZStack scalnames, vecnames;
         if (atomic) {
             scalnames.Push("State");

From 9bd43223bb0eca41586ae0e99ee18bedd064295b Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:57:12 -0300
Subject: [PATCH 049/187] Update material types

---
 Projects/ErrorEstimationMHM/main_Journal.cpp |  6 +--
 Projects/Tools/Tools.cpp                     | 48 ++++++++------------
 2 files changed, 22 insertions(+), 32 deletions(-)

diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp
index de90f874..5b886691 100644
--- a/Projects/ErrorEstimationMHM/main_Journal.cpp
+++ b/Projects/ErrorEstimationMHM/main_Journal.cpp
@@ -592,7 +592,7 @@ void InsertMaterialsInMHMMesh(TPZMHMixedMeshControl &control, const ProblemConfi
     int dim = control.GMesh()->Dimension();
     cmesh.SetDimModel(dim);
 
-    auto *mat = new TPZMixedPoisson(1, dim);
+    auto *mat = new TPZMixedDarcyFlow(1, dim);
 
     TPZFMatrix K(3, 3, 0), invK(3, 3, 0);
     K.Identity();
@@ -633,7 +633,7 @@ void CreateMHMCompMeshHeteroPerm(TPZMHMixedMeshControl *mhm, const ProblemConfig
     int dim = mhm->GMesh()->Dimension();
     cmesh.SetDimModel(dim);
 
-    auto *mat = new TPZMixedPoisson(1, dim);
+    auto *mat = new TPZMixedDarcyFlow(1, dim);
 
     TPZFMatrix K(3, 3, 0), invK(3, 3, 0);
     K.Identity();
@@ -701,7 +701,7 @@ void CreateMHMCompMeshPermFunction(TPZMHMixedMeshControl &mhm) {
 
     // Insert the material objects in the multiphysics mesh
     TPZCompMesh *cmesh = mhm.CMesh().operator->();
-    auto *mix = new TPZMixedPoisson(1, cmesh->Dimension());
+    auto *mix = new TPZMixedDarcyFlow(1, cmesh->Dimension());
     TPZAutoPointer> perm_function = new TPZDummyFunction(&PeriodicPermeabilityFunction, 3);
     mix->SetPermeabilityFunction(perm_function);
     mix->SetForcingFunction(PeriodicProblemForcingFunction, 1);
diff --git a/Projects/Tools/Tools.cpp b/Projects/Tools/Tools.cpp
index 01797568..27241db7 100644
--- a/Projects/Tools/Tools.cpp
+++ b/Projects/Tools/Tools.cpp
@@ -38,9 +38,9 @@ void Tools::PrintGeometry(TPZGeoMesh *gmesh, const std::string &file_name, bool
 
 TPZCompMesh* Tools::CreatePressureMesh(const ProblemConfig& problem) {
     TPZCompMesh* cmesh = new TPZCompMesh(problem.gmesh);
-    TPZMaterial* mat = 0;
+    TPZMaterial* mat = nullptr;
     for (auto matid : problem.materialids) {
-        TPZMixedPoisson* mix = new TPZMixedPoisson(matid, cmesh->Dimension());
+        auto * mix = new TPZMixedDarcyFlow(matid, cmesh->Dimension());
         if (!mat) mat = mix;
         cmesh->InsertMaterialObject(mix);
     }
@@ -59,17 +59,16 @@ TPZCompMesh* Tools::CreatePressureMesh(const ProblemConfig& problem) {
         Prefinamento(cmesh, problem.ndivisions, problem.porder);
     }
     
-    
     return cmesh;
 }
 
 TPZCompMesh* Tools::CreateFluxHDivMesh(const ProblemConfig& problem) {
     int dim = problem.gmesh->Dimension();
-    TPZCompMesh* cmesh = new TPZCompMesh(problem.gmesh);
-    TPZMaterial* mat = NULL;
+    auto* cmesh = new TPZCompMesh(problem.gmesh);
+    TPZNullMaterial* mat = nullptr;
     problem.gmesh->ResetReference();
     for (auto matid : problem.materialids) {
-        TPZVecL2* mix = new TPZVecL2(matid);
+        auto * mix = new TPZNullMaterial(matid);
         mix->SetDimension(dim);
         if (!mat) mat = mix;
         cmesh->InsertMaterialObject(mix);
@@ -103,15 +102,14 @@ TPZCompMesh* Tools::CreateFluxHDivMesh(const ProblemConfig& problem) {
 
 TPZMultiphysicsCompMesh* Tools::CreateHDivMesh(const ProblemConfig& problem) {
 
-    TPZMultiphysicsCompMesh* cmesh = new TPZMultiphysicsCompMesh(problem.gmesh);
-    TPZMaterial* mat = NULL;
+    auto* cmesh = new TPZMultiphysicsCompMesh(problem.gmesh);
+    TPZMixedDarcyFlow *mat = nullptr;
     TPZFMatrix K(3, 3, 0), invK(3, 3, 0);
     K.Identity();
     invK.Identity();
     
     STATE Km = problem.Km;
 
-    
     if (problem.TensorNonConst && problem.gmesh->Dimension() == 3) {
         for (int i = 0; i < 3; i++) {
             for (int j = 0; j < 3; j++) {
@@ -127,9 +125,6 @@ TPZMultiphysicsCompMesh* Tools::CreateHDivMesh(const ProblemConfig& problem) {
         
     }
 
-//    K.Print(std::cout);
-//    invK.Print(std::cout);
-    
     for (auto matid : problem.materialids) {
         TPZMixedPoisson *mix = new TPZMixedPoisson(matid, cmesh->Dimension());
         mix->SetForcingFunction(problem.exact.operator*().ForcingFunction());
@@ -148,23 +143,19 @@ TPZMultiphysicsCompMesh* Tools::CreateHDivMesh(const ProblemConfig& problem) {
         int bctype;
     
         switch (matid) {
-            case -1 :{
-            bctype = 0;
+            case -1 : {
+                bctype = 0;
                 break;
             }
-                
-                
-            case -2:{
-            bctype = 1;
-    
-            break;
-            }
-            case -3:{
-            bctype = 4;// different from mixed (bctype 2) already implemented on TPZMixedPoisson3d
-            val1(0,0) = Km ;
+            case -2: {
+                bctype = 1;
 
-                
-            break;
+                break;
+            }
+            case -3: {
+                bctype = 4;// different from mixed (bctype 2) already implemented on TPZMixedPoisson3d
+                val1(0, 0) = Km;
+                break;
             }
         }
         TPZBndCond* bc = mat->CreateBC(mat, matid, bctype, val1, val2);
@@ -653,9 +644,8 @@ void Tools::DivideLowerDimensionalElements(TPZGeoMesh* gmesh) {
 
 TPZCompMesh* Tools::CMeshH1(const ProblemConfig& problem) {
 
-    TPZCompMesh* cmesh = new TPZCompMesh(problem.gmesh);
-    TPZMaterial* mat = 0;
-
+    auto* cmesh = new TPZCompMesh(problem.gmesh);
+    TPZDarcyFlow* mat = nullptr;
 
     for (auto matid : problem.materialids) {
         TPZMatPoisson3d *mix = new TPZMatPoisson3d(matid, cmesh->Dimension());

From f4d05e8d95debdcb90813a95295bedcf47ecc846 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:58:00 -0300
Subject: [PATCH 050/187] Update material types

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 212aea6f..8074c678 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -1822,17 +1822,17 @@ void TPZHDivErrorEstimator::PlotInterfaceFluxes(const std::string &filename, boo
 void TPZHDivErrorEstimator::SwitchMaterialObjects() {
 
     for (auto mat : fPostProcMesh.MaterialVec()) {
-        TPZMixedDarcyFlow *mixpoisson = dynamic_cast(mat.second);
+        auto *mixpoisson = dynamic_cast(mat.second);
         if (mixpoisson) {
             TPZMixedDarcyFlow *newmat;
             if (fPostProcesswithHDiv) {
-                newmat = new TPZMixedHDivErrorEstimate(*mixpoisson);
+                newmat = new TPZMixedHDivErrorEstimate(*mixpoisson);
             } else {
                 newmat = new TPZHDivErrorEstimateMaterial(*mixpoisson);
             }
 
             if (mixpoisson->HasForcingFunction()) {
-                newmat->SetForcingFunction(mixpoisson->ForcingFunction());
+                newmat->SetForcingFunction(mixpoisson->ForcingFunction(), mixpoisson->ForcingFunctionPOrder());
             }
             if (mixpoisson->HasExactSol()) {
                 newmat->SetExactSol(mixpoisson->ExactSol(), mixpoisson->PolynomialOrderExact());
@@ -2181,7 +2181,7 @@ void TPZHDivErrorEstimator::ComputePressureWeights() {
         }
         if (!mat) DebugStop();
 
-        TPZBndCond *bcmat = dynamic_cast(mat);
+        auto *bcmat = dynamic_cast *>(mat);
         if (bcmat) {
             switch(bcmat->Type()) {
                 case 0: // Dirichlet BC
@@ -2307,7 +2307,7 @@ void TPZHDivErrorEstimator::CreateSkeletonElements(TPZCompMesh *pressure_mesh) {
 #endif
 
     // Create skeleton elements in pressure mesh
-    TPZNullMaterial *skeletonMat = new TPZNullMaterial(fPressureSkeletonMatId);
+    auto *skeletonMat = new TPZNullMaterial(fPressureSkeletonMatId);
     skeletonMat->SetDimension(dim - 1);
     pressure_mesh->InsertMaterialObject(skeletonMat);
 

From bf52be1238ba4c0ae488715f3079b2dc07f10600 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 13:59:42 -0300
Subject: [PATCH 051/187] Fix forcing function and exact solution insertions

---
 ErrorEstimation/TPZMHMHDivErrorEstimator.cpp |  7 +-
 Projects/ErrorEstimationMHM/main_Journal.cpp | 67 +++++++++++---------
 Projects/Tools/Tools.cpp                     | 57 ++++++++++++-----
 3 files changed, 84 insertions(+), 47 deletions(-)

diff --git a/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp b/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
index 9a33ad25..852bda22 100644
--- a/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
@@ -480,7 +480,12 @@ TPZCompMesh *TPZMHMHDivErrorEstimator::CreateInternallyContinuousPressureMesh()
             TPZMaterial *pressure_mat = original_pressure->FindMaterial(bcID);
             TPZMaterial *bc_mat = pressure_mat->CreateBC(pressure_mat, mat->Id(), bc->Type(), bc->Val1(), bc->Val2());
             if (fExact) {
-                bc_mat->SetForcingFunction(fExact->Exact());
+                auto ff_bc = [this](const TPZVec &loc, TPZVec &rhsVal,
+                                    TPZFMatrix &matVal) {
+                    this->fExact->Exact()->Execute(loc, rhsVal, matVal);
+                };
+
+                bc_mat->SetForcingFunctionBC(ff_bc);
             }
             reconstruction_pressure->InsertMaterialObject(bc_mat);
         }
diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp
index 5b886691..d107d0d9 100644
--- a/Projects/ErrorEstimationMHM/main_Journal.cpp
+++ b/Projects/ErrorEstimationMHM/main_Journal.cpp
@@ -594,13 +594,16 @@ void InsertMaterialsInMHMMesh(TPZMHMixedMeshControl &control, const ProblemConfi
 
     auto *mat = new TPZMixedDarcyFlow(1, dim);
 
-    TPZFMatrix K(3, 3, 0), invK(3, 3, 0);
-    K.Identity();
-    invK.Identity();
+    auto ff_lambda = [config](const TPZVec &loc, TPZVec &result) {
+        config.exact.operator*().ForcingFunction()->Execute(loc, result);
+    };
+    auto exact_sol_lambda = [config](const TPZVec &loc, TPZVec &result, TPZFMatrix &deriv) {
+        config.exact.operator*().Exact()->Execute(loc, result, deriv);
+    };
 
-    mat->SetExactSol(config.exact.operator*().Exact());
-    mat->SetForcingFunction(config.exact.operator*().ForcingFunction());
-    mat->SetPermeabilityTensor(K, invK);
+    mat->SetForcingFunction(ff_lambda, 5);
+    mat->SetExactSol(exact_sol_lambda, 5);
+    mat->SetPermeabilityFunction(1);
 
     cmesh.InsertMaterialObject(mat);
 
@@ -608,8 +611,14 @@ void InsertMaterialsInMHMMesh(TPZMHMixedMeshControl &control, const ProblemConfi
         TPZFNMatrix<1, REAL> val1(1, 1, 0.);
         TPZManVector val2(1, 0.);
         int bctype = 0;
-        TPZBndCond *bc = mat->CreateBC(mat, matid, bctype, val1, val2);
-        bc->TPZMaterial::SetForcingFunction(config.exact.operator*().Exact());
+        auto *bc = mat->CreateBC(mat, matid, bctype, val1, val2);
+
+        auto ff_bc_lambda = [config](const TPZVec &loc,
+                                     TPZVec &rhsVal,
+                                     TPZFMatrix &matVal) {
+            config.exact.operator*().Exact()->Execute(loc, rhsVal, matVal);
+        };
+        bc->SetForcingFunctionBC(ff_bc_lambda);
         cmesh.InsertMaterialObject(bc);
     }
 }
@@ -635,29 +644,23 @@ void CreateMHMCompMeshHeteroPerm(TPZMHMixedMeshControl *mhm, const ProblemConfig
 
     auto *mat = new TPZMixedDarcyFlow(1, dim);
 
-    TPZFMatrix K(3, 3, 0), invK(3, 3, 0);
-    K.Identity();
-    K *= 5.;
-    invK.Identity();
-    invK *= 1./5.;
+    auto ff_lambda = [config](const TPZVec &loc, TPZVec &result) {
+        config.exact.operator*().ForcingFunction()->Execute(loc, result);
+    };
+    auto exact_sol_lambda = [config](const TPZVec &loc, TPZVec &result, TPZFMatrix &deriv) {
+        config.exact.operator*().Exact()->Execute(loc, result, deriv);
+    };
 
-    mat->SetExactSol(config.exact.operator*().Exact());
-    mat->SetForcingFunction(config.exact.operator*().ForcingFunction());
-    mat->SetPermeabilityTensor(K, invK);
+    mat->SetForcingFunction(ff_lambda, 5);
+    mat->SetExactSol(exact_sol_lambda, 5);
+    mat->SetPermeabilityFunction(5);
 
     cmesh.InsertMaterialObject(mat);
 
-    auto *mat2 = new TPZMixedPoisson(2, dim);
-
-    TPZFMatrix K2(3, 3, 0), invK2(3, 3, 0);
-    K2.Identity();
-    K2 *= 1.;
-    invK2.Identity();
-    invK2 *= 1./1.;
-
-    mat2->SetExactSol(config.exact.operator*().Exact());
-    mat2->SetForcingFunction(config.exact.operator*().ForcingFunction());
-    mat2->SetPermeabilityTensor(K2, invK2);
+    auto *mat2 = new TPZMixedDarcyFlow(2, dim);
+    mat2->SetForcingFunction(ff_lambda, 5);
+    mat2->SetExactSol(exact_sol_lambda, 5);
+    mat2->SetPermeabilityFunction(1);
 
     cmesh.InsertMaterialObject(mat2);
 
@@ -665,8 +668,14 @@ void CreateMHMCompMeshHeteroPerm(TPZMHMixedMeshControl *mhm, const ProblemConfig
         TPZFNMatrix<1, REAL> val1(1, 1, 0.);
         TPZManVector val2(1, 0.);
         int bctype = 0;
-        TPZBndCond *bc = mat->CreateBC(mat, matid, bctype, val1, val2);
-        bc->TPZMaterial::SetForcingFunction(config.exact.operator*().Exact());
+        auto *bc = mat->CreateBC(mat, matid, bctype, val1, val2);
+
+        auto ff_bc_lambda = [config](const TPZVec &loc,
+                                     TPZVec &rhsVal,
+                                     TPZFMatrix &matVal) {
+            config.exact.operator*().Exact()->Execute(loc, rhsVal, matVal);
+        };
+        bc->SetForcingFunctionBC(ff_bc_lambda);
         cmesh.InsertMaterialObject(bc);
     }
 
diff --git a/Projects/Tools/Tools.cpp b/Projects/Tools/Tools.cpp
index 27241db7..d913869f 100644
--- a/Projects/Tools/Tools.cpp
+++ b/Projects/Tools/Tools.cpp
@@ -82,8 +82,11 @@ TPZCompMesh* Tools::CreateFluxHDivMesh(const ProblemConfig& problem) {
         } else {
             bctype = 1;
         }
-        TPZBndCond* bc = mat->CreateBC(mat, matid, bctype, val1, val2);
-        bc->TPZMaterial::SetForcingFunction(problem.exact.operator*().Exact());
+        TPZBndCondT* bc = mat->CreateBC(mat, matid, bctype, val1, val2);
+        auto ff_lambda = [problem](const TPZVec &loc, TPZVec &rhsVal, TPZFMatrix &matVal) {
+            problem.exact.operator*().Exact()->Execute(loc, rhsVal, matVal);
+        };
+        bc->SetForcingFunctionBC(ff_lambda);
         cmesh->InsertMaterialObject(bc);
     }
     cmesh->SetDefaultOrder(problem.porder);
@@ -93,11 +96,9 @@ TPZCompMesh* Tools::CreateFluxHDivMesh(const ProblemConfig& problem) {
     if (problem.prefine) {
         Prefinamento(cmesh, problem.ndivisions, problem.porder);
     }
-    
-    
+
     cmesh->InitializeBlock();
     return cmesh;
-    
 }
 
 TPZMultiphysicsCompMesh* Tools::CreateHDivMesh(const ProblemConfig& problem) {
@@ -126,10 +127,18 @@ TPZMultiphysicsCompMesh* Tools::CreateHDivMesh(const ProblemConfig& problem) {
     }
 
     for (auto matid : problem.materialids) {
-        TPZMixedPoisson *mix = new TPZMixedPoisson(matid, cmesh->Dimension());
-        mix->SetForcingFunction(problem.exact.operator*().ForcingFunction());
-        mix->SetExactSol(problem.exact.operator*().Exact());
-        mix->SetPermeabilityTensor(K, invK);
+        auto *mix = new TPZMixedDarcyFlow(matid, cmesh->Dimension());
+
+        auto ff_lambda = [problem](const TPZVec &loc, TPZVec &result) {
+            problem.exact.operator*().ForcingFunction()->Execute(loc, result);
+        };
+        auto exact_sol_lambda = [problem](const TPZVec &loc, TPZVec &result, TPZFMatrix &deriv) {
+            problem.exact.operator*().Exact()->Execute(loc, result, deriv);
+        };
+
+        mix->SetForcingFunction(ff_lambda, 5);
+        mix->SetExactSol(exact_sol_lambda, 5);
+        mix->SetPermeabilityFunction(K(0,0));
 
         if (!mat) mat = mix;
 
@@ -158,8 +167,11 @@ TPZMultiphysicsCompMesh* Tools::CreateHDivMesh(const ProblemConfig& problem) {
                 break;
             }
         }
-        TPZBndCond* bc = mat->CreateBC(mat, matid, bctype, val1, val2);
-        bc->TPZMaterial::SetForcingFunction(problem.exact.operator*().Exact());
+        TPZBndCondT* bc = mat->CreateBC(mat, matid, bctype, val1, val2);
+        auto ff_lambda = [problem](const TPZVec &loc, TPZVec &rhsVal, TPZFMatrix &matVal) {
+            problem.exact.operator*().Exact()->Execute(loc, rhsVal, matVal);
+        };
+        bc->SetForcingFunctionBC(ff_lambda);
         cmesh->InsertMaterialObject(bc);
     }
     cmesh->ApproxSpace().SetAllCreateFunctionsMultiphysicElem();
@@ -648,9 +660,18 @@ TPZCompMesh* Tools::CMeshH1(const ProblemConfig& problem) {
     TPZDarcyFlow* mat = nullptr;
 
     for (auto matid : problem.materialids) {
-        TPZMatPoisson3d *mix = new TPZMatPoisson3d(matid, cmesh->Dimension());
-        mix->SetExactSol(problem.exact.operator*().Exact());
-        mix->SetForcingFunction(problem.exact.operator*().ForcingFunction());
+        auto *mix = new TPZDarcyFlow(matid, cmesh->Dimension());
+
+
+        auto ff_lambda = [problem](const TPZVec &loc, TPZVec &result) {
+            problem.exact.operator*().ForcingFunction()->Execute(loc, result);
+        };
+        auto exact_sol_lambda = [problem](const TPZVec &loc, TPZVec &result, TPZFMatrix &deriv) {
+            problem.exact.operator*().Exact()->Execute(loc, result, deriv);
+        };
+
+        mix->SetForcingFunction(ff_lambda, 5);
+        mix->SetExactSol(exact_sol_lambda, 5);
 
         if (!mat) mat = mix;
         cmesh->InsertMaterialObject(mix);
@@ -660,9 +681,11 @@ TPZCompMesh* Tools::CMeshH1(const ProblemConfig& problem) {
         TPZFNMatrix<1, REAL> val1(1, 1, 0.);
         TPZManVector val2(1, 0.);
         int bctype = 0;
-        val2.Zero();
-        TPZBndCond *bc = mat->CreateBC(mat, matid, bctype, val1, val2);
-        bc->TPZMaterial::SetForcingFunction(problem.exact.operator*().Exact());
+        auto *bc = mat->CreateBC(mat, matid, bctype, val1, val2);
+        auto ff_lambda = [problem](const TPZVec &loc, TPZVec &rhsVal, TPZFMatrix &matVal) {
+            problem.exact.operator*().Exact()->Execute(loc, rhsVal, matVal);
+        };
+        bc->SetForcingFunctionBC(ff_lambda);
 
         cmesh->InsertMaterialObject(bc);
     }

From d5dae3602c65758756d7f4ceec0dd0bea7db6809 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 1 Jun 2021 14:00:38 -0300
Subject: [PATCH 052/187] Update material types

---
 ErrorEstimation/TPZMHMHDivErrorEstimator.cpp | 20 +++++++++++---------
 1 file changed, 11 insertions(+), 9 deletions(-)

diff --git a/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp b/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
index 852bda22..41944d6b 100644
--- a/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
@@ -48,12 +48,13 @@ void TPZMHMHDivErrorEstimator::CreatePostProcessingMesh()
     if (fPostProcesswithHDiv) {
         CreateFluxSkeletonElements(meshvec[0]);
         // TODO move this to InsertMaterials method
-        TPZNullMaterial *skeletonMat = new TPZNullMaterial(fPressureSkeletonMatId);
-        skeletonMat->SetDimension(GMesh()->Dimension() - 1);
+        auto *skeletonMat = new TPZLagrangeMultiplierCS(
+                fPressureSkeletonMatId, GMesh()->Dimension() - 1, 1);
         fPostProcMesh.InsertMaterialObject(skeletonMat);
 
-        TPZNullMaterial *wrapMat = new TPZNullMaterial(fHDivWrapMatId);
-        skeletonMat->SetDimension(GMesh()->Dimension() - 1);
+        auto *wrapMat = new TPZLagrangeMultiplierCS(fHDivWrapMatId,
+                                                           GMesh()->Dimension() -
+                                                           1, 1);
         fPostProcMesh.InsertMaterialObject(wrapMat);
     }
 
@@ -474,11 +475,12 @@ TPZCompMesh *TPZMHMHDivErrorEstimator::CreateInternallyContinuousPressureMesh()
     std::set bcMatIDs;
     for (auto it : fOriginal->MaterialVec()) {
         TPZMaterial *mat = it.second;
-        TPZBndCond *bc = dynamic_cast(mat);
+        auto *bc = dynamic_cast *>(mat);
         if (bc) {
             int bcID = bc->Material()->Id();
-            TPZMaterial *pressure_mat = original_pressure->FindMaterial(bcID);
-            TPZMaterial *bc_mat = pressure_mat->CreateBC(pressure_mat, mat->Id(), bc->Type(), bc->Val1(), bc->Val2());
+            TPZMaterial * press = original_pressure->FindMaterial(bcID);
+            auto *pressure_mat = dynamic_cast*>(original_pressure->FindMaterial(bcID));
+            TPZBndCondT *bc_mat = pressure_mat->CreateBC(pressure_mat, mat->Id(), bc->Type(), bc->Val1(), bc->Val2());
             if (fExact) {
                 auto ff_bc = [this](const TPZVec &loc, TPZVec &rhsVal,
                                     TPZFMatrix &matVal) {
@@ -808,7 +810,7 @@ void TPZMHMHDivErrorEstimator::CreateSkeletonApproximationSpace(TPZCompMesh *pre
     int dim = gmesh->Dimension();
 
     // Create skeleton elements in pressure mesh
-    TPZNullMaterial *skeletonMat = new TPZNullMaterial(fPressureSkeletonMatId);
+    auto *skeletonMat = new TPZNullMaterial(fPressureSkeletonMatId);
     skeletonMat->SetDimension(dim - 1);
     pressure_mesh->InsertMaterialObject(skeletonMat);
 
@@ -1127,7 +1129,7 @@ void TPZMHMHDivErrorEstimator::CreateMultiphysicsInterfaces() {
         fMultiPhysicsInterfaceMatId = FindFreeMatId(this->GMesh());
     }
 
-    TPZLagrangeMultiplier *interfaceMat = new TPZLagrangeMultiplier(fMultiPhysicsInterfaceMatId, dim - 1, 1);
+    auto *interfaceMat = new TPZLagrangeMultiplier(fMultiPhysicsInterfaceMatId, dim - 1, 1);
     fPostProcMesh.InsertMaterialObject(interfaceMat);
     std::cout << "Created interface material of index " << fMultiPhysicsInterfaceMatId << '\n';
 

From c448b8b56f3934d48aa0a68287b2a47ee04dd7ea Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Wed, 2 Jun 2021 10:56:16 -0300
Subject: [PATCH 053/187] Change atomic mesh material

---
 Projects/Tools/Tools.cpp | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/Projects/Tools/Tools.cpp b/Projects/Tools/Tools.cpp
index d913869f..fa4df877 100644
--- a/Projects/Tools/Tools.cpp
+++ b/Projects/Tools/Tools.cpp
@@ -38,9 +38,10 @@ void Tools::PrintGeometry(TPZGeoMesh *gmesh, const std::string &file_name, bool
 
 TPZCompMesh* Tools::CreatePressureMesh(const ProblemConfig& problem) {
     TPZCompMesh* cmesh = new TPZCompMesh(problem.gmesh);
-    TPZMaterial* mat = nullptr;
+    TPZNullMaterial* mat = nullptr;
     for (auto matid : problem.materialids) {
-        auto * mix = new TPZMixedDarcyFlow(matid, cmesh->Dimension());
+        auto * mix = new TPZNullMaterial(matid);
+        mix->SetDimension(cmesh->Dimension());
         if (!mat) mat = mix;
         cmesh->InsertMaterialObject(mix);
     }

From 9c88b360594253de7950c35e669f0bf257580b5d Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Mon, 7 Jun 2021 11:00:56 -0300
Subject: [PATCH 054/187] Add template parameters to struct matrix

---
 Projects/Tools/Tools.cpp    | 10 +++++++---
 Projects/Tools/ToolsMHM.cpp |  2 +-
 2 files changed, 8 insertions(+), 4 deletions(-)

diff --git a/Projects/Tools/Tools.cpp b/Projects/Tools/Tools.cpp
index fa4df877..b900cff7 100644
--- a/Projects/Tools/Tools.cpp
+++ b/Projects/Tools/Tools.cpp
@@ -16,6 +16,7 @@
 #include 
 #include 
 #include 
+#include 
 #include "DataStructure.h"
 
 
@@ -83,7 +84,7 @@ TPZCompMesh* Tools::CreateFluxHDivMesh(const ProblemConfig& problem) {
         } else {
             bctype = 1;
         }
-        TPZBndCondT* bc = mat->CreateBC(mat, matid, bctype, val1, val2);
+        auto * bc = mat->CreateBC(mat, matid, bctype, val1, val2);
         auto ff_lambda = [problem](const TPZVec &loc, TPZVec &rhsVal, TPZFMatrix &matVal) {
             problem.exact.operator*().Exact()->Execute(loc, rhsVal, matVal);
         };
@@ -167,8 +168,11 @@ TPZMultiphysicsCompMesh* Tools::CreateHDivMesh(const ProblemConfig& problem) {
                 val1(0, 0) = Km;
                 break;
             }
+            default: {
+                bctype = -1;
+            }
         }
-        TPZBndCondT* bc = mat->CreateBC(mat, matid, bctype, val1, val2);
+        auto * bc = mat->CreateBC(mat, matid, bctype, val1, val2);
         auto ff_lambda = [problem](const TPZVec &loc, TPZVec &rhsVal, TPZFMatrix &matVal) {
             problem.exact.operator*().Exact()->Execute(loc, rhsVal, matVal);
         };
@@ -424,7 +428,7 @@ void Tools::SolveHybridProblem(TPZCompMesh *Hybridmesh, std::pair Inte
     //    TPZFrontStructMatrix > strmat(Hybridmesh);
     //    strmat.SetNumThreads(2);
     //    strmat.SetDecomposeType(ELDLt);
-    TPZSkylineStructMatrix strmat(Hybridmesh);
+    TPZSkylineStructMatrix strmat(Hybridmesh);
     strmat.SetNumThreads(0);
 #endif
 
diff --git a/Projects/Tools/ToolsMHM.cpp b/Projects/Tools/ToolsMHM.cpp
index 612baf4a..6c5ff179 100644
--- a/Projects/Tools/ToolsMHM.cpp
+++ b/Projects/Tools/ToolsMHM.cpp
@@ -408,7 +408,7 @@ void SolveProblem(const TPZAutoPointer& cmesh, const TPZVec strmat(cmesh.operator->());
     strmat.SetNumThreads(0/*config.n_threads*/);
 #else
-    TPZSkylineStructMatrix strmat(cmesh.operator->());
+    TPZSkylineStructMatrix strmat(cmesh.operator->());
     strmat.SetNumThreads(config.n_threads);
 #endif
 

From dfafcfe47178d15c55a3145cdfe15c9db3f15290 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 8 Jun 2021 14:58:25 -0300
Subject: [PATCH 055/187] Rename CreateHDivMesh to CreateMixedMesh

---
 Projects/ErrorEstimationHDiv/main.cpp           | 9 ++++-----
 Projects/ErrorEstimationHDiv/mainAdaptivity.cpp | 4 ++--
 Projects/ErrorEstimationMHM/main_MHM.cpp        | 1 +
 Projects/Tools/Tools.cpp                        | 4 ++--
 Projects/Tools/Tools.h                          | 2 +-
 5 files changed, 10 insertions(+), 10 deletions(-)

diff --git a/Projects/ErrorEstimationHDiv/main.cpp b/Projects/ErrorEstimationHDiv/main.cpp
index cee0f8c9..aee3d328 100644
--- a/Projects/ErrorEstimationHDiv/main.cpp
+++ b/Projects/ErrorEstimationHDiv/main.cpp
@@ -7,13 +7,12 @@
 
 #include "ProblemConfig.h"
 #include "TPZBFileStream.h"
-#include "TPZGmshReader.h"
 #include "TPZHDivErrorEstimator.h"
 #include "TPZHybridizeHDiv.h"
 #include "TPZMultiphysicsCompMesh.h"
 #include "TPZRefPatternDataBase.h"
 #include "Tools.h"
-#include "pzbndcond.h"
+#include "TPZBndCond.h"
 #include "pzlog.h"
 #include "tpzgeoelrefpattern.h"
 #include 
@@ -55,7 +54,7 @@ void RunSingularProblemHDiv() {
     config.bcmaterialids.insert(-1);
     config.makepressurecontinuous = true;
 
-    int nRef = 2;
+    int nRef = 3;
 
     config.ndivisions = 0;
     config.gmesh = CreateLShapeGeoMesh(nRef);
@@ -66,7 +65,7 @@ void RunSingularProblemHDiv() {
     TPZHybridizeHDiv hybridizer;
     TPZMultiphysicsCompMesh *hybridMesh = CreateHybridCompMesh(config, hybridizer);
 
-    Tools::SolveHybridProblem(hybridMesh, hybridizer.fInterfaceMatid, config, false);
+    Tools::SolveHybridProblem(hybridMesh, hybridizer.fInterfaceMatid, config, true);
 
     // Reconstruct potential and estimate error
     EstimateError(config, hybridMesh, hybridizer);
@@ -78,7 +77,7 @@ void RunSingularProblemHDiv() {
 
 TPZMultiphysicsCompMesh *CreateHybridCompMesh(const ProblemConfig &config, TPZHybridizeHDiv &hybridizer) {
 
-    TPZMultiphysicsCompMesh *cmesh_HDiv = Tools::CreateHDivMesh(config); // Hdiv x L2
+    TPZMultiphysicsCompMesh *cmesh_HDiv = Tools::CreateMixedMesh(config); // Hdiv x L2
 
 #ifdef PZDEBUG
     {
diff --git a/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp b/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
index 53e42ea2..1898ea8e 100644
--- a/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
+++ b/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
@@ -102,7 +102,7 @@ else
         
     TPZManVector meshvec_HDiv(2, 0);
         
-    TPZMultiphysicsCompMesh* cmesh_HDiv = Tools::CreateHDivMesh(config); //Hdiv x L2
+    TPZMultiphysicsCompMesh* cmesh_HDiv = Tools::CreateMixedMesh(config); //Hdiv x L2
     cmesh_HDiv->InitializeBlock();
     Tools::SolveMixedProblem(cmesh_HDiv, config);
     
@@ -131,7 +131,7 @@ else
               TPZMultiphysicsCompMesh* cmesh_HDiv = nullptr;
               
               
-              cmesh_HDiv = Tools::CreateHDivMesh(config);//Hdiv x L2
+              cmesh_HDiv = Tools::CreateMixedMesh(config);//Hdiv x L2
               cmesh_HDiv->InitializeBlock();
                #ifdef PZDEBUG2
               {
diff --git a/Projects/ErrorEstimationMHM/main_MHM.cpp b/Projects/ErrorEstimationMHM/main_MHM.cpp
index 42e281d2..3d453e1d 100644
--- a/Projects/ErrorEstimationMHM/main_MHM.cpp
+++ b/Projects/ErrorEstimationMHM/main_MHM.cpp
@@ -9,6 +9,7 @@
 //#include 
 #include 
 #include 
+#include 
 
 void RunSmoothProblem();
 void RunHighGradientProblem();
diff --git a/Projects/Tools/Tools.cpp b/Projects/Tools/Tools.cpp
index b900cff7..82d1efe4 100644
--- a/Projects/Tools/Tools.cpp
+++ b/Projects/Tools/Tools.cpp
@@ -103,7 +103,7 @@ TPZCompMesh* Tools::CreateFluxHDivMesh(const ProblemConfig& problem) {
     return cmesh;
 }
 
-TPZMultiphysicsCompMesh* Tools::CreateHDivMesh(const ProblemConfig& problem) {
+TPZMultiphysicsCompMesh* Tools::CreateMixedMesh(const ProblemConfig& problem) {
 
     auto* cmesh = new TPZMultiphysicsCompMesh(problem.gmesh);
     TPZMixedDarcyFlow *mat = nullptr;
@@ -468,7 +468,7 @@ void Tools::SolveHybridProblem(TPZCompMesh *Hybridmesh, std::pair Inte
         sout << problem.dir_name << "/" << "OriginalHybrid_Order_" << problem.porder << "Nref_" << problem.ndivisions
              << "NAdapStep_" << problem.adaptivityStep << ".vtk";
         an.DefineGraphMesh(2, scalnames, vecnames, sout.str());
-        int resolution = 0;
+        int resolution = 2;
         an.PostProcess(resolution, Hybridmesh->Dimension());
 
         if (problem.exact.operator*().Exact()) {
diff --git a/Projects/Tools/Tools.h b/Projects/Tools/Tools.h
index 1e0c58da..d6bf0be4 100644
--- a/Projects/Tools/Tools.h
+++ b/Projects/Tools/Tools.h
@@ -55,7 +55,7 @@ namespace Tools {
 
     TPZCompMesh *CreatePressureMesh(const ProblemConfig &problem);
 
-    TPZMultiphysicsCompMesh *CreateHDivMesh(const ProblemConfig &problem);
+    TPZMultiphysicsCompMesh *CreateMixedMesh(const ProblemConfig &problem);
 
     void UniformRefinement(int nDiv, TPZGeoMesh *gmesh);
 

From 4c79fe0d22cbde42a47117ec26739b742fe1bf52 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Tue, 8 Jun 2021 15:02:52 -0300
Subject: [PATCH 056/187] Accomodate changes in NeoPZ

---
 Projects/ErrorEstimationMHM/main_MHM.cpp | 29 ++++++++++++++----------
 1 file changed, 17 insertions(+), 12 deletions(-)

diff --git a/Projects/ErrorEstimationMHM/main_MHM.cpp b/Projects/ErrorEstimationMHM/main_MHM.cpp
index 3d453e1d..f03230c6 100644
--- a/Projects/ErrorEstimationMHM/main_MHM.cpp
+++ b/Projects/ErrorEstimationMHM/main_MHM.cpp
@@ -433,10 +433,10 @@ void SolveMHMProblem(TPZMHMixedMeshControl *mhm, const ProblemConfig &config) {
     TPZAutoPointer cmesh = mhm->CMesh();
 
     bool shouldrenumber = true;
-    TPZAnalysis an(cmesh, shouldrenumber);
+    TPZLinearAnalysis an(cmesh, shouldrenumber);
 
 #ifdef PZ_USING_MKL
-    TPZSymetricSpStructMatrix strmat(cmesh.operator->());
+    TPZSSpStructMatrix strmat(cmesh.operator->());
     strmat.SetNumThreads(0 /*config.n_threads*/);
 #else
     TPZSkylineStructMatrix strmat(cmesh.operator->());
@@ -528,23 +528,28 @@ void InsertMaterialsInMHMMesh(TPZMHMixedMeshControl &control, const ProblemConfi
     int dim = control.GMesh()->Dimension();
     cmesh.SetDimModel(dim);
 
-    TPZMixedPoisson *mat = new TPZMixedPoisson(1, dim);
+    auto *mat = new TPZMixedDarcyFlow(1, dim);
 
-    TPZFMatrix K(3, 3, 0), invK(3, 3, 0);
-    K.Identity();
-    invK.Identity();
+    auto exact_lambda = [config](const TPZVec &loc, TPZVec &result, TPZFMatrix &deriv) {
+        config.exact.operator*().Exact()->Execute(loc, result, deriv);
+    };
+
+    auto ff_lambda = [config](const TPZVec &loc, TPZVec &result) {
+        config.exact.operator*().ForcingFunction()->Execute(loc, result);
+    };
 
-    mat->SetExactSol(config.exact.operator*().Exact());
-    mat->SetForcingFunction(config.exact.operator*().ForcingFunction());
-    mat->SetPermeabilityTensor(K, invK);
+    mat->SetPermeabilityFunction(1);
+    mat->SetExactSol(exact_lambda, 8);
+    mat->SetForcingFunction(ff_lambda, 8);
 
     cmesh.InsertMaterialObject(mat);
 
     for (auto matid : config.bcmaterialids) {
-        TPZFNMatrix<1, REAL> val1(1, 1, 0.), val2(1, 1, 0.);
+        TPZFNMatrix<1, REAL> val1(1, 1, 0.);
+        TPZManVector val2(1, 0.);
         int bctype = 0;
-        TPZBndCond *bc = mat->CreateBC(mat, matid, bctype, val1, val2);
-        bc->TPZMaterial::SetForcingFunction(config.exact.operator*().Exact());
+        auto *bc = mat->CreateBC(mat, matid, bctype, val1, val2);
+        bc->SetForcingFunctionBC(exact_lambda);
         cmesh.InsertMaterialObject(bc);
     }
 }

From b168df98636f4feeb650eb9840be0cde096cebe2 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Wed, 9 Jun 2021 16:15:45 -0300
Subject: [PATCH 057/187] Ignore some files while working with HDiv and MHM
 estimation

---
 ErrorEstimation/CMakeLists.txt              |  4 ++--
 ErrorEstimation/Material/CMakeLists.txt     | 16 ++++++++--------
 Projects/CMakeLists.txt                     |  8 ++++----
 Projects/ErrorEstimationHDiv/CMakeLists.txt | 12 ++++++------
 4 files changed, 20 insertions(+), 20 deletions(-)

diff --git a/ErrorEstimation/CMakeLists.txt b/ErrorEstimation/CMakeLists.txt
index 85e6f2e8..db6d1380 100644
--- a/ErrorEstimation/CMakeLists.txt
+++ b/ErrorEstimation/CMakeLists.txt
@@ -4,8 +4,8 @@ add_library(ErrorEstimationLib
     ProblemConfig.h
     TPZHDivErrorEstimator.cpp
     TPZHDivErrorEstimator.h
-    TPZHybridH1ErrorEstimator.cpp
-    TPZHybridH1ErrorEstimator.h
+    #TPZHybridH1ErrorEstimator.cpp
+    #TPZHybridH1ErrorEstimator.h
     TPZMHMHDivErrorEstimator.cpp
     TPZMHMHDivErrorEstimator.h
     # Related tools
diff --git a/ErrorEstimation/Material/CMakeLists.txt b/ErrorEstimation/Material/CMakeLists.txt
index 4a146fa6..0613cc68 100644
--- a/ErrorEstimation/Material/CMakeLists.txt
+++ b/ErrorEstimation/Material/CMakeLists.txt
@@ -4,14 +4,14 @@ target_sources(ErrorEstimationLib PUBLIC
     TPZHDivErrorEstimateMaterial.h
     TPZMixedHdivErrorEstimate.cpp
     TPZMixedHdivErrorEstimate
-    TPZMatLaplacianHybrid.cpp
-    TPZMatLaplacianHybrid.h
-    TPZPressureProjection.h
-    TPZPressureProjection.cpp
-    TPZHybridH1ErrorEstimateMaterial.h
-    TPZHybridH1ErrorEstimateMaterial.cpp
-    TPZSteklovMaterial.h
-    TPZSteklovMaterial.cpp
+    #TPZMatLaplacianHybrid.cpp
+    #TPZMatLaplacianHybrid.h
+    #TPZPressureProjection.h
+    #TPZPressureProjection.cpp
+    #TPZHybridH1ErrorEstimateMaterial.h
+    #TPZHybridH1ErrorEstimateMaterial.cpp
+    #TPZSteklovMaterial.h
+    #TPZSteklovMaterial.cpp
 )
 
 target_include_directories(ErrorEstimationLib PUBLIC ${CMAKE_CURRENT_LIST_DIR})
diff --git a/Projects/CMakeLists.txt b/Projects/CMakeLists.txt
index b3d2cd8e..78658431 100644
--- a/Projects/CMakeLists.txt
+++ b/Projects/CMakeLists.txt
@@ -2,9 +2,9 @@
 add_subdirectory(Tools)
 
 # Created executable targets
-add_subdirectory(ErrorEstimationH1)
+#add_subdirectory(ErrorEstimationH1)
 add_subdirectory(ErrorEstimationHDiv)
-add_subdirectory(HybridH1)
+#add_subdirectory(HybridH1)
 add_subdirectory(ErrorEstimationMHM)
 
 # This project is marked as optional since it requires OpenCV external library
@@ -16,12 +16,12 @@ endif()
 # This project is marked as optional since it requires libInterpolate external library
 option(BUILD_UNISIM_PROJECT "Whether to build estimation on UNISIM mesh" OFF)
 if(BUILD_UNISIM_PROJECT)
-    add_subdirectory(UNISIM)
+    #add_subdirectory(UNISIM)
 endif()
 
 # This project is marked as optional since it requires libInterpolate external library
 option(BUILD_SPE10_PROJECT "Whether to build estimation on SPE10 mesh" OFF)
 if(BUILD_SPE10_PROJECT)
-    add_subdirectory(SPE10)
+    #add_subdirectory(SPE10)
 endif()
 
diff --git a/Projects/ErrorEstimationHDiv/CMakeLists.txt b/Projects/ErrorEstimationHDiv/CMakeLists.txt
index 912b4dec..55f1a496 100644
--- a/Projects/ErrorEstimationHDiv/CMakeLists.txt
+++ b/Projects/ErrorEstimationHDiv/CMakeLists.txt
@@ -1,15 +1,15 @@
 # Project to apply error estimation for H(div) simulations
-add_executable(HeteroPermeability main_HeteroPermeability.cpp)
-target_link_libraries(HeteroPermeability Tools ErrorEstimationLib)
+#add_executable(HeteroPermeability main_HeteroPermeability.cpp)
+#target_link_libraries(HeteroPermeability Tools ErrorEstimationLib)
 
 add_executable(HybridHDiv main.cpp)
 target_link_libraries(HybridHDiv Tools ErrorEstimationLib)
 
-add_executable(AdaptivityTest mainAdaptivity.cpp)
-target_link_libraries(AdaptivityTest Tools ErrorEstimationLib)
+#add_executable(AdaptivityTest mainAdaptivity.cpp)
+#target_link_libraries(AdaptivityTest Tools ErrorEstimationLib)
 
-add_executable(SteklovProblem mainSteklov.cpp)
-target_link_libraries(SteklovProblem Tools ErrorEstimationLib)
+#add_executable(SteklovProblem mainSteklov.cpp)
+#target_link_libraries(SteklovProblem Tools ErrorEstimationLib)
 
 configure_file(../Meshes/Quad.msh Quad.msh COPYONLY)
 configure_file(../Meshes/Cube.msh Cube.msh COPYONLY)

From 4e7c9891ec46ff4ca8327ffd7cf8f4e83b8b4c7d Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Wed, 16 Jun 2021 14:07:51 -0300
Subject: [PATCH 058/187] Remove unused header

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 1 -
 1 file changed, 1 deletion(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 8074c678..00d4eaeb 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -24,7 +24,6 @@
 #include "pzelementgroup.h"
 #include "pzelmat.h"
 #include "pzintel.h"
-//#include "pzmat1dlin.h"
 #include "pzsubcmesh.h"
 #include "pzstepsolver.h"
 #include "TPZVTKGeoMesh.h"

From 0d82de69f2dd378a0def6d93286f3cbcf80eff7d Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Wed, 16 Jun 2021 14:09:01 -0300
Subject: [PATCH 059/187] Using auto when pointer type is deduced

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 00d4eaeb..9cd3002c 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -199,7 +199,7 @@ TPZCompMesh *TPZHDivErrorEstimator::CreatePressureMesh() {
         std::set bcMatIDs = GetBCMatIDs(&fPostProcMesh);
         for (auto bcID : bcMatIDs) {
             TPZMaterial *mat = mult->FindMaterial(bcID);
-            TPZBndCondT *bc = dynamic_cast *>(mat);
+            auto *bc = dynamic_cast *>(mat);
             if (!bc) DebugStop();
 
             int volumetricMatId = bc->Material()->Id();
@@ -398,12 +398,12 @@ void TPZHDivErrorEstimator::ComputeElementStiffnesses() {
 
     for (auto cel:fPostProcMesh.ElementVec()) {
         if (!cel) continue;
-        TPZCondensedCompEl *condense = dynamic_cast(cel);
+        auto *condense = dynamic_cast(cel);
         if (condense) {
             // for Mark proposal ek correspond to local dirichlet problem
             condense->Assemble();
         }
-        TPZSubCompMesh *subcmesh = dynamic_cast(cel);
+        auto *subcmesh = dynamic_cast(cel);
         if (subcmesh) {
             subcmesh->Assemble();
         }
@@ -879,7 +879,7 @@ void TPZHDivErrorEstimator::ComputeAverage(TPZCompMesh *pressuremesh, int64_t ie
     if (!cel) DebugStop();
     TPZGeoEl *gel = cel->Reference();
     if (!gel) DebugStop();
-    TPZInterpolatedElement *intel = dynamic_cast(cel);
+    auto *intel = dynamic_cast(cel);
     if (!intel) DebugStop();
     int nc = cel->NConnects();
     int order = cel->Connect(nc - 1).Order();
@@ -1627,7 +1627,7 @@ bool TPZHDivErrorEstimator::IsDirichletCondition(TPZGeoElSide gelside) {
     TPZGeoEl *gel = gelside.Element();
     int matid = gel->MaterialId();
     TPZMaterial *mat = fPostProcMesh.FindMaterial(matid);
-    TPZBndCond *bc = dynamic_cast(mat);
+    auto *bc = dynamic_cast(mat);
     if (!bc) return false;
     int typ = bc->Type();
     //  std::cout<<"type "<< typ<<"\n";
@@ -2046,7 +2046,7 @@ void TPZHDivErrorEstimator::PrepareElementsForH1Reconstruction() {
         
         if (elementsToGroup.size()) {
             int64_t index;
-            TPZElementGroup *elGroup = new TPZElementGroup(fPostProcMesh, index);
+            auto *elGroup = new TPZElementGroup(fPostProcMesh, index);
             for (const auto &it : elementsToGroup) {
                 elGroup->AddElement(fPostProcMesh.Element(it));
             }

From 06cd95ad393f4c9f8489d9d63d8e13f548cd43f8 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Wed, 16 Jun 2021 14:11:27 -0300
Subject: [PATCH 060/187] Replace SwitchMaterialObjects by
 InsertPostProcMaterials

A cleaner way of creating post proc materials
---
 ErrorEstimation/TPZHDivErrorEstimator.cpp    | 53 +++++++++-----------
 ErrorEstimation/TPZHDivErrorEstimator.h      |  2 +-
 ErrorEstimation/TPZMHMHDivErrorEstimator.cpp |  2 +-
 3 files changed, 25 insertions(+), 32 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 9cd3002c..44df0fa4 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -295,17 +295,8 @@ void TPZHDivErrorEstimator::CreatePostProcessingMesh() {
     // initialize the post processing mesh
     fPostProcMesh.SetReference(fOriginal->Reference());
     int dim = fOriginal->Dimension();
-    fOriginal->CopyMaterials(fPostProcMesh);
-    
-    {
-        fPostProcMesh.DeleteMaterial(fHybridizer.fHDivWrapMatid);
-        fPostProcMesh.DeleteMaterial(fHybridizer.fInterfaceMatid.first);
-        fPostProcMesh.DeleteMaterial(fHybridizer.fInterfaceMatid.second);
-        fPostProcMesh.DeleteMaterial(fHybridizer.fLagrangeInterface);
-    }
-    
     // switch the material from mixed to TPZMixedHdivErrorEstimate...
-    SwitchMaterialObjects();
+    InsertPostProcMaterials();
     
     TPZManVector meshvec(4, 0);
     meshvec[0] = 0;
@@ -1818,33 +1809,35 @@ void TPZHDivErrorEstimator::PlotInterfaceFluxes(const std::string &filename, boo
 }
 
 /// switch material object from mixed poisson to TPZMixedHdivErrorEstimate
-void TPZHDivErrorEstimator::SwitchMaterialObjects() {
+void TPZHDivErrorEstimator::InsertPostProcMaterials() {
 
-    for (auto mat : fPostProcMesh.MaterialVec()) {
-        auto *mixpoisson = dynamic_cast(mat.second);
-        if (mixpoisson) {
-            TPZMixedDarcyFlow *newmat;
+    for (auto it : fOriginal->MaterialVec()) {
+        auto *orig_mat = dynamic_cast(it.second);
+        if (orig_mat) {
+            TPZMixedDarcyFlow *new_mat;
             if (fPostProcesswithHDiv) {
-                newmat = new TPZMixedHDivErrorEstimate(*mixpoisson);
+                new_mat = new TPZMixedHDivErrorEstimate(*orig_mat);
             } else {
-                newmat = new TPZHDivErrorEstimateMaterial(*mixpoisson);
+                new_mat = new TPZHDivErrorEstimateMaterial(*orig_mat);
             }
-
-            if (mixpoisson->HasForcingFunction()) {
-                newmat->SetForcingFunction(mixpoisson->ForcingFunction(), mixpoisson->ForcingFunctionPOrder());
+            if (orig_mat->HasForcingFunction()) {
+                new_mat->SetForcingFunction(orig_mat->ForcingFunction(), orig_mat->ForcingFunctionPOrder());
             }
-            if (mixpoisson->HasExactSol()) {
-                newmat->SetExactSol(mixpoisson->ExactSol(), mixpoisson->PolynomialOrderExact());
+            if (orig_mat->HasExactSol()) {
+                new_mat->SetExactSol(orig_mat->ExactSol(), orig_mat->PolynomialOrderExact());
             }
+            fPostProcMesh.InsertMaterialObject(new_mat);
+        }
+    }
 
-            for (auto bcmat : fPostProcMesh.MaterialVec()) {
-                TPZBndCond *bc = dynamic_cast(bcmat.second);
-                if (bc) {
-                    bc->SetMaterial(newmat);
-                }
-            }
-            fPostProcMesh.MaterialVec()[newmat->Id()] = newmat;
-            delete mixpoisson;
+    for (auto it : fOriginal->MaterialVec()) {
+        auto *orig_bc = dynamic_cast(it.second);
+        if (orig_bc) {
+            it.second->Clone(fPostProcMesh.MaterialVec());
+            auto *new_mat = fPostProcMesh.FindMaterial(orig_bc->Material()->Id());
+            auto *new_bc = dynamic_cast(fPostProcMesh.FindMaterial(orig_bc->Id()));
+            if (!new_bc) DebugStop();
+            new_bc->SetMaterial(new_mat);
         }
     }
 }
diff --git a/ErrorEstimation/TPZHDivErrorEstimator.h b/ErrorEstimation/TPZHDivErrorEstimator.h
index 7b8d3a5d..3c8f4a7f 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.h
+++ b/ErrorEstimation/TPZHDivErrorEstimator.h
@@ -155,7 +155,7 @@ class TPZHDivErrorEstimator {
     virtual void CopySolutionFromSkeleton();
 
     /// switch material object from mixed poisson to TPZMixedHdivErrorEstimate
-    virtual void SwitchMaterialObjects();
+    virtual void InsertPostProcMaterials();
 
     /// compute the effectivity indices of the pressure error and flux error and store in the element solution
     void ComputeEffectivityIndices();
diff --git a/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp b/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
index 41944d6b..868f46d5 100644
--- a/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
@@ -25,7 +25,7 @@ void TPZMHMHDivErrorEstimator::CreatePostProcessingMesh()
 
     fOriginal->CopyMaterials(fPostProcMesh);
     // Switch the material from mixed to TPZMHMHDivErrorEstimationMaterial
-    SwitchMaterialObjects();
+    InsertPostProcMaterials();
 
     TPZManVector meshvec(4);
     TPZManVector active(4,0);

From 1776b1c644a326eda0faa3dadb26c570002b8c5c Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Wed, 16 Jun 2021 14:11:54 -0300
Subject: [PATCH 061/187] Add nodiscard keyword to PressureSkeletonMatId method

---
 ErrorEstimation/TPZHDivErrorEstimator.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.h b/ErrorEstimation/TPZHDivErrorEstimator.h
index 3c8f4a7f..b5c33de2 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.h
+++ b/ErrorEstimation/TPZHDivErrorEstimator.h
@@ -80,7 +80,7 @@ class TPZHDivErrorEstimator {
     // Plots State solution of elements of target dimension
     static void PlotState(const std::string& filename, int targetDim, TPZCompMesh* cmesh, bool atomic = true);
 
-    int PressureSkeletonMatId() const { return fPressureSkeletonMatId; }
+    [[nodiscard]] int PressureSkeletonMatId() const { return fPressureSkeletonMatId; }
 
     TPZMultiphysicsCompMesh *PostProcMesh() { return &fPostProcMesh; }
     TPZGeoMesh *GMesh() { return fOriginal->Reference(); }

From a11452f5c6744e7caceb54939f6abb7c8a503646 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Wed, 16 Jun 2021 14:12:42 -0300
Subject: [PATCH 062/187] Pass 'gelside' param as a const reference in
 IsDirichletCondition method

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 2 +-
 ErrorEstimation/TPZHDivErrorEstimator.h   | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 44df0fa4..d85387d2 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -1614,7 +1614,7 @@ void TPZHDivErrorEstimator::ComputeEffectivityIndices() {
 
 /// returns true if the material associated with the element is a boundary condition
 /// and if the boundary condition is dirichlet type
-bool TPZHDivErrorEstimator::IsDirichletCondition(TPZGeoElSide gelside) {
+bool TPZHDivErrorEstimator::IsDirichletCondition(const TPZGeoElSide& gelside) {
     TPZGeoEl *gel = gelside.Element();
     int matid = gel->MaterialId();
     TPZMaterial *mat = fPostProcMesh.FindMaterial(matid);
diff --git a/ErrorEstimation/TPZHDivErrorEstimator.h b/ErrorEstimation/TPZHDivErrorEstimator.h
index b5c33de2..c397bcba 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.h
+++ b/ErrorEstimation/TPZHDivErrorEstimator.h
@@ -165,7 +165,7 @@ class TPZHDivErrorEstimator {
 
     /// returns true if the material associated with the element is a boundary condition
     /// and if the boundary condition is dirichlet type
-    bool IsDirichletCondition(TPZGeoElSide gelside);
+    bool IsDirichletCondition(const TPZGeoElSide& gelside);
 
     void RestrainSkeletonSides(TPZCompMesh *pressure_mesh);
 

From 809b3183f0f8421c5dff8723ef325a4d6485c07e Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Wed, 16 Jun 2021 14:13:26 -0300
Subject: [PATCH 063/187] Remove duplicated call

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index d85387d2..be8e5e8b 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -1760,11 +1760,10 @@ void TPZHDivErrorEstimator::PlotPressureSkeleton(const std::string &filename, bo
 
     if (!reconstructed) {
         pressure = fOriginal->MeshVector()[1];
-        scalnames.Push("State");
     } else {
         pressure = PressureMesh();
-        scalnames.Push("State");
     }
+    scalnames.Push("State");
 
     TPZLinearAnalysis an(pressure, false);
 

From 2884deaec99b75897c116657dc8e3081b4e5ab72 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Wed, 16 Jun 2021 14:14:23 -0300
Subject: [PATCH 064/187] Use empty to check if set has elements

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index be8e5e8b..38e8d498 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -2036,7 +2036,7 @@ void TPZHDivErrorEstimator::PrepareElementsForH1Reconstruction() {
             }
         }
         
-        if (elementsToGroup.size()) {
+        if (!elementsToGroup.empty()) {
             int64_t index;
             auto *elGroup = new TPZElementGroup(fPostProcMesh, index);
             for (const auto &it : elementsToGroup) {

From 06d9ff846123bb5c7ac68ba4e6b4d16e05cc3269 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Wed, 16 Jun 2021 17:21:31 -0300
Subject: [PATCH 065/187] Use auto when type is easily deduced

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp    | 78 ++++++++++----------
 ErrorEstimation/TPZMHMHDivErrorEstimator.cpp | 38 +++++-----
 2 files changed, 58 insertions(+), 58 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 38e8d498..d42585d1 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -248,7 +248,7 @@ TPZCompMesh *TPZHDivErrorEstimator::CreatePressureMesh() {
             TPZGeoEl *bcGeoEl = gmesh->Element(bcElID);
             // We load the volumetric element reference so it shares its connects with the BC element to be created
             neighCel->LoadElementReference();
-            TPZInterpolatedElement *intel = dynamic_cast(neighCel);
+            auto *intel = dynamic_cast(neighCel);
             if (!intel) DebugStop();
             // Get order of the neighbour side of the volumetric element
             int iside = neighSide.Side();
@@ -420,7 +420,7 @@ void TPZHDivErrorEstimator::IncreaseSideOrders(TPZCompMesh *mesh) {
         if (gel->Dimension() != dim) {
             continue;
         }
-        TPZInterpolatedElement *intel = dynamic_cast (cel);
+        auto *intel = dynamic_cast (cel);
         int nc = cel->NConnects();
         int order = cel->Connect(nc - 1).Order();
         int nsides = gel->NSides();
@@ -476,12 +476,12 @@ void TPZHDivErrorEstimator::IncreasePressureSideOrders(TPZCompMesh *cmesh) {
         int maxOrder = 0;
 
         for (int ineigh = 0; ineigh < nneigh; ineigh++) {
-            TPZInterpolatedElement *intelS = dynamic_cast(celstack[ineigh].Element());
+            auto *intelS = dynamic_cast(celstack[ineigh].Element());
             int orderEl = intelS->GetPreferredOrder();
             maxOrder = (orderEl > maxOrder) ? orderEl : maxOrder;
         }
 
-        TPZInterpolatedElement *intel = dynamic_cast (cel);
+        auto *intel = dynamic_cast (cel);
         int nsides = gel->NSides();
         int ncorner = gel->NCornerNodes();
         
@@ -514,7 +514,7 @@ void TPZHDivErrorEstimator::CreateEdgeSkeletonMesh(TPZCompMesh *pressuremesh) {
     if (pressuremesh->MaterialVec().find(fPressureSkeletonMatId) != pressuremesh->MaterialVec().end()) {
         DebugStop();
     }
-    TPZNullMaterial *nullmat = new TPZNullMaterial(fPressureSkeletonMatId);
+    auto *nullmat = new TPZNullMaterial(fPressureSkeletonMatId);
     pressuremesh->InsertMaterialObject(nullmat);
     int dim = fPostProcMesh.Dimension();
     int64_t nel = pressuremesh->NElements();
@@ -523,7 +523,7 @@ void TPZHDivErrorEstimator::CreateEdgeSkeletonMesh(TPZCompMesh *pressuremesh) {
     for (int64_t el = 0; el < nel; el++) {
         TPZCompEl *cel = pressuremesh->Element(el);
         if (!cel) continue;
-        TPZInterpolatedElement *intel = dynamic_cast(cel);
+        auto *intel = dynamic_cast(cel);
         if (!intel) DebugStop();
         TPZGeoEl *gel = cel->Reference();
         if (!gel) DebugStop();
@@ -607,7 +607,7 @@ void TPZHDivErrorEstimator::RestrainSmallEdges(TPZCompMesh *pressuremesh) {
     for (int64_t el = 0; el < nel; el++) {
         TPZCompEl *cel = pressuremesh->Element(el);
         if (!cel) continue;
-        TPZInterpolatedElement *intel = dynamic_cast(cel);
+        auto *intel = dynamic_cast(cel);
         if (!intel) DebugStop();
         TPZGeoEl *gel = cel->Reference();
         if (!gel) DebugStop();
@@ -620,7 +620,7 @@ void TPZHDivErrorEstimator::RestrainSmallEdges(TPZCompMesh *pressuremesh) {
         bool onlyinterpolated = true;
         TPZCompElSide large_celside = gelside.LowerLevelCompElementList2(onlyinterpolated);
         if (large_celside) {
-            TPZInterpolatedElement *largeintel = dynamic_cast(large_celside.Element());
+            auto *largeintel = dynamic_cast(large_celside.Element());
             if (!largeintel) DebugStop();
             int largeside = large_celside.Side();
             intel->RestrainSide(nsides - 1, largeintel, largeside);
@@ -652,7 +652,7 @@ void TPZHDivErrorEstimator::AdjustNeighbourPolynomialOrders(TPZCompMesh *pressur
     for (int64_t el = 0; el < nel; el++) {
         TPZCompEl *cel = pressureHybrid->Element(el);
         if (!cel) continue;
-        TPZInterpolatedElement *intel = dynamic_cast(cel);
+        auto *intel = dynamic_cast(cel);
         if (!intel) DebugStop();
         TPZGeoEl *gel = intel->Reference();
         if (gel->Dimension() >= dim) continue;
@@ -664,7 +664,7 @@ void TPZHDivErrorEstimator::AdjustNeighbourPolynomialOrders(TPZCompMesh *pressur
         for (int64_t el = 0; el < nel; el++) {
             TPZCompEl *cel = pressureHybrid->Element(el);
             if (!cel) continue;
-            TPZInterpolatedElement *intel = dynamic_cast(cel);
+            auto *intel = dynamic_cast(cel);
             if (!intel) DebugStop();
             TPZGeoEl *gel = intel->Reference();
             if (gel->Dimension() >= dim) continue;
@@ -696,7 +696,7 @@ void TPZHDivErrorEstimator::AdjustNeighbourPolynomialOrders(TPZCompMesh *pressur
                 for (int ieq = 0; ieq < nequal; ieq++) {
                     TPZCompEl *celneigh = celstack[ieq].Element();
                     int celside = celstack[ieq].Side();
-                    TPZInterpolatedElement *intelneigh = dynamic_cast(celneigh);
+                    auto *intelneigh = dynamic_cast(celneigh);
                     if (!intelneigh) DebugStop();
                     int nneighconnects = intelneigh->NSideConnects(celside);
                     int neighporder = intelneigh->SideConnect(nneighconnects - 1, celside).Order();
@@ -711,7 +711,7 @@ void TPZHDivErrorEstimator::AdjustNeighbourPolynomialOrders(TPZCompMesh *pressur
                 for (int ieq = 0; ieq < nequal; ieq++) {
                     TPZCompEl *celneigh = celstack[ieq].Element();
                     int celside = celstack[ieq].Side();
-                    TPZInterpolatedElement *intelneigh = dynamic_cast(celneigh);
+                    auto *intelneigh = dynamic_cast(celneigh);
                     if (!intelneigh) DebugStop();
                     int nneighconnects = intelneigh->NSideConnects(celside);
                     int neighporder = intelneigh->SideConnect(nneighconnects - 1, celside).Order();
@@ -736,7 +736,7 @@ void TPZHDivErrorEstimator::AdjustNeighbourPolynomialOrders(TPZCompMesh *pressur
         int porder = it.second;
         TPZCompEl *cel = pressureHybrid->Element(index);
         if (!cel) DebugStop();
-        TPZInterpolatedElement *intel = dynamic_cast(cel);
+        auto *intel = dynamic_cast(cel);
         if (!intel) DebugStop();
         intel->SetSideOrder(side, porder);
     }
@@ -760,7 +760,7 @@ void TPZHDivErrorEstimator::ComputeAveragePressures(int target_dim) {
     for (int64_t el = 0; el < nel; el++) {
         TPZCompEl *cel = pressure_mesh->Element(el);
         if (!cel) continue;
-        TPZInterpolatedElement *intel = dynamic_cast(cel);
+        auto *intel = dynamic_cast(cel);
         if (!intel) DebugStop();
         TPZGeoEl *gel = intel->Reference();
         if (gel->Dimension() != target_dim + 1 && gel->MaterialId() != fPressureSkeletonMatId) continue;
@@ -779,7 +779,7 @@ void TPZHDivErrorEstimator::ComputeAveragePressures(int target_dim) {
         int matid = gel->MaterialId();
         TPZMaterial *mat = pressure_mesh->FindMaterial(matid);
         // TODO change this. Look for matIDs in bcMatIds instead. Only cast in debug mode for further checks
-        TPZBndCond *bc = dynamic_cast(mat);
+        auto *bc = dynamic_cast(mat);
         if (bc) continue;
         
         // Skip calculation if the element is a small skeleton
@@ -837,7 +837,7 @@ void TPZHDivErrorEstimator::ComputeBoundaryL2Projection(int target_dim){
         int matid = gel->MaterialId();
         TPZMaterial *mat = pressuremesh->FindMaterial(matid);
         
-        TPZBndCond *bc = dynamic_cast(mat);
+        auto *bc = dynamic_cast(mat);
         if (!bc || (bc->Type() != 0)) continue;
         
         cel->CalcStiff(ekbc, efbc);
@@ -1073,7 +1073,7 @@ void TPZHDivErrorEstimator::TransferEdgeSolution() {
     for (int64_t el = 0; el < nel; el++) {
         TPZCompEl *cel = pressureHybrid->Element(el);
         if (!cel) continue;
-        TPZInterpolatedElement *intel = dynamic_cast(cel);
+        auto *intel = dynamic_cast(cel);
         if (!intel) DebugStop();
         TPZGeoEl *gel = intel->Reference();
         if (gel->Dimension() > 2) continue;
@@ -1084,7 +1084,7 @@ void TPZHDivErrorEstimator::TransferEdgeSolution() {
     for (int64_t el = 0; el < nel; el++) {
         TPZCompEl *cel = pressureHybrid->Element(el);
         if (!cel) continue;
-        TPZInterpolatedElement *intel = dynamic_cast(cel);
+        auto *intel = dynamic_cast(cel);
         if (!intel) DebugStop();
         TPZGeoEl *gel = cel->Reference();
         if (!gel) DebugStop();
@@ -1115,7 +1115,7 @@ void TPZHDivErrorEstimator::TransferEdgeSolution() {
             int nshape_edge = pressureHybrid->Block().Size(edge_seqnum);
             for (int ieq = 0; ieq < nequal; ieq++) {
                 TPZCompEl *celneigh = equal[ieq].Element();
-                TPZInterpolatedElement *intelneigh = dynamic_cast(celneigh);
+                auto *intelneigh = dynamic_cast(celneigh);
                 TPZGeoEl *neighgel = intelneigh->Reference();
                 if (!intelneigh) DebugStop();
                 if (neighgel->MaterialId() != fHybridizer.fLagrangeInterface) {
@@ -1153,7 +1153,7 @@ void TPZHDivErrorEstimator::ComputeNodalAverages() {
     for (int64_t el = 0; el < nel; el++) {
         TPZCompEl *cel = pressure_mesh->Element(el);
         if (!cel) continue;
-        TPZInterpolatedElement *intel = dynamic_cast(cel);
+        auto *intel = dynamic_cast(cel);
         if (!intel) DebugStop();
         TPZGeoEl *gel = intel->Reference();
         if (gel->Dimension() != dim - 1) continue;
@@ -1166,7 +1166,7 @@ void TPZHDivErrorEstimator::ComputeNodalAverages() {
     TPZStack nodesToImposeSolution;
     for (int64_t el = 0; el < nel; el++) {
         TPZCompEl *cel = pressure_mesh->Element(el);
-        TPZInterpolatedElement *intel = dynamic_cast(cel);
+        auto *intel = dynamic_cast(cel);
         if (!intel) {
             continue;
         }
@@ -1218,7 +1218,7 @@ void TPZHDivErrorEstimator::ComputeNodalAverages() {
             if (neigh_celside.Reference().Dimension() != 0) continue;
 
             // Get solution of the neighbour
-            TPZInterpolatedElement *neigh_intel = dynamic_cast(neigh_celside.Element());
+            auto *neigh_intel = dynamic_cast(neigh_celside.Element());
             if (!neigh_intel) DebugStop();
 
             int64_t neigh_conindex = neigh_intel->ConnectIndex(neigh_celside.Side());
@@ -1233,7 +1233,7 @@ void TPZHDivErrorEstimator::ComputeNodalAverages() {
             }
 
             // Set solution to given connect
-            TPZInterpolatedElement *intel = dynamic_cast(node_celside.Element());
+            auto *intel = dynamic_cast(node_celside.Element());
             if (!intel) DebugStop();
 
             int side = node_gelside.Side();
@@ -1289,14 +1289,14 @@ void TPZHDivErrorEstimator::ComputeNodalAverage(TPZCompElSide &node_celside)
             continue;
         }
         
-        TPZInterpolatedElement *intel = dynamic_cast(celside.Element());
+        auto *intel = dynamic_cast(celside.Element());
         if (!intel) DebugStop();
         int64_t index = intel->Index();
         REAL weight = fPressureweights[index];
 
         if (IsZero(weight)) {
-            TPZMaterial *mat = intel->Material();
-            TPZBndCond *bc = dynamic_cast(mat);
+            mat = intel->Material();
+            auto *bc = dynamic_cast(mat);
             if (!bc) DebugStop();
             
             continue;
@@ -1472,7 +1472,7 @@ void TPZHDivErrorEstimator::ComputeEffectivityIndices() {
 
         TPZCompEl *cel = cmesh->Element(el);
         if (!cel) continue;
-        TPZSubCompMesh *subcmesh = dynamic_cast(cel);
+        auto *subcmesh = dynamic_cast(cel);
         if (subcmesh) {
             ComputeEffectivityIndices(subcmesh);
         }
@@ -1552,7 +1552,7 @@ void TPZHDivErrorEstimator::ComputeEffectivityIndices() {
 
         TPZCompEl *cel = cmesh->Element(el);
         if (!cel) continue;
-        TPZSubCompMesh *subcmesh = dynamic_cast(cel);
+        auto *subcmesh = dynamic_cast(cel);
         if (subcmesh) {
             ComputeEffectivityIndices(subcmesh);
         }
@@ -1989,7 +1989,7 @@ void TPZHDivErrorEstimator::PrepareElementsForH1Reconstruction() {
         
         for (int i = 0; i < compNeighSides.size(); i++) {
             TPZCompEl *neighCel = compNeighSides[i].Element();
-            TPZInterpolatedElement *neighIntEl = dynamic_cast(neighCel);
+            auto *neighIntEl = dynamic_cast(neighCel);
             if (!neighIntEl) DebugStop();
             
             int sideNum = compNeighSides[i].Side();
@@ -2013,7 +2013,7 @@ void TPZHDivErrorEstimator::PrepareElementsForH1Reconstruction() {
         if (!gel) DebugStop();
         
         if (gel->Dimension() != fPostProcMesh.Dimension()) continue;
-        TPZMultiphysicsElement *mcel = dynamic_cast(cel);
+        auto *mcel = dynamic_cast(cel);
         if (!mcel) DebugStop();
         
         std::set elementsToGroup;
@@ -2028,7 +2028,7 @@ void TPZHDivErrorEstimator::PrepareElementsForH1Reconstruction() {
                 TPZCompElSide compSide = compNeighSides[i];
                 TPZCompEl *neighCel = compSide.Element();
                 TPZMaterial *mat = neighCel->Material();
-                TPZBndCond *bc = dynamic_cast(mat);
+                auto *bc = dynamic_cast(mat);
                 if (bc) {
                     elementsToGroup.insert(mcel->Index());
                     elementsToGroup.insert(neighCel->Index());
@@ -2067,17 +2067,17 @@ void TPZHDivErrorEstimator::PrepareElementsForH1Reconstruction() {
         if (!cel) continue;
         TPZGeoEl *gel = cel->Reference();
         if (!gel) {
-            TPZElementGroup *group = dynamic_cast(cel);
+            auto *group = dynamic_cast(cel);
             if (!group) DebugStop();
         }
         if (gel && gel->Dimension() != fPostProcMesh.Dimension()) continue;
-        TPZCondensedCompEl *condense = new TPZCondensedCompEl(cel, false);
+        auto *condense = new TPZCondensedCompEl(cel, false);
     }
     
     // @TODO what is the meaning of this? phil
     for (auto matit : fPostProcMesh.MaterialVec()) {
         TPZMaterial *mat = matit.second;
-        TPZHDivErrorEstimateMaterial *errormat = dynamic_cast(mat);
+        auto *errormat = dynamic_cast(mat);
         if (errormat) {
             errormat->fNeumannLocalProblem = false;
         }
@@ -2104,7 +2104,7 @@ void TPZHDivErrorEstimator::CopySolutionFromSkeleton() {
     for (int64_t el = 0; el < nel; el++) {
         TPZCompEl *cel = pressuremesh->Element(el);
         if (!cel) continue;
-        TPZInterpolatedElement *intel = dynamic_cast(cel);
+        auto *intel = dynamic_cast(cel);
         if (!intel) DebugStop();
         TPZGeoEl *gel = intel->Reference();
         if (gel->Dimension() != dim) continue;
@@ -2123,7 +2123,7 @@ void TPZHDivErrorEstimator::CopySolutionFromSkeleton() {
                 TPZCompElSide cneigh = celstack[ist];
                 TPZGeoElSide gneigh = cneigh.Reference();
                 if (gneigh.Element()->MaterialId() == this->fPressureSkeletonMatId || IsDirichletCondition(gneigh)) {
-                    TPZInterpolatedElement *intelneigh = dynamic_cast(cneigh.Element());
+                    auto *intelneigh = dynamic_cast(cneigh.Element());
                     if (!intelneigh) DebugStop();
                     TPZConnect &con_neigh = intelneigh->Connect(cneigh.Side());
                     int64_t con_seqnum = con_neigh.SequenceNumber();
@@ -2346,12 +2346,12 @@ void TPZHDivErrorEstimator::RestrainSkeletonSides(TPZCompMesh *pressure_mesh) {
 
         TPZCompEl *smallCel = small.Element()->Reference();
         if (!smallCel) DebugStop();
-        TPZInterpolatedElement *smallIntel = dynamic_cast(smallCel);
+        auto *smallIntel = dynamic_cast(smallCel);
         if (!smallIntel) DebugStop();
 
         TPZCompEl *largeCel = largerNeigh.Element()->Reference();
         if (!largeCel) DebugStop();
-        TPZInterpolatedElement *largeIntel = dynamic_cast(largeCel);
+        auto *largeIntel = dynamic_cast(largeCel);
         if (!largeIntel) DebugStop();
 
         TPZManVector xicenter(small.Element()->Dimension(), 0.);
@@ -2418,7 +2418,7 @@ bool TPZHDivErrorEstimator::IsAdjacentToHangingNode(const TPZCompElSide &celside
         if (neigh_gelside.Element()->Dimension() != dim - 1) {
             continue;
         }
-        TPZInterpolatedElement *intel = dynamic_cast(neigh_celside.Element());
+        auto *intel = dynamic_cast(neigh_celside.Element());
         if (!intel) DebugStop();
 
         int64_t conindex = intel->ConnectIndex(neigh_celside.Side());
diff --git a/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp b/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
index 868f46d5..42b79b26 100644
--- a/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
@@ -76,7 +76,7 @@ void TPZMHMHDivErrorEstimator::CreatePostProcessingMesh()
         for (int i = 0; i < fluxMesh->NElements(); i++) {
             TPZCompEl *cel = fluxMesh->Element(i);
             if (!cel) continue;
-            TPZInterpolatedElement * intel = dynamic_cast(cel);
+            auto *intel = dynamic_cast(cel);
             if (!intel) continue;
 
             TPZGeoEl * gel = cel->Reference();
@@ -126,7 +126,7 @@ void TPZMHMHDivErrorEstimator::SubStructurePostProcessingMesh()
         TPZCompEl *cel = gel->Reference();
         if(!cel) continue;
         TPZCompMesh *mesh = cel->Mesh();
-        TPZSubCompMesh *submesh = dynamic_cast(mesh);
+        auto *submesh = dynamic_cast(mesh);
         if (submesh) {
             orig_submesh_per_gel[iel] = submesh;
         }
@@ -153,7 +153,7 @@ void TPZMHMHDivErrorEstimator::SubStructurePostProcessingMesh()
         auto iter = submeshmap.find(submesh_orig);
         if (iter == submeshmap.end()) {
             int64_t index;
-            TPZSubCompMesh *new_submesh = new TPZSubCompMesh(fPostProcMesh,index);
+            auto *new_submesh = new TPZSubCompMesh(fPostProcMesh,index);
             submeshmap[submesh_orig] = new_submesh;
             new_submesh_per_cel[el] = new_submesh;
         } else {
@@ -306,7 +306,7 @@ void TPZMHMHDivErrorEstimator::SubStructurePostProcessingMesh()
         int64_t nel = fPostProcMesh.NElements();
         for (int64_t el = 0; el < nel; el++) {
             TPZCompEl *cel = fPostProcMesh.Element(el);
-            TPZSubCompMesh *sub = dynamic_cast(cel);
+            auto *sub = dynamic_cast(cel);
             if (sub) {
 
                 if (fPostProcesswithHDiv) {
@@ -338,7 +338,7 @@ TPZCompMesh *TPZMHMHDivErrorEstimator::CreateFluxMesh()
     for (int64_t el = 0; elElement(el);
         if(!cel) continue;
-        TPZInterpolatedElement *intel = dynamic_cast(cel);
+        auto *intel = dynamic_cast(cel);
         TPZGeoEl *gel = cel->Reference();
         bool isbcmat = fMHM->fMaterialBCIds.find(gel->MaterialId()) != fMHM->fMaterialBCIds.end();
         // if the element is of lower dimension and is not a boundary
@@ -394,7 +394,7 @@ TPZCompMesh *TPZMHMHDivErrorEstimator::CreateDiscontinuousPressureMesh()
     for (int64_t el = 0; elElement(el);
         if(!cel) continue;
-        TPZInterpolatedElement *intel = dynamic_cast(cel);
+        auto *intel = dynamic_cast(cel);
         if(!intel) DebugStop();
         TPZGeoEl *gel = cel->Reference();
         int matid = gel->MaterialId();
@@ -450,7 +450,7 @@ TPZCompMesh *TPZMHMHDivErrorEstimator::CreateInternallyContinuousPressureMesh()
                 if (neighbour.Element()->Dimension() != dim) {
                     TPZMaterial *neighMat = fPostProcMesh.FindMaterial(neighbour.Element()->MaterialId());
                     if (neighMat) {
-                        TPZBndCond *bc = dynamic_cast(neighMat);
+                        auto *bc = dynamic_cast(neighMat);
                         if (bc) {
                             int64_t bcId = neighbour.Element()->Index();
                             MHMOfEachGeoEl[bcId] = {geoToMHM[el], bcId, nullptr};
@@ -465,7 +465,7 @@ TPZCompMesh *TPZMHMHDivErrorEstimator::CreateInternallyContinuousPressureMesh()
     std::sort(&MHMOfEachGeoEl[0], &MHMOfEachGeoEl[nel - 1] + 1);
 
     // Create pressure mesh
-    TPZCompMesh *reconstruction_pressure = new TPZCompMesh(gmesh);
+    auto *reconstruction_pressure = new TPZCompMesh(gmesh);
 
     // Copies volume materials
     original_pressure->CopyMaterials(*reconstruction_pressure);
@@ -523,7 +523,7 @@ TPZCompMesh *TPZMHMHDivErrorEstimator::CreateInternallyContinuousPressureMesh()
 
         int64_t index;
         TPZCompEl *new_cel = reconstruction_pressure->CreateCompEl(gel, index);
-        TPZInterpolatedElement *new_intel = dynamic_cast(new_cel);
+        auto *new_intel = dynamic_cast(new_cel);
 
         TPZCompEl * orig_cel = std::get<2>(MHMOfEachGeoEl[i]);
         if (orig_cel) {
@@ -605,7 +605,7 @@ void TPZMHMHDivErrorEstimator::TransferEmbeddedElements()
     // connect_submesh : pointer to the submesh if there is only one subdomain that owns the connect
     for (int64_t el=0; el(cel);
+        auto *sub = dynamic_cast(cel);
         if(!sub) continue;
         int nconnect = sub->NConnects();
         for(int ic=0; ic(cel);
+        auto *sub = dynamic_cast(cel);
         if(sub) continue;
         std::set submeshes;
         int nconnect = cel->NConnects();
@@ -647,7 +647,7 @@ void TPZMHMHDivErrorEstimator::TransferEmbeddedElements()
     fPostProcMesh.ComputeNodElCon();
     for (int64_t el=0; el(cel);
+        auto *sub = dynamic_cast(cel);
         if(!sub) continue;
         sub->MakeAllInternal();
     }
@@ -687,7 +687,7 @@ void TPZMHMHDivErrorEstimator::ComputeAveragePressures(int target_dim)
         if(!gel) continue;
         if(gel->Dimension() == target_dim)
         {
-            TPZInterpolatedElement *intel = dynamic_cast(cel);
+            auto *intel = dynamic_cast(cel);
             if(!intel) DebugStop();
             
             int matId = gel->MaterialId();
@@ -726,7 +726,7 @@ void TPZMHMHDivErrorEstimator::ComputeNodalAverages()
         if(!cel) continue;
         TPZGeoEl *gel = cel->Reference();
         if(!gel || !gel->Reference()) continue;
-        TPZInterpolatedElement *intel = dynamic_cast(cel);
+        auto *intel = dynamic_cast(cel);
         if(!intel) DebugStop();
         if (gel->Dimension() == dim-1) {
             int ncorner = gel->NCornerNodes();
@@ -834,7 +834,7 @@ void TPZMHMHDivErrorEstimator::CopySolutionFromSkeleton() {
     int64_t nel = pressuremesh->NElements();
     for (int64_t el = 0; el < nel; el++) {
         TPZCompEl* cel = pressuremesh->Element(el);
-        TPZInterpolatedElement *intel = dynamic_cast(cel);
+        auto *intel = dynamic_cast(cel);
         if (!cel) continue;
         if(!intel) DebugStop();
         // load just d dimensional elements
@@ -849,7 +849,7 @@ void TPZMHMHDivErrorEstimator::CopySolutionFromSkeleton() {
     for (int64_t el = 0; el < nel; el++) {
         TPZCompEl* cel = pressuremesh->Element(el);
         if (!cel) continue;
-        TPZInterpolatedElement* intel = dynamic_cast(cel);
+        auto *intel = dynamic_cast(cel);
         if (!intel) DebugStop();
         TPZGeoEl* gel = cel->Reference();
         // filters just (d-1) dimensional elements
@@ -999,7 +999,7 @@ void TPZMHMHDivErrorEstimator::VerifySolutionConsistency(TPZCompMesh* cmesh) {
 #endif
 
                     // Checks pressure value on these nodes
-                    TPZInterpolatedElement *intel = dynamic_cast(cneighbour.Element());
+                    auto *intel = dynamic_cast(cneighbour.Element());
                     if (!intel) DebugStop();
                 }
             }
@@ -1090,7 +1090,7 @@ void TPZMHMHDivErrorEstimator::CreateFluxSkeletonElements(TPZCompMesh *flux_mesh
             if (neighGel->Dimension() != dim) continue;
             TPZCompEl *neighCel = geltocel[neighGel];
             if (!neighCel) DebugStop();
-            TPZInterpolatedElement *neighIntel = dynamic_cast(neighCel);
+            auto *neighIntel = dynamic_cast(neighCel);
             if (!neighIntel) DebugStop();
 
             // TODO sometimes the order here is 1, I think it should always be 3 for the case I'm running. Need to
@@ -1105,7 +1105,7 @@ void TPZMHMHDivErrorEstimator::CreateFluxSkeletonElements(TPZCompMesh *flux_mesh
             TPZGeoElBC gbc(neighbour, fHDivWrapMatId);
             int64_t index;
             TPZCompEl * wrap = flux_mesh->ApproxSpace().CreateCompEl(gbc.CreatedElement(), *flux_mesh, index);
-            TPZInterpolatedElement *wrapintel = dynamic_cast(wrap);
+            auto *wrapintel = dynamic_cast(wrap);
             neighIntel->SetSideOrient(neighbour.Side(), 1);
             wrapintel->SetSideOrient(gbc.CreatedElement()->NSides()-1,1);
             int64_t newc_index = wrap->ConnectIndex(0);

From 8a761dc70f939aaa64c496e41abae1c5fc5fdb6a Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 17 Jun 2021 09:34:39 -0300
Subject: [PATCH 066/187] Add dummy return to remove warning

---
 Projects/Tools/Tools.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/Projects/Tools/Tools.cpp b/Projects/Tools/Tools.cpp
index 82d1efe4..61d39010 100644
--- a/Projects/Tools/Tools.cpp
+++ b/Projects/Tools/Tools.cpp
@@ -1035,6 +1035,7 @@ TPZGeoMesh* Tools::CreateGeoMesh(int nel, TPZVec& bcids, int dim, bool isOr
         return gmesh;
     }
     DebugStop(); // Dim should be 2 or 3
+    return nullptr;
 }
 
 void Tools::DrawGeoMesh(ProblemConfig &config, PreConfig &preConfig) {

From 632aa739b9794cca4a3489677de1ea4a1f1206dc Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 17 Jun 2021 09:35:29 -0300
Subject: [PATCH 067/187] Add explicit keywords to ctors

---
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h | 2 +-
 ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h    | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
index 7915e021..405d0d3c 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
@@ -25,7 +25,7 @@ class TPZHDivErrorEstimateMaterial: public virtual TPZMatBase
Date: Thu, 17 Jun 2021 09:36:05 -0300
Subject: [PATCH 068/187] Comment declaration of function

---
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
index 405d0d3c..7814e1de 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
@@ -58,8 +58,8 @@ class TPZHDivErrorEstimateMaterial: public virtual TPZMatBase> &data, TPZVec &errors) override;
 
-    void ErrorsBC(const TPZVec> &data, TPZVec &u_exact, TPZFMatrix &du_exact,
-                  TPZVec &errors, TPZBndCond &bc);
+    //void ErrorsBC(const TPZVec> &data, TPZVec &u_exact, TPZFMatrix &du_exact,
+    //              TPZVec &errors, TPZBndCond &bc);
 
     [[nodiscard]] int VariableIndex(const std::string &name) const override;
     [[nodiscard]] int NSolutionVariables(int var) const override;

From 4b72a1171d1b4bd868133751d389649659450450 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 17 Jun 2021 09:37:08 -0300
Subject: [PATCH 069/187] Improve compute errors method

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 20 ++++++++------------
 1 file changed, 8 insertions(+), 12 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index d42585d1..119f69f9 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -74,22 +74,18 @@ void TPZHDivErrorEstimator::ComputeErrors(TPZVec&errorVec, TPZVec& e
         an.SetExact(fExact->ExactSolution());
     }
 
-    int64_t nErrorCols = 6;
-    errorVec.resize(nErrorCols);
-    for (int64_t i = 0; i < nErrorCols; i++) {
-        errorVec[i] = 0;
-    }
-    
+    constexpr int64_t nErrorCols = 6;
+    errorVec.Resize(nErrorCols);
+    errorVec.Fill(0);
+
     int64_t nelem = fPostProcMesh.NElements();
     fPostProcMesh.LoadSolution(fPostProcMesh.Solution());
     fPostProcMesh.ExpandSolution();
     fPostProcMesh.ElementSolution().Redim(nelem, 5);
-    for(int64_t el = 0; el(cel);
-        if(subc)
-        {
+        auto *subc = dynamic_cast(cel);
+        if(subc) {
             int64_t nelsub = subc->NElements();
             subc->ElementSolution().Redim(nelsub, 5);
         }
@@ -98,7 +94,7 @@ void TPZHDivErrorEstimator::ComputeErrors(TPZVec&errorVec, TPZVec& e
     // Calculate error and store in element solution
     bool store_error = true;
     an.PostProcessError(errorVec, store_error);
-    
+
     TPZCompMeshTools::UnCondensedElements(&fPostProcMesh);
     TPZCompMeshTools::UnGroupElements(&fPostProcMesh);
 

From 8978b1e8000f9242d742730e74020366e4f8a770 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 17 Jun 2021 09:38:05 -0300
Subject: [PATCH 070/187] Add range based loops

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 119f69f9..0852e012 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -1325,11 +1325,11 @@ void TPZHDivErrorEstimator::ComputeNodalAverage(TPZCompElSide &node_celside)
     
     TPZManVector averageSol(nstate, 0);
     REAL sum_weight = 0.;
-    for (auto it = connects.begin(); it != connects.end(); it++) {
-        REAL weight = it->second.first;
+    for (auto & connect : connects) {
+        REAL weight = connect.second.first;
         sum_weight += weight;
         for (int istate = 0; istate < nstate; istate++) {
-            averageSol[istate] += it->second.second[istate] * weight;
+            averageSol[istate] += connect.second.second[istate] * weight;
         }
     }
     
@@ -1347,8 +1347,8 @@ void TPZHDivErrorEstimator::ComputeNodalAverage(TPZCompElSide &node_celside)
         LOGPZ_DEBUG(logger, sout.str())
     }
 #endif
-    for (auto it = connects.begin(); it != connects.end(); it++) {
-        int64_t conindex = it->first;
+    for (auto & connect : connects) {
+        int64_t conindex = connect.first;
         TPZConnect &c = pressure_mesh->ConnectVec()[conindex];
         int64_t seqnum = c.SequenceNumber();
         

From 07495b7a5368405905685dc1ede1e3f759c73889 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 17 Jun 2021 09:38:52 -0300
Subject: [PATCH 071/187] Use uint to avoid narrowing conversions

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 0852e012..37c95f2e 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -844,7 +844,7 @@ void TPZHDivErrorEstimator::ComputeBoundaryL2Projection(int target_dim){
             TPZConnect &c = cel->Connect(ic);
             int64_t seqnum = c.SequenceNumber();
             int64_t pos = pressuremesh->Block().Position(seqnum);
-            int ndof = c.NShape() * c.NState();
+            uint ndof = c.NShape() * c.NState();
             for (int idf = 0; idf < ndof; idf++) {
                 mesh_sol(pos + idf, 0) = efbc.fMat(count++);
             }
@@ -1037,7 +1037,7 @@ void TPZHDivErrorEstimator::ComputeAverage(TPZCompMesh *pressuremesh, int64_t ie
         TPZConnect &c = cel->Connect(ic);
         int64_t seqnum = c.SequenceNumber();
         int64_t pos = pressuremesh->Block().Position(seqnum);
-        int ndof = c.NShape() * c.NState();
+        uint ndof = c.NShape() * c.NState();
         for (int idf = 0; idf < ndof; idf++) {
             mesh_sol(pos + idf, 0) = L2Rhs(count++);
         }
@@ -2110,7 +2110,7 @@ void TPZHDivErrorEstimator::CopySolutionFromSkeleton() {
             TPZGeoElSide gelside(gel, is);
             TPZConnect &c = intel->Connect(is);
             int64_t c_seqnum = c.SequenceNumber();
-            int c_blocksize = c.NShape() * c.NState();
+            uint c_blocksize = c.NShape() * c.NState();
             
             TPZStack celstack;
             gelside.EqualLevelCompElementList(celstack, 1, 0);
@@ -2123,7 +2123,7 @@ void TPZHDivErrorEstimator::CopySolutionFromSkeleton() {
                     if (!intelneigh) DebugStop();
                     TPZConnect &con_neigh = intelneigh->Connect(cneigh.Side());
                     int64_t con_seqnum = con_neigh.SequenceNumber();
-                    int con_size = con_neigh.NState() * con_neigh.NShape();
+                    uint con_size = con_neigh.NState() * con_neigh.NShape();
                     if (con_size != c_blocksize) DebugStop();
                     for (int ibl = 0; ibl < con_size; ibl++) {
 

From 764d941c63e5b0e0b9b29bbe725ac0f20d380e09 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 17 Jun 2021 09:39:20 -0300
Subject: [PATCH 072/187] Fix type of material cast

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 37c95f2e..d329229a 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -199,7 +199,8 @@ TPZCompMesh *TPZHDivErrorEstimator::CreatePressureMesh() {
             if (!bc) DebugStop();
 
             int volumetricMatId = bc->Material()->Id();
-            TPZMatBase *pressuremat = dynamic_cast*>(pressureMesh->FindMaterial(volumetricMatId));
+            TPZMaterial * volumetricMat = pressureMesh->FindMaterial(volumetricMatId);
+            auto *pressuremat = dynamic_cast*>(volumetricMat);
             if (!pressuremat) DebugStop();
 
             TPZBndCondT *newbc = pressuremat->CreateBC(pressuremat, bc->Id(), bc->Type(), bc->Val1(), bc->Val2());

From d1c9c57b53ce325976a8ccdc75c6c656ae176f47 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 17 Jun 2021 09:40:16 -0300
Subject: [PATCH 073/187] Access static method through class

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index d329229a..d872ddf0 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -359,7 +359,7 @@ void TPZHDivErrorEstimator::CreatePostProcessingMesh() {
         // construction of the multiphysics mesh
         //cria elementos de interface
         fHybridizer.CreateInterfaceElements(&fPostProcMesh);
-        fHybridizer.GroupandCondenseElements(&fPostProcMesh);
+        TPZHybridizeHDiv::GroupandCondenseElements(&fPostProcMesh);
         fPostProcMesh.CleanUpUnconnectedNodes();
     }
     else {

From 6a97e321451057abc8ecb867bc46e2b26c755fe0 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 17 Jun 2021 09:40:47 -0300
Subject: [PATCH 074/187] Remove redeclaration of vars

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index d872ddf0..0f474fa4 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -626,9 +626,9 @@ void TPZHDivErrorEstimator::RestrainSmallEdges(TPZCompMesh *pressuremesh) {
                 TPZGeoElSide gelside_small(gel, side);
                 TPZCompElSide celside_restraint = gelside_small.LowerLevelCompElementList2(onlyinterpolated);
                 if (celside_restraint) {
-                    TPZInterpolatedElement *largeintel = dynamic_cast(celside_restraint.Element());
+                    largeintel = dynamic_cast(celside_restraint.Element());
                     if (!largeintel) DebugStop();
-                    int largeside = large_celside.Side();
+                    largeside = large_celside.Side();
                     intel->RestrainSide(side, largeintel, largeside);
                 }
             }
@@ -1574,9 +1574,9 @@ void TPZHDivErrorEstimator::ComputeEffectivityIndices() {
             }
 #endif
 
-            TPZGeoEl *gel = cel->Reference();
+            gel = cel->Reference();
 
-            REAL hk = gel->CharacteristicSize();
+            hk = gel->CharacteristicSize();
 
             REAL oscilatorytherm = 0;
             if (i == 2) {

From f0ce889eb386992449003a2563b4bff977a45af8 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 17 Jun 2021 09:41:15 -0300
Subject: [PATCH 075/187] Replace type by auto

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 0f474fa4..4eb825a2 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -1943,7 +1943,7 @@ void TPZHDivErrorEstimator::VerifySolutionConsistency(TPZCompMesh *cmesh) {
 #endif
                     
                     // Checks pressure value on these nodes
-                    TPZInterpolatedElement *intel = dynamic_cast(cneighbour.Element());
+                    auto *intel = dynamic_cast(cneighbour.Element());
                     if (!intel) DebugStop();
                 }
             }

From 54ad5f23fd6b3a1f1f3bba64ba999dfc06eb5c94 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 17 Jun 2021 09:41:48 -0300
Subject: [PATCH 076/187] Make AdjustNeighbourPolynomialOrders method static

---
 ErrorEstimation/TPZHDivErrorEstimator.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.h b/ErrorEstimation/TPZHDivErrorEstimator.h
index c397bcba..59fae3e2 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.h
+++ b/ErrorEstimation/TPZHDivErrorEstimator.h
@@ -137,7 +137,7 @@ class TPZHDivErrorEstimator {
 
     /// adjust the interpolation orders so as to create an H1/2 boundary mesh
     // this method is called by the CreateEdgeSkeletonMesh method
-    void AdjustNeighbourPolynomialOrders(TPZCompMesh *pressure_mesh);
+    static void AdjustNeighbourPolynomialOrders(TPZCompMesh *pressure_mesh);
 
     /// restrain the edge elements that have larger elements as neighbours
     void RestrainSmallEdges(TPZCompMesh *pressuremesh);

From ead6cf9485d46fb04ca89163861f83e16456a428 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 17 Jun 2021 09:42:25 -0300
Subject: [PATCH 077/187] Small fixes to remove warnings

---
 ErrorEstimation/TPZMHMHDivErrorEstimator.cpp | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp b/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
index 42b79b26..e39f6049 100644
--- a/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
@@ -164,7 +164,7 @@ void TPZMHMHDivErrorEstimator::SubStructurePostProcessingMesh()
     fPostProcMesh.ComputeNodElCon();
     // TODO  refactor here
     std::cout << "Transferring volumetric elements...\n";
-    if(1) {
+    if(true) {
 
         TPZVec connectToSubcmesh(fPostProcMesh.NConnects(), nullptr);
         // transfer the elements in the submesh indicated by elementgroup
@@ -303,7 +303,7 @@ void TPZMHMHDivErrorEstimator::SubStructurePostProcessingMesh()
 
     // set an analysis type for the submeshes
     {
-        int64_t nel = fPostProcMesh.NElements();
+        nel = fPostProcMesh.NElements();
         for (int64_t el = 0; el < nel; el++) {
             TPZCompEl *cel = fPostProcMesh.Element(el);
             auto *sub = dynamic_cast(cel);
@@ -637,7 +637,7 @@ void TPZMHMHDivErrorEstimator::TransferEmbeddedElements()
         }
         if(submeshes.size() == 1)
         {
-            TPZSubCompMesh *sub = *submeshes.begin();
+            sub = *submeshes.begin();
             if(sub)
             {
                 sub->TransferElement(&fPostProcMesh, el);
@@ -862,7 +862,7 @@ void TPZMHMHDivErrorEstimator::CopySolutionFromSkeleton() {
             
             TPZConnect &c = intel->Connect(is);
             int64_t c_gelSide_seqnum  = c.SequenceNumber();
-            int c_blocksize = c.NShape() * c.NState();
+            uint c_blocksize = c.NShape() * c.NState();
             TPZStack celstack;
 
             gelside.EqualLevelCompElementList(celstack, 1, 0);
@@ -873,11 +873,11 @@ void TPZMHMHDivErrorEstimator::CopySolutionFromSkeleton() {
                 TPZCompElSide cneigh = celstack[ist];
                 TPZGeoElSide gneigh = cneigh.Reference();
 
-                TPZInterpolatedElement *intelneigh = dynamic_cast(cneigh.Element());
+                auto *intelneigh = dynamic_cast(cneigh.Element());
                 if (!intelneigh) DebugStop();
                 TPZConnect &con_neigh = intelneigh->Connect(cneigh.Side());
                 int64_t c_neigh_seqnum = con_neigh.SequenceNumber();
-                int con_size = con_neigh.NState() * con_neigh.NShape();
+                uint con_size = con_neigh.NState() * con_neigh.NShape();
                 if (con_size != c_blocksize) DebugStop();
                 for (int ibl = 0; ibl < con_size; ibl++) {
                     sol.at(block.at(c_neigh_seqnum, 0, ibl, 0)) = sol.at(block.at(c_gelSide_seqnum, 0, ibl, 0));

From 5c60acbb28955a895b095fc334d33773e23db833 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Thu, 17 Jun 2021 09:43:07 -0300
Subject: [PATCH 078/187] Make RestrainSkeletonSides method const

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 2 +-
 ErrorEstimation/TPZHDivErrorEstimator.h   | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 4eb825a2..65ba6f72 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -2314,7 +2314,7 @@ void TPZHDivErrorEstimator::CreateSkeletonElements(TPZCompMesh *pressure_mesh) {
 
 }
 
-void TPZHDivErrorEstimator::RestrainSkeletonSides(TPZCompMesh *pressure_mesh) {
+void TPZHDivErrorEstimator::RestrainSkeletonSides(TPZCompMesh *pressure_mesh) const {
 
     TPZGeoMesh *gmesh = pressure_mesh->Reference();
     gmesh->ResetReference();
diff --git a/ErrorEstimation/TPZHDivErrorEstimator.h b/ErrorEstimation/TPZHDivErrorEstimator.h
index 59fae3e2..4d9e5a37 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.h
+++ b/ErrorEstimation/TPZHDivErrorEstimator.h
@@ -167,7 +167,7 @@ class TPZHDivErrorEstimator {
     /// and if the boundary condition is dirichlet type
     bool IsDirichletCondition(const TPZGeoElSide& gelside);
 
-    void RestrainSkeletonSides(TPZCompMesh *pressure_mesh);
+    void RestrainSkeletonSides(TPZCompMesh *pressure_mesh) const;
 
     // Checks if the solution is in fact continuous
     virtual void VerifySolutionConsistency(TPZCompMesh* cmesh);

From 99c0ebd78b6165067942682680cd9d98bd12fb22 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Fri, 25 Jun 2021 10:09:26 -0300
Subject: [PATCH 079/187] Update headers in TPZHDivErrorEstimator

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 21 +++++++++++----------
 1 file changed, 11 insertions(+), 10 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 65ba6f72..6c079499 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -6,17 +6,17 @@
 //  Created by Philippe Devloo on 10/06/18.
 //
 
-#include 
-#include 
-#include "TPZElementMatrixT.h"
 #include "TPZHDivErrorEstimator.h"
+#include "DarcyFlow/TPZMixedDarcyFlow.h"
+#include "TPZAnalysis.h"
+#include "TPZBndCond.h"
+#include "TPZCompMeshTools.h"
+#include "TPZElementMatrixT.h"
 #include "TPZGeoElSideAncestors.h"
 #include "TPZGeoElSidePartition.h"
 #include "TPZInterfaceEl.h"
 #include "TPZNullMaterial.h"
-#include "DarcyFlow/TPZMixedDarcyFlow.h"
-#include "TPZAnalysis.h"
-#include "TPZBndCond.h"
+#include "TPZVTKGeoMesh.h"
 #include "pzbuildmultiphysicsmesh.h"
 #include "pzcmesh.h"
 #include "pzcompel.h"
@@ -24,11 +24,12 @@
 #include "pzelementgroup.h"
 #include "pzelmat.h"
 #include "pzintel.h"
-#include "pzsubcmesh.h"
-#include "pzstepsolver.h"
-#include "TPZVTKGeoMesh.h"
 #include "pzmultiphysicscompel.h"
-#include "TPZCompMeshTools.h"
+#include "pzstepsolver.h"
+#include "pzsubcmesh.h"
+#include 
+#include 
+#include 
 
 #ifdef LOG4CXX
 static LoggerPtr logger(Logger::getLogger("HDivErrorEstimator"));

From cbc5e3bd0551ebbd08a6196f8576eb576de1713e Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Fri, 25 Jun 2021 10:10:22 -0300
Subject: [PATCH 080/187] Add maybe_unused specifier to suppress warnings

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 6 +++---
 ErrorEstimation/TPZHDivErrorEstimator.h   | 6 +++---
 2 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 6c079499..c58a278a 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -1750,7 +1750,7 @@ void TPZHDivErrorEstimator::PotentialReconstruction() {
     }
 }
 
-void TPZHDivErrorEstimator::PlotPressureSkeleton(const std::string &filename, bool reconstructed) {
+[[maybe_unused]] void TPZHDivErrorEstimator::PlotPressureSkeleton(const std::string &filename, bool reconstructed) {
     
     TPZCompMesh *pressure = nullptr;
 
@@ -1778,7 +1778,7 @@ void TPZHDivErrorEstimator::PlotPressureSkeleton(const std::string &filename, bo
     }
 }
 
-void TPZHDivErrorEstimator::PlotInterfaceFluxes(const std::string &filename, bool reconstructed) {
+[[maybe_unused]] void TPZHDivErrorEstimator::PlotInterfaceFluxes(const std::string &filename, bool reconstructed) {
     TPZCompMesh *flux_mesh = nullptr;
     if (reconstructed) {
         if (!fPostProcesswithHDiv) DebugStop();
@@ -2209,7 +2209,7 @@ void TPZHDivErrorEstimator::ComputePressureWeights() {
     std::cout << "Finished computing pressure weights\n";
 }
 
-void TPZHDivErrorEstimator::PlotState(const std::string& filename, int targetDim, TPZCompMesh* cmesh, bool atomic) {
+[[maybe_unused]] void TPZHDivErrorEstimator::PlotState(const std::string& filename, int targetDim, TPZCompMesh* cmesh, bool atomic) {
     
     std::ofstream outTXT("PressuretoStateGraph.txt");
     cmesh->Print(outTXT);
diff --git a/ErrorEstimation/TPZHDivErrorEstimator.h b/ErrorEstimation/TPZHDivErrorEstimator.h
index 4d9e5a37..ed402da0 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.h
+++ b/ErrorEstimation/TPZHDivErrorEstimator.h
@@ -74,11 +74,11 @@ class TPZHDivErrorEstimator {
     /// create graphical output of estimated and true errors using the analysis
     void PostProcessing(TPZAnalysis &an, std::string &out);
 
-    void PlotPressureSkeleton(const std::string &filename, bool reconstructed = true);
-    void PlotInterfaceFluxes(const std::string &filename, bool reconstructed = true);
+    [[maybe_unused]] void PlotPressureSkeleton(const std::string &filename, bool reconstructed = true);
+    [[maybe_unused]] void PlotInterfaceFluxes(const std::string &filename, bool reconstructed = true);
 
     // Plots State solution of elements of target dimension
-    static void PlotState(const std::string& filename, int targetDim, TPZCompMesh* cmesh, bool atomic = true);
+    [[maybe_unused]] static void PlotState(const std::string& filename, int targetDim, TPZCompMesh* cmesh, bool atomic = true);
 
     [[nodiscard]] int PressureSkeletonMatId() const { return fPressureSkeletonMatId; }
 

From ccdb1e113f263c3dbbb9180311395c3ac81cbf4a Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Fri, 25 Jun 2021 10:11:03 -0300
Subject: [PATCH 081/187] Update headers in TPZMHMHDivErrorEstimator

---
 ErrorEstimation/TPZMHMHDivErrorEstimator.cpp | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp b/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
index e39f6049..d445ba1b 100644
--- a/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
@@ -1,17 +1,17 @@
 
 #include "TPZMHMHDivErrorEstimator.h"
-#include "TPZNullMaterial.h"
+#include "TPZBndCond.h"
 #include "TPZLagrangeMultiplierCS.h"
+#include "TPZNullMaterial.h"
 #include "TPZVTKGeoMesh.h"
-#include "TPZBndCond.h"
 #include "pzintel.h"
 #include "pzsubcmesh.h"
+#include 
 #include 
 #include 
 #include 
-#include 
 #include 
-
+#include 
 
 #ifdef LOG4CXX
 static LoggerPtr logger(Logger::getLogger("HDivErrorEstimator"));

From d61870f91ea30ce0cef47127b9b48d8fe7ce7290 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Fri, 25 Jun 2021 10:12:27 -0300
Subject: [PATCH 082/187] Add dummy TPZDarcyFlow material to use its
 ContributeBC

---
 ErrorEstimation/TPZMHMHDivErrorEstimator.cpp | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp b/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
index d445ba1b..ebb6736c 100644
--- a/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
@@ -23,7 +23,7 @@ void TPZMHMHDivErrorEstimator::CreatePostProcessingMesh()
     // initialize the post processing mesh
     fPostProcMesh.SetReference(fOriginal->Reference());
 
-    fOriginal->CopyMaterials(fPostProcMesh);
+    //fOriginal->CopyMaterials(fPostProcMesh);
     // Switch the material from mixed to TPZMHMHDivErrorEstimationMaterial
     InsertPostProcMaterials();
 
@@ -473,6 +473,9 @@ TPZCompMesh *TPZMHMHDivErrorEstimator::CreateInternallyContinuousPressureMesh()
 
     // Copies BC materials
     std::set bcMatIDs;
+
+    auto * dummy_mat = new TPZDarcyFlow(-999, fPostProcMesh.Dimension());
+    reconstruction_pressure->InsertMaterialObject(dummy_mat);
     for (auto it : fOriginal->MaterialVec()) {
         TPZMaterial *mat = it.second;
         auto *bc = dynamic_cast *>(mat);
@@ -480,7 +483,7 @@ TPZCompMesh *TPZMHMHDivErrorEstimator::CreateInternallyContinuousPressureMesh()
             int bcID = bc->Material()->Id();
             TPZMaterial * press = original_pressure->FindMaterial(bcID);
             auto *pressure_mat = dynamic_cast*>(original_pressure->FindMaterial(bcID));
-            TPZBndCondT *bc_mat = pressure_mat->CreateBC(pressure_mat, mat->Id(), bc->Type(), bc->Val1(), bc->Val2());
+            TPZBndCondT *bc_mat = dummy_mat->CreateBC(dummy_mat, mat->Id(), bc->Type(), bc->Val1(), bc->Val2());
             if (fExact) {
                 auto ff_bc = [this](const TPZVec &loc, TPZVec &rhsVal,
                                     TPZFMatrix &matVal) {

From 12504d7f3f25923b836fdac91f964aee16829784 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Fri, 25 Jun 2021 10:20:14 -0300
Subject: [PATCH 083/187] Fix size of matrices and variable assignment

---
 .../Material/TPZHDivErrorEstimateMaterial.cpp       | 13 ++++++-------
 .../Material/TPZMixedHdivErrorEstimate.cpp          |  3 +--
 2 files changed, 7 insertions(+), 9 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index ba7df81d..8a194f81 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -66,21 +66,19 @@ void TPZHDivErrorEstimateMaterial::Contribute(const TPZVec &phiuk = datavec[H1functionposition].phi;
     TPZFMatrix &dphiukaxes = datavec[H1functionposition].dphix;
-    TPZFNMatrix<9, REAL> dphiuk(3, dphiukaxes.Cols());
+    TPZFNMatrix<9, REAL> dphiuk(3, 1);
     TPZAxesTools::Axes2XYZ(dphiukaxes, dphiuk, datavec[H1functionposition].axes);
 
-
     int nphiuk = phiuk.Rows();
 
-    TPZFMatrix solsigmafem(3, nphiuk), solukfem(1, 1);
+    TPZFMatrix solsigmafem(3, 1), solukfem(1, 1);
     solsigmafem.Zero();
     solukfem.Zero();
 
@@ -96,8 +94,9 @@ void TPZHDivErrorEstimateMaterial::Contribute(const TPZVec PermTensor;
-    TPZFNMatrix<9, REAL> InvPermTensor;
+
+    TPZFNMatrix<9, REAL> PermTensor(1, 1, 0.);
+    TPZFNMatrix<9, REAL> InvPermTensor(1, 1, 0.);
 
     GetPermeabilities(datavec[1].x, PermTensor, InvPermTensor);
 
diff --git a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
index 59132066..276ef6bc 100644
--- a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
+++ b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
@@ -123,7 +123,6 @@ TPZMixedHDivErrorEstimate::Solution(const TPZVec> &datav
     }
 
 
-    STATE pressureexact = 0.;
     TPZManVector pressvec(1,0.);
     TPZFNMatrix<9, STATE> gradu(dim, 1, 0.), fluxinv(dim, 1);
 
@@ -134,7 +133,7 @@ TPZMixedHDivErrorEstimate::Solution(const TPZVec> &datav
     }
 
     PermTensor.Multiply(gradu, fluxinv);
-    pressureexact = pressvec[0];
+    STATE pressureexact = pressvec[0];
     switch (var)
     {
         case 40://FluxFem

From ce9d4adc1a1835995e5284f8af3808e5bf5234ab Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Fri, 25 Jun 2021 10:20:39 -0300
Subject: [PATCH 084/187] Add default keyword to dtor

---
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index 8a194f81..c7107794 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -24,7 +24,7 @@ TPZHDivErrorEstimateMaterial::TPZHDivErrorEstimateMaterial(const TPZMixedDarcyFl
 TPZHDivErrorEstimateMaterial::TPZHDivErrorEstimateMaterial(const TPZHDivErrorEstimateMaterial ©)
         : TPZMixedDarcyFlow(copy) {}
 
-TPZHDivErrorEstimateMaterial::~TPZHDivErrorEstimateMaterial() {}
+TPZHDivErrorEstimateMaterial::~TPZHDivErrorEstimateMaterial() = default;
 
 TPZHDivErrorEstimateMaterial &TPZHDivErrorEstimateMaterial::operator=(const TPZHDivErrorEstimateMaterial ©) {
     TPZMixedDarcyFlow::operator=(copy);

From 5f4e5db7147d739e3757aefbaf66da0c6766cc5e Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Fri, 25 Jun 2021 11:29:36 -0300
Subject: [PATCH 085/187] Fix method documentation

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index c58a278a..f7f0ba9a 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -1432,12 +1432,13 @@ void TPZHDivErrorEstimator::ComputeEffectivityIndices(TPZSubCompMesh *subcmesh)
 
 /// compute the effectivity indices of the pressure error and flux error and store in the element solution
 void TPZHDivErrorEstimator::ComputeEffectivityIndices() {
-    /**The  ElementSolution() is a matrix with 4 cols,
+    /**The  ElementSolution() is a matrix with 5 cols,
      col 0: pressure exact error
      col 1: pressure estimate error
      col 2: flux exact error
      col 3: flux estimate error
-     Is increased 2 cols on ElementSolution() to store the efectivity index for pressure and flux
+     col 4: residual/oscillatory term
+     Is increased 2 cols on ElementSolution() to store the effectivity index for pressure and flux
      **/
 
     TPZCompMesh *cmesh = &fPostProcMesh;

From 2654f5d576a8be713232b186a02769bb0cf69467 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Fri, 25 Jun 2021 11:46:11 -0300
Subject: [PATCH 086/187] Fix usage of permeability and general code cleaning

---
 .../Material/TPZHDivErrorEstimateMaterial.cpp | 72 +++++++------------
 1 file changed, 27 insertions(+), 45 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index c7107794..aad04f28 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -10,7 +10,6 @@
 #include "TPZAnalyticSolution.h"
 #include "TPZBndCond.h"
 
-
 #ifdef LOG4CXX
 static LoggerPtr logger(Logger::getLogger("pz.errorestimation.hdiv"));
 #endif
@@ -109,11 +108,7 @@ void TPZHDivErrorEstimateMaterial::Contribute(const TPZVec> &datavec, REAL weight,
@@ -186,12 +181,12 @@ void TPZHDivErrorEstimateMaterial::ContributeBC(const TPZVec PermTensor, InvPermTensor;
+        TPZFNMatrix<9, REAL> PermTensor(1, 1, 0.), InvPermTensor(1, 1, 0.);
         GetPermeabilities(datavec[0].x, PermTensor, InvPermTensor);
 
         for (int i = 0; i < 3; i++) {
             for (int j = 0; j < 3; j++) {
-                normflux += datavec[2].normal[i] * PermTensor(i, j) * gradu(j, 0);
+                normflux += datavec[2].normal[i] * PermTensor(0, 0) * gradu(j, 0);
             }
         }
 
@@ -267,7 +262,7 @@ void TPZHDivErrorEstimateMaterial::Errors(const TPZVec>
       error[1] - error computed with reconstructed pressure
       error[2] - energy error computed with exact solution
       error[3] - energy error computed with reconstructed solution
-      error[4] - oscilatory data error
+      error[4] - oscillatory data error
      **/
 
     errors.Resize(NEvalErrors());
@@ -276,10 +271,6 @@ void TPZHDivErrorEstimateMaterial::Errors(const TPZVec>
 
     TPZManVector fluxfem(3);
     STATE divsigmafem, pressurefem, pressurereconstructed;
-    divsigmafem = 0.;
-    pressurefem = 0.;
-    pressurereconstructed = 0.;
-
 
     TPZFNMatrix<3, REAL> fluxreconstructed(3, 1), fluxreconstructed2(3, 1);
 
@@ -294,8 +285,7 @@ void TPZHDivErrorEstimateMaterial::Errors(const TPZVec>
         divtest += data[2].dsol[0](j, j);
     }
 
-    int H1functionposition = 0;
-    H1functionposition = FirstNonNullApproxSpaceIndex(data);
+    int H1functionposition = FirstNonNullApproxSpaceIndex(data);
 
 
     TPZVec divsigma(1);
@@ -310,9 +300,7 @@ void TPZHDivErrorEstimateMaterial::Errors(const TPZVec>
         this->fForcingFunction(data[H1functionposition].x, divsigma);
     }
 
-    REAL residual = 0.;
-
-    residual = (divsigma[0] - divsigmafem) * (divsigma[0] - divsigmafem);
+    REAL residual = (divsigma[0] - divsigmafem) * (divsigma[0] - divsigmafem);
 
 
     pressurereconstructed = data[H1functionposition].sol[0][0];
@@ -320,12 +308,12 @@ void TPZHDivErrorEstimateMaterial::Errors(const TPZVec>
 
     pressurefem = data[3].sol[0][0];
 
-    TPZFNMatrix<9, REAL> PermTensor;
-    TPZFNMatrix<9, REAL> InvPermTensor;
+    TPZFNMatrix<9, REAL> PermTensor(1, 1, 0.);
+    TPZFNMatrix<9, REAL> InvPermTensor(1, 1, 0.);
 
     GetPermeabilities(data[2].x, PermTensor, InvPermTensor);
 
-    TPZFNMatrix<3, REAL> fluxexactneg;
+    TPZFNMatrix<3, REAL> fluxexactneg(3, 1);
 
     //sigmarec = -K grad(urec)
     //  sigmak = -K graduk
@@ -333,9 +321,8 @@ void TPZHDivErrorEstimateMaterial::Errors(const TPZVec>
     {
         TPZFNMatrix<9, REAL> gradpressure(3, 1);
         for (int i = 0; i < 3; i++) {
-            gradpressure(i, 0) = du_exact[i];
+            fluxexactneg(i, 0) = PermTensor(0,0) * du_exact[i];
         }
-        PermTensor.Multiply(gradpressure, fluxexactneg);
     }
 
 
@@ -344,16 +331,12 @@ void TPZHDivErrorEstimateMaterial::Errors(const TPZVec>
     TPZAxesTools::Axes2XYZ(dsolaxes, fluxrec, data[H1functionposition].axes);
 
     for (int id = 0; id < 3; id++) {
-        fluxreconstructed2(id, 0) = (-1.) * fluxrec(id, 0);
+        fluxreconstructed(id, 0) = (-1.) * PermTensor(0,0) * fluxrec(id, 0);
     }
 
-    PermTensor.Multiply(fluxreconstructed2, fluxreconstructed);
-
-
     REAL innerexact = 0.;
     REAL innerestimate = 0.;
 
-
 #ifdef PZDEBUG2
     std::cout<<"flux fem "<>
 #endif
 
     for (int i = 0; i < 3; i++) {
-        for (int j = 0; j < 3; j++) {
-            innerexact += (fluxfem[i] + fluxexactneg(i, 0)) * InvPermTensor(i, j) *
-                          (fluxfem[j] + fluxexactneg(j, 0));//Pq esta somando: o fluxo fem esta + e o exato -
-            innerestimate +=
-                    (fluxfem[i] - fluxreconstructed[i]) * InvPermTensor(i, j) * (fluxfem[j] - fluxreconstructed[j]);
-        }
+        innerexact += (fluxfem[i] + fluxexactneg(i, 0)) * InvPermTensor(0, 0) *
+                      (fluxfem[i] + fluxexactneg(i, 0)); // Pq esta somando: o fluxo fem esta + e o exato -
+        innerestimate +=
+            (fluxfem[i] - fluxreconstructed[i]) * InvPermTensor(0, 0) * (fluxfem[i] - fluxreconstructed[i]);
     }
 
 #ifdef PZDEBUG2
@@ -420,7 +401,6 @@ int TPZHDivErrorEstimateMaterial::NSolutionVariables(int var) const {
         case 41:
         case 42:
             return 3;
-            break;
         case 43:
         case 44:
         case 45:
@@ -434,7 +414,6 @@ int TPZHDivErrorEstimateMaterial::NSolutionVariables(int var) const {
         case 105:
         case 106:
             return 1;
-            break;
         default:
             DebugStop();
             break;
@@ -459,11 +438,10 @@ TPZHDivErrorEstimateMaterial::Solution(const TPZVec> &da
      datavec[3] L2 mesh fem, u_h
      **/
 
-    int H1functionposition = 0;
-    H1functionposition = FirstNonNullApproxSpaceIndex(datavec);
+    int H1functionposition = FirstNonNullApproxSpaceIndex(datavec);
 
-    TPZFNMatrix<9, REAL> PermTensor;
-    TPZFNMatrix<9, REAL> InvPermTensor;
+    TPZFNMatrix<9, REAL> PermTensor(1, 1, 0.);
+    TPZFNMatrix<9, REAL> InvPermTensor(1, 1, 0.);
 
     GetPermeabilities(datavec[2].x, PermTensor, InvPermTensor);
 
@@ -475,7 +453,9 @@ TPZHDivErrorEstimateMaterial::Solution(const TPZVec> &da
         this->fExactSol(datavec[H1functionposition].x, pressexact, gradu);
     }
 
-    PermTensor.Multiply(gradu, fluxinv);
+    for (int i = 0; i < 3; i++) {
+        fluxinv(i, 0) = PermTensor(0, 0) * gradu(i, 0);
+    }
 
     int dim = this->fDim;
     switch (var) {
@@ -486,11 +466,13 @@ TPZHDivErrorEstimateMaterial::Solution(const TPZVec> &da
             break;
         case 41: {//FluxReconstructed is grad U
             TPZFMatrix &dsolaxes = datavec[H1functionposition].dsol[0];
-            TPZFNMatrix<9, REAL> dsol(3, 0);
-            TPZFNMatrix<9, REAL> KGradsol(3, 0);
+            TPZFNMatrix<9, REAL> dsol(3, 1);
+            TPZFNMatrix<9, REAL> KGradsol(3, 1);
             TPZAxesTools::Axes2XYZ(dsolaxes, dsol, datavec[H1functionposition].axes);
 
-            PermTensor.Multiply(dsol, KGradsol);
+            for (int i = 0; i < 3; i++) {
+                KGradsol(i, 0) = PermTensor(0, 0) * dsol(i, 0);
+            }
 
             for (int id = 0; id < fDim; id++) {
                 Solout[id] = -KGradsol(id, 0);//dsol(id,0);//derivate

From ea386b07fe254be226917f0a161d2c0f2cc7c1af Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Fri, 25 Jun 2021 12:35:36 -0300
Subject: [PATCH 087/187] Add default keyword to TPZMixedHdivErrorEstimate dtor

---
 ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp | 5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)

diff --git a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
index 276ef6bc..dc061382 100644
--- a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
+++ b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
@@ -23,10 +23,7 @@ TPZMixedHDivErrorEstimate::TPZMixedHDivErrorEstimate(const TPZMixedDarcyFlow &co
     
 }
 
-TPZMixedHDivErrorEstimate::~TPZMixedHDivErrorEstimate()
-{
-    
-}
+TPZMixedHDivErrorEstimate::~TPZMixedHDivErrorEstimate() = default;
 
 TPZMixedHDivErrorEstimate::TPZMixedHDivErrorEstimate(const TPZMixedHDivErrorEstimate &cp) : TPZMixedDarcyFlow(cp)
 {

From ded9f78b97a3c09e9e16a6d018b5470b5bc92284 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Fri, 25 Jun 2021 12:37:17 -0300
Subject: [PATCH 088/187] Make fHybridizer private and add maybe_unused keyword
 to it's setter func

---
 ErrorEstimation/TPZHDivErrorEstimator.h | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.h b/ErrorEstimation/TPZHDivErrorEstimator.h
index ed402da0..b17deaae 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.h
+++ b/ErrorEstimation/TPZHDivErrorEstimator.h
@@ -33,8 +33,6 @@ class TPZHDivErrorEstimator {
     TPZVec fPressureweights;
     /// weights associated with material ids
     std::map fMatid_weights;
-    // object to assist in creating a hybridized version of the computational mesh
-    TPZHybridizeHDiv fHybridizer;
 
     // material id of the dim-1 skeleton elements
     int fPressureSkeletonMatId = 0;
@@ -43,6 +41,10 @@ class TPZHDivErrorEstimator {
     /// whether the post processing mesh will be H(div) or H1
     bool fPostProcesswithHDiv = false;
 
+private:
+    // object to assist in creating a hybridized version of the computational mesh
+    TPZHybridizeHDiv fHybridizer;
+
 public:
     explicit TPZHDivErrorEstimator(TPZMultiphysicsCompMesh &originalMesh, bool postProcWithHDiv = false)
         : fOriginal(&originalMesh), fPostProcMesh(nullptr), fExact(nullptr) {
@@ -62,7 +64,7 @@ class TPZHDivErrorEstimator {
     /// Set the analytic solution object
     void SetAnalyticSolution(TPZAnalyticSolution &exact) { fExact = &exact; }
 
-    void SetHybridizer(TPZHybridizeHDiv &hybridizer) { fHybridizer = hybridizer; }
+    [[maybe_unused]] void SetHybridizer(TPZHybridizeHDiv &hybridizer) { fHybridizer = hybridizer; }
 
     /// compute the element errors comparing the reconstructed solution based on average pressures
     /// with the original solution

From 665a5b73481169f213c145384e89b34800e291cf Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Fri, 25 Jun 2021 12:37:33 -0300
Subject: [PATCH 089/187] Delete GlobalEffectivityIndex declaration

---
 ErrorEstimation/TPZHDivErrorEstimator.h | 2 --
 1 file changed, 2 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.h b/ErrorEstimation/TPZHDivErrorEstimator.h
index b17deaae..4cf79ba1 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.h
+++ b/ErrorEstimation/TPZHDivErrorEstimator.h
@@ -149,8 +149,6 @@ class TPZHDivErrorEstimator {
 
     /// compute the nodal average of all elements that share a point
     void ComputeNodalAverage(TPZCompElSide &node_celside);
-    //compute the global efectivity index using the CharacteristicSize() of element
-    void GlobalEffectivityIndex();
 
     /// copy the solution from the neighbouring skeleton elements
     // this is a placeholder for the derived class TPZHDivErrorEstimatorH1

From da1f8882f869a73277035c06123347d3a0b92401 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Fri, 25 Jun 2021 12:39:10 -0300
Subject: [PATCH 090/187] Move variable declaration

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index f7f0ba9a..5e840825 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -75,10 +75,6 @@ void TPZHDivErrorEstimator::ComputeErrors(TPZVec&errorVec, TPZVec& e
         an.SetExact(fExact->ExactSolution());
     }
 
-    constexpr int64_t nErrorCols = 6;
-    errorVec.Resize(nErrorCols);
-    errorVec.Fill(0);
-
     int64_t nelem = fPostProcMesh.NElements();
     fPostProcMesh.LoadSolution(fPostProcMesh.Solution());
     fPostProcMesh.ExpandSolution();
@@ -110,6 +106,9 @@ void TPZHDivErrorEstimator::ComputeErrors(TPZVec&errorVec, TPZVec& e
         elementerror = 0;
     }
 
+    constexpr int64_t nErrorCols = 6;
+    errorVec.Resize(nErrorCols);
+
     TPZFMatrix &elsol = fPostProcMesh.ElementSolution();
     for (int64_t i = 0; i < nelem; i++) {
         TPZCompEl *cel = fPostProcMesh.Element(i);

From df889ffd73f5ba9e4ffdb3572b0f3445d7f246a1 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Fri, 25 Jun 2021 12:39:45 -0300
Subject: [PATCH 091/187] Add dummy TPZDarcyFlow material so BCs can use it's
 ContributeBC method

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 5e840825..f0f1a87b 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -193,6 +193,9 @@ TPZCompMesh *TPZHDivErrorEstimator::CreatePressureMesh() {
 
         // Insert BC materials in pressure reconstruction mesh
         std::set bcMatIDs = GetBCMatIDs(&fPostProcMesh);
+        // Insert dummy volumetric material since we need ContributeBC
+        auto *dummy_mat = new TPZDarcyFlow(-999, fPostProcMesh.Dimension());
+
         for (auto bcID : bcMatIDs) {
             TPZMaterial *mat = mult->FindMaterial(bcID);
             auto *bc = dynamic_cast *>(mat);
@@ -203,7 +206,7 @@ TPZCompMesh *TPZHDivErrorEstimator::CreatePressureMesh() {
             auto *pressuremat = dynamic_cast*>(volumetricMat);
             if (!pressuremat) DebugStop();
 
-            TPZBndCondT *newbc = pressuremat->CreateBC(pressuremat, bc->Id(), bc->Type(), bc->Val1(), bc->Val2());
+            TPZBndCondT *newbc = dummy_mat->CreateBC(dummy_mat, bc->Id(), bc->Type(), bc->Val1(), bc->Val2());
             if (bc->HasForcingFunctionBC()) {
                 newbc->SetForcingFunctionBC(bc->ForcingFunctionBC());
             }

From 20b89857be7f6a9228c93ec0eeac4e511214fdde Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Fri, 25 Jun 2021 12:40:25 -0300
Subject: [PATCH 092/187] Simplify code since nstate is always equal to 1

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 9 +++------
 1 file changed, 3 insertions(+), 6 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index f0f1a87b..4d40eccb 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -1281,7 +1281,7 @@ void TPZHDivErrorEstimator::ComputeNodalAverage(TPZCompElSide &node_celside)
     // and the solution of that connect. The weight of Dirichlet condition is
     // higher and will be used later to impose the value of the BC in the
     // connects when needed
-    std::map>> connects;
+    std::map> connects;
     for (int elc = 0; elc < celstack.size(); elc++) {
         TPZCompElSide celside = celstack[elc];
         TPZGeoElSide gelside = celside.Reference();
@@ -1312,10 +1312,7 @@ void TPZHDivErrorEstimator::ComputeNodalAverage(TPZCompElSide &node_celside)
         int64_t seqnum = c.SequenceNumber();
         if (c.NState() != nstate || c.NShape() != 1) DebugStop();
         TPZManVector pt(0), x(3);
-        TPZManVector sol(nstate, 0.);
-        for (int istate = 0; istate < nstate; istate++) {
-            sol[istate] = solMatrix.at(block.at(seqnum, 0, istate, 0));
-        }
+        STATE sol = solMatrix.at(block.at(seqnum, 0, 0, 0));
 #ifdef LOG4CXX
         if(logger->isDebugEnabled())
         {
@@ -1333,7 +1330,7 @@ void TPZHDivErrorEstimator::ComputeNodalAverage(TPZCompElSide &node_celside)
         REAL weight = connect.second.first;
         sum_weight += weight;
         for (int istate = 0; istate < nstate; istate++) {
-            averageSol[istate] += connect.second.second[istate] * weight;
+            averageSol[istate] += connect.second.second * weight;
         }
     }
     

From e193b5b58a31b36d268c471e0d62259a81c768ff Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Fri, 25 Jun 2021 12:41:53 -0300
Subject: [PATCH 093/187] Hardcode number of errors which should be always
 equals to 5

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 21 +++++++++------------
 1 file changed, 9 insertions(+), 12 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 4d40eccb..104153a0 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -1375,28 +1375,25 @@ void TPZHDivErrorEstimator::ComputeNodalAverage(TPZCompElSide &node_celside)
 void TPZHDivErrorEstimator::ComputeEffectivityIndices(TPZSubCompMesh *subcmesh) {
     TPZFMatrix &elsol = subcmesh->ElementSolution();
     int64_t nrows = elsol.Rows();
-    int64_t ncols = 5; // subcmesh->ElementSolution().Cols();
-
-    if (subcmesh->ElementSolution().Cols() != 7) {
-        // TODO I made some changes to be able to run the code again.
-        //  Sometimes subcmesh->ElementSolution().Cols() equals 5  sometimes it's already 7.
-        //  I'm not sure if this behaviour is expected.
-        subcmesh->ElementSolution().Resize(nrows, 7);
+    if (subcmesh->ElementSolution().Cols() != 5) {
+       // DebugStop();
     }
+    subcmesh->ElementSolution().Resize(nrows, 7);
 
     int64_t nel = subcmesh->NElements();
     TPZManVector errors(5, 0.);
     for (int64_t el = 0; el < nel; el++) {
-        for (int i = 0; i < ncols; i++) {
+        for (int i = 0; i < 5; i++) {
             errors[i] += elsol(el, i) * elsol(el, i);
         }
     }
-    for (int i = 0; i < ncols; i++) {
+    for (int i = 0; i < 5; i++) {
         errors[i] = sqrt(errors[i]);
     }
 
+    // Substitute original errors by a constant in each subcmesh
     for (int64_t el = 0; el < nel; el++) {
-        for (int i = 0; i < ncols; i++) {
+        for (int i = 0; i < 5; i++) {
             elsol(el, i) = errors[i];
         }
     }
@@ -1419,11 +1416,11 @@ void TPZHDivErrorEstimator::ComputeEffectivityIndices(TPZSubCompMesh *subcmesh)
             }
 
             if (abs(ErrorEstimate) < tol) {
-                elsol(el, ncols + i / 2) = 1.;
+                elsol(el, 5 + i / 2) = 1.;
 
             } else {
                 REAL EfIndex = (ErrorEstimate + oscillatoryterm) / ErrorExact;
-                elsol(el, ncols + i / 2) = EfIndex;
+                elsol(el, 5 + i / 2) = EfIndex;
             }
         }
     }

From d05350ecde2c7cdbf8a96940f02b695299d24cce Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Fri, 25 Jun 2021 12:42:20 -0300
Subject: [PATCH 094/187] [ongoing] Work on the logic of computing errors for
 subcmeshes

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 104153a0..a572e04d 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -1469,6 +1469,7 @@ void TPZHDivErrorEstimator::ComputeEffectivityIndices() {
         if (!cel) continue;
         auto *subcmesh = dynamic_cast(cel);
         if (subcmesh) {
+            //continue;
             ComputeEffectivityIndices(subcmesh);
         }
         TPZGeoEl *gel = cel->Reference();
@@ -1549,7 +1550,7 @@ void TPZHDivErrorEstimator::ComputeEffectivityIndices() {
         if (!cel) continue;
         auto *subcmesh = dynamic_cast(cel);
         if (subcmesh) {
-            ComputeEffectivityIndices(subcmesh);
+            //ComputeEffectivityIndices(subcmesh);
         }
         TPZGeoEl *gel = cel->Reference();
         if (!gel) continue;

From e1f1b074e74145615d1be8f707ea56a333928102 Mon Sep 17 00:00:00 2001
From: Gustavo Batistela 
Date: Fri, 25 Jun 2021 16:30:04 -0300
Subject: [PATCH 095/187] Fixing SPE10 according to PZ changes

---
 Projects/CMakeLists.txt      |  2 +-
 Projects/SPE10/mainSPE10.cpp | 51 ++++++++++++++++--------------------
 2 files changed, 24 insertions(+), 29 deletions(-)

diff --git a/Projects/CMakeLists.txt b/Projects/CMakeLists.txt
index 78658431..5df72e5e 100644
--- a/Projects/CMakeLists.txt
+++ b/Projects/CMakeLists.txt
@@ -22,6 +22,6 @@ endif()
 # This project is marked as optional since it requires libInterpolate external library
 option(BUILD_SPE10_PROJECT "Whether to build estimation on SPE10 mesh" OFF)
 if(BUILD_SPE10_PROJECT)
-    #add_subdirectory(SPE10)
+    add_subdirectory(SPE10)
 endif()
 
diff --git a/Projects/SPE10/mainSPE10.cpp b/Projects/SPE10/mainSPE10.cpp
index 7a3482f0..7e757fa4 100644
--- a/Projects/SPE10/mainSPE10.cpp
+++ b/Projects/SPE10/mainSPE10.cpp
@@ -3,6 +3,7 @@
 //
 
 #include "Tools.h"
+#include 
 #include 
 #include 
 #include 
@@ -20,7 +21,7 @@ Interpolator interpolator;
 // Function declarations
 void ReadSPE10CellPermeabilities(TPZVec*perm_vec, int layer);
 TPZGeoMesh *CreateSPE10GeoMesh();
-void PermeabilityFunction(const TPZVec &x, TPZVec &res, TPZFMatrix &res_mat);
+void PermeabilityFunction(const TPZVec &x, TPZMatrix &K, TPZMatrix &invK);
 void InsertMaterials(TPZCompMesh *cmesh);
 void CreateSPE10MHMCompMesh(TPZMHMixedMeshControl &mhm);
 void SolveMHMProblem(TPZMHMixedMeshControl &mhm);
@@ -67,7 +68,7 @@ TPZGeoMesh *CreateSPE10GeoMesh() {
 
     const TPZManVector x0 = {0, 0, 0};
     const TPZManVector x1 = {220., 60., 0.};
-    const TPZManVector ndiv = {20, 6, 0};
+    const TPZManVector ndiv = {22, 6, 0};
 
     TPZGenGrid2D gen(ndiv, x0, x1);
 
@@ -116,23 +117,15 @@ void ReadSPE10CellPermeabilities(TPZVec *perm_vec, const int layer) {
     std::cout << "Finished reading permeability data from input file!\n";
 }
 
-void PermeabilityFunction(const TPZVec &x, TPZVec &res, TPZFMatrix &res_mat) {
-
-    for (int i = 0; i < 2; i++) {
-        auto perm = interpolator(x[0], x[1]);
-        if (perm <= 1) {
-            perm = 1;
-        } else {
-            perm += 1;
-        }
-        res_mat(i + 2, i) = 1 / perm;
-        res_mat(i, i) = perm;
+void PermeabilityFunction(const TPZVec &x, TPZMatrix &K, TPZMatrix &invK) {
+    auto perm = interpolator(x[0], x[1]);
+    if (perm <= 1) {
+        perm = 1;
+    } else {
+        perm += 1;
     }
-    //std::cout << "[" << x[0] << ", " << x[1] << "]\n";
-    //std::cout << "[" << res_mat(0, 0) << " " << res_mat(0, 1) << "\n";
-    //std::cout        << res_mat(1, 0) << " " << res_mat(1, 1) << "\n";
-    //std::cout        << res_mat(2, 0) << " " << res_mat(2, 1) << "\n";
-    //std::cout        << res_mat(3, 0) << " " << res_mat(3, 1) << "]\n\n";
+    K(0, 0) = perm;
+    invK(0, 0) = 1 / perm;
 }
 
 void CreateSPE10MHMCompMesh(TPZMHMixedMeshControl &mhm) {
@@ -179,13 +172,13 @@ void SolveMHMProblem(TPZMHMixedMeshControl &mhm) {
     TPZAutoPointer cmesh = mhm.CMesh();
 
     bool should_renumber = true;
-    TPZAnalysis an(cmesh, should_renumber);
+    TPZLinearAnalysis an(cmesh, should_renumber);
 
 #ifdef PZ_USING_MKL
-    TPZSymetricSpStructMatrix strmat(cmesh.operator->());
-    strmat.SetNumThreads(8);
+    TPZSSpStructMatrix strmat(cmesh.operator->());
+    strmat.SetNumThreads(0);
 #else
-    TPZSkylineStructMatrix strmat(cmesh.operator->());
+    TPZSkylineStructMatrix strmat(cmesh.operator->());
     strmat.SetNumThreads(8);
 #endif
 
@@ -224,15 +217,17 @@ void SolveMHMProblem(TPZMHMixedMeshControl &mhm) {
 
 void InsertMaterials(TPZCompMesh *cmesh) {
 
-    auto *mix = new TPZMixedPoisson(1, cmesh->Dimension());
-    TPZAutoPointer> perm_function = new TPZDummyFunction(&PermeabilityFunction, 3);
-    mix->SetPermeabilityFunction(perm_function);
+    auto *mix = new TPZMixedDarcyFlow(1, cmesh->Dimension());
+    std::function &coord, TPZMatrix &K, TPZMatrix &InvK)> func =
+        PermeabilityFunction;
+    mix->SetPermeabilityFunction(func);
 
-    TPZFNMatrix<1, REAL> val1(1, 1, 0.), val2(1, 1, 0.);
+    TPZFNMatrix<1, REAL> val1(1, 1, 0.);
+    TPZManVector val2(1, 0.);
     constexpr int dirichlet_bc = 0;
 
     // Pressure at reservoir boundary
-    val2(0, 0) = 1;
+    val2[0] = 1;
     TPZBndCond *pressure_left = mix->CreateBC(mix, -1, dirichlet_bc, val1, val2);
 
     cmesh->InsertMaterialObject(mix);
@@ -247,7 +242,7 @@ void EstimateError(TPZMHMixedMeshControl *mhm) {
     TPZMultiphysicsCompMesh *originalMesh = dynamic_cast(mhm->CMesh().operator->());
     if (!originalMesh) DebugStop();
 
-    bool postProcWithHDiv = true;
+    bool postProcWithHDiv = false;
     TPZMHMHDivErrorEstimator ErrorEstimator(*originalMesh, mhm, postProcWithHDiv);
     ErrorEstimator.PotentialReconstruction();
 

From e18f52cd803acc96d21abf3509e3a93ad1b9e498 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 16 Jul 2021 11:16:24 -0300
Subject: [PATCH 096/187] Add template to struct matrix class

---
 Projects/ErrorEstimationMHM/main_Journal.cpp | 2 +-
 Projects/ErrorEstimationMHM/main_MHM.cpp     | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp
index d107d0d9..a1775ab2 100644
--- a/Projects/ErrorEstimationMHM/main_Journal.cpp
+++ b/Projects/ErrorEstimationMHM/main_Journal.cpp
@@ -500,7 +500,7 @@ void SolveMHMProblem(TPZMHMixedMeshControl *mhm, const ProblemConfig &config) {
     TPZSSpStructMatrix strmat(cmesh.operator->());
     strmat.SetNumThreads(4);
 #else
-    TPZSkylineStructMatrix strmat(cmesh.operator->());
+    TPZSkylineStructMatrix strmat(cmesh.operator->());
     strmat.SetNumThreads(0);
 #endif
 
diff --git a/Projects/ErrorEstimationMHM/main_MHM.cpp b/Projects/ErrorEstimationMHM/main_MHM.cpp
index f03230c6..25dc1ddd 100644
--- a/Projects/ErrorEstimationMHM/main_MHM.cpp
+++ b/Projects/ErrorEstimationMHM/main_MHM.cpp
@@ -439,7 +439,7 @@ void SolveMHMProblem(TPZMHMixedMeshControl *mhm, const ProblemConfig &config) {
     TPZSSpStructMatrix strmat(cmesh.operator->());
     strmat.SetNumThreads(0 /*config.n_threads*/);
 #else
-    TPZSkylineStructMatrix strmat(cmesh.operator->());
+    TPZSkylineStructMatrix strmat(cmesh.operator->());
     strmat.SetNumThreads(0);
 #endif
 

From ee228d69903de6d09a105853bde0291ab94c4eec Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 21 Jul 2021 10:22:43 -0300
Subject: [PATCH 097/187] Rename hdiv adaptivity target

---
 Projects/ErrorEstimationHDiv/CMakeLists.txt | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/Projects/ErrorEstimationHDiv/CMakeLists.txt b/Projects/ErrorEstimationHDiv/CMakeLists.txt
index 55f1a496..9805ef89 100644
--- a/Projects/ErrorEstimationHDiv/CMakeLists.txt
+++ b/Projects/ErrorEstimationHDiv/CMakeLists.txt
@@ -5,8 +5,8 @@
 add_executable(HybridHDiv main.cpp)
 target_link_libraries(HybridHDiv Tools ErrorEstimationLib)
 
-#add_executable(AdaptivityTest mainAdaptivity.cpp)
-#target_link_libraries(AdaptivityTest Tools ErrorEstimationLib)
+add_executable(AdaptivityHDiv mainAdaptivity.cpp)
+target_link_libraries(AdaptivityHDiv Tools ErrorEstimationLib)
 
 #add_executable(SteklovProblem mainSteklov.cpp)
 #target_link_libraries(SteklovProblem Tools ErrorEstimationLib)

From b51efd4437e32f93e08ddcf20443b379b2dbba8f Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 21 Jul 2021 10:23:08 -0300
Subject: [PATCH 098/187] Clean and fix H(div) adaptivity target

---
 .../ErrorEstimationHDiv/mainAdaptivity.cpp    | 185 +++++-------------
 1 file changed, 48 insertions(+), 137 deletions(-)

diff --git a/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp b/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
index 1898ea8e..4ce4b493 100644
--- a/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
+++ b/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
@@ -3,33 +3,19 @@
 //
 
 #include "TPZRefPatternDataBase.h"
-#include "TPZGmshReader.h"
-
 #include "tpzarc3d.h"
-#include "tpzgeoblend.h"
-#include "TPZGeoLinear.h"
-
 #include 
-#include 
-
 #include "ProblemConfig.h"
 #include "TPZHDivErrorEstimator.h"
 #include "Tools.h"
 
-//#include "pzelchdiv.h"
-
-bool readGeoMeshFromFile = false;
-bool postProcessWithHDiv = false;
-int refinementSteps = 1;
+constexpr bool postProcessWithHDiv = false;
+constexpr int refinementSteps = 4;
 
+TPZMultiphysicsCompMesh *CreateHybridCompMesh(const ProblemConfig &config, TPZHybridizeHDiv &hybridizer);
 TPZGeoMesh *CreateLShapeGeoMesh(int nCoarseRef, int nInternalRef, TPZStack &mhmIndexes);
-void TracingTriangleBug(TPZMultiphysicsCompMesh* multiphysics);
 
-int main(int argc, char* argv[]) {
-
-#ifdef LOG4CXX
-    InitializePZLOG();
-#endif
+int main() {
 
     // Initializing uniform refinements for reference elements
     gRefDBase.InitializeUniformRefPattern(EOned);
@@ -37,8 +23,7 @@ int main(int argc, char* argv[]) {
     gRefDBase.InitializeUniformRefPattern(ETriangle);
 
     // Creates geometric mesh
-
-    TPZGeoMesh *gmeshOriginal = nullptr; // CreateLShapeMesh(bcIDs);//CreateLShapeMesh(bcIDs);
+    TPZGeoMesh *gmeshOriginal;
 
     ProblemConfig config;
 
@@ -57,118 +42,27 @@ int main(int argc, char* argv[]) {
     std::string command = "mkdir -p " + config.dir_name;
     system(command.c_str());
 
-    if (readGeoMeshFromFile) {
-        std::string meshfilename = "../LMesh.msh"; //"../LMesh3.msh";
+    TPZManVector bcids(8, -1);
+    bcids[1] = -1;
+    gmeshOriginal = Tools::CreateLShapeMesh(bcids);
+    config.materialids.insert(1);
+    config.bcmaterialids.insert(-1);
 
-        TPZGmshReader gmsh;
-        gmsh.GetDimNamePhysical()[1]["dirichlet"] = 2;
-        gmsh.GetDimNamePhysical()[2]["domain"] = 1;
-        gmsh.SetFormatVersion("4.1");
-        gmeshOriginal = gmsh.GeometricGmshMesh(meshfilename);
-        gmsh.PrintPartitionSummary(std::cout);
-        config.materialids.insert(1);
-        config.bcmaterialids.insert(2);
+    Tools::UniformRefinement(2, 2 , gmeshOriginal) ;
+    Tools::DivideLowerDimensionalElements(gmeshOriginal);
 
-    }
-else
-
-    {
-        //TPZManVector bcIDs(8, -1);
-        TPZManVector bcids(8,-1);
-        bcids[1] = -1;
-        //constants for Robin boundary conditions
-        // sigma.n=Km(u-u_d)-g
-        //Particular cases: 1) Km=0---> Neumann, 2) Km=infinity-->Dirichlet
-        //config.coefG = 0.;//nao passar mais isso
-        config.Km = 1.e12;//pow(10,2);
-        
-        gmeshOriginal = Tools::CreateLShapeMesh(bcids);//CreateGeoMesh(1, bcIDs);//
-
-
-        config.materialids.insert(1);
-        config.bcmaterialids.insert(-1); // dirichlet
-        //config.bcmaterialids.insert(-2); // neumann
-        //config.bcmaterialids.insert(-3); // Robin
-
-        
-    }
-    
-    gmeshOriginal->SetDimension(config.dimension);
-    config.gmesh = gmeshOriginal;
-    Tools::UniformRefinement(2, 2 , config.gmesh) ;
-    Tools::DivideLowerDimensionalElements(config.gmesh);
-    
-        
-        
-    TPZManVector meshvec_HDiv(2, 0);
-        
-    TPZMultiphysicsCompMesh* cmesh_HDiv = Tools::CreateMixedMesh(config); //Hdiv x L2
-    cmesh_HDiv->InitializeBlock();
-    Tools::SolveMixedProblem(cmesh_HDiv, config);
-    
-    meshvec_HDiv = cmesh_HDiv->MeshVector();
-    
-    
     for (int iSteps = 0; iSteps < refinementSteps; iSteps++) {
-    
-    
+
+        config.gmesh = new TPZGeoMesh(*gmeshOriginal);
         config.adaptivityStep = iSteps;
-        
-   //     UniformRefinement(iSteps, gmeshOriginal);
-        
-        #ifdef PZDEBUG
-                {
-                    std::ofstream out("gmeshToSolve.vtk");
-                    TPZVTKGeoMesh::PrintGMeshVTK(gmeshOriginal, out);
-                }
-        #endif
-        
-    
-        
-
-              TPZManVector meshvec_HDiv(2, 0);
-              
-              TPZMultiphysicsCompMesh* cmesh_HDiv = nullptr;
-              
-              
-              cmesh_HDiv = Tools::CreateMixedMesh(config);//Hdiv x L2
-              cmesh_HDiv->InitializeBlock();
-               #ifdef PZDEBUG2
-              {
-                  std::ofstream out("MultiPhysicsMesh.txt");
-                  cmesh_HDiv->Print(out);
-                  std::ofstream outvtk("MultiPhysicsMesh.vtk");
-                  
-                  TPZVTKGeoMesh::PrintCMeshVTK(cmesh_HDiv,outvtk);
-        
-                  
-              }
-              #endif
-              
-              meshvec_HDiv = cmesh_HDiv->MeshVector();
-              
-              //cria malha hibrida
-              TPZHybridizeHDiv hybrid;
-              auto HybridMesh = hybrid.Hybridize(cmesh_HDiv);
-              HybridMesh->CleanUpUnconnectedNodes();
-              HybridMesh->AdjustBoundaryElements();
-              
-              delete cmesh_HDiv;
-              delete meshvec_HDiv[0];
-              delete meshvec_HDiv[1];
-              
-              cmesh_HDiv = (HybridMesh);//malha hribrida
-              meshvec_HDiv[0] = (HybridMesh)->MeshVector()[0];//malha Hdiv
-              meshvec_HDiv[1] = (HybridMesh)->MeshVector()[1];//malha L2
-
-        Tools::SolveHybridProblem(cmesh_HDiv, hybrid.fInterfaceMatid, config,false);
-    
-    
-   
-        //reconstroi potencial e calcula o erro
+
+        TPZMultiphysicsCompMesh *mixedCompMesh = Tools::CreateMixedMesh(config); // Hdiv x L2
+        mixedCompMesh->InitializeBlock();
+        Tools::SolveMixedProblem(mixedCompMesh, config);
+
+        // Estimate error and run adaptive process
         {
-            bool postProcWithHDiv = false;
-            TPZHDivErrorEstimator HDivEstimate(*cmesh_HDiv, postProcWithHDiv);
+            TPZHDivErrorEstimator HDivEstimate(*mixedCompMesh, postProcessWithHDiv);
             HDivEstimate.SetAnalyticSolution(config.exact);
 
             HDivEstimate.PotentialReconstruction();
@@ -177,17 +71,9 @@ else
             std::string vtkPath = "adaptivity_error_results.vtk";
             HDivEstimate.ComputeErrors(errorvec, elementerrors, vtkPath);
             Tools::hAdaptivity(HDivEstimate.PostProcMesh(), gmeshOriginal, config);
-            #ifdef PZDEBUG
-                    {
-                        std::ofstream out("gmeshAdapty.vtk");
-                        TPZVTKGeoMesh::PrintGMeshVTK(gmeshOriginal, out);
-                    }
-            #endif
-    }
-    
-   // return 0;
-        
+        }
     }
+    return 0;
 }
 
 TPZGeoMesh *CreateLShapeGeoMesh(int nCoarseRef, int nInternalRef, TPZStack &mhmIndexes) {
@@ -217,3 +103,28 @@ TPZGeoMesh *CreateLShapeGeoMesh(int nCoarseRef, int nInternalRef, TPZStackPrint(out);
+    }
+#endif
+
+    // Hybridize mesh
+    TPZMultiphysicsCompMesh* hybridMesh = hybridizer.Hybridize(cmesh_HDiv);
+    hybridMesh->CleanUpUnconnectedNodes(); // Enumereate connects correctly
+    hybridMesh->AdjustBoundaryElements();
+
+    delete cmesh_HDiv;
+
+    std::cout << "---Original PerifericalMaterialId --- " << std::endl;
+    std::cout << " LagrangeInterface = " << hybridizer.fLagrangeInterface << std::endl;
+    std::cout << " HDivWrapMatid = " << hybridizer.fHDivWrapMatid << std::endl;
+    std::cout << " InterfaceMatid = " << hybridizer.fInterfaceMatid << std::endl;
+    return hybridMesh;
+}

From 7f817134db62611e2d6fc2e509dce5d764a0f90d Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 21 Jul 2021 15:46:42 -0300
Subject: [PATCH 099/187] Add adaptivity step member variable to error
 estimator class

---
 ErrorEstimation/TPZHDivErrorEstimator.h | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.h b/ErrorEstimation/TPZHDivErrorEstimator.h
index 4cf79ba1..146eca57 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.h
+++ b/ErrorEstimation/TPZHDivErrorEstimator.h
@@ -41,6 +41,8 @@ class TPZHDivErrorEstimator {
     /// whether the post processing mesh will be H(div) or H1
     bool fPostProcesswithHDiv = false;
 
+    int fAdaptivityStep{0};
+
 private:
     // object to assist in creating a hybridized version of the computational mesh
     TPZHybridizeHDiv fHybridizer;
@@ -66,6 +68,8 @@ class TPZHDivErrorEstimator {
 
     [[maybe_unused]] void SetHybridizer(TPZHybridizeHDiv &hybridizer) { fHybridizer = hybridizer; }
 
+    void SetAdaptivityStep(int step) { fAdaptivityStep = step; };
+
     /// compute the element errors comparing the reconstructed solution based on average pressures
     /// with the original solution
     virtual void ComputeErrors(TPZVec &error_vec, TPZVec &element_errors, std::string&vtkPath);

From d18b44f097c50524a31aaefcb241605e56f0e95b Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 21 Jul 2021 15:46:52 -0300
Subject: [PATCH 100/187] Remove obsolete comment

---
 ErrorEstimation/TPZHDivErrorEstimator.h | 2 --
 1 file changed, 2 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.h b/ErrorEstimation/TPZHDivErrorEstimator.h
index 146eca57..94a3476e 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.h
+++ b/ErrorEstimation/TPZHDivErrorEstimator.h
@@ -61,8 +61,6 @@ class TPZHDivErrorEstimator {
 
     ~TPZHDivErrorEstimator();
 
-    //void SetProblemConfig(const ProblemConfig &cfg) { fProblemConfig = cfg; }
-
     /// Set the analytic solution object
     void SetAnalyticSolution(TPZAnalyticSolution &exact) { fExact = &exact; }
 

From e1e1fac15412430eb1d80cdd95162417f53622ce Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 21 Jul 2021 15:48:28 -0300
Subject: [PATCH 101/187] Remove unused headers and functions from hdiv
 adaptivity main

---
 .../ErrorEstimationHDiv/mainAdaptivity.cpp    | 64 +------------------
 1 file changed, 3 insertions(+), 61 deletions(-)

diff --git a/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp b/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
index 4ce4b493..cd5cb32d 100644
--- a/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
+++ b/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
@@ -2,18 +2,13 @@
 // Created by Gustavo Batistela on 12/07/19.
 //
 
-#include "TPZRefPatternDataBase.h"
-#include "tpzarc3d.h"
-#include 
 #include "ProblemConfig.h"
 #include "TPZHDivErrorEstimator.h"
+#include "TPZRefPatternDataBase.h"
 #include "Tools.h"
 
 constexpr bool postProcessWithHDiv = false;
-constexpr int refinementSteps = 4;
-
-TPZMultiphysicsCompMesh *CreateHybridCompMesh(const ProblemConfig &config, TPZHybridizeHDiv &hybridizer);
-TPZGeoMesh *CreateLShapeGeoMesh(int nCoarseRef, int nInternalRef, TPZStack &mhmIndexes);
+constexpr int refinementSteps = 7;
 
 int main() {
 
@@ -74,57 +69,4 @@ int main() {
         }
     }
     return 0;
-}
-
-TPZGeoMesh *CreateLShapeGeoMesh(int nCoarseRef, int nInternalRef, TPZStack &mhmIndexes) {
-
-    TPZVec bcIDs(8, -1);
-    TPZGeoMesh *gmesh = Tools::CreateQuadLShapeMesh(bcIDs);
-    gmesh->SetDimension(2);
-    gmesh->BuildConnectivity();
-
-    Tools::UniformRefinement(nCoarseRef, gmesh);
-    Tools::DivideLowerDimensionalElements(gmesh);
-
-    int64_t nElem = gmesh->NElements();
-    for (int64_t i = 0; i < nElem; i++) {
-        TPZGeoEl *gel = gmesh->Element(i);
-        if (gel->Dimension() != gmesh->Dimension() || gel->NSubElements() > 0) continue;
-        mhmIndexes.Push(i);
-    }
-
-    Tools::UniformRefinement(nInternalRef, gmesh);
-    Tools::DivideLowerDimensionalElements(gmesh);
-
-    for (int64_t i = 0; i < mhmIndexes.size(); i++) {
-        std::cout << mhmIndexes[i] << '\n';
-    }
-    std::cout << '\n';
-
-    return gmesh;
-}
-
-TPZMultiphysicsCompMesh *CreateHybridCompMesh(const ProblemConfig &config, TPZHybridizeHDiv &hybridizer) {
-
-    TPZMultiphysicsCompMesh *cmesh_HDiv = Tools::CreateMixedMesh(config); // Hdiv x L2
-
-#ifdef PZDEBUG
-    {
-        ofstream out("MixedMesh.txt");
-        cmesh_HDiv->Print(out);
-    }
-#endif
-
-    // Hybridize mesh
-    TPZMultiphysicsCompMesh* hybridMesh = hybridizer.Hybridize(cmesh_HDiv);
-    hybridMesh->CleanUpUnconnectedNodes(); // Enumereate connects correctly
-    hybridMesh->AdjustBoundaryElements();
-
-    delete cmesh_HDiv;
-
-    std::cout << "---Original PerifericalMaterialId --- " << std::endl;
-    std::cout << " LagrangeInterface = " << hybridizer.fLagrangeInterface << std::endl;
-    std::cout << " HDivWrapMatid = " << hybridizer.fHDivWrapMatid << std::endl;
-    std::cout << " InterfaceMatid = " << hybridizer.fInterfaceMatid << std::endl;
-    return hybridMesh;
-}
+}
\ No newline at end of file

From d589e6830f9a0f7b72936c5b1a41a576c49f5665 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 21 Jul 2021 15:48:52 -0300
Subject: [PATCH 102/187] Update problem settings on hdiv main adaptivity

---
 .../ErrorEstimationHDiv/mainAdaptivity.cpp    | 25 +++++++++++--------
 1 file changed, 14 insertions(+), 11 deletions(-)

diff --git a/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp b/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
index cd5cb32d..5badaca2 100644
--- a/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
+++ b/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
@@ -22,8 +22,8 @@ int main() {
 
     ProblemConfig config;
 
-    config.porder = 1;
-    config.hdivmais = 1;
+    config.porder = 2;
+    config.hdivmais = 3;
 
     config.dimension = 2;
     config.makepressurecontinuous = true;
@@ -31,11 +31,12 @@ int main() {
     config.exact = new TLaplaceExample1;
     config.exact.operator*().fExact = TLaplaceExample1::ESinMark;
 
-    config.dir_name = "AdaptivityLShape";
+    config.dir_name = "HDivAdaptivity";
     config.problemname = "ESinSinMark";
-
-    std::string command = "mkdir -p " + config.dir_name;
-    system(command.c_str());
+    {
+        std::string command = "mkdir -p " + config.dir_name;
+        system(command.c_str());
+    }
 
     TPZManVector bcids(8, -1);
     bcids[1] = -1;
@@ -46,10 +47,10 @@ int main() {
     Tools::UniformRefinement(2, 2 , gmeshOriginal) ;
     Tools::DivideLowerDimensionalElements(gmeshOriginal);
 
-    for (int iSteps = 0; iSteps < refinementSteps; iSteps++) {
+    for (int iStep = 0; iStep < refinementSteps; iStep++) {
 
         config.gmesh = new TPZGeoMesh(*gmeshOriginal);
-        config.adaptivityStep = iSteps;
+        config.adaptivityStep = iStep;
 
         TPZMultiphysicsCompMesh *mixedCompMesh = Tools::CreateMixedMesh(config); // Hdiv x L2
         mixedCompMesh->InitializeBlock();
@@ -59,12 +60,14 @@ int main() {
         {
             TPZHDivErrorEstimator HDivEstimate(*mixedCompMesh, postProcessWithHDiv);
             HDivEstimate.SetAnalyticSolution(config.exact);
-
+            HDivEstimate.SetAdaptivityStep(iStep);
             HDivEstimate.PotentialReconstruction();
             TPZManVector elementerrors;
             TPZManVector errorvec;
-            std::string vtkPath = "adaptivity_error_results.vtk";
-            HDivEstimate.ComputeErrors(errorvec, elementerrors, vtkPath);
+            std::stringstream outVTK;
+            outVTK << config.dir_name << "/" << config.problemname << "-Errors.vtk";
+            auto stringVTK = outVTK.str();
+            HDivEstimate.ComputeErrors(errorvec, elementerrors, stringVTK);
             Tools::hAdaptivity(HDivEstimate.PostProcMesh(), gmeshOriginal, config);
         }
     }

From 400b6bcc868081d6503ff2f23117b90792817a65 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 21 Jul 2021 16:09:51 -0300
Subject: [PATCH 103/187] Set step of TPZLinearAnalysis when postprocessing
 error

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index a572e04d..d69403cb 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -75,6 +75,8 @@ void TPZHDivErrorEstimator::ComputeErrors(TPZVec&errorVec, TPZVec& e
         an.SetExact(fExact->ExactSolution());
     }
 
+    an.SetStep(fAdaptivityStep);
+
     int64_t nelem = fPostProcMesh.NElements();
     fPostProcMesh.LoadSolution(fPostProcMesh.Solution());
     fPostProcMesh.ExpandSolution();

From bfb12452c779e3768223793af84df043b95f7481 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 22 Jul 2021 10:12:00 -0300
Subject: [PATCH 104/187] Update Hdiv adaptivity problem

---
 Projects/ErrorEstimationHDiv/mainAdaptivity.cpp | 14 ++++++--------
 1 file changed, 6 insertions(+), 8 deletions(-)

diff --git a/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp b/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
index 5badaca2..cf84bf41 100644
--- a/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
+++ b/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
@@ -8,7 +8,7 @@
 #include "Tools.h"
 
 constexpr bool postProcessWithHDiv = false;
-constexpr int refinementSteps = 7;
+constexpr int refinementSteps = 15;
 
 int main() {
 
@@ -22,29 +22,27 @@ int main() {
 
     ProblemConfig config;
 
-    config.porder = 2;
+    config.porder = 1;
     config.hdivmais = 3;
 
     config.dimension = 2;
     config.makepressurecontinuous = true;
 
     config.exact = new TLaplaceExample1;
-    config.exact.operator*().fExact = TLaplaceExample1::ESinMark;
+    config.exact.operator*().fExact = TLaplaceExample1::EBoundaryLayer;
 
     config.dir_name = "HDivAdaptivity";
-    config.problemname = "ESinSinMark";
+    config.problemname = "EBoundaryLayer";
     {
         std::string command = "mkdir -p " + config.dir_name;
         system(command.c_str());
     }
 
-    TPZManVector bcids(8, -1);
-    bcids[1] = -1;
-    gmeshOriginal = Tools::CreateLShapeMesh(bcids);
+    TPZManVector bcids(4, -1);
+    gmeshOriginal = Tools::CreateGeoMesh(2, bcids);
     config.materialids.insert(1);
     config.bcmaterialids.insert(-1);
 
-    Tools::UniformRefinement(2, 2 , gmeshOriginal) ;
     Tools::DivideLowerDimensionalElements(gmeshOriginal);
 
     for (int iStep = 0; iStep < refinementSteps; iStep++) {

From c8bd5e20231db2d3dab3aed73d3e8795a8fe7de1 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Tue, 27 Jul 2021 14:15:47 -0300
Subject: [PATCH 105/187] Fix forcing function conditional in H(div) error
 estimator material

---
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index aad04f28..da3717e4 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -294,9 +294,9 @@ void TPZHDivErrorEstimateMaterial::Errors(const TPZVec>
     TPZManVector u_exact(1);
     TPZFNMatrix<9, STATE> du_exact(3, 3);
     if (this->fExactSol) {
-
         this->fExactSol(data[H1functionposition].x, u_exact, du_exact);
-
+    }
+    if (this->fForcingFunction) {
         this->fForcingFunction(data[H1functionposition].x, divsigma);
     }
 

From 8ce153c06063921625613413123ba5a07a717911 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 5 Aug 2021 17:41:13 -0300
Subject: [PATCH 106/187] Compute exact errors only if the exact solution has
 been set

---
 .../Material/TPZHDivErrorEstimateMaterial.cpp       | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index da3717e4..e4759d9e 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -344,18 +344,25 @@ void TPZHDivErrorEstimateMaterial::Errors(const TPZVec>
 #endif
 
     for (int i = 0; i < 3; i++) {
-        innerexact += (fluxfem[i] + fluxexactneg(i, 0)) * InvPermTensor(0, 0) *
-                      (fluxfem[i] + fluxexactneg(i, 0)); // Pq esta somando: o fluxo fem esta + e o exato -
+        if (this->fExactSol) {
+            innerexact += (fluxfem[i] + fluxexactneg(i, 0)) * InvPermTensor(0, 0) *
+                          (fluxfem[i] + fluxexactneg(i, 0)); // Pq esta somando: o fluxo fem esta + e o exato -
+        }
         innerestimate +=
             (fluxfem[i] - fluxreconstructed[i]) * InvPermTensor(0, 0) * (fluxfem[i] - fluxreconstructed[i]);
     }
 
+    STATE exact_pressure_error = 0;
+    if (this->fExactSol) {
+        exact_pressure_error = (pressurefem - u_exact[0]) * (pressurefem - u_exact[0]);
+    }
+
 #ifdef PZDEBUG2
     std::cout<<"potential fem "<
Date: Fri, 6 Aug 2021 12:18:09 -0300
Subject: [PATCH 107/187] Call ComputeEffectivityIndices even when no exact
 solution is set

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index d69403cb..d09b6dbc 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -97,7 +97,7 @@ void TPZHDivErrorEstimator::ComputeErrors(TPZVec&errorVec, TPZVec& e
     TPZCompMeshTools::UnCondensedElements(&fPostProcMesh);
     TPZCompMeshTools::UnGroupElements(&fPostProcMesh);
 
-    if (fExact) ComputeEffectivityIndices();
+    ComputeEffectivityIndices();
 
     if (!vtkPath.empty()) {
         PostProcessing(an, vtkPath);

From 0068d212c24580fdceefac1d665a0b902632b222 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 6 Aug 2021 12:19:02 -0300
Subject: [PATCH 108/187] Comment unused code block

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index d09b6dbc..342337f6 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -1977,14 +1977,14 @@ void TPZHDivErrorEstimator::PrepareElementsForH1Reconstruction() {
         TPZGeoElSide skelSide(gel, gel->NSides() - 1);
         TPZStack compNeighSides;
         skelSide.EqualLevelCompElementList(compNeighSides, 1, 0);
-        if (compNeighSides.size() == 1) {
-            TPZCompElSide large = skelSide.LowerLevelCompElementList2(true);
-            if (large) {
-                std::cout << "Gel: " << gel->Index() << " Side: " << skelSide.Side() << '\n';
-                //compNeighSides.Push(large);
-            }
-        }
-        
+        //if (compNeighSides.size() == 1) {
+        //    TPZCompElSide large = skelSide.LowerLevelCompElementList2(true);
+        //    if (large) {
+        //        std::cout << "Gel: " << gel->Index() << " Side: " << skelSide.Side() << '\n';
+        //        //compNeighSides.Push(large);
+        //    }
+        //}
+
         for (int i = 0; i < compNeighSides.size(); i++) {
             TPZCompEl *neighCel = compNeighSides[i].Element();
             auto *neighIntEl = dynamic_cast(neighCel);

From 592e43075815e89fc10b836d5fac1931a2b63c3b Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 6 Aug 2021 12:19:38 -0300
Subject: [PATCH 109/187] Delete print messages

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 8 +-------
 1 file changed, 1 insertion(+), 7 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 342337f6..5a53e499 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -119,7 +119,7 @@ void TPZHDivErrorEstimator::ComputeErrors(TPZVec&errorVec, TPZVec& e
         if (!gel) continue;
         elementErrors[gel->Index()] = elsol(i, 3);
     }
-    
+
 }
 
 void TPZHDivErrorEstimator::PostProcessing(TPZAnalysis &an, std::string &out) {
@@ -2356,9 +2356,6 @@ void TPZHDivErrorEstimator::RestrainSkeletonSides(TPZCompMesh *pressure_mesh) co
         gel->CenterPoint(nsides - 1, xicenter);
         TPZManVector xcenter(3, 0.);
         gel->X(xicenter, xcenter);
-        std::cout << "Restriction @ [" << xcenter << "]:"
-                  << "  Small El: " << small.Element()->Index() << ", Side: " << small.Side()
-                  << "  Large El: " << largerNeigh.Element()->Index() << ", Side: " << largerNeigh.Side() << "\n";
         smallIntel->RestrainSide(small.Side(), largeIntel, largerNeigh.Side());
         
         // Restrain subsides
@@ -2370,9 +2367,6 @@ void TPZHDivErrorEstimator::RestrainSkeletonSides(TPZCompMesh *pressure_mesh) co
             if (subLargerNeigh.Element() == subsmall.Element()) DebugStop();
             gel->CenterPoint(iside, xicenter);
             gel->X(xicenter, xcenter);
-            std::cout << "SubRestriction @ [" << xcenter << "]:"
-                      << "  Small El: " << small.Element()->Index() << ", Side: " << subsmall.Side()
-                      << "  Large El: " << largerNeigh.Element()->Index() << ", Side: " << subLargerNeigh.Side() << "\n";
             smallIntel->RestrainSide(subsmall.Side(), largeIntel, subLargerNeigh.Side());
         }
     }

From 2c6baa69c842002981201670800aabdc0c76141b Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 6 Aug 2021 12:23:58 -0300
Subject: [PATCH 110/187] Delete print messages

---
 ErrorEstimation/TPZHybridH1ErrorEstimator.cpp | 3 ---
 1 file changed, 3 deletions(-)

diff --git a/ErrorEstimation/TPZHybridH1ErrorEstimator.cpp b/ErrorEstimation/TPZHybridH1ErrorEstimator.cpp
index eb100dfb..fe9a7f3a 100644
--- a/ErrorEstimation/TPZHybridH1ErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHybridH1ErrorEstimator.cpp
@@ -1186,9 +1186,6 @@ void TPZHybridH1ErrorEstimator::RestrainSkeletonSides(TPZCompMesh *pressure_mesh
             if (subLargerNeigh.Element() == subsmall.Element()) DebugStop();
             gel->CenterPoint(iside, xicenter);
             gel->X(xicenter, xcenter);
-            //std::cout << "SubRestriction @ [" << xcenter << "]:"
-            //          << "  Small El: " << small.Element()->Index() << ", Side: " << subsmall.Side()
-             //         << "  Large El: " << largerNeigh.Element()->Index() << ", Side: " << subLargerNeigh.Side() << "\n";
             smallIntel->RestrainSide(subsmall.Side(), largeIntel, subLargerNeigh.Side());
         }
     }

From 97b48b37d9e3c0c45e73e941f9e187cf17b42d0b Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 11 Aug 2021 11:29:01 -0300
Subject: [PATCH 111/187] Add cmesh member var to ProblemConfig

---
 ErrorEstimation/ProblemConfig.h | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/ErrorEstimation/ProblemConfig.h b/ErrorEstimation/ProblemConfig.h
index 229d69b0..1b53cb47 100644
--- a/ErrorEstimation/ProblemConfig.h
+++ b/ErrorEstimation/ProblemConfig.h
@@ -14,9 +14,9 @@
 /// class to guide the error estimator
 struct ProblemConfig
 {
-    
+    TPZCompMesh *cmesh = nullptr;
     /// geometric mesh on which the computational meshes are based
-    TPZGeoMesh *gmesh = 0;
+    TPZGeoMesh *gmesh = nullptr;
     /// polynomial order of the original mesh
     int porder = 2;
     /// increment in internal order of flux and pressure
@@ -41,7 +41,7 @@ struct ProblemConfig
     bool GalvisExample = false;
     bool TensorNonConst = false;
     bool MeshNonConvex = false;
-    
+
     STATE alpha=1;
     STATE Km = 0.;
     STATE coefG = 0.;

From 33be6026a47b300f8a09c0d52df7265bc911c4fd Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 11 Aug 2021 11:29:49 -0300
Subject: [PATCH 112/187] Print hdiv adaptivity problem errors

---
 Projects/ErrorEstimationHDiv/mainAdaptivity.cpp | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp b/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
index cf84bf41..bfc37df5 100644
--- a/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
+++ b/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
@@ -67,6 +67,11 @@ int main() {
             auto stringVTK = outVTK.str();
             HDivEstimate.ComputeErrors(errorvec, elementerrors, stringVTK);
             Tools::hAdaptivity(HDivEstimate.PostProcMesh(), gmeshOriginal, config);
+
+            std::stringstream outTXT;
+            outTXT << config.dir_name << "/" << config.problemname << "-Errors-Step" << config.adaptivityStep << ".txt";
+            std::ofstream fileTXT(outTXT.str());
+            Tools::PrintErrors(fileTXT, config, errorvec);
         }
     }
     return 0;

From 9da43fd1c7a3919d6f5bef7ed9e0534c449f8484 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 11 Aug 2021 11:30:07 -0300
Subject: [PATCH 113/187] Set problem config cmesh

---
 Projects/ErrorEstimationHDiv/mainAdaptivity.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp b/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
index bfc37df5..4c93a719 100644
--- a/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
+++ b/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
@@ -53,6 +53,7 @@ int main() {
         TPZMultiphysicsCompMesh *mixedCompMesh = Tools::CreateMixedMesh(config); // Hdiv x L2
         mixedCompMesh->InitializeBlock();
         Tools::SolveMixedProblem(mixedCompMesh, config);
+        config.cmesh = mixedCompMesh;
 
         // Estimate error and run adaptive process
         {

From 95c0130f3a50c903e13bc10dcd596de597f55cef Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 11 Aug 2021 11:30:40 -0300
Subject: [PATCH 114/187] Print nequations

---
 Projects/Tools/Tools.cpp | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/Projects/Tools/Tools.cpp b/Projects/Tools/Tools.cpp
index 61d39010..e3c4c71f 100644
--- a/Projects/Tools/Tools.cpp
+++ b/Projects/Tools/Tools.cpp
@@ -1073,6 +1073,9 @@ void Tools::PrintErrors(std::ofstream& out, const ProblemConfig& config, const T
     if (config.adaptivityStep != -1) {
         ss << ", AdaptivityStep = " << config.adaptivityStep;
     }
+    if (config.cmesh) {
+        ss << ", NEquations = " << config.cmesh->NEquations();
+    }
     ss << '\n';
     ss << "Global estimator = " << error_vec[3] << "\n";
     ss << "|ufem-urec| = " << error_vec[1] << "\n";

From 05ce7876fa7cd1f8d89493bb1f364dc9e216abd9 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 11 Aug 2021 15:45:31 -0300
Subject: [PATCH 115/187] Set secondary problems with uniform refinement

---
 .../ErrorEstimationHDiv/mainAdaptivity.cpp    | 93 +++++++++++++++++--
 1 file changed, 84 insertions(+), 9 deletions(-)

diff --git a/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp b/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
index 4c93a719..d7e91ef2 100644
--- a/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
+++ b/Projects/ErrorEstimationHDiv/mainAdaptivity.cpp
@@ -7,11 +7,19 @@
 #include "TPZRefPatternDataBase.h"
 #include "Tools.h"
 
-constexpr bool postProcessWithHDiv = false;
-constexpr int refinementSteps = 15;
+void RunAdaptivitySuite(int refinementSteps);
+void RunUniformRefinementSuite(int refinementSteps);
 
 int main() {
 
+    constexpr int adaptivitySteps = 8;
+    constexpr int uniformSteps = 6;
+    RunAdaptivitySuite(adaptivitySteps);
+    RunUniformRefinementSuite(uniformSteps);
+}
+
+void RunAdaptivitySuite(int refinementSteps) {
+
     // Initializing uniform refinements for reference elements
     gRefDBase.InitializeUniformRefPattern(EOned);
     gRefDBase.InitializeUniformRefPattern(EQuadrilateral);
@@ -23,7 +31,7 @@ int main() {
     ProblemConfig config;
 
     config.porder = 1;
-    config.hdivmais = 3;
+    config.hdivmais = 2;
 
     config.dimension = 2;
     config.makepressurecontinuous = true;
@@ -31,15 +39,15 @@ int main() {
     config.exact = new TLaplaceExample1;
     config.exact.operator*().fExact = TLaplaceExample1::EBoundaryLayer;
 
-    config.dir_name = "HDivAdaptivity";
-    config.problemname = "EBoundaryLayer";
+    config.dir_name = "HDivAdaptivityEquations";
+    config.problemname = "Adaptivity";
     {
         std::string command = "mkdir -p " + config.dir_name;
         system(command.c_str());
     }
 
     TPZManVector bcids(4, -1);
-    gmeshOriginal = Tools::CreateGeoMesh(2, bcids);
+    gmeshOriginal = Tools::CreateGeoMesh(3, bcids);
     config.materialids.insert(1);
     config.bcmaterialids.insert(-1);
 
@@ -57,7 +65,8 @@ int main() {
 
         // Estimate error and run adaptive process
         {
-            TPZHDivErrorEstimator HDivEstimate(*mixedCompMesh, postProcessWithHDiv);
+            bool postProcWithHDiv = false;
+            TPZHDivErrorEstimator HDivEstimate(*mixedCompMesh, postProcWithHDiv);
             HDivEstimate.SetAnalyticSolution(config.exact);
             HDivEstimate.SetAdaptivityStep(iStep);
             HDivEstimate.PotentialReconstruction();
@@ -75,5 +84,71 @@ int main() {
             Tools::PrintErrors(fileTXT, config, errorvec);
         }
     }
-    return 0;
-}
\ No newline at end of file
+}
+
+void RunUniformRefinementSuite(int refinementSteps) {
+
+    // Initializing uniform refinements for reference elements
+    gRefDBase.InitializeUniformRefPattern(EOned);
+    gRefDBase.InitializeUniformRefPattern(EQuadrilateral);
+    gRefDBase.InitializeUniformRefPattern(ETriangle);
+
+    ProblemConfig config;
+
+    config.porder = 1;
+    config.hdivmais = 2;
+
+    config.dimension = 2;
+    config.makepressurecontinuous = true;
+
+    config.exact = new TLaplaceExample1;
+    config.exact.operator*().fExact = TLaplaceExample1::EBoundaryLayer;
+
+    config.dir_name = "HDivAdaptivityEquations";
+    config.problemname = "UnifRef";
+    {
+        std::string command = "mkdir -p " + config.dir_name;
+        system(command.c_str());
+    }
+
+    for (int iStep = 0; iStep < refinementSteps; iStep++) {
+
+        // Creates geometric mesh
+        TPZGeoMesh *gmeshOriginal;
+
+        TPZManVector bcids(4, -1);
+        int nelem = 3 * static_cast(pow(2.0, iStep));
+        gmeshOriginal = Tools::CreateGeoMesh(nelem, bcids);
+        config.materialids.insert(1);
+        config.bcmaterialids.insert(-1);
+
+        Tools::DivideLowerDimensionalElements(gmeshOriginal);
+
+        config.gmesh = new TPZGeoMesh(*gmeshOriginal);
+        config.adaptivityStep = iStep;
+
+        TPZMultiphysicsCompMesh *mixedCompMesh = Tools::CreateMixedMesh(config); // Hdiv x L2
+        mixedCompMesh->InitializeBlock();
+        Tools::SolveMixedProblem(mixedCompMesh, config);
+        config.cmesh = mixedCompMesh;
+
+        {
+            bool postProcessWithHDiv = false;
+            TPZHDivErrorEstimator HDivEstimate(*mixedCompMesh, postProcessWithHDiv);
+            HDivEstimate.SetAnalyticSolution(config.exact);
+            HDivEstimate.SetAdaptivityStep(iStep);
+            HDivEstimate.PotentialReconstruction();
+            TPZManVector elementerrors;
+            TPZManVector errorvec;
+            std::stringstream outVTK;
+            outVTK << config.dir_name << "/" << config.problemname << "-Errors.vtk";
+            auto stringVTK = outVTK.str();
+            HDivEstimate.ComputeErrors(errorvec, elementerrors, stringVTK);
+
+            std::stringstream outTXT;
+            outTXT << config.dir_name << "/" << config.problemname << "-Errors-Step" << config.adaptivityStep << ".txt";
+            std::ofstream fileTXT(outTXT.str());
+            Tools::PrintErrors(fileTXT, config, errorvec);
+        }
+    }
+}

From dccaeb751ee7d0ebcd517c19c565028c1507082e Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 13 Aug 2021 12:12:34 -0300
Subject: [PATCH 116/187] Add Permeability var to material solution

---
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index e4759d9e..bb096ef2 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -389,6 +389,8 @@ int TPZHDivErrorEstimateMaterial::VariableIndex(const std::string &name) const {
     if (name == "PressureFem") return 43;
     if (name == "PressureReconstructed") return 44;
     if (name == "PressureExact") return 45;
+    if (name == "POrder") return 46;
+    if (name == "Permeability") return 47;
     if (name == "PressureErrorExact") return 100;
     if (name == "PressureErrorEstimate") return 101;
     if (name == "EnergyErrorExact") return 102;
@@ -396,7 +398,6 @@ int TPZHDivErrorEstimateMaterial::VariableIndex(const std::string &name) const {
     if (name == "ResidualError") return 104;
     if (name == "PressureEffectivityIndex") return 105;
     if (name == "EnergyEffectivityIndex") return 106;
-    if (name == "POrder") return 46;
 
     return -1;
 }
@@ -505,6 +506,9 @@ TPZHDivErrorEstimateMaterial::Solution(const TPZVec> &da
         case 46://order p
             Solout[0] = datavec[1].p;
             break;
+        case 47: // Permeability
+            Solout[0] = PermTensor(0, 0);
+            break;
 
         default:
             DebugStop();

From 1c1f8e4d9c4421aaa98b17dfcf5a3a64cb7b61c3 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 13 Aug 2021 12:12:53 -0300
Subject: [PATCH 117/187] Include Permeability in post processing

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 5a53e499..c3c2178f 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -144,7 +144,8 @@ void TPZHDivErrorEstimator::PostProcessing(TPZAnalysis &an, std::string &out) {
         vecnames.Push("FluxFem");
         vecnames.Push("FluxReconstructed");
         scalnames.Push("POrder");
-        
+        scalnames.Push("Permeability");
+
         int dim = fPostProcMesh.Reference()->Dimension();
 
         an.DefineGraphMesh(dim, scalnames, vecnames, out);

From 4b7b6647784ccc6e44f831fd2fdec14ea4d98f8f Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 13 Aug 2021 15:41:46 -0300
Subject: [PATCH 118/187] Fix assess of submesh error

---
 Projects/ErrorEstimationMHM/main_Journal.cpp | 84 +++++++-------------
 1 file changed, 29 insertions(+), 55 deletions(-)

diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp
index a1775ab2..e9f06a3d 100644
--- a/Projects/ErrorEstimationMHM/main_Journal.cpp
+++ b/Projects/ErrorEstimationMHM/main_Journal.cpp
@@ -79,10 +79,10 @@ int main() {
     TPZLogger::InitializePZLOG();
     gRefDBase.InitializeAllUniformRefPatterns();
 
-    const std::set nCoarseDiv = {2, 4, 6, 8};
-    const std::set nInternalRef = {0, 1, 2, 3};
-    const std::set kOrder = {1, 2};
-    const std::set nOrder = {1, 2};
+    const std::set nCoarseDiv = {8};
+    const std::set nInternalRef = {0};
+    const std::set kOrder = {1};
+    const std::set nOrder = {2};
 
     //RunSmoothProblemSuite(nCoarseDiv, nInternalRef, kOrder, nOrder);
 
@@ -890,7 +890,7 @@ void RunHighGradientAdaptivityProblem(const int n_steps){
     config.exact = new TLaplaceExample1;
     config.exact.operator*().fExact = TLaplaceExample1::EBoundaryLayer;
     config.problemname = "EBoundaryLayer";
-    config.dir_name = "Adaptivity";
+    config.dir_name = "MHMAdaptivity";
     config.porder = 2;
     config.hdivmais = 3;
     config.materialids.insert(1);
@@ -969,24 +969,23 @@ void MHMAdaptivity(TPZMHMixedMeshControl *mhm, TPZGeoMesh *gmeshToRefine, Proble
     TPZMultiphysicsCompMesh *cmesh = dynamic_cast(mhm->CMesh().operator->());
     if (!cmesh) DebugStop();
 
-    TPZFMatrix &sol = cmesh->Solution();
-    TPZSolutionMatrix &elsol = cmesh->ElementSolution();
+    TPZFMatrix &sol = postProcMesh->ElementSolution();
+    TPZSolutionMatrix &elsol = postProcMesh->ElementSolution();
     int64_t nelem = elsol.Rows();
     int64_t nelem2 = sol.Rows();
 
     //postProcessMesh->ElementSolution().Print("ElSolutionForAdaptivity",std::cout);
 
     // Iterates through element errors to get the maximum value
-    REAL maxError = 0.;
+    STATE maxError = 0.;
     for (int64_t iel = 0; iel < nelem; iel++) {
-        TPZCompEl* cel = cmesh->ElementVec()[iel];
-        if (!cel) continue;
-        if (cel->Dimension() != cmesh->Dimension()) continue;
-        REAL elementError = 0;//elsol(iel, fluxErrorEstimateCol);
 
+        auto * submesh = dynamic_cast(postProcMesh->ElementVec()[iel]);
+        if (!submesh) continue;
 
-        if (elementError > maxError) {
-            maxError = elementError;
+        STATE submeshError = sol(iel, fluxErrorEstimateCol);
+        if (submeshError > maxError) {
+            maxError = submeshError;
         }
     }
 
@@ -996,50 +995,25 @@ void MHMAdaptivity(TPZMHMixedMeshControl *mhm, TPZGeoMesh *gmeshToRefine, Proble
     REAL threshold = 0.2 * maxError;
 
     for (int64_t iel = 0; iel < nelem; iel++) {
-        TPZCompEl* cel = cmesh->ElementVec()[iel];
-        if (!cel) continue;
-        if (cel->Dimension() != cmesh->Dimension()) continue;
-
-        REAL elementError = 0;//elsol(iel, fluxErrorEstimateCol);
-        //prefinement
-        if (elementError > threshold) {
-
-            std::cout << "element error " << elementError << "el " << iel << "\n";
-            TPZGeoEl* gel = cel->Reference();
-            int iel = gel->Id();
-
-            TPZVec sons;
-            TPZGeoEl* gelToRefine = gmeshToRefine->ElementVec()[iel];
-            if (gelToRefine && !gelToRefine->HasSubElement()) {
-                gelToRefine->Divide(sons);
-#ifdef LOG4CXX2
-                int nsides = gelToRefine->NSides();
-                TPZVec loccenter(gelToRefine->Dimension());
-                TPZVec center(3);
-                gelToRefine->CenterPoint(nsides - 1, loccenter);
-
-                gelToRefine->X(loccenter, center);
-                static LoggerPtr logger(Logger::getLogger("HDivErrorEstimator"));
-                if (logger->isDebugEnabled()) {
-                    std::stringstream sout;
-                    sout << "\nCenter coord: = " << center[0] << " " << center[1] << "\n";
-                    sout << "Error = " << elementError << "\n\n";
-                    LOGPZ_DEBUG(logger, sout.str())
-                }
-#endif
-            }
-        } else {
-            std::cout << "como refinar em p? " << "\n";
-//            TPZInterpolationSpace *sp = dynamic_cast(cel);
-//            if(!sp) continue;
-//            int level = sp->Reference()->Level();
-//            int ordem = config.porder + (config.adaptivityStep -1 ) + (level);
-//            std::cout<<"level "<< level<<" ordem "<PRefine(ordem);
 
+        auto * submesh = dynamic_cast(postProcMesh->ElementVec()[iel]);
+        if (!submesh) continue;
+
+        STATE submeshError = sol(iel, fluxErrorEstimateCol);
+        if (submeshError > threshold) {
+            std::cout << "Adapt me, my error is " << submeshError << " !!!\n";
         }
     }
-    Tools::DivideLowerDimensionalElements(gmeshToRefine);
+    //std::cout << "element error " << elementError << "el " << iel << "\n";
+    //TPZGeoEl *gel = cel->Reference();
+    //int iel = gel->Id();
+
+    //TPZVec sons;
+    //TPZGeoEl *gelToRefine = gmeshToRefine->ElementVec()[iel];
+    //if (gelToRefine && !gelToRefine->HasSubElement()) {
+    //    gelToRefine->Divide(sons);
+    //}
+    //Tools::DivideLowerDimensionalElements(gmeshToRefine);
 }
 
 void EstimateError(ProblemConfig &config, TPZMHMixedMeshControl *mhm, TPZMHMHDivErrorEstimator& estimator) {

From b9ffbcf49b2127cf0452a9d774852a03fdd0a52f Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Tue, 24 Aug 2021 17:26:44 -0300
Subject: [PATCH 119/187] Implement MHM Adaptivity example

---
 Projects/ErrorEstimationMHM/main_Journal.cpp | 153 ++++++++++---------
 1 file changed, 83 insertions(+), 70 deletions(-)

diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp
index e9f06a3d..c45f2a23 100644
--- a/Projects/ErrorEstimationMHM/main_Journal.cpp
+++ b/Projects/ErrorEstimationMHM/main_Journal.cpp
@@ -49,8 +49,12 @@ TPZGeoMesh *CreateQuadGeoMesh(int nCoarseDiv, int nInternalRef);
 TPZGeoMesh *CreateLShapeGeoMesh(int nCoarseRef, int nInternalRef, TPZStack &mhmIndexes);
 
 void InsertMaterialsInMHMMesh(TPZMHMixedMeshControl &control, const ProblemConfig &config);
-void CreateMHMCompMesh(TPZMHMixedMeshControl *mhm, const ProblemConfig &config, int nInternalRef,
-                       bool definePartitionByCoarseIndex, TPZManVector& mhmIndexes);
+void CreateMHMCompMesh(TPZMHMixedMeshControl *mhm, const ProblemConfig &config, bool definePartitionByCoarseIndex,
+                       TPZManVector &mhmIndexes);
+
+void CreateMHMCompMesh(TPZMHMixedMeshControl *mhm, const ProblemConfig &config, bool definePartitionByCoarseIndex,
+                       TPZManVector &mhmIndexes, const std::set& skelsToDivide);
+
 void CreateMHMCompMeshHeteroPerm(TPZMHMixedMeshControl *mhm, const ProblemConfig &config, int nInternalRef,
                                  bool definePartitionByCoarseIndex, TPZManVector& mhmIndexes);
 
@@ -59,8 +63,8 @@ void SolveMHMProblem(TPZMHMixedMeshControl *mhm, const ProblemConfig &config);
 void EstimateError(ProblemConfig &config, TPZMHMixedMeshControl *mhm);
 void EstimateError(ProblemConfig &config, TPZMHMixedMeshControl *mhm, TPZMHMHDivErrorEstimator &estimator);
 
-void MHMAdaptivity(TPZMHMixedMeshControl *mhm, TPZGeoMesh *gmeshToRefine, ProblemConfig &config,
-                   TPZCompMesh *postProcMesh);
+void MHMAdaptivity(TPZMHMixedMeshControl *mhm, ProblemConfig &config, TPZCompMesh *postProcMesh,
+                   std::set &skelsToRefine);
 
 void CreateMHMCompMeshPermFunction(TPZMHMixedMeshControl &mhm);
 void PeriodicPermeabilityFunction(const TPZVec &coord, TPZVec &res, TPZFMatrix &res_mat);
@@ -88,7 +92,7 @@ int main() {
 
     //RunInnerSingularityProblemSuite(nCoarseDiv, nInternalRef, kOrder, nOrder);
 
-    RunHighGradientAdaptivityProblem(5);
+    RunHighGradientAdaptivityProblem(2);
 
     //RunNonConvexProblem();
     //std::ofstream out_latex("LatexGraphs.txt", std::ios::trunc);
@@ -151,7 +155,7 @@ void RunSmoothProblem(const int nCoarseDiv, const int nInternalRef, const int k,
     TPZManVector coarseIndexes;
     ComputeCoarseIndices(config.gmesh, coarseIndexes);
     bool definePartitionByCoarseIndexes = true;
-    CreateMHMCompMesh(mhm, config, nInternalRef, definePartitionByCoarseIndexes, coarseIndexes);
+    CreateMHMCompMesh(mhm, config, definePartitionByCoarseIndexes, coarseIndexes);
 
     SolveMHMProblem(mhm, config);
     TPZCompMesh *cmesh = nullptr;
@@ -188,7 +192,7 @@ void RunHighGradientProblem(const int nCoarseDiv, const int nInternalRef) {
     TPZManVector coarseIndexes;
     ComputeCoarseIndices(config.gmesh, coarseIndexes);
     bool definePartitionByCoarseIndexes = true;
-    CreateMHMCompMesh(mhm, config, nInternalRef, definePartitionByCoarseIndexes, coarseIndexes);
+    CreateMHMCompMesh(mhm, config, definePartitionByCoarseIndexes, coarseIndexes);
 
     SolveMHMProblem(mhm, config);
     EstimateError(config, mhm);
@@ -225,7 +229,7 @@ void RunNonConvexProblem() {
 
     auto *mhm = new TPZMHMixedMeshControl(config.gmesh);
     bool definePartitionByCoarseIndexes = false;
-    CreateMHMCompMesh(mhm, config, nInternalRef, definePartitionByCoarseIndexes, coarseIndexes);
+    CreateMHMCompMesh(mhm, config, definePartitionByCoarseIndexes, coarseIndexes);
 
     SolveMHMProblem(mhm, config);
     TPZCompMesh *cmesh = nullptr;
@@ -460,7 +464,37 @@ TPZGeoMesh *CreateLShapeGeoMesh(int nCoarseRef, int nInternalRef, TPZStack &mhmIndexes, const std::set &skelsToDivide) {
+
+    if (definePartitionByCoarseIndex) {
+        mhm->DefinePartitionbyCoarseIndices(mhmIndexes);
+    } else {
+        mhm->DefinePartition(mhmIndexes);
+    }
+
+    // Indicate material indices to the MHM control structure
+    mhm->fMaterialIds = config.materialids;
+    mhm->fMaterialBCIds = config.bcmaterialids;
+
+    // Insert the material objects in the multiphysics mesh
+    InsertMaterialsInMHMMesh(*mhm, config);
+
+    // General approximation order settings
+    mhm->SetInternalPOrder(config.porder);
+    mhm->SetSkeletonPOrder(config.porder);
+    mhm->SetHdivmaismaisPOrder(config.hdivmais);
+
+    // Refine skeleton elements
+    for (auto skelid : skelsToDivide) mhm->DivideSkeletonElement(skelid);
+
+    mhm->DivideBoundarySkeletonElements();
+    // Creates MHM mesh
+    bool substructure = true;
+    mhm->BuildComputationalMesh(substructure);
+}
+
+void CreateMHMCompMesh(TPZMHMixedMeshControl *mhm, const ProblemConfig &config,
                        bool definePartitionByCoarseIndex, TPZManVector& mhmIndexes) {
 
     if (definePartitionByCoarseIndex) {
@@ -897,8 +931,8 @@ void RunHighGradientAdaptivityProblem(const int n_steps){
     config.bcmaterialids.insert(-1);
     config.makepressurecontinuous = true;
 
-    int nCoarseRef = 5;
-    int nInternalRef = 1;
+    int nCoarseRef = 3;
+    int nInternalRef = 2;
 
     config.ndivisions = nCoarseRef;
     config.gmesh = CreateQuadGeoMesh(nCoarseRef, nInternalRef);
@@ -912,56 +946,41 @@ void RunHighGradientAdaptivityProblem(const int n_steps){
         TPZVTKGeoMesh::PrintGMeshVTK(config.gmesh, file);
     }
 
-    auto *mhm = new TPZMHMixedMeshControl(config.gmesh);
-    TPZManVector coarseIndexes;
-    ComputeCoarseIndices(config.gmesh, coarseIndexes);
-    bool definePartitionByCoarseIndexes = true;
-    CreateMHMCompMesh(mhm, config, nInternalRef, definePartitionByCoarseIndexes, coarseIndexes);
-
-    {
-        std::string fileName = config.dir_name + "/" + config.problemname + "GeoMeshAfterPartition.vtk";
-        std::ofstream file(fileName);
-        TPZVTKGeoMesh::PrintGMeshVTK(config.gmesh, file);
-    }
-
-    SolveMHMProblem(mhm, config);
-
-    bool postProcWithHDiv = false;
-    TPZMultiphysicsCompMesh *originalMesh = dynamic_cast(mhm->CMesh().operator->());
-    if (!originalMesh) DebugStop();
-    TPZMHMHDivErrorEstimator estimator(*originalMesh, mhm, postProcWithHDiv);
-    EstimateError(config, mhm, estimator);
+    std::set skelsToRefine;
+    for (int i = 0; i < n_steps; i++) {
 
-    auto *postprocmesh = estimator.PostProcMesh();
-    if (!postprocmesh) DebugStop();
+        auto *mhm = new TPZMHMixedMeshControl(config.gmesh);
+        TPZManVector coarseIndexes;
+        ComputeCoarseIndices(config.gmesh, coarseIndexes);
+        bool definePartitionByCoarseIndexes = true;
+        CreateMHMCompMesh(mhm, config, definePartitionByCoarseIndexes, coarseIndexes, skelsToRefine);
 
-    const auto sol = postprocmesh->ElementSolution();
-    int64_t nelem = sol.Rows();
-
-    MHMAdaptivity(mhm, config.gmesh, config, postprocmesh);
-    //for (int iSteps = 0; iSteps < n_steps; iSteps++) {
+        {
+            std::string fileName = config.dir_name + "/" + config.problemname + "GeoMeshAfterPartition.vtk";
+            std::ofstream file(fileName);
+            TPZVTKGeoMesh::PrintGMeshVTK(config.gmesh, file);
+        }
 
-    //    {
-    //        std::string fileName = config.dir_name + "/" + config.problemname + "GeoMeshAdapt.vtk";
-    //        std::ofstream file(fileName);
-    //        TPZVTKGeoMesh::PrintGMeshVTK(config.gmesh, file);
-    //    }
+        SolveMHMProblem(mhm, config);
 
-    //    config.adaptivityStep = iSteps;
+        bool postProcWithHDiv = false;
+        TPZMultiphysicsCompMesh *originalMesh = dynamic_cast(mhm->CMesh().operator->());
+        if (!originalMesh) DebugStop();
+        TPZMHMHDivErrorEstimator estimator(*originalMesh, mhm, postProcWithHDiv);
+        EstimateError(config, mhm, estimator);
 
-    //    mhm = new TPZMHMixedMeshControl(config.gmesh);
-    //    ComputeCoarseIndices(config.gmesh, coarseIndexes);
-    //    definePartitionByCoarseIndexes = true;
-    //    CreateMHMCompMesh(mhm, config, nInternalRef, definePartitionByCoarseIndexes, coarseIndexes);
+        auto *postprocmesh = estimator.PostProcMesh();
+        if (!postprocmesh) DebugStop();
 
-    //    SolveMHMProblem(mhm, config);
-    //    EstimateError(config, mhm);
+        const auto sol = postprocmesh->ElementSolution();
+        int64_t nelem = sol.Rows();
 
-    //}
+        MHMAdaptivity(mhm, config, postprocmesh, skelsToRefine);
+    }
 }
 
-void MHMAdaptivity(TPZMHMixedMeshControl *mhm, TPZGeoMesh *gmeshToRefine, ProblemConfig &config,
-                   TPZCompMesh *postProcMesh) {
+void MHMAdaptivity(TPZMHMixedMeshControl *mhm, ProblemConfig &config, TPZCompMesh *postProcMesh,
+                   std::set &skelsToRefine) {
 
     // Column of the flux error estimate on the element solution matrix
     const int fluxErrorEstimateCol = 3;
@@ -972,14 +991,10 @@ void MHMAdaptivity(TPZMHMixedMeshControl *mhm, TPZGeoMesh *gmeshToRefine, Proble
     TPZFMatrix &sol = postProcMesh->ElementSolution();
     TPZSolutionMatrix &elsol = postProcMesh->ElementSolution();
     int64_t nelem = elsol.Rows();
-    int64_t nelem2 = sol.Rows();
-
-    //postProcessMesh->ElementSolution().Print("ElSolutionForAdaptivity",std::cout);
 
     // Iterates through element errors to get the maximum value
     STATE maxError = 0.;
     for (int64_t iel = 0; iel < nelem; iel++) {
-
         auto * submesh = dynamic_cast(postProcMesh->ElementVec()[iel]);
         if (!submesh) continue;
 
@@ -989,31 +1004,29 @@ void MHMAdaptivity(TPZMHMixedMeshControl *mhm, TPZGeoMesh *gmeshToRefine, Proble
         }
     }
 
-    std::cout << "max error " << maxError << "\n";
+    std::cout << "Max error: " << maxError << "\n";
 
     // Refines elements which error are bigger than 30% of the maximum error
     REAL threshold = 0.2 * maxError;
-
     for (int64_t iel = 0; iel < nelem; iel++) {
-
         auto * submesh = dynamic_cast(postProcMesh->ElementVec()[iel]);
         if (!submesh) continue;
 
         STATE submeshError = sol(iel, fluxErrorEstimateCol);
         if (submeshError > threshold) {
-            std::cout << "Adapt me, my error is " << submeshError << " !!!\n";
+            std::cout << "Refine me, my error is " << submeshError << "!\n";
+            TPZGeoEl * gel = submesh->Element(0)->Reference();
+            const auto geoToMHM = mhm->GetGeoToMHMDomain();
+            const auto submesh_id = geoToMHM[gel->Index()];
+            const auto interfaces = mhm->GetInterfaces();
+            for (auto interface : interfaces) {
+                if (interface.second.first == submesh_id || interface.second.second == submesh_id) {
+                    skelsToRefine.insert(interface.first);
+                    std::cout << "Interface to refine: " << interface.first << "\n";
+                }
+            }
         }
     }
-    //std::cout << "element error " << elementError << "el " << iel << "\n";
-    //TPZGeoEl *gel = cel->Reference();
-    //int iel = gel->Id();
-
-    //TPZVec sons;
-    //TPZGeoEl *gelToRefine = gmeshToRefine->ElementVec()[iel];
-    //if (gelToRefine && !gelToRefine->HasSubElement()) {
-    //    gelToRefine->Divide(sons);
-    //}
-    //Tools::DivideLowerDimensionalElements(gmeshToRefine);
 }
 
 void EstimateError(ProblemConfig &config, TPZMHMixedMeshControl *mhm, TPZMHMHDivErrorEstimator& estimator) {

From 30cb936db393088fafdfdb1255aac256149e5ea2 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Tue, 24 Aug 2021 21:54:39 -0300
Subject: [PATCH 120/187] Fix order of skeletons to be refined

---
 Projects/ErrorEstimationMHM/main_Journal.cpp | 59 +++++++++++---------
 1 file changed, 32 insertions(+), 27 deletions(-)

diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp
index c45f2a23..e74c02d7 100644
--- a/Projects/ErrorEstimationMHM/main_Journal.cpp
+++ b/Projects/ErrorEstimationMHM/main_Journal.cpp
@@ -6,9 +6,9 @@
 #include 
 #include 
 //#include 
+#include 
 #include 
 #include 
-#include 
 
 struct ErrorResult {
     ErrorResult(const std::string &s, const int nIntRef, const int nCoarseDiv, const int kOrder, const int nOrder,
@@ -35,7 +35,7 @@ struct ErrorResult {
 std::vector result_vec;
 
 const int porder = 1;
-const int hdivmais = 3;
+const int hdivmais = 4;
 std::string dir_name = "Journal_k" + std::to_string(porder) + "n" + std::to_string(hdivmais);
 
 void RunSmoothProblem(int nCoarseDiv, int nInternalRef, int k, int n);
@@ -53,7 +53,7 @@ void CreateMHMCompMesh(TPZMHMixedMeshControl *mhm, const ProblemConfig &config,
                        TPZManVector &mhmIndexes);
 
 void CreateMHMCompMesh(TPZMHMixedMeshControl *mhm, const ProblemConfig &config, bool definePartitionByCoarseIndex,
-                       TPZManVector &mhmIndexes, const std::set& skelsToDivide);
+                       TPZManVector &mhmIndexes, const std::vector& skelsToDivide);
 
 void CreateMHMCompMeshHeteroPerm(TPZMHMixedMeshControl *mhm, const ProblemConfig &config, int nInternalRef,
                                  bool definePartitionByCoarseIndex, TPZManVector& mhmIndexes);
@@ -64,7 +64,7 @@ void EstimateError(ProblemConfig &config, TPZMHMixedMeshControl *mhm);
 void EstimateError(ProblemConfig &config, TPZMHMixedMeshControl *mhm, TPZMHMHDivErrorEstimator &estimator);
 
 void MHMAdaptivity(TPZMHMixedMeshControl *mhm, ProblemConfig &config, TPZCompMesh *postProcMesh,
-                   std::set &skelsToRefine);
+                   std::vector &skelsToRefine);
 
 void CreateMHMCompMeshPermFunction(TPZMHMixedMeshControl &mhm);
 void PeriodicPermeabilityFunction(const TPZVec &coord, TPZVec &res, TPZFMatrix &res_mat);
@@ -92,7 +92,7 @@ int main() {
 
     //RunInnerSingularityProblemSuite(nCoarseDiv, nInternalRef, kOrder, nOrder);
 
-    RunHighGradientAdaptivityProblem(2);
+    RunHighGradientAdaptivityProblem(4);
 
     //RunNonConvexProblem();
     //std::ofstream out_latex("LatexGraphs.txt", std::ios::trunc);
@@ -465,7 +465,7 @@ TPZGeoMesh *CreateLShapeGeoMesh(int nCoarseRef, int nInternalRef, TPZStack &mhmIndexes, const std::set &skelsToDivide) {
+                       TPZManVector &mhmIndexes, const std::vector &skelsToDivide) {
 
     if (definePartitionByCoarseIndex) {
         mhm->DefinePartitionbyCoarseIndices(mhmIndexes);
@@ -486,7 +486,9 @@ void CreateMHMCompMesh(TPZMHMixedMeshControl *mhm, const ProblemConfig &config,
     mhm->SetHdivmaismaisPOrder(config.hdivmais);
 
     // Refine skeleton elements
-    for (auto skelid : skelsToDivide) mhm->DivideSkeletonElement(skelid);
+    for (auto skelid : skelsToDivide) {
+        mhm->DivideSkeletonElement(skelid);
+    }
 
     mhm->DivideBoundarySkeletonElements();
     // Creates MHM mesh
@@ -925,30 +927,30 @@ void RunHighGradientAdaptivityProblem(const int n_steps){
     config.exact.operator*().fExact = TLaplaceExample1::EBoundaryLayer;
     config.problemname = "EBoundaryLayer";
     config.dir_name = "MHMAdaptivity";
-    config.porder = 2;
-    config.hdivmais = 3;
+    config.porder = 1;
+    config.hdivmais = 2;
     config.materialids.insert(1);
     config.bcmaterialids.insert(-1);
     config.makepressurecontinuous = true;
 
     int nCoarseRef = 3;
-    int nInternalRef = 2;
+    int nInternalRef = 4;
 
     config.ndivisions = nCoarseRef;
-    config.gmesh = CreateQuadGeoMesh(nCoarseRef, nInternalRef);
 
     std::string command = "mkdir -p " + config.dir_name;
     system(command.c_str());
 
-    {
-        std::string fileName = config.dir_name + "/" + config.problemname + "GeoMesh.vtk";
-        std::ofstream file(fileName);
-        TPZVTKGeoMesh::PrintGMeshVTK(config.gmesh, file);
-    }
-
-    std::set skelsToRefine;
+    std::vector skelsToRefine;
     for (int i = 0; i < n_steps; i++) {
 
+        config.gmesh = CreateQuadGeoMesh(nCoarseRef, nInternalRef);
+        {
+            std::string fileName = config.dir_name + "/" + config.problemname + "GeoMesh.vtk";
+            std::ofstream file(fileName);
+            TPZVTKGeoMesh::PrintGMeshVTK(config.gmesh, file);
+        }
+
         auto *mhm = new TPZMHMixedMeshControl(config.gmesh);
         TPZManVector coarseIndexes;
         ComputeCoarseIndices(config.gmesh, coarseIndexes);
@@ -967,20 +969,18 @@ void RunHighGradientAdaptivityProblem(const int n_steps){
         TPZMultiphysicsCompMesh *originalMesh = dynamic_cast(mhm->CMesh().operator->());
         if (!originalMesh) DebugStop();
         TPZMHMHDivErrorEstimator estimator(*originalMesh, mhm, postProcWithHDiv);
+        estimator.SetAdaptivityStep(i);
         EstimateError(config, mhm, estimator);
 
         auto *postprocmesh = estimator.PostProcMesh();
         if (!postprocmesh) DebugStop();
 
-        const auto sol = postprocmesh->ElementSolution();
-        int64_t nelem = sol.Rows();
-
         MHMAdaptivity(mhm, config, postprocmesh, skelsToRefine);
     }
 }
 
 void MHMAdaptivity(TPZMHMixedMeshControl *mhm, ProblemConfig &config, TPZCompMesh *postProcMesh,
-                   std::set &skelsToRefine) {
+                   std::vector &skelsToRefine) {
 
     // Column of the flux error estimate on the element solution matrix
     const int fluxErrorEstimateCol = 3;
@@ -1008,25 +1008,30 @@ void MHMAdaptivity(TPZMHMixedMeshControl *mhm, ProblemConfig &config, TPZCompMes
 
     // Refines elements which error are bigger than 30% of the maximum error
     REAL threshold = 0.2 * maxError;
+    const auto geoToMHM = mhm->GetGeoToMHMDomain();
+    const auto interfaces = mhm->GetInterfaces();
+
+    std::set interfacesToRefine;
     for (int64_t iel = 0; iel < nelem; iel++) {
         auto * submesh = dynamic_cast(postProcMesh->ElementVec()[iel]);
         if (!submesh) continue;
 
         STATE submeshError = sol(iel, fluxErrorEstimateCol);
         if (submeshError > threshold) {
-            std::cout << "Refine me, my error is " << submeshError << "!\n";
             TPZGeoEl * gel = submesh->Element(0)->Reference();
-            const auto geoToMHM = mhm->GetGeoToMHMDomain();
             const auto submesh_id = geoToMHM[gel->Index()];
-            const auto interfaces = mhm->GetInterfaces();
+            // std::cout << "Refining submesh " << submesh_id << " which error is " << submeshError << ".\n";
             for (auto interface : interfaces) {
                 if (interface.second.first == submesh_id || interface.second.second == submesh_id) {
-                    skelsToRefine.insert(interface.first);
-                    std::cout << "Interface to refine: " << interface.first << "\n";
+                    interfacesToRefine.insert(interface.first);
                 }
             }
         }
     }
+
+    for (auto it : interfacesToRefine) {
+        skelsToRefine.push_back(it);
+    }
 }
 
 void EstimateError(ProblemConfig &config, TPZMHMixedMeshControl *mhm, TPZMHMHDivErrorEstimator& estimator) {

From aedff2149f75f521cb9bec4b2751d3b90ef42c4c Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 25 Aug 2021 13:10:05 -0300
Subject: [PATCH 121/187] Add adaptivity step to gmesh to be printed

---
 Projects/ErrorEstimationMHM/main_Journal.cpp | 18 +++++++-----------
 1 file changed, 7 insertions(+), 11 deletions(-)

diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp
index e74c02d7..a6dff904 100644
--- a/Projects/ErrorEstimationMHM/main_Journal.cpp
+++ b/Projects/ErrorEstimationMHM/main_Journal.cpp
@@ -924,8 +924,8 @@ void RunHighGradientAdaptivityProblem(const int n_steps){
     ProblemConfig config;
     config.dimension = 2;
     config.exact = new TLaplaceExample1;
-    config.exact.operator*().fExact = TLaplaceExample1::EBoundaryLayer;
-    config.problemname = "EBoundaryLayer";
+    config.exact.operator*().fExact = TLaplaceExample1::EArcTan;
+    config.problemname = "EArcTan";
     config.dir_name = "MHMAdaptivity";
     config.porder = 1;
     config.hdivmais = 2;
@@ -933,7 +933,7 @@ void RunHighGradientAdaptivityProblem(const int n_steps){
     config.bcmaterialids.insert(-1);
     config.makepressurecontinuous = true;
 
-    int nCoarseRef = 3;
+    int nCoarseRef = 4;
     int nInternalRef = 4;
 
     config.ndivisions = nCoarseRef;
@@ -945,11 +945,6 @@ void RunHighGradientAdaptivityProblem(const int n_steps){
     for (int i = 0; i < n_steps; i++) {
 
         config.gmesh = CreateQuadGeoMesh(nCoarseRef, nInternalRef);
-        {
-            std::string fileName = config.dir_name + "/" + config.problemname + "GeoMesh.vtk";
-            std::ofstream file(fileName);
-            TPZVTKGeoMesh::PrintGMeshVTK(config.gmesh, file);
-        }
 
         auto *mhm = new TPZMHMixedMeshControl(config.gmesh);
         TPZManVector coarseIndexes;
@@ -958,7 +953,8 @@ void RunHighGradientAdaptivityProblem(const int n_steps){
         CreateMHMCompMesh(mhm, config, definePartitionByCoarseIndexes, coarseIndexes, skelsToRefine);
 
         {
-            std::string fileName = config.dir_name + "/" + config.problemname + "GeoMeshAfterPartition.vtk";
+            std::string fileName =
+                config.dir_name + "/" + config.problemname + "GMesh" + std::to_string(i) + ".vtk";
             std::ofstream file(fileName);
             TPZVTKGeoMesh::PrintGMeshVTK(config.gmesh, file);
         }
@@ -1007,7 +1003,7 @@ void MHMAdaptivity(TPZMHMixedMeshControl *mhm, ProblemConfig &config, TPZCompMes
     std::cout << "Max error: " << maxError << "\n";
 
     // Refines elements which error are bigger than 30% of the maximum error
-    REAL threshold = 0.2 * maxError;
+    REAL threshold = 0.5 * maxError;
     const auto geoToMHM = mhm->GetGeoToMHMDomain();
     const auto interfaces = mhm->GetInterfaces();
 
@@ -1020,7 +1016,7 @@ void MHMAdaptivity(TPZMHMixedMeshControl *mhm, ProblemConfig &config, TPZCompMes
         if (submeshError > threshold) {
             TPZGeoEl * gel = submesh->Element(0)->Reference();
             const auto submesh_id = geoToMHM[gel->Index()];
-            // std::cout << "Refining submesh " << submesh_id << " which error is " << submeshError << ".\n";
+             std::cout << "Refining submesh " << submesh_id << " which error is " << submeshError << ".\n";
             for (auto interface : interfaces) {
                 if (interface.second.first == submesh_id || interface.second.second == submesh_id) {
                     interfacesToRefine.insert(interface.first);

From 4d8e18f9ddcf57383a2d9eb5f32bbaa08b03b318 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 26 Aug 2021 16:20:03 -0300
Subject: [PATCH 122/187] Start implementation of reference solution feature

---
 .../Material/TPZHDivErrorEstimateMaterial.h   |   7 +
 ErrorEstimation/TPZMHMHDivErrorEstimator.h    |   6 +
 Projects/ErrorEstimationMHM/CMakeLists.txt    |   3 +
 .../main_RefSolValidation.cpp                 | 384 ++++++++++++++++++
 4 files changed, 400 insertions(+)
 create mode 100644 Projects/ErrorEstimationMHM/main_RefSolValidation.cpp

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
index 7814e1de..bf496938 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
@@ -69,6 +69,13 @@ class TPZHDivErrorEstimateMaterial: public virtual TPZMatBase> &datavec);
+
+    void SetReferenceSolution(bool hasRefSol) {
+        fHasReferenceSolution = hasRefSol;
+    }
+
+private:
+    bool fHasReferenceSolution = false;
 };
 
 #endif /* TPZHDivErrorEstimateMaterial_hpp */
diff --git a/ErrorEstimation/TPZMHMHDivErrorEstimator.h b/ErrorEstimation/TPZMHMHDivErrorEstimator.h
index cb286316..4e55646a 100644
--- a/ErrorEstimation/TPZMHMHDivErrorEstimator.h
+++ b/ErrorEstimation/TPZMHMHDivErrorEstimator.h
@@ -32,12 +32,18 @@ class TPZMHMHDivErrorEstimator : public TPZHDivErrorEstimator {
 
     virtual ~TPZMHMHDivErrorEstimator() = default;
 
+    void SetReferenceSolution(bool hasRefSol) {
+        fHasReferenceSolution = hasRefSol;
+    }
+
 private:
     // material id of the dim-1 multiphysic inerface and wrap elements
     // (only used for HDiv reconstruction)
     int fMultiPhysicsInterfaceMatId = 0;
     int fHDivWrapMatId = 0;
 
+    bool fHasReferenceSolution = false;
+
     /// a pointer to the datastructure used to generate the MHM mesh
     TPZMHMixedMeshControl *fMHM = nullptr;
     // a method for generating the HDiv mesh
diff --git a/Projects/ErrorEstimationMHM/CMakeLists.txt b/Projects/ErrorEstimationMHM/CMakeLists.txt
index c8db4df8..c01e420b 100644
--- a/Projects/ErrorEstimationMHM/CMakeLists.txt
+++ b/Projects/ErrorEstimationMHM/CMakeLists.txt
@@ -4,3 +4,6 @@ target_link_libraries(MHM_Estimation Tools ErrorEstimationLib)
 
 add_executable(MHM_Journal main_Journal.cpp)
 target_link_libraries(MHM_Journal Tools ErrorEstimationLib)
+
+add_executable(MHM_RefSol main_RefSolValidation.cpp)
+target_link_libraries(MHM_RefSol Tools ErrorEstimationLib)
diff --git a/Projects/ErrorEstimationMHM/main_RefSolValidation.cpp b/Projects/ErrorEstimationMHM/main_RefSolValidation.cpp
new file mode 100644
index 00000000..5d1c7226
--- /dev/null
+++ b/Projects/ErrorEstimationMHM/main_RefSolValidation.cpp
@@ -0,0 +1,384 @@
+//
+// Created by Gustavo Batistela on 25/08/21.
+//
+#include "pzgmesh.h"
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+void RunReferenceSolutionValidationProblem();
+
+TPZGeoMesh *CreateQuadGeoMesh(int nCoarseDiv, int nInternalRef);
+
+void InsertMaterialsInMHMMesh(TPZMHMixedMeshControl &control, const ProblemConfig &config);
+void CreateMHMCompMesh(TPZMHMixedMeshControl *mhm, const ProblemConfig &config, bool definePartitionByCoarseIndex,
+                       TPZManVector &mhmIndexes);
+
+void CreateMHMCompMesh(TPZMHMixedMeshControl *mhm, const ProblemConfig &config, bool definePartitionByCoarseIndex,
+                       TPZManVector &mhmIndexes, const std::vector &skelsToDivide);
+
+void CreateMHMCompMeshHeteroPerm(TPZMHMixedMeshControl *mhm, const ProblemConfig &config, int nInternalRef,
+                                 bool definePartitionByCoarseIndex, TPZManVector &mhmIndexes);
+
+void SolveMHMProblem(TPZMHMixedMeshControl *mhm, const ProblemConfig &config);
+
+void EstimateError(ProblemConfig &config, TPZMHMixedMeshControl *mhm);
+
+int main() {
+    TPZLogger::InitializePZLOG();
+    gRefDBase.InitializeAllUniformRefPatterns();
+
+    RunReferenceSolutionValidationProblem();
+
+    return 0;
+}
+
+TPZGeoMesh *CreateQuadGeoMesh(int nCoarseDiv, int nInternalRef) {
+
+    TPZManVector bcIDs(4, -1);
+    TPZGeoMesh *gmesh = Tools::CreateGeoMesh(nCoarseDiv, bcIDs);
+    gmesh->SetDimension(2);
+
+    Tools::UniformRefinement(nInternalRef, gmesh);
+    Tools::DivideLowerDimensionalElements(gmesh);
+
+    return gmesh;
+}
+
+TPZGeoMesh *CreateCubeGeoMesh(int nCoarseRef, int nInternalRef, TPZStack &coarseIndexes) {
+
+    auto *gmesh = new TPZGeoMesh();
+    gmesh->SetDimension(3);
+    int matID = 1;
+
+    // Creates matrix with node coordinates
+    const int NodeNumber = 8;
+    REAL coordinates[NodeNumber][3] = {{0., 0., 0.}, {1., 0., 0.}, {1., 1., 0.}, {0., 1., 0.},
+                                       {0., 0., 1.}, {1., 0., 1.}, {1., 1., 1.}, {0., 1., 1.}};
+
+    // Inserts coordinates in the TPZGeoMesh object
+    for (int i = 0; i < NodeNumber; i++) {
+        int64_t nodeID = gmesh->NodeVec().AllocateNewElement();
+
+        TPZVec nodeCoord(3);
+        nodeCoord[0] = coordinates[i][0];
+        nodeCoord[1] = coordinates[i][1];
+        nodeCoord[2] = coordinates[i][2];
+
+        gmesh->NodeVec()[nodeID] = TPZGeoNode(i, nodeCoord, *gmesh);
+    }
+
+    // Creates cube element
+    TPZManVector nodeIDs(8);
+    nodeIDs[0] = 0;
+    nodeIDs[1] = 1;
+    nodeIDs[2] = 2;
+    nodeIDs[3] = 3;
+    nodeIDs[4] = 4;
+    nodeIDs[5] = 5;
+    nodeIDs[6] = 6;
+    nodeIDs[7] = 7;
+    new TPZGeoElRefPattern(nodeIDs, matID, *gmesh);
+
+    // Creates boundary faces
+    nodeIDs.Resize(4);
+    matID = -1;
+    nodeIDs[0] = 0;
+    nodeIDs[1] = 1;
+    nodeIDs[2] = 2;
+    nodeIDs[3] = 3;
+    new TPZGeoElRefPattern(nodeIDs, matID, *gmesh);
+    nodeIDs[0] = 4;
+    nodeIDs[1] = 5;
+    nodeIDs[2] = 6;
+    nodeIDs[3] = 7;
+    new TPZGeoElRefPattern(nodeIDs, matID, *gmesh);
+
+    for (int i = 0; i < 4; i++) {
+        nodeIDs[0] = (0 + i) % 4;
+        nodeIDs[1] = (1 + i) % 4;
+        nodeIDs[2] = nodeIDs[1] + 4;
+        nodeIDs[3] = nodeIDs[0] + 4;
+        new TPZGeoElRefPattern(nodeIDs, matID, *gmesh);
+    }
+
+    gmesh->BuildConnectivity();
+
+    Tools::UniformRefinement(nCoarseRef, gmesh);
+    Tools::DivideLowerDimensionalElements(gmesh);
+
+    int64_t nElem = gmesh->NElements();
+
+    coarseIndexes.clear();
+    for (int64_t i = 0; i < nElem; i++) {
+        TPZGeoEl *gel = gmesh->Element(i);
+        if (gel->Dimension() != gmesh->Dimension() || gel->NSubElements() > 0) continue;
+        coarseIndexes.Push(i);
+    }
+
+    Tools::UniformRefinement(nInternalRef, gmesh);
+
+    return gmesh;
+}
+
+TPZGeoMesh *CreateLShapeGeoMesh(int nCoarseRef, int nInternalRef, TPZStack &mhmIndexes) {
+
+    TPZVec bcIDs(8, -1);
+    TPZGeoMesh *gmesh = Tools::CreateQuadLShapeMesh(bcIDs);
+    gmesh->SetDimension(2);
+    gmesh->BuildConnectivity();
+
+    Tools::UniformRefinement(nCoarseRef, gmesh);
+    Tools::DivideLowerDimensionalElements(gmesh);
+
+    int64_t nElem = gmesh->NElements();
+    for (int64_t i = 0; i < nElem; i++) {
+        TPZGeoEl *gel = gmesh->Element(i);
+        if (gel->Dimension() != gmesh->Dimension() || gel->NSubElements() > 0) continue;
+        mhmIndexes.Push(i);
+    }
+
+    Tools::UniformRefinement(nInternalRef, gmesh);
+    Tools::DivideLowerDimensionalElements(gmesh);
+
+    for (int64_t i = 0; i < mhmIndexes.size(); i++) {
+        std::cout << mhmIndexes[i] << '\n';
+    }
+    std::cout << '\n';
+
+    return gmesh;
+}
+
+void CreateMHMCompMesh(TPZMHMixedMeshControl *mhm, const ProblemConfig &config, bool definePartitionByCoarseIndex,
+                       TPZManVector &mhmIndexes, const std::vector &skelsToDivide) {
+
+    if (definePartitionByCoarseIndex) {
+        mhm->DefinePartitionbyCoarseIndices(mhmIndexes);
+    } else {
+        mhm->DefinePartition(mhmIndexes);
+    }
+
+    // Indicate material indices to the MHM control structure
+    mhm->fMaterialIds = config.materialids;
+    mhm->fMaterialBCIds = config.bcmaterialids;
+
+    // Insert the material objects in the multiphysics mesh
+    InsertMaterialsInMHMMesh(*mhm, config);
+
+    // General approximation order settings
+    mhm->SetInternalPOrder(config.porder);
+    mhm->SetSkeletonPOrder(config.porder);
+    mhm->SetHdivmaismaisPOrder(config.hdivmais);
+
+    // Refine skeleton elements
+    for (auto skelid : skelsToDivide) {
+        mhm->DivideSkeletonElement(skelid);
+    }
+
+    mhm->DivideBoundarySkeletonElements();
+    // Creates MHM mesh
+    bool substructure = true;
+    mhm->BuildComputationalMesh(substructure);
+}
+
+void CreateMHMCompMesh(TPZMHMixedMeshControl *mhm, const ProblemConfig &config, bool definePartitionByCoarseIndex,
+                       TPZManVector &mhmIndexes) {
+
+    if (definePartitionByCoarseIndex) {
+        mhm->DefinePartitionbyCoarseIndices(mhmIndexes);
+    } else {
+        mhm->DefinePartition(mhmIndexes);
+    }
+
+    // Indicate material indices to the MHM control structure
+    mhm->fMaterialIds = config.materialids;
+    mhm->fMaterialBCIds = config.bcmaterialids;
+
+    // Insert the material objects in the multiphysics mesh
+    InsertMaterialsInMHMMesh(*mhm, config);
+
+    // General approximation order settings
+    mhm->SetInternalPOrder(config.porder);
+    mhm->SetSkeletonPOrder(config.porder);
+    mhm->SetHdivmaismaisPOrder(config.hdivmais);
+
+    // Refine skeleton elements
+    mhm->DivideSkeletonElements(0);
+    mhm->DivideBoundarySkeletonElements();
+    // Creates MHM mesh
+    bool substructure = true;
+    mhm->BuildComputationalMesh(substructure);
+}
+
+void SolveMHMProblem(TPZMHMixedMeshControl *mhm, const ProblemConfig &config) {
+
+    TPZAutoPointer cmesh = mhm->CMesh();
+
+    bool shouldrenumber = true;
+    TPZLinearAnalysis an(cmesh, shouldrenumber);
+
+#ifdef PZ_USING_MKL
+    TPZSSpStructMatrix strmat(cmesh.operator->());
+    strmat.SetNumThreads(4);
+#else
+    TPZSkylineStructMatrix strmat(cmesh.operator->());
+    strmat.SetNumThreads(0);
+#endif
+
+    an.SetStructuralMatrix(strmat);
+    TPZStepSolver step;
+    step.SetDirect(ELDLt);
+    an.SetSolver(step);
+    std::cout << "Assembling\n";
+    an.Assemble();
+
+    std::cout << "Solving\n";
+    an.Solve();
+    std::cout << "Finished\n";
+    an.LoadSolution(); // compute internal dofs
+
+    TPZMFSolutionTransfer transfer;
+    transfer.BuildTransferData(cmesh.operator->());
+    transfer.TransferFromMultiphysics();
+
+    TPZStack scalnames, vecnames;
+    TPZMaterial *mat = cmesh->FindMaterial(1);
+    if (!mat) {
+        DebugStop();
+    }
+
+    scalnames.Push("Pressure");
+    scalnames.Push("Permeability");
+    vecnames.Push("Flux");
+
+    if (config.exact) {
+        scalnames.Push("ExactPressure");
+        vecnames.Push("ExactFlux");
+    }
+
+    std::cout << "Post Processing...\n";
+
+    int resolution = 2;
+    std::stringstream plotname;
+    plotname << config.dir_name << "/" << config.problemname << "-" << config.ndivisions << "-" << config.ninternalref
+             << "-Results.vtk";
+    an.DefineGraphMesh(cmesh->Dimension(), scalnames, vecnames, plotname.str());
+    an.PostProcess(resolution, cmesh->Dimension());
+}
+
+void EstimateError(ProblemConfig &config, TPZMHMixedMeshControl *mhm) {
+
+    std::cout << "\nError Estimation processing for MHM-Hdiv problem " << std::endl;
+
+    // Error estimation
+    TPZMultiphysicsCompMesh *originalMesh = dynamic_cast(mhm->CMesh().operator->());
+    if (!originalMesh) DebugStop();
+
+    bool postProcWithHDiv = false;
+    TPZMHMHDivErrorEstimator ErrorEstimator(*originalMesh, mhm, postProcWithHDiv);
+    ErrorEstimator.SetAnalyticSolution(config.exact);
+    ErrorEstimator.PotentialReconstruction();
+
+    std::string command = "mkdir -p " + config.dir_name;
+    system(command.c_str());
+
+    TPZManVector errors;
+    TPZManVector elementerrors;
+    std::stringstream outVTK;
+    outVTK << config.dir_name << "/" << config.problemname << "-" << config.ndivisions << "-" << config.ninternalref
+           << "-Errors.vtk";
+    std::string outVTKstring = outVTK.str();
+    ErrorEstimator.ComputeErrors(errors, elementerrors, outVTKstring);
+
+    {
+        std::string fileName = config.dir_name + "/" + config.problemname + "-GlobalErrors.txt";
+        std::ofstream file(fileName, std::ios::app);
+        Tools::PrintErrors(file, config, errors);
+    }
+
+}
+
+void InsertMaterialsInMHMMesh(TPZMHMixedMeshControl &control, const ProblemConfig &config) {
+    TPZCompMesh &cmesh = control.CMesh();
+
+    int dim = control.GMesh()->Dimension();
+    cmesh.SetDimModel(dim);
+
+    auto *mat = new TPZMixedDarcyFlow(1, dim);
+
+    auto ff_lambda = [config](const TPZVec &loc, TPZVec &result) {
+        config.exact.operator*().ForcingFunction()->Execute(loc, result);
+    };
+    auto exact_sol_lambda = [config](const TPZVec &loc, TPZVec &result, TPZFMatrix &deriv) {
+        config.exact.operator*().Exact()->Execute(loc, result, deriv);
+    };
+
+    mat->SetForcingFunction(ff_lambda, 5);
+    mat->SetExactSol(exact_sol_lambda, 5);
+    mat->SetPermeabilityFunction(1);
+
+    cmesh.InsertMaterialObject(mat);
+
+    for (auto matid : config.bcmaterialids) {
+        TPZFNMatrix<1, REAL> val1(1, 1, 0.);
+        TPZManVector val2(1, 0.);
+        int bctype = 0;
+        auto *bc = mat->CreateBC(mat, matid, bctype, val1, val2);
+
+        auto ff_bc_lambda = [config](const TPZVec &loc, TPZVec &rhsVal, TPZFMatrix &matVal) {
+            config.exact.operator*().Exact()->Execute(loc, rhsVal, matVal);
+        };
+        bc->SetForcingFunctionBC(ff_bc_lambda);
+        cmesh.InsertMaterialObject(bc);
+    }
+}
+
+void RunReferenceSolutionValidationProblem() {
+
+    ProblemConfig config;
+    config.dimension = 2;
+    config.exact = new TLaplaceExample1;
+    config.exact.operator*().fExact = TLaplaceExample1::EArcTan;
+    config.problemname = "EArcTan";
+    config.dir_name = "MHMAdaptivity";
+    config.porder = 1;
+    config.hdivmais = 2;
+    config.materialids.insert(1);
+    config.bcmaterialids.insert(-1);
+    config.makepressurecontinuous = true;
+
+    int nCoarseRef = 4;
+    int nInternalRef = 4;
+
+    config.ndivisions = nCoarseRef;
+
+    std::string command = "mkdir -p " + config.dir_name;
+    system(command.c_str());
+
+    std::vector skelsToRefine;
+
+    config.gmesh = CreateQuadGeoMesh(nCoarseRef, nInternalRef);
+
+    auto *mhm = new TPZMHMixedMeshControl(config.gmesh);
+    TPZManVector coarseIndexes;
+    ComputeCoarseIndices(config.gmesh, coarseIndexes);
+    bool definePartitionByCoarseIndexes = true;
+    CreateMHMCompMesh(mhm, config, definePartitionByCoarseIndexes, coarseIndexes, skelsToRefine);
+
+    {
+        std::string fileName = config.dir_name + "/" + config.problemname + "GMesh.vtk";
+        std::ofstream file(fileName);
+        TPZVTKGeoMesh::PrintGMeshVTK(config.gmesh, file);
+    }
+
+    SolveMHMProblem(mhm, config);
+
+    bool postProcWithHDiv = false;
+    TPZMultiphysicsCompMesh *originalMesh = dynamic_cast(mhm->CMesh().operator->());
+    if (!originalMesh) DebugStop();
+    TPZMHMHDivErrorEstimator estimator(*originalMesh, mhm, postProcWithHDiv);
+    EstimateError(config, mhm);
+}

From 9096ce1ea9431289f37cb8343edf89562c9e47cc Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 3 Sep 2021 16:22:09 -0300
Subject: [PATCH 123/187] Update permeability class name

---
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h | 2 +-
 ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h    | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
index bf496938..77083552 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
@@ -16,7 +16,7 @@
 #include "TPZMaterialDataT.h"
 
 class TPZHDivErrorEstimateMaterial: public virtual TPZMatBase,
-        TPZMatErrorCombinedSpaces, TPZDarcyFlowInterface>, public TPZMixedDarcyFlow {
+        TPZMatErrorCombinedSpaces, TPZIsotropicPermeability>, public virtual TPZMixedDarcyFlow {
 
 public:
     TPZHDivErrorEstimateMaterial(int matid, int dim);
diff --git a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
index da1c1a5b..7f7ff552 100644
--- a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
+++ b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
@@ -15,7 +15,7 @@
 
 
 class TPZMixedHDivErrorEstimate : public virtual TPZMatBase,
-        TPZMatErrorCombinedSpaces, TPZDarcyFlowInterface>, public TPZMixedDarcyFlow {
+        TPZMatErrorCombinedSpaces, TPZIsotropicPermeability>, public TPZMixedDarcyFlow {
 
 public:
     

From 811096f95cfe7c36328f87c643fa878ac3359995 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 3 Sep 2021 16:25:10 -0300
Subject: [PATCH 124/187] Update method to set constant permeability

---
 Projects/ErrorEstimationMHM/main_Journal.cpp |  6 +-
 Projects/Tools/Tools.cpp                     | 78 ++++++++------------
 2 files changed, 35 insertions(+), 49 deletions(-)

diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp
index a6dff904..cb8c2dda 100644
--- a/Projects/ErrorEstimationMHM/main_Journal.cpp
+++ b/Projects/ErrorEstimationMHM/main_Journal.cpp
@@ -639,7 +639,7 @@ void InsertMaterialsInMHMMesh(TPZMHMixedMeshControl &control, const ProblemConfi
 
     mat->SetForcingFunction(ff_lambda, 5);
     mat->SetExactSol(exact_sol_lambda, 5);
-    mat->SetPermeabilityFunction(1);
+    mat->SetConstantPermeability(1);
 
     cmesh.InsertMaterialObject(mat);
 
@@ -689,14 +689,14 @@ void CreateMHMCompMeshHeteroPerm(TPZMHMixedMeshControl *mhm, const ProblemConfig
 
     mat->SetForcingFunction(ff_lambda, 5);
     mat->SetExactSol(exact_sol_lambda, 5);
-    mat->SetPermeabilityFunction(5);
+    mat->SetConstantPermeability(5);
 
     cmesh.InsertMaterialObject(mat);
 
     auto *mat2 = new TPZMixedDarcyFlow(2, dim);
     mat2->SetForcingFunction(ff_lambda, 5);
     mat2->SetExactSol(exact_sol_lambda, 5);
-    mat2->SetPermeabilityFunction(1);
+    mat2->SetConstantPermeability(1);
 
     cmesh.InsertMaterialObject(mat2);
 
diff --git a/Projects/Tools/Tools.cpp b/Projects/Tools/Tools.cpp
index e3c4c71f..10b54f5d 100644
--- a/Projects/Tools/Tools.cpp
+++ b/Projects/Tools/Tools.cpp
@@ -140,7 +140,7 @@ TPZMultiphysicsCompMesh* Tools::CreateMixedMesh(const ProblemConfig& problem) {
 
         mix->SetForcingFunction(ff_lambda, 5);
         mix->SetExactSol(exact_sol_lambda, 5);
-        mix->SetPermeabilityFunction(K(0,0));
+        mix->SetConstantPermeability(K(0,0));
 
         if (!mat) mat = mix;
 
@@ -535,7 +535,7 @@ void Tools::SolveMixedProblem(TPZCompMesh* cmesh_HDiv, const ProblemConfig& conf
 
 
     TPZSSpStructMatrix strmat(cmesh_HDiv);
-    strmat.SetNumThreads(0);
+    strmat.SetNumThreads(8);
     an.SetStructuralMatrix(strmat);
 
     std::set matids;
@@ -582,35 +582,35 @@ void Tools::SolveMixedProblem(TPZCompMesh* cmesh_HDiv, const ProblemConfig& conf
     int resolution = 2;
     an.PostProcess(resolution, dim);
 
-    if (config.exact.operator*().Exact()) {
-        TPZManVector errors(4, 0.);
-        an.SetThreadsForError(0);
-        an.SetExact(config.exact.operator*().ExactSolution());
-        an.PostProcessError(errors, false);
-
-        // Erro
-        std::ofstream myfile;
-        /*Error on MixedPoisson
-           [0] L2 for pressure
-           [1] L2 for flux
-           [2] L2 for div(flux)
-           [3] Grad pressure (Semi H1)
-           [4] Hdiv norm
-           */
-
-          // Erro
-          myfile.open("ErrorMixed.txt", std::ios::app);
-          myfile << "\n\n Error for Mixed formulation ";
-          myfile << "\n-------------------------------------------------- \n";
-          myfile << "Ndiv = " << config.ndivisions
-                 << " Order k = " << config.porder << " n "< errors(4, 0.);
+    //    an.SetThreadsForError(0);
+    //    an.SetExact(config.exact.operator*().ExactSolution());
+    //    an.PostProcessError(errors, false);
+
+    //    // Erro
+    //    std::ofstream myfile;
+    //    /*Error on MixedPoisson
+    //       [0] L2 for pressure
+    //       [1] L2 for flux
+    //       [2] L2 for div(flux)
+    //       [3] Grad pressure (Semi H1)
+    //       [4] Hdiv norm
+    //       */
+
+    //      // Erro
+    //      myfile.open("ErrorMixed.txt", std::ios::app);
+    //      myfile << "\n\n Error for Mixed formulation ";
+    //      myfile << "\n-------------------------------------------------- \n";
+    //      myfile << "Ndiv = " << config.ndivisions
+    //             << " Order k = " << config.porder << " n "<Dimension() != postProcessMesh->Dimension()) continue;
         REAL elementError = elsol(iel, fluxErrorEstimateCol);
 
-
         if (elementError > maxError) {
             maxError = elementError;
         }
@@ -739,15 +738,11 @@ void Tools::hAdaptivity(TPZCompMesh* postProcessMesh, TPZGeoMesh* gmeshToRefine,
         if (cel->Dimension() != postProcessMesh->Dimension()) continue;
 
         REAL elementError = elsol(iel, fluxErrorEstimateCol);
-        //prefinement
         if (elementError > threshold) {
-
-            std::cout << "element error " << elementError << "el " << iel << "\n";
             TPZGeoEl* gel = cel->Reference();
-            int iel = gel->Id();
 
             TPZVec sons;
-            TPZGeoEl* gelToRefine = gmeshToRefine->ElementVec()[iel];
+            TPZGeoEl* gelToRefine = gmeshToRefine->ElementVec()[gel->Id()];
             if (gelToRefine && !gelToRefine->HasSubElement()) {
                 gelToRefine->Divide(sons);
 #ifdef LOG4CXX2
@@ -766,15 +761,6 @@ void Tools::hAdaptivity(TPZCompMesh* postProcessMesh, TPZGeoMesh* gmeshToRefine,
                 }
 #endif
             }
-        } else {
-            std::cout << "como refinar em p? " << "\n";
-//            TPZInterpolationSpace *sp = dynamic_cast(cel);
-//            if(!sp) continue;
-//            int level = sp->Reference()->Level();
-//            int ordem = config.porder + (config.adaptivityStep -1 ) + (level);
-//            std::cout<<"level "<< level<<" ordem "<PRefine(ordem);
-
         }
     }
     DivideLowerDimensionalElements(gmeshToRefine);

From 4cc260cc8c6012126694cceeee648c6a5e19dee8 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 3 Sep 2021 16:26:52 -0300
Subject: [PATCH 125/187] Add base class alias and use it in copy ctor

---
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp | 3 ++-
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h   | 3 +++
 2 files changed, 5 insertions(+), 1 deletion(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index bb096ef2..3e6f2a30 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -18,7 +18,8 @@ TPZHDivErrorEstimateMaterial::TPZHDivErrorEstimateMaterial(int matid, int dim) :
 
 TPZHDivErrorEstimateMaterial::TPZHDivErrorEstimateMaterial() : TPZMixedDarcyFlow() {}
 
-TPZHDivErrorEstimateMaterial::TPZHDivErrorEstimateMaterial(const TPZMixedDarcyFlow ©) : TPZMixedDarcyFlow(copy) {}
+TPZHDivErrorEstimateMaterial::TPZHDivErrorEstimateMaterial(const TPZMixedDarcyFlow ©)
+    : TBase(copy), TPZMixedDarcyFlow(copy) {}
 
 TPZHDivErrorEstimateMaterial::TPZHDivErrorEstimateMaterial(const TPZHDivErrorEstimateMaterial ©)
         : TPZMixedDarcyFlow(copy) {}
diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
index 77083552..9edf8bd4 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
@@ -18,6 +18,9 @@
 class TPZHDivErrorEstimateMaterial: public virtual TPZMatBase,
         TPZMatErrorCombinedSpaces, TPZIsotropicPermeability>, public virtual TPZMixedDarcyFlow {
 
+    // type alias to improve constructor readability
+    using TBase = TPZMatBase,
+        TPZMatErrorCombinedSpaces, TPZIsotropicPermeability>;
 public:
     TPZHDivErrorEstimateMaterial(int matid, int dim);
 

From 62e1a9eb7141c6fc773e1eccaa224dccb2ff2dc9 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 3 Sep 2021 16:27:28 -0300
Subject: [PATCH 126/187] Comment unused broken code

---
 ErrorEstimation/TPZMFSolutionTransfer.cpp | 28 +++++++++++------------
 1 file changed, 14 insertions(+), 14 deletions(-)

diff --git a/ErrorEstimation/TPZMFSolutionTransfer.cpp b/ErrorEstimation/TPZMFSolutionTransfer.cpp
index d9f05bf3..4daa6953 100644
--- a/ErrorEstimation/TPZMFSolutionTransfer.cpp
+++ b/ErrorEstimation/TPZMFSolutionTransfer.cpp
@@ -20,20 +20,20 @@ void TPZMFSolutionTransfer::Match::TransferFromMultiphysics(TPZCompMesh * cmesh)
         DebugStop();
     }
 #ifdef PZDEBUG
-    int64_t nblockMF = blockMF.NBlocks();
-    int64_t nblockAto = blockAto->NBlocks();
-    if(seqMF < nblockMF-1)
-    {
-        int64_t PosMF = blockMF.Position(seqMF);
-        int64_t nextPosMF = blockMF.Position(seqMF+1);
-        if(nextPosMF-PosMF != blocksizeMF) DebugStop();
-    }
-    if(seqAto < nblockAto-1)
-    {
-        int64_t PosAto = blockAto->Position(seqAto);
-        int64_t nextPosAto = blockAto->Position(seqAto+1);
-        if(nextPosAto-PosAto != blocksizeAto) DebugStop();
-    }
+    //int64_t nblockMF = blockMF.NBlocks();
+    //int64_t nblockAto = blockAtomic->NBlocks();
+    //if(seqMF < nblockMF-1)
+    //{
+    //    int64_t PosMF = blockMF.Position(seqMF);
+    //    int64_t nextPosMF = blockMF.Position(seqMF+1);
+    //    if(nextPosMF-PosMF != blocksizeMF) DebugStop();
+    //}
+    //if(seqAto < nblockAto-1)
+    //{
+    //    int64_t PosAto = blockAto->Position(seqAto);
+    //    int64_t nextPosAto = blockAto->Position(seqAto+1);
+    //    if(nextPosAto-PosAto != blocksizeAto) DebugStop();
+    //}
 #endif
     TPZFMatrix solAtomic = fblockTarget.first->Solution();
     TPZFMatrix solMF = cmesh->Solution();

From 9f391fe26198775b73fc25c7b3778b399065c248 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 3 Sep 2021 16:28:25 -0300
Subject: [PATCH 127/187] Add safety verification

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index c3c2178f..d5f3438c 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -1833,6 +1833,7 @@ void TPZHDivErrorEstimator::InsertPostProcMaterials() {
         if (orig_bc) {
             it.second->Clone(fPostProcMesh.MaterialVec());
             auto *new_mat = fPostProcMesh.FindMaterial(orig_bc->Material()->Id());
+            if (!new_mat) DebugStop();
             auto *new_bc = dynamic_cast(fPostProcMesh.FindMaterial(orig_bc->Id()));
             if (!new_bc) DebugStop();
             new_bc->SetMaterial(new_mat);

From 2e5affe8aca9bafdd95e8ec4555cb48df46966d5 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 3 Sep 2021 16:29:19 -0300
Subject: [PATCH 128/187] Update access of permeability value

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index d5f3438c..26639aa9 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -2194,15 +2194,12 @@ void TPZHDivErrorEstimator::ComputePressureWeights() {
             auto *mixpoisson = dynamic_cast(mat);
             if (!mixpoisson) DebugStop();
 
-            REAL perm;
             TPZVec xi(gel->Dimension(), 0.);
             gel->CenterPoint(gel->NSides() - 1, xi);
             TPZVec x(3, 0.);
             gel->X(xi, x);
 
-            TPZFNMatrix<1, STATE> K(1, 1, 0.), InvK(1, 1, 0.);
-            mixpoisson->GetPermeabilities(x, K, InvK);
-            perm = K(0, 0);
+            STATE perm = mixpoisson->GetPermeability(x);
             if (IsZero(perm)) DebugStop();
             this->fPressureweights[el] = perm;
             fMatid_weights[matid] = perm;

From 4afe0ae0c99523a2e0d5c59344820a5d5a20bc43 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 3 Sep 2021 16:45:20 -0300
Subject: [PATCH 129/187] Remove matricial permeabilities from material

---
 .../Material/TPZHDivErrorEstimateMaterial.cpp | 77 +++++--------------
 1 file changed, 19 insertions(+), 58 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index 3e6f2a30..e9bd20cf 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -68,7 +68,6 @@ void TPZHDivErrorEstimateMaterial::Contribute(const TPZVec &phiuk = datavec[H1functionposition].phi;
@@ -76,15 +75,10 @@ void TPZHDivErrorEstimateMaterial::Contribute(const TPZVec dphiuk(3, 1);
     TPZAxesTools::Axes2XYZ(dphiukaxes, dphiuk, datavec[H1functionposition].axes);
 
-    int nphiuk = phiuk.Rows();
-
     TPZFMatrix solsigmafem(3, 1), solukfem(1, 1);
     solsigmafem.Zero();
     solukfem.Zero();
 
-
-
-
     //potetial fem
     solukfem(0, 0) = datavec[3].sol[0][0];
     //flux fem
@@ -93,23 +87,18 @@ void TPZHDivErrorEstimateMaterial::Contribute(const TPZVec PermTensor(1, 1, 0.);
-    TPZFNMatrix<9, REAL> InvPermTensor(1, 1, 0.);
-
-    GetPermeabilities(datavec[1].x, PermTensor, InvPermTensor);
-
-
+    auto dim = datavec[H1functionposition].axes.Rows();
+    auto nphiuk = phiuk.Rows();
     TPZFMatrix kgraduk(3, nphiuk, 0.);
 
-
     for (int irow = 0; irow < nphiuk; irow++) {
 
         //K graduk
         for (int id = 0; id < dim; id++) {
 
-            kgraduk(id, irow) += PermTensor(0, 0) * dphiuk(id, irow);
+            kgraduk(id, irow) += perm * dphiuk(id, irow);
             //bk = (-1)*int_k sigmaukfem.grad phi_i,here dphiuk is multiplied by axes
             //the minus sign is necessary because we are working with sigma_h = - K grad u, Mark works with sigma_h = K grad u
 
@@ -159,11 +148,11 @@ void TPZHDivErrorEstimateMaterial::ContributeBC(const TPZVec
      ef+= 
     */
-    int H1functionposition = FirstNonNullApproxSpaceIndex(datavec);
-    int dim = datavec[H1functionposition].axes.Rows();
+    auto H1functionposition = FirstNonNullApproxSpaceIndex(datavec);
+    auto dim = datavec[H1functionposition].axes.Rows();
 
     TPZFMatrix &phi_i = datavec[H1functionposition].phi;
-    int nphi_i = phi_i.Rows();
+    auto nphi_i = phi_i.Rows();
 
     TPZFMatrix solsigmafem(3, 1);
     solsigmafem.Zero();
@@ -182,12 +171,11 @@ void TPZHDivErrorEstimateMaterial::ContributeBC(const TPZVec PermTensor(1, 1, 0.), InvPermTensor(1, 1, 0.);
-        GetPermeabilities(datavec[0].x, PermTensor, InvPermTensor);
+        STATE perm = GetPermeability(datavec[1].x);
 
         for (int i = 0; i < 3; i++) {
             for (int j = 0; j < 3; j++) {
-                normflux += datavec[2].normal[i] * PermTensor(0, 0) * gradu(j, 0);
+                normflux += datavec[2].normal[i] * perm * gradu(j, 0);
             }
         }
 
@@ -240,8 +228,6 @@ void TPZHDivErrorEstimateMaterial::FillDataRequirements(TPZVec>
       error[4] - oscillatory data error
      **/
 
-    errors.Resize(NEvalErrors());
-    errors.Fill(0.0);
-
-
     TPZManVector fluxfem(3);
     STATE divsigmafem, pressurefem, pressurereconstructed;
 
     TPZFNMatrix<3, REAL> fluxreconstructed(3, 1), fluxreconstructed2(3, 1);
 
-
     fluxfem = data[2].sol[0];
 
-
     divsigmafem = data[2].divsol[0][0];
 
     STATE divtest = 0.;
@@ -288,7 +268,6 @@ void TPZHDivErrorEstimateMaterial::Errors(const TPZVec>
 
     int H1functionposition = FirstNonNullApproxSpaceIndex(data);
 
-
     TPZVec divsigma(1);
     divsigma[0] = 0.;
 
@@ -302,17 +281,10 @@ void TPZHDivErrorEstimateMaterial::Errors(const TPZVec>
     }
 
     REAL residual = (divsigma[0] - divsigmafem) * (divsigma[0] - divsigmafem);
-
-
     pressurereconstructed = data[H1functionposition].sol[0][0];
-
-
     pressurefem = data[3].sol[0][0];
 
-    TPZFNMatrix<9, REAL> PermTensor(1, 1, 0.);
-    TPZFNMatrix<9, REAL> InvPermTensor(1, 1, 0.);
-
-    GetPermeabilities(data[2].x, PermTensor, InvPermTensor);
+    STATE perm = GetPermeability(data[1].x);
 
     TPZFNMatrix<3, REAL> fluxexactneg(3, 1);
 
@@ -322,17 +294,16 @@ void TPZHDivErrorEstimateMaterial::Errors(const TPZVec>
     {
         TPZFNMatrix<9, REAL> gradpressure(3, 1);
         for (int i = 0; i < 3; i++) {
-            fluxexactneg(i, 0) = PermTensor(0,0) * du_exact[i];
+            fluxexactneg(i, 0) = perm * du_exact[i];
         }
     }
 
-
     TPZFMatrix &dsolaxes = data[H1functionposition].dsol[0];
     TPZFNMatrix<9, REAL> fluxrec(3, 0);
     TPZAxesTools::Axes2XYZ(dsolaxes, fluxrec, data[H1functionposition].axes);
 
     for (int id = 0; id < 3; id++) {
-        fluxreconstructed(id, 0) = (-1.) * PermTensor(0,0) * fluxrec(id, 0);
+        fluxreconstructed(id, 0) = (-1.) * perm * fluxrec(id, 0);
     }
 
     REAL innerexact = 0.;
@@ -346,11 +317,10 @@ void TPZHDivErrorEstimateMaterial::Errors(const TPZVec>
 
     for (int i = 0; i < 3; i++) {
         if (this->fExactSol) {
-            innerexact += (fluxfem[i] + fluxexactneg(i, 0)) * InvPermTensor(0, 0) *
-                          (fluxfem[i] + fluxexactneg(i, 0)); // Pq esta somando: o fluxo fem esta + e o exato -
+            innerexact += (fluxfem[i] + fluxexactneg(i, 0)) * (fluxfem[i] + fluxexactneg(i, 0)) / perm;
+            // Pq esta somando: o fluxo fem esta + e o exato -
         }
-        innerestimate +=
-            (fluxfem[i] - fluxreconstructed[i]) * InvPermTensor(0, 0) * (fluxfem[i] - fluxreconstructed[i]);
+        innerestimate += (fluxfem[i] - fluxreconstructed[i]) * (fluxfem[i] - fluxreconstructed[i]) / perm;
     }
 
     STATE exact_pressure_error = 0;
@@ -449,11 +419,7 @@ TPZHDivErrorEstimateMaterial::Solution(const TPZVec> &da
 
     int H1functionposition = FirstNonNullApproxSpaceIndex(datavec);
 
-    TPZFNMatrix<9, REAL> PermTensor(1, 1, 0.);
-    TPZFNMatrix<9, REAL> InvPermTensor(1, 1, 0.);
-
-    GetPermeabilities(datavec[2].x, PermTensor, InvPermTensor);
-
+    STATE perm = GetPermeability(datavec[1].x);
 
     TPZManVector pressexact(1, 0.);
     TPZFNMatrix<9, STATE> gradu(3, 1, 0.), fluxinv(3, 1);
@@ -463,7 +429,7 @@ TPZHDivErrorEstimateMaterial::Solution(const TPZVec> &da
     }
 
     for (int i = 0; i < 3; i++) {
-        fluxinv(i, 0) = PermTensor(0, 0) * gradu(i, 0);
+        fluxinv(i, 0) = perm * gradu(i, 0);
     }
 
     int dim = this->fDim;
@@ -476,15 +442,10 @@ TPZHDivErrorEstimateMaterial::Solution(const TPZVec> &da
         case 41: {//FluxReconstructed is grad U
             TPZFMatrix &dsolaxes = datavec[H1functionposition].dsol[0];
             TPZFNMatrix<9, REAL> dsol(3, 1);
-            TPZFNMatrix<9, REAL> KGradsol(3, 1);
             TPZAxesTools::Axes2XYZ(dsolaxes, dsol, datavec[H1functionposition].axes);
 
-            for (int i = 0; i < 3; i++) {
-                KGradsol(i, 0) = PermTensor(0, 0) * dsol(i, 0);
-            }
-
             for (int id = 0; id < fDim; id++) {
-                Solout[id] = -KGradsol(id, 0);//dsol(id,0);//derivate
+                Solout[id] = -perm * dsol(id, 0); // derivate
             }
         }
 
@@ -508,7 +469,7 @@ TPZHDivErrorEstimateMaterial::Solution(const TPZVec> &da
             Solout[0] = datavec[1].p;
             break;
         case 47: // Permeability
-            Solout[0] = PermTensor(0, 0);
+            Solout[0] = perm;
             break;
 
         default:

From 0078e9eb46c1c5777d4437cb7dba8ed6da436cbf Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 10 Sep 2021 11:47:40 -0300
Subject: [PATCH 130/187] Fix namespace of STL variable

---
 Projects/ErrorEstimationHDiv/main.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/Projects/ErrorEstimationHDiv/main.cpp b/Projects/ErrorEstimationHDiv/main.cpp
index aee3d328..c74a91f9 100644
--- a/Projects/ErrorEstimationHDiv/main.cpp
+++ b/Projects/ErrorEstimationHDiv/main.cpp
@@ -81,7 +81,7 @@ TPZMultiphysicsCompMesh *CreateHybridCompMesh(const ProblemConfig &config, TPZHy
 
 #ifdef PZDEBUG
     {
-        ofstream out("MixedMesh.txt");
+        std::ofstream out("MixedMesh.txt");
         cmesh_HDiv->Print(out);
     }
 #endif

From c7723bd0018a19454d3751de7f12535b12ae9387 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 10 Sep 2021 11:49:23 -0300
Subject: [PATCH 131/187] Substitute obsolete perm function by a lambda

---
 Projects/ErrorEstimationMHM/main_Journal.cpp | 34 ++++++++------------
 1 file changed, 14 insertions(+), 20 deletions(-)

diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp
index cb8c2dda..da6354b3 100644
--- a/Projects/ErrorEstimationMHM/main_Journal.cpp
+++ b/Projects/ErrorEstimationMHM/main_Journal.cpp
@@ -67,7 +67,6 @@ void MHMAdaptivity(TPZMHMixedMeshControl *mhm, ProblemConfig &config, TPZCompMes
                    std::vector &skelsToRefine);
 
 void CreateMHMCompMeshPermFunction(TPZMHMixedMeshControl &mhm);
-void PeriodicPermeabilityFunction(const TPZVec &coord, TPZVec &res, TPZFMatrix &res_mat);
 void PeriodicProblemForcingFunction(const TPZVec  &pt, TPZVec  &result);
 
 void PrintLatexGraphs(std::ostream & out);
@@ -747,7 +746,20 @@ void CreateMHMCompMeshPermFunction(TPZMHMixedMeshControl &mhm) {
     // Insert the material objects in the multiphysics mesh
     TPZCompMesh *cmesh = mhm.CMesh().operator->();
     auto *mix = new TPZMixedDarcyFlow(1, cmesh->Dimension());
-    TPZAutoPointer> perm_function = new TPZDummyFunction(&PeriodicPermeabilityFunction, 3);
+
+    std::function &coord)> perm_function = [](const TPZVec &coord) {
+        constexpr auto epsilon = 0.04;
+        constexpr auto P = 1.8;
+        const auto x = coord[0];
+        const auto y = coord[1];
+
+        REAL term_1 = 2 + P * cos(2 * M_PI * (x - 0.5) / epsilon);
+        REAL term_2 = 2 + P * cos(2 * M_PI * (y - 0.5) / epsilon);
+
+        auto perm = 1 / (term_1 * term_2);
+        return perm;
+    };
+
     mix->SetPermeabilityFunction(perm_function);
     mix->SetForcingFunction(PeriodicProblemForcingFunction, 1);
 
@@ -773,24 +785,6 @@ void CreateMHMCompMeshPermFunction(TPZMHMixedMeshControl &mhm) {
     mhm.BuildComputationalMesh(substructure);
 }
 
-void PeriodicPermeabilityFunction(const TPZVec &coord, TPZVec &res, TPZFMatrix &res_mat) {
-
-    constexpr auto epsilon = 0.04;
-    constexpr auto P = 1.8;
-    const auto x = coord[0];
-    const auto y = coord[1];
-
-    REAL term_1 = 2 + P * cos(2 * M_PI * (x - 0.5) / epsilon);
-    REAL term_2 = 2 + P * cos(2 * M_PI * (y - 0.5) / epsilon);
-
-    auto perm = 1 / (term_1 * term_2);
-
-    for (int i = 0; i < 2; i++) {
-        res_mat(i, i) = perm;
-        res_mat(i + 2, i) = 1 / perm;
-    }
-}
-
 void PeriodicProblemForcingFunction(const TPZVec &pt, TPZVec &result) { result[0] = -1; }
 
 void PrintLatexGraphs(std::ostream & out) {

From e82eff7fe449bae7d3bc343ac329a17ce8ebb883 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 10 Sep 2021 11:50:01 -0300
Subject: [PATCH 132/187] Correct method that sets a constant permeability
 field

---
 Projects/ErrorEstimationMHM/main_MHM.cpp              | 2 +-
 Projects/ErrorEstimationMHM/main_RefSolValidation.cpp | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/Projects/ErrorEstimationMHM/main_MHM.cpp b/Projects/ErrorEstimationMHM/main_MHM.cpp
index 25dc1ddd..dadeb744 100644
--- a/Projects/ErrorEstimationMHM/main_MHM.cpp
+++ b/Projects/ErrorEstimationMHM/main_MHM.cpp
@@ -538,7 +538,7 @@ void InsertMaterialsInMHMMesh(TPZMHMixedMeshControl &control, const ProblemConfi
         config.exact.operator*().ForcingFunction()->Execute(loc, result);
     };
 
-    mat->SetPermeabilityFunction(1);
+    mat->SetConstantPermeability(1);
     mat->SetExactSol(exact_lambda, 8);
     mat->SetForcingFunction(ff_lambda, 8);
 
diff --git a/Projects/ErrorEstimationMHM/main_RefSolValidation.cpp b/Projects/ErrorEstimationMHM/main_RefSolValidation.cpp
index 5d1c7226..46274df1 100644
--- a/Projects/ErrorEstimationMHM/main_RefSolValidation.cpp
+++ b/Projects/ErrorEstimationMHM/main_RefSolValidation.cpp
@@ -318,7 +318,7 @@ void InsertMaterialsInMHMMesh(TPZMHMixedMeshControl &control, const ProblemConfi
 
     mat->SetForcingFunction(ff_lambda, 5);
     mat->SetExactSol(exact_sol_lambda, 5);
-    mat->SetPermeabilityFunction(1);
+    mat->SetConstantPermeability(1);
 
     cmesh.InsertMaterialObject(mat);
 

From 6a0f3a9a48bd0565237da56cc1dc87fedd4c6304 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 10 Sep 2021 11:50:47 -0300
Subject: [PATCH 133/187] Update permeability function type

---
 Projects/SPE10/mainSPE10.cpp | 10 ++++------
 1 file changed, 4 insertions(+), 6 deletions(-)

diff --git a/Projects/SPE10/mainSPE10.cpp b/Projects/SPE10/mainSPE10.cpp
index 7e757fa4..97aec028 100644
--- a/Projects/SPE10/mainSPE10.cpp
+++ b/Projects/SPE10/mainSPE10.cpp
@@ -21,7 +21,7 @@ Interpolator interpolator;
 // Function declarations
 void ReadSPE10CellPermeabilities(TPZVec*perm_vec, int layer);
 TPZGeoMesh *CreateSPE10GeoMesh();
-void PermeabilityFunction(const TPZVec &x, TPZMatrix &K, TPZMatrix &invK);
+STATE PermeabilityFunction(const TPZVec &x);
 void InsertMaterials(TPZCompMesh *cmesh);
 void CreateSPE10MHMCompMesh(TPZMHMixedMeshControl &mhm);
 void SolveMHMProblem(TPZMHMixedMeshControl &mhm);
@@ -117,15 +117,14 @@ void ReadSPE10CellPermeabilities(TPZVec *perm_vec, const int layer) {
     std::cout << "Finished reading permeability data from input file!\n";
 }
 
-void PermeabilityFunction(const TPZVec &x, TPZMatrix &K, TPZMatrix &invK) {
+STATE PermeabilityFunction(const TPZVec &x) {
     auto perm = interpolator(x[0], x[1]);
     if (perm <= 1) {
         perm = 1;
     } else {
         perm += 1;
     }
-    K(0, 0) = perm;
-    invK(0, 0) = 1 / perm;
+    return perm;
 }
 
 void CreateSPE10MHMCompMesh(TPZMHMixedMeshControl &mhm) {
@@ -218,8 +217,7 @@ void SolveMHMProblem(TPZMHMixedMeshControl &mhm) {
 void InsertMaterials(TPZCompMesh *cmesh) {
 
     auto *mix = new TPZMixedDarcyFlow(1, cmesh->Dimension());
-    std::function &coord, TPZMatrix &K, TPZMatrix &InvK)> func =
-        PermeabilityFunction;
+    std::function &coord)> func = PermeabilityFunction;
     mix->SetPermeabilityFunction(func);
 
     TPZFNMatrix<1, REAL> val1(1, 1, 0.);

From 1a79c56f6501d4c461796dabdc8af2bdc98831c3 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 10 Sep 2021 11:51:09 -0300
Subject: [PATCH 134/187] Fix usage of permeability in Errors and Solution
 methods

---
 .../Material/TPZMixedHdivErrorEstimate.cpp    | 71 +++++--------------
 1 file changed, 19 insertions(+), 52 deletions(-)

diff --git a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
index dc061382..e802b024 100644
--- a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
+++ b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.cpp
@@ -104,33 +104,21 @@ TPZMixedHDivErrorEstimate::Solution(const TPZVec> &datav
     
      **/
 
-    TPZFNMatrix<9,REAL> PermTensor;
-    TPZFNMatrix<9,REAL> InvPermTensor;
+    const auto perm = GetPermeability(datavec[1].x);
 
-    TPZMixedDarcyFlow::GetPermeabilities(datavec[1].x, PermTensor, InvPermTensor);
+    TPZManVector pressexact(1, 0.);
+    TPZFNMatrix<9, STATE> gradu(3, 1, 0.), fluxinv(3, 1);
 
-    int dim = TPZMixedDarcyFlow::fDim;
-
-    if (TPZMixedDarcyFlow::fPermeabilityFunction) {
-        PermTensor.Redim(dim, dim);
-        InvPermTensor.Redim(dim, dim);
-        TPZFNMatrix<1, STATE> K(1, 1, 0);
-        TPZFNMatrix<1, STATE> InvK(1, 1, 0);
-        TPZMixedDarcyFlow::fPermeabilityFunction(datavec[1].x, K, InvK);
+    if (fExactSol) {
+        this->fExactSol(datavec[0].x, pressexact, gradu);
     }
 
-
-    TPZManVector pressvec(1,0.);
-    TPZFNMatrix<9, STATE> gradu(dim, 1, 0.), fluxinv(dim, 1);
-
-    if(TPZMixedDarcyFlow::fExactSol) {
-        TPZMixedDarcyFlow::fExactSol(datavec[0].x, pressvec,gradu);
-        gradu.Resize(3, 1);
-        //gradu(2,0) = 0.;
+    for (int i = 0; i < 3; i++) {
+        fluxinv(i, 0) = perm * gradu(i, 0);
     }
 
-    PermTensor.Multiply(gradu, fluxinv);
-    STATE pressureexact = pressvec[0];
+    int dim = this->fDim;
+
     switch (var)
     {
         case 40://FluxFem
@@ -149,7 +137,7 @@ TPZMixedHDivErrorEstimate::Solution(const TPZVec> &datav
             Solout[0] = datavec[1].sol[0][0];
             break;
         case 45:
-            Solout[0] = pressureexact;
+            Solout[0] = pressexact[0];
             break;
         case 46:
             Solout[0] = datavec[1].p;
@@ -199,44 +187,23 @@ void TPZMixedHDivErrorEstimate::Errors(const TPZVec> &da
     pressurereconstructed[0] = data[1].sol[0][0];
     pressurefem[0] = data[3].sol[0][0];
 
-    TPZFNMatrix<9,REAL> PermTensor;
-    TPZFNMatrix<9,REAL> InvPermTensor;
-
-    TPZMixedDarcyFlow::GetPermeabilities(data[1].x, PermTensor, InvPermTensor);
-
-    if(this->fPermeabilityFunction){
-        PermTensor.Redim(dim, dim);
-        InvPermTensor.Redim(dim, dim);
-        TPZFNMatrix<1, STATE> K(1, 1, 0);
-        TPZFNMatrix<1, STATE> InvK(1, 1, 0);
-        this->fPermeabilityFunction(data[1].x, K, InvK);
-        for(int id=0; id fluxexactneg;
+    const auto perm = GetPermeability(data[1].x);
 
     //sigma=-K grad(u)
+    TPZFNMatrix<3, REAL> fluxexactneg(3, 1);
+
     {
-        TPZFNMatrix<9,REAL> gradpressure(dim,1);
-        for (int i=0; i gradpressure(3, 1);
+        for (int i = 0; i < 3; i++) {
+            fluxexactneg(i, 0) = perm * du_exact[i];
         }
-        PermTensor.Multiply(gradpressure,fluxexactneg);
     }
 
-
     REAL innerexact = 0.;
     REAL innerestimate = 0.;
-    for (int i=0; i
Date: Mon, 13 Sep 2021 10:55:16 -0300
Subject: [PATCH 135/187] Standardize header guard

---
 ErrorEstimation/TPZMHMHDivErrorEstimator.h | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/ErrorEstimation/TPZMHMHDivErrorEstimator.h b/ErrorEstimation/TPZMHMHDivErrorEstimator.h
index 4e55646a..23cb4818 100644
--- a/ErrorEstimation/TPZMHMHDivErrorEstimator.h
+++ b/ErrorEstimation/TPZMHMHDivErrorEstimator.h
@@ -5,8 +5,8 @@
 //  Created by Philippe Devloo on 10/06/18.
 //
 
-#ifndef TPZMHMHDivErrorEstimator_hpp
-#define TPZMHMHDivErrorEstimator_hpp
+#ifndef TPZMHMHDIVERRORESTIMATOR_H
+#define TPZMHMHDIVERRORESTIMATOR_H
 
 #include "TPZHDivErrorEstimator.h"
 #include "TPZMHMixedMeshControl.h"
@@ -91,4 +91,4 @@ class TPZMHMHDivErrorEstimator : public TPZHDivErrorEstimator {
     void ComputeConnectsNextToSkeleton(std::set& connectList);
 };
 
-#endif /* TPZHybridHDivErrorEstimator_hpp */
+#endif
\ No newline at end of file

From 316445bc6edb3524f173e26cd15e5cc8344b7a92 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Tue, 21 Sep 2021 10:03:11 -0300
Subject: [PATCH 136/187] Clean up Error methods

---
 .../Material/TPZHDivErrorEstimateMaterial.cpp | 29 ++-----------------
 1 file changed, 2 insertions(+), 27 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index e9bd20cf..e8110ca4 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -252,12 +252,10 @@ void TPZHDivErrorEstimateMaterial::Errors(const TPZVec>
       error[4] - oscillatory data error
      **/
 
-    TPZManVector fluxfem(3);
+    TPZManVector fluxfem = data[2].sol[0];
     STATE divsigmafem, pressurefem, pressurereconstructed;
 
-    TPZFNMatrix<3, REAL> fluxreconstructed(3, 1), fluxreconstructed2(3, 1);
-
-    fluxfem = data[2].sol[0];
+    TPZFNMatrix<3, REAL> fluxreconstructed(3, 1);
 
     divsigmafem = data[2].divsol[0][0];
 
@@ -309,12 +307,6 @@ void TPZHDivErrorEstimateMaterial::Errors(const TPZVec>
     REAL innerexact = 0.;
     REAL innerestimate = 0.;
 
-#ifdef PZDEBUG2
-    std::cout<<"flux fem "<fExactSol) {
             innerexact += (fluxfem[i] + fluxexactneg(i, 0)) * (fluxfem[i] + fluxexactneg(i, 0)) / perm;
@@ -328,29 +320,12 @@ void TPZHDivErrorEstimateMaterial::Errors(const TPZVec>
         exact_pressure_error = (pressurefem - u_exact[0]) * (pressurefem - u_exact[0]);
     }
 
-#ifdef PZDEBUG2
-    std::cout<<"potential fem "<isDebugEnabled()) {
-        std::stringstream sout;
-        sout << "Coord: " << data[H1functionposition].x[0] << ", " << data[H1functionposition].x[1] << ", "
-             << data[H1functionposition].x[2] << '\n';
-        sout << "PressureReconstructed = " << pressurereconstructed << "\n";
-        sout << "FluxReconstructed = " << fluxreconstructed[0] << ", " << fluxreconstructed[1] << ", "
-             << fluxreconstructed[2] << "\n";
-        LOGPZ_DEBUG(logger, sout.str())
-    }
-#endif
 }
 
 int TPZHDivErrorEstimateMaterial::VariableIndex(const std::string &name) const {

From 160624c14b0244cd49272a69801e94906adbc20e Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 22 Sep 2021 10:47:14 -0300
Subject: [PATCH 137/187] Add method to get adaptivity step

---
 ErrorEstimation/TPZHDivErrorEstimator.h | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.h b/ErrorEstimation/TPZHDivErrorEstimator.h
index 94a3476e..ae4b1a95 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.h
+++ b/ErrorEstimation/TPZHDivErrorEstimator.h
@@ -68,6 +68,8 @@ class TPZHDivErrorEstimator {
 
     void SetAdaptivityStep(int step) { fAdaptivityStep = step; };
 
+    [[nodiscard]] int AdaptivityStep() const { return fAdaptivityStep; };
+
     /// compute the element errors comparing the reconstructed solution based on average pressures
     /// with the original solution
     virtual void ComputeErrors(TPZVec &error_vec, TPZVec &element_errors, std::string&vtkPath);

From 8549f15a1763b63133007b4187d1eb055900b56b Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 22 Sep 2021 10:49:05 -0300
Subject: [PATCH 138/187] Add adaptivity to SPE10

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp |   1 +
 Projects/SPE10/mainSPE10.cpp              | 152 ++++++++++++++++------
 2 files changed, 113 insertions(+), 40 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 26639aa9..8dcda079 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -92,6 +92,7 @@ void TPZHDivErrorEstimator::ComputeErrors(TPZVec&errorVec, TPZVec& e
     
     // Calculate error and store in element solution
     bool store_error = true;
+    an.SetThreadsForError(12);
     an.PostProcessError(errorVec, store_error);
 
     TPZCompMeshTools::UnCondensedElements(&fPostProcMesh);
diff --git a/Projects/SPE10/mainSPE10.cpp b/Projects/SPE10/mainSPE10.cpp
index 97aec028..1cd6abba 100644
--- a/Projects/SPE10/mainSPE10.cpp
+++ b/Projects/SPE10/mainSPE10.cpp
@@ -23,12 +23,14 @@ void ReadSPE10CellPermeabilities(TPZVec*perm_vec, int layer);
 TPZGeoMesh *CreateSPE10GeoMesh();
 STATE PermeabilityFunction(const TPZVec &x);
 void InsertMaterials(TPZCompMesh *cmesh);
-void CreateSPE10MHMCompMesh(TPZMHMixedMeshControl &mhm);
-void SolveMHMProblem(TPZMHMixedMeshControl &mhm);
-void EstimateError(TPZMHMixedMeshControl *mhm);
+void CreateSPE10MHMCompMesh(TPZMHMixedMeshControl &mhm, const std::vector &skelsToDivide);
+void SolveMHMProblem(TPZMHMixedMeshControl &mhm, int adaptivity_step);
+void EstimateError(TPZMHMixedMeshControl &mhm, TPZMHMHDivErrorEstimator &estimator);
+void MHMAdaptivity(TPZMHMixedMeshControl *mhm, TPZCompMesh *postProcMesh, std::vector &skelsToRefine);
 
 int main() {
 
+    constexpr int adaptivity_steps = 3;
     constexpr int layer = 36;
     constexpr int nx = 220;
     constexpr int ny = 60;
@@ -37,28 +39,45 @@ int main() {
     auto perm_vec = TPZManVector(n_cells, 1);
     ReadSPE10CellPermeabilities(&perm_vec, layer);
 
-    TPZGeoMesh *gmesh = CreateSPE10GeoMesh();
-    std::cout << "SPE10 initial grid created. NElem: " << gmesh->NElements() << "\n";
-    Tools::PrintGeometry(gmesh, "SPE10GeoMesh", false, true);
-
-    std::vector x, y, perm;
-    for (int i = 0; i < nx; i++) {
-        for (int j = 0; j < ny; j++) {
-            const int cell_id = ny * i + j;
-            const double cell_perm = perm_vec[cell_id];
-            x.push_back(0.5 + i);
-            y.push_back(0.5 + j);
-            perm.push_back(cell_perm);
+    std::vector skelsToRefine;
+    for (int step = 0; step < adaptivity_steps; step++) {
+
+        TPZGeoMesh *gmesh = CreateSPE10GeoMesh();
+        std::cout << "SPE10 initial grid created. NElem: " << gmesh->NElements() << "\n";
+
+        std::vector x, y, perm;
+        for (int i = 0; i < nx; i++) {
+            for (int j = 0; j < ny; j++) {
+                const int cell_id = ny * i + j;
+                const double cell_perm = perm_vec[cell_id];
+                x.push_back(0.5 + i);
+                y.push_back(0.5 + j);
+                perm.push_back(cell_perm);
+            }
         }
-    }
 
-    interpolator.setData(x.size(), x.data(), y.data(), perm.data());
+        interpolator.setData(x.size(), x.data(), y.data(), perm.data());
+
+        TPZMHMixedMeshControl mhm(gmesh);
+        CreateSPE10MHMCompMesh(mhm, skelsToRefine);
+        std::stringstream filename;
+        filename << "SPE10GeoMesh-Step" << step;
+        Tools::PrintGeometry(gmesh, filename.str(), false, true);
+
+        SolveMHMProblem(mhm, step);
+
+        bool postProcWithHDiv = false;
+        TPZMultiphysicsCompMesh *originalMesh = dynamic_cast(mhm.CMesh().operator->());
+        if (!originalMesh) DebugStop();
+        TPZMHMHDivErrorEstimator estimator(*originalMesh, &mhm, postProcWithHDiv);
+        estimator.SetAdaptivityStep(step);
+        EstimateError(mhm, estimator);
 
-    TPZMHMixedMeshControl mhm(gmesh);
-    CreateSPE10MHMCompMesh(mhm);
+        auto *postprocmesh = estimator.PostProcMesh();
+        if (!postprocmesh) DebugStop();
 
-    SolveMHMProblem(mhm);
-    EstimateError(&mhm);
+        MHMAdaptivity(&mhm, postprocmesh, skelsToRefine);
+    }
 
     return 0;
 }
@@ -94,8 +113,8 @@ void ReadSPE10CellPermeabilities(TPZVec *perm_vec, const int layer) {
     }
 
     int cell_id = 0;
-    const int n_cells = perm_vec->size();
-    const int start_line = 1 + n_cells * (layer - 1) / 6;
+    const auto n_cells = perm_vec->size();
+    const auto start_line = 1 + n_cells * (layer - 1) / 6;
 
     int line_num = 0;
     int line_num2 = 0;
@@ -127,7 +146,7 @@ STATE PermeabilityFunction(const TPZVec &x) {
     return perm;
 }
 
-void CreateSPE10MHMCompMesh(TPZMHMixedMeshControl &mhm) {
+void CreateSPE10MHMCompMesh(TPZMHMixedMeshControl &mhm, const std::vector &skelsToDivide) {
 
     TPZGeoMesh *gmesh = mhm.GMesh().operator->();
     TPZManVector coarse_indexes;
@@ -153,20 +172,17 @@ void CreateSPE10MHMCompMesh(TPZMHMixedMeshControl &mhm) {
     mhm.SetHdivmaismaisPOrder(1);
 
     // Refine skeleton elements
-    mhm.DivideSkeletonElements(0);
+    for (auto skelid : skelsToDivide) {
+        mhm.DivideSkeletonElement(skelid);
+    }
     mhm.DivideBoundarySkeletonElements();
 
     // Creates MHM mesh
     bool substructure = true;
     mhm.BuildComputationalMesh(substructure);
-    //{
-    //    std::string fileName = "CompMesh.txt";
-    //    std::ofstream file(fileName);
-    //    mhm.CMesh()->Print(file);
-    //}
 }
 
-void SolveMHMProblem(TPZMHMixedMeshControl &mhm) {
+void SolveMHMProblem(TPZMHMixedMeshControl &mhm, const int adaptivity_step) {
 
     TPZAutoPointer cmesh = mhm.CMesh();
 
@@ -209,8 +225,9 @@ void SolveMHMProblem(TPZMHMixedMeshControl &mhm) {
     vecnames.Push("Flux");
 
     int resolution = 0;
-    std::string plotname = "SPE10-Results.vtk";
-    an.DefineGraphMesh(cmesh->Dimension(), scalnames, vecnames, plotname);
+    std::stringstream plotname;
+    plotname << "SPE10-Results-Step" << adaptivity_step << ".vtk";
+    an.DefineGraphMesh(cmesh->Dimension(), scalnames, vecnames, plotname.str());
     an.PostProcess(resolution, cmesh->Dimension());
 }
 
@@ -232,23 +249,78 @@ void InsertMaterials(TPZCompMesh *cmesh) {
     cmesh->InsertMaterialObject(pressure_left);
 }
 
-void EstimateError(TPZMHMixedMeshControl *mhm) {
+void EstimateError(TPZMHMixedMeshControl &mhm, TPZMHMHDivErrorEstimator &estimator) {
 
     std::cout << "\nError Estimation processing for MHM-Hdiv problem " << std::endl;
 
     // Error estimation
-    TPZMultiphysicsCompMesh *originalMesh = dynamic_cast(mhm->CMesh().operator->());
+    TPZMultiphysicsCompMesh *originalMesh = dynamic_cast(mhm.CMesh().operator->());
     if (!originalMesh) DebugStop();
 
-    bool postProcWithHDiv = false;
-    TPZMHMHDivErrorEstimator ErrorEstimator(*originalMesh, mhm, postProcWithHDiv);
-    ErrorEstimator.PotentialReconstruction();
+    estimator.PotentialReconstruction();
 
     std::string command = "mkdir SPE10";
     system(command.c_str());
 
     TPZManVector errors;
     TPZManVector elementerrors;
-    std::string outVTK = "SPE10-Errors.vtk";
-    ErrorEstimator.ComputeErrors(errors, elementerrors, outVTK);
+    std::stringstream plotname;
+    plotname << "SPE10-Errors-Step" << estimator.AdaptivityStep() << ".vtk";
+    auto plotname_str = plotname.str();
+    estimator.ComputeErrors(errors, elementerrors, plotname_str);
+    std::cout << "Finished computing errors!";
 }
+
+void MHMAdaptivity(TPZMHMixedMeshControl *mhm, TPZCompMesh *postProcMesh, std::vector &skelsToRefine) {
+
+    // Column of the flux error estimate on the element solution matrix
+    const int fluxErrorEstimateCol = 3;
+
+    TPZMultiphysicsCompMesh *cmesh = dynamic_cast(mhm->CMesh().operator->());
+    if (!cmesh) DebugStop();
+
+    TPZFMatrix &sol = postProcMesh->ElementSolution();
+    TPZSolutionMatrix &elsol = postProcMesh->ElementSolution();
+    int64_t nelem = elsol.Rows();
+
+    // Iterates through element errors to get the maximum value
+    STATE maxError = 0.;
+    for (int64_t iel = 0; iel < nelem; iel++) {
+        auto * submesh = dynamic_cast(postProcMesh->ElementVec()[iel]);
+        if (!submesh) continue;
+
+        STATE submeshError = sol(iel, fluxErrorEstimateCol);
+        if (submeshError > maxError) {
+            maxError = submeshError;
+        }
+    }
+
+    std::cout << "Max error: " << maxError << "\n";
+
+    // Refines elements which error are bigger than 30% of the maximum error
+    REAL threshold = 0.5 * maxError;
+    const auto geoToMHM = mhm->GetGeoToMHMDomain();
+    const auto interfaces = mhm->GetInterfaces();
+
+    std::set interfacesToRefine;
+    for (int64_t iel = 0; iel < nelem; iel++) {
+        auto * submesh = dynamic_cast(postProcMesh->ElementVec()[iel]);
+        if (!submesh) continue;
+
+        STATE submeshError = sol(iel, fluxErrorEstimateCol);
+        if (submeshError > threshold) {
+            TPZGeoEl * gel = submesh->Element(0)->Reference();
+            const auto submesh_id = geoToMHM[gel->Index()];
+            std::cout << "Refining submesh " << submesh_id << " which error is " << submeshError << ".\n";
+            for (auto interface : interfaces) {
+                if (interface.second.first == submesh_id || interface.second.second == submesh_id) {
+                    interfacesToRefine.insert(interface.first);
+                }
+            }
+        }
+    }
+
+    for (auto it : interfacesToRefine) {
+        skelsToRefine.push_back(it);
+    }
+}
\ No newline at end of file

From 240a9c70b80b69f390dfd3a467436f3655aa88b8 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 22 Sep 2021 10:49:23 -0300
Subject: [PATCH 139/187] Fix deprecated include

---
 Projects/Tools/ToolsMHM.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/Projects/Tools/ToolsMHM.h b/Projects/Tools/ToolsMHM.h
index eab7765c..06a45ef4 100644
--- a/Projects/Tools/ToolsMHM.h
+++ b/Projects/Tools/ToolsMHM.h
@@ -8,7 +8,7 @@
 #ifndef ToolsMHM_hpp
 #define ToolsMHM_hpp
 
-#include 
+#include 
 
 #endif /* ToolsMHM_hpp */
 

From 7db6e9dfb6c927db02012a198b6054b83b6fcb15 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Mon, 27 Sep 2021 13:34:50 -0300
Subject: [PATCH 140/187] Create data structure to store the reference solution

---
 .../Material/TPZHDivErrorEstimateMaterial.h   |  2 +-
 ErrorEstimation/TPZHDivErrorEstimator.cpp     | 21 +++++++++++++++++--
 ErrorEstimation/TPZHDivErrorEstimator.h       |  4 ++++
 3 files changed, 24 insertions(+), 3 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
index 9edf8bd4..6e72926a 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
@@ -78,7 +78,7 @@ class TPZHDivErrorEstimateMaterial: public virtual TPZMatBaseSetReferenceSolution(fHasReferenceSolution);
+                new_mat = ee_mat;
             }
             if (orig_mat->HasForcingFunction()) {
                 new_mat->SetForcingFunction(orig_mat->ForcingFunction(), orig_mat->ForcingFunctionPOrder());
@@ -2446,4 +2448,19 @@ std::set TPZHDivErrorEstimator::GetBCMatIDs(const TPZCompMesh* cmesh) {
         }
     }
     return bc_mat_ids;
-}
\ No newline at end of file
+}
+
+void TPZHDivErrorEstimator::SetReferenceSolutionMeshes(TPZCompMesh* ref_pressure, TPZCompMesh* ref_flux) {
+    fHasReferenceSolution = true;
+    auto &mesh_vec = fPostProcMesh.MeshVector();
+    auto active_spaces = fPostProcMesh.GetActiveApproximationSpaces();
+
+    mesh_vec.resize(6);
+    active_spaces.resize(6);
+
+    mesh_vec[4] = ref_pressure;
+    mesh_vec[5] = ref_flux;
+
+    active_spaces[4] = 0;
+    active_spaces[5] = 0;
+}
diff --git a/ErrorEstimation/TPZHDivErrorEstimator.h b/ErrorEstimation/TPZHDivErrorEstimator.h
index ae4b1a95..925f7763 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.h
+++ b/ErrorEstimation/TPZHDivErrorEstimator.h
@@ -43,6 +43,8 @@ class TPZHDivErrorEstimator {
 
     int fAdaptivityStep{0};
 
+    bool fHasReferenceSolution{false};
+
 private:
     // object to assist in creating a hybridized version of the computational mesh
     TPZHybridizeHDiv fHybridizer;
@@ -184,6 +186,8 @@ class TPZHDivErrorEstimator {
     bool IsAdjacentToHangingNode(const TPZCompElSide &celside);
 
     static std::set GetBCMatIDs(const TPZCompMesh* cmesh);
+
+    void SetReferenceSolutionMeshes(TPZCompMesh* ref_pressure, TPZCompMesh* ref_flux);
 };
 
 #endif /* TPZHybridHDivErrorEstimator_hpp */

From d1623880c9127cdd37ca76368152ad7faa6611a3 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 6 Oct 2021 16:06:29 -0300
Subject: [PATCH 141/187] Fix typo

---
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index e8110ca4..3391dece 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -213,7 +213,7 @@ void TPZHDivErrorEstimateMaterial::ContributeBC(const TPZVec
Date: Wed, 6 Oct 2021 16:07:34 -0300
Subject: [PATCH 142/187] Clean up Errors method

---
 .../Material/TPZHDivErrorEstimateMaterial.cpp | 133 +++++++-----------
 1 file changed, 54 insertions(+), 79 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index 3391dece..552b60ee 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -239,93 +239,68 @@ TPZHDivErrorEstimateMaterial::FillBoundaryConditionDataRequirements(int type,
 }
 
 void TPZHDivErrorEstimateMaterial::Errors(const TPZVec> &data, TPZVec &errors) {
-    /**
-     datavec[0] H1 mesh, uh_reconstructed
-     datavec[1] L2 mesh,
-     datavec[2] Hdiv fem mesh, sigma_h
-     datavec[3] L2 mesh fem, u_h
-     
-      error[0] - error computed with exact pressure
-      error[1] - error computed with reconstructed pressure
-      error[2] - energy error computed with exact solution
-      error[3] - energy error computed with reconstructed solution
-      error[4] - oscillatory data error
-     **/
-
-    TPZManVector fluxfem = data[2].sol[0];
-    STATE divsigmafem, pressurefem, pressurereconstructed;
-
-    TPZFNMatrix<3, REAL> fluxreconstructed(3, 1);
-
-    divsigmafem = data[2].divsol[0][0];
-
-    STATE divtest = 0.;
-    for (int j = 0; j < fDim; j++) {
-        divtest += data[2].dsol[0](j, j);
+    /*
+     * data[0]: H1 mesh, uh_reconstructed
+     * data[1]: L2 mesh,
+     * data[2]: Hdiv fem mesh, sigma_h
+     * data[3]: L2 mesh fem, u_h
+     *
+     * error[0]: error computed with exact/reference pressure
+     * error[1]: error computed with reconstructed pressure
+     * error[2]: energy error computed with exact/reference solution
+     * error[3]: energy error computed with reconstructed solution
+     * error[4]: oscillatory data error
+     */
+
+    // Variables to store error norms/components
+    STATE flux_error_estimate = 0.;
+    STATE flux_error_exact = 0.;
+    STATE pressure_error_estimate = 0.;
+    STATE pressure_error_exact = 0.;
+    STATE residual_error = 0.;
+
+    const auto perm = GetPermeability(data[1].x);
+
+    const auto pressurefem = data[3].sol[0][0];
+    const auto &fluxfem = data[2].sol[0];
+    const auto divfluxfem = data[2].divsol[0][0];
+    const auto pressurerec = data[1].sol[0][0];
+
+    // Calculate estimated errors
+    const auto &du_rec = data[1].dsol[0];
+    TPZFNMatrix<3, REAL> flux_rec(3, 1);
+    TPZAxesTools::Axes2XYZ(du_rec, flux_rec, data[1].axes);
+    pressure_error_estimate = (pressurefem - pressurerec) * (pressurefem - pressurerec);
+    for (int i = 0; i < 3; i++) {
+        flux_rec(i, 0) = -perm * flux_rec(i, 0);
+        flux_error_estimate += (fluxfem[i] - flux_rec(i, 0)) * (fluxfem[i] - flux_rec(i, 0)) / perm;
     }
 
-    int H1functionposition = FirstNonNullApproxSpaceIndex(data);
-
-    TPZVec divsigma(1);
-    divsigma[0] = 0.;
-
-    TPZManVector u_exact(1);
-    TPZFNMatrix<9, STATE> du_exact(3, 3);
+    // Calculate exact errors, if applicable
     if (this->fExactSol) {
-        this->fExactSol(data[H1functionposition].x, u_exact, du_exact);
-    }
-    if (this->fForcingFunction) {
-        this->fForcingFunction(data[H1functionposition].x, divsigma);
-    }
-
-    REAL residual = (divsigma[0] - divsigmafem) * (divsigma[0] - divsigmafem);
-    pressurereconstructed = data[H1functionposition].sol[0][0];
-    pressurefem = data[3].sol[0][0];
-
-    STATE perm = GetPermeability(data[1].x);
-
-    TPZFNMatrix<3, REAL> fluxexactneg(3, 1);
-
-    //sigmarec = -K grad(urec)
-    //  sigmak = -K graduk
-
-    {
-        TPZFNMatrix<9, REAL> gradpressure(3, 1);
+        TPZManVector u_exact(1);
+        TPZFNMatrix<3, STATE> flux_exact(3, 1);
+        this->fExactSol(data[1].x, u_exact, flux_exact);
+        pressure_error_exact = (pressurefem - u_exact[0]) * (pressurefem - u_exact[0]);
         for (int i = 0; i < 3; i++) {
-            fluxexactneg(i, 0) = perm * du_exact[i];
-        }
-    }
-
-    TPZFMatrix &dsolaxes = data[H1functionposition].dsol[0];
-    TPZFNMatrix<9, REAL> fluxrec(3, 0);
-    TPZAxesTools::Axes2XYZ(dsolaxes, fluxrec, data[H1functionposition].axes);
-
-    for (int id = 0; id < 3; id++) {
-        fluxreconstructed(id, 0) = (-1.) * perm * fluxrec(id, 0);
-    }
-
-    REAL innerexact = 0.;
-    REAL innerestimate = 0.;
-
-    for (int i = 0; i < 3; i++) {
-        if (this->fExactSol) {
-            innerexact += (fluxfem[i] + fluxexactneg(i, 0)) * (fluxfem[i] + fluxexactneg(i, 0)) / perm;
-            // Pq esta somando: o fluxo fem esta + e o exato -
+            flux_exact(i, 0) = -perm * flux_exact(i, 0);
+            flux_error_exact += (fluxfem[i] - flux_exact(i, 0)) * (fluxfem[i] - flux_exact(i, 0)) / perm;
         }
-        innerestimate += (fluxfem[i] - fluxreconstructed[i]) * (fluxfem[i] - fluxreconstructed[i]) / perm;
     }
 
-    STATE exact_pressure_error = 0;
-    if (this->fExactSol) {
-        exact_pressure_error = (pressurefem - u_exact[0]) * (pressurefem - u_exact[0]);
+    // Calculate residual component
+    TPZManVector source_term(1, 0);
+    if (this->fForcingFunction) {
+        this->fForcingFunction(data[1].x, source_term);
     }
-
-    errors[0] = exact_pressure_error;
-    errors[1] =
-            (pressurefem - pressurereconstructed) * (pressurefem - pressurereconstructed);//error pressure reconstructed
-    errors[2] = innerexact;//error flux exact
-    errors[3] = innerestimate;//error flux reconstructed
-    errors[4] = residual; //||f - Proj_divsigma||
+    residual_error = (source_term[0] - divfluxfem) * (source_term[0] - divfluxfem);
+
+    // Fill error vector
+    errors[0] = pressure_error_exact;
+    errors[1] = pressure_error_estimate;
+    errors[2] = flux_error_exact;
+    errors[3] = flux_error_estimate;
+    errors[4] = residual_error;
 }
 
 int TPZHDivErrorEstimateMaterial::VariableIndex(const std::string &name) const {

From 588c84b322786c40645a73b3196e2941b52d52aa Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 6 Oct 2021 16:07:46 -0300
Subject: [PATCH 143/187] Remove commented method

---
 .../Material/TPZHDivErrorEstimateMaterial.cpp | 83 -------------------
 1 file changed, 83 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index 552b60ee..eb21ea1d 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -426,86 +426,3 @@ TPZHDivErrorEstimateMaterial::Solution(const TPZVec> &da
             DebugStop();
     }
 }
-
-//void TPZHDivErrorEstimateMaterial::ErrorsBC(TPZVec &data, TPZVec &u_exact,
-//                                            TPZFMatrix &du_exact, TPZVec &errors, TPZBndCond &bc) {
-//
-//    if (bc.Type() == 4) {
-//
-//
-//        errors.Resize(NEvalErrors());
-//        errors.Fill(0.0);
-//
-//
-//        TPZFNMatrix<3, REAL> fluxreconstructed(3, 1), fluxreconstructed2(3, 1);
-//        TPZManVector fluxfem(3);
-//
-//        int H1functionposition = 0;
-//        H1functionposition = FirstNonNullApproxSpaceIndex(data);
-//
-//        REAL normalsigmafem = 0., normalsigmarec = 0., urec = 0.;;
-//        normalsigmafem = data[2].sol[0][0];// sigma.n
-//        urec = data[H1functionposition].sol[0][0];
-//
-//
-//        REAL u_D = 0., g = 0.;
-//        REAL normflux = 0.;
-//
-//        TPZManVector fluxrec(fDim);
-//        this->Solution(data, VariableIndex("FluxReconstructed"), fluxrec);
-//
-//        //      std::cout<<"flux_rec "< PermTensor, InvPermTensor;
-//        TPZManVector res(3);
-//        TPZFNMatrix<9, STATE> gradu(this->Dimension(), 1);
-//
-//        if (bc.HasForcingFunction()) {
-//            bc.ForcingFunction()->Execute(data[H1functionposition].x, res, gradu);
-//            GetPermeabilities(data[0].x, PermTensor, InvPermTensor);
-//            u_D = res[0];
-//
-//
-//        } else {
-//            // usualmente updatebc coloca o valor exato no val2
-//            u_D = bc.Val2()(0, 0);
-//        }
-//
-//
-//        for (int i = 0; i < 3; i++) {
-//            for (int j = 0; j < 3; j++) {
-//
-//                normflux += data[2].normal[i] * PermTensor(i, j) * gradu(j, 0);
-//
-//            }
-//        }
-//        g = (-1) * normflux;
-//
-//        //       std::cout<<"n_0 "<
Date: Wed, 13 Oct 2021 17:00:29 -0300
Subject: [PATCH 144/187] Decrease post processing resolution

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 2a5c23fe..3fbba652 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -2232,7 +2232,7 @@ void TPZHDivErrorEstimator::ComputePressureWeights() {
             plotname = out.str();
         }
         an.DefineGraphMesh(targetDim, scalnames, vecnames, plotname);
-        an.PostProcess(4, targetDim);
+        an.PostProcess(0, targetDim);
     }
 }
 

From 00d2403857c71fd70d9aec9017bd2222c808a942 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 13 Oct 2021 17:06:38 -0300
Subject: [PATCH 145/187] Update MHM adaptivity process

---
 Projects/ErrorEstimationMHM/main_Journal.cpp | 72 ++++++++++++--------
 1 file changed, 43 insertions(+), 29 deletions(-)

diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp
index da6354b3..97b7bccf 100644
--- a/Projects/ErrorEstimationMHM/main_Journal.cpp
+++ b/Projects/ErrorEstimationMHM/main_Journal.cpp
@@ -43,7 +43,7 @@ void RunNonConvexProblem();
 void RunHighGradientProblem(int nCoarseDiv, int nInternalRef);
 void RunInnerSingularityProblem(int nCoarseDiv, int nInternalRef, int k, int n);
 void RunPeriodicPermProblem(int nCoarseDiv, int nInternalRef);
-void RunHighGradientAdaptivityProblem(int n_steps);
+void RunHighGradientAdaptivityProblem(int n_divisions);
 
 TPZGeoMesh *CreateQuadGeoMesh(int nCoarseDiv, int nInternalRef);
 TPZGeoMesh *CreateLShapeGeoMesh(int nCoarseRef, int nInternalRef, TPZStack &mhmIndexes);
@@ -53,7 +53,7 @@ void CreateMHMCompMesh(TPZMHMixedMeshControl *mhm, const ProblemConfig &config,
                        TPZManVector &mhmIndexes);
 
 void CreateMHMCompMesh(TPZMHMixedMeshControl *mhm, const ProblemConfig &config, bool definePartitionByCoarseIndex,
-                       TPZManVector &mhmIndexes, const std::vector& skelsToDivide);
+                       TPZManVector &mhmIndexes, const std::vector &refLevelPerSubdomain);
 
 void CreateMHMCompMeshHeteroPerm(TPZMHMixedMeshControl *mhm, const ProblemConfig &config, int nInternalRef,
                                  bool definePartitionByCoarseIndex, TPZManVector& mhmIndexes);
@@ -64,7 +64,7 @@ void EstimateError(ProblemConfig &config, TPZMHMixedMeshControl *mhm);
 void EstimateError(ProblemConfig &config, TPZMHMixedMeshControl *mhm, TPZMHMHDivErrorEstimator &estimator);
 
 void MHMAdaptivity(TPZMHMixedMeshControl *mhm, ProblemConfig &config, TPZCompMesh *postProcMesh,
-                   std::vector &skelsToRefine);
+                   std::vector &refLevelPerSubdomain);
 
 void CreateMHMCompMeshPermFunction(TPZMHMixedMeshControl &mhm);
 void PeriodicProblemForcingFunction(const TPZVec  &pt, TPZVec  &result);
@@ -83,7 +83,7 @@ int main() {
     gRefDBase.InitializeAllUniformRefPatterns();
 
     const std::set nCoarseDiv = {8};
-    const std::set nInternalRef = {0};
+    const std::set nInternalRef = {1};
     const std::set kOrder = {1};
     const std::set nOrder = {2};
 
@@ -99,6 +99,7 @@ int main() {
 
     return 0;
 }
+
 void RunInnerSingularityProblemSuite(const std::set &nCoarseDiv, const std::set &nInternalRef,
                                      const std::set &kOrder, const std::set &nOrder) {
     for (const auto k : kOrder) {
@@ -464,7 +465,7 @@ TPZGeoMesh *CreateLShapeGeoMesh(int nCoarseRef, int nInternalRef, TPZStack &mhmIndexes, const std::vector &skelsToDivide) {
+                       TPZManVector &mhmIndexes, const std::vector &refLevelPerSubdomain) {
 
     if (definePartitionByCoarseIndex) {
         mhm->DefinePartitionbyCoarseIndices(mhmIndexes);
@@ -484,9 +485,15 @@ void CreateMHMCompMesh(TPZMHMixedMeshControl *mhm, const ProblemConfig &config,
     mhm->SetSkeletonPOrder(config.porder);
     mhm->SetHdivmaismaisPOrder(config.hdivmais);
 
-    // Refine skeleton elements
-    for (auto skelid : skelsToDivide) {
-        mhm->DivideSkeletonElement(skelid);
+    const auto interfaces = mhm->GetInterfaces();
+    if (!refLevelPerSubdomain.empty()) {
+        for (auto interface : interfaces) {
+            if (interface.first == interface.second.first || interface.first == interface.second.second) continue;
+            auto right_ref_level = refLevelPerSubdomain[interface.second.first];
+            auto left_ref_level = refLevelPerSubdomain[interface.second.second];
+            const auto n_divisions = std::max(right_ref_level, left_ref_level);
+            mhm->DivideSkeletonElement(interface.first, n_divisions);
+        }
     }
 
     mhm->DivideBoundarySkeletonElements();
@@ -913,7 +920,7 @@ void PrintLatexGraphs(std::ostream & out) {
     std::cout << latex_text.str();
 }
 
-void RunHighGradientAdaptivityProblem(const int n_steps){
+void RunHighGradientAdaptivityProblem(const int n_divisions){
 
     ProblemConfig config;
     config.dimension = 2;
@@ -927,28 +934,33 @@ void RunHighGradientAdaptivityProblem(const int n_steps){
     config.bcmaterialids.insert(-1);
     config.makepressurecontinuous = true;
 
-    int nCoarseRef = 4;
-    int nInternalRef = 4;
+    int nCoarseRef = 7;
+    int nInternalRef = n_divisions;
 
     config.ndivisions = nCoarseRef;
 
     std::string command = "mkdir -p " + config.dir_name;
     system(command.c_str());
 
-    std::vector skelsToRefine;
-    for (int i = 0; i < n_steps; i++) {
-
+    std::vector refLevelPerSubdomain;
+    int max_refinement = 0;
+    int adaptivity_step = 0;
+    while (max_refinement <= n_divisions) {
         config.gmesh = CreateQuadGeoMesh(nCoarseRef, nInternalRef);
 
         auto *mhm = new TPZMHMixedMeshControl(config.gmesh);
         TPZManVector coarseIndexes;
         ComputeCoarseIndices(config.gmesh, coarseIndexes);
         bool definePartitionByCoarseIndexes = true;
-        CreateMHMCompMesh(mhm, config, definePartitionByCoarseIndexes, coarseIndexes, skelsToRefine);
+        CreateMHMCompMesh(mhm, config, definePartitionByCoarseIndexes, coarseIndexes, refLevelPerSubdomain);
+        if (max_refinement == 0) {
+            const auto n_subdomains = mhm->Coarse_to_Submesh().size();
+            refLevelPerSubdomain.resize(n_subdomains, 0);
+        }
 
         {
-            std::string fileName =
-                config.dir_name + "/" + config.problemname + "GMesh" + std::to_string(i) + ".vtk";
+            std::string fileName = config.dir_name + "/" + config.problemname + "GMesh" + std::to_string(nCoarseRef) +
+                                   "x" + std::to_string(nCoarseRef) + std::to_string(adaptivity_step) + ".vtk";
             std::ofstream file(fileName);
             TPZVTKGeoMesh::PrintGMeshVTK(config.gmesh, file);
         }
@@ -959,18 +971,22 @@ void RunHighGradientAdaptivityProblem(const int n_steps){
         TPZMultiphysicsCompMesh *originalMesh = dynamic_cast(mhm->CMesh().operator->());
         if (!originalMesh) DebugStop();
         TPZMHMHDivErrorEstimator estimator(*originalMesh, mhm, postProcWithHDiv);
-        estimator.SetAdaptivityStep(i);
+        estimator.SetAdaptivityStep(adaptivity_step);
         EstimateError(config, mhm, estimator);
 
         auto *postprocmesh = estimator.PostProcMesh();
         if (!postprocmesh) DebugStop();
 
-        MHMAdaptivity(mhm, config, postprocmesh, skelsToRefine);
+        MHMAdaptivity(mhm, config, postprocmesh, refLevelPerSubdomain);
+        adaptivity_step++;
+
+        max_refinement = *std::max_element(refLevelPerSubdomain.begin(), refLevelPerSubdomain.end());
+        std::cout << "Max ref level: " << max_refinement << '\n';
     }
 }
 
 void MHMAdaptivity(TPZMHMixedMeshControl *mhm, ProblemConfig &config, TPZCompMesh *postProcMesh,
-                   std::vector &skelsToRefine) {
+                   std::vector &refLevelPerSubdomain) {
 
     // Column of the flux error estimate on the element solution matrix
     const int fluxErrorEstimateCol = 3;
@@ -1001,7 +1017,6 @@ void MHMAdaptivity(TPZMHMixedMeshControl *mhm, ProblemConfig &config, TPZCompMes
     const auto geoToMHM = mhm->GetGeoToMHMDomain();
     const auto interfaces = mhm->GetInterfaces();
 
-    std::set interfacesToRefine;
     for (int64_t iel = 0; iel < nelem; iel++) {
         auto * submesh = dynamic_cast(postProcMesh->ElementVec()[iel]);
         if (!submesh) continue;
@@ -1010,18 +1025,17 @@ void MHMAdaptivity(TPZMHMixedMeshControl *mhm, ProblemConfig &config, TPZCompMes
         if (submeshError > threshold) {
             TPZGeoEl * gel = submesh->Element(0)->Reference();
             const auto submesh_id = geoToMHM[gel->Index()];
-             std::cout << "Refining submesh " << submesh_id << " which error is " << submeshError << ".\n";
-            for (auto interface : interfaces) {
-                if (interface.second.first == submesh_id || interface.second.second == submesh_id) {
-                    interfacesToRefine.insert(interface.first);
-                }
-            }
+            refLevelPerSubdomain[submesh_id]++;
+            std::cout << "Refining submesh " << submesh_id << " which error is " << submeshError << ".\n";
         }
     }
 
-    for (auto it : interfacesToRefine) {
-        skelsToRefine.push_back(it);
+    for (auto i = 0; i < refLevelPerSubdomain.size(); i++) {
+        if (refLevelPerSubdomain[i] != 0) {
+            std::cout << i << ": " << refLevelPerSubdomain[i] << '\n';
+        }
     }
+    std::cout << "Done!\n";
 }
 
 void EstimateError(ProblemConfig &config, TPZMHMixedMeshControl *mhm, TPZMHMHDivErrorEstimator& estimator) {

From 364731d7422553c95ed879d055bf728dd31624b3 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 27 Oct 2021 15:56:12 -0300
Subject: [PATCH 146/187] Create ToolsSPE10 and start working on new gmesh

---
 Projects/SPE10/CMakeLists.txt |   2 +-
 Projects/SPE10/ToolsSPE10.cpp | 113 ++++++++++++++++++++++++++++++++++
 Projects/SPE10/ToolsSPE10.h   |  16 +++++
 Projects/SPE10/mainSPE10.cpp  |  17 ++++-
 4 files changed, 144 insertions(+), 4 deletions(-)
 create mode 100644 Projects/SPE10/ToolsSPE10.cpp
 create mode 100644 Projects/SPE10/ToolsSPE10.h

diff --git a/Projects/SPE10/CMakeLists.txt b/Projects/SPE10/CMakeLists.txt
index 77ab7635..fbcbb1b6 100644
--- a/Projects/SPE10/CMakeLists.txt
+++ b/Projects/SPE10/CMakeLists.txt
@@ -1,4 +1,4 @@
-add_executable(SPE10 mainSPE10.cpp)
+add_executable(SPE10 mainSPE10.cpp ToolsSPE10.cpp ToolsSPE10.h)
 target_link_libraries(SPE10 PRIVATE Tools ErrorEstimationLib)
 
 find_package(libInterpolate REQUIRED)
diff --git a/Projects/SPE10/ToolsSPE10.cpp b/Projects/SPE10/ToolsSPE10.cpp
new file mode 100644
index 00000000..88eadc97
--- /dev/null
+++ b/Projects/SPE10/ToolsSPE10.cpp
@@ -0,0 +1,113 @@
+//
+// Created by Gustavo Batistela on 10/26/21.
+//
+
+#include "ToolsSPE10.h"
+#include 
+#include 
+#include 
+
+[[maybe_unused]] TPZGeoMesh *SPE10::CreateFineGridGeoMesh() {
+
+    TPZManVector bcIDs = {-2, -1, -2, -2};
+    TPZManVector n_elements = {220, 60};
+    TPZManVector x0 = {0, 0, 0};
+    TPZManVector x1 = {220, 60, 0};
+
+    TPZGenGrid2D gen(n_elements, x0, x1, 1, 0);
+    gen.SetRefpatternElements(true);
+
+    auto *gmesh = new TPZGeoMesh;
+    gen.Read(gmesh);
+
+    gen.SetBC(gmesh, 4, bcIDs[0]);
+    gen.SetBC(gmesh, 5, bcIDs[1]);
+    gen.SetBC(gmesh, 6, bcIDs[2]);
+    gen.SetBC(gmesh, 7, bcIDs[3]);
+
+    gmesh->SetDimension(2);
+
+    return gmesh;
+}
+
+[[maybe_unused]] TPZGeoMesh *SPE10::CreateMHMGeoMesh() {
+
+    auto* gmesh = new TPZGeoMesh();
+    gmesh->SetDimension(2);
+
+    TPZManVector coord(3, 0.);
+
+    for (int y = 0; y <= 8; y++) {
+        for (int x = 0; x <= 28; x++) {
+            coord = {8.0 * x, 8.0 * y, 0};
+            if (x == 28) coord[0] = 220.;
+            if (y == 8) coord[1] = 60.;
+
+            // Create new node
+            const auto newID = gmesh->NodeVec().AllocateNewElement();
+            std::cout << newID << ": " << coord[0] << ", " << coord[1] << ", " << coord[2] << '\n';
+            gmesh->NodeVec()[newID].Initialize(coord, *gmesh);
+        }
+    }
+
+    constexpr int porousMediaMatId = 1;
+    constexpr int bcMatId1 = -1;
+    constexpr int bcMatId2 = -2;
+
+    // Inserts quad elements
+    TPZManVector nodesIdVec(4);
+    for (int y = 0; y < 8; y++) {
+        for (int x = 0; x < 28; x++) {
+            nodesIdVec[0] = 29 * y + x;
+            nodesIdVec[1] = 29 * y + x + 1;
+            nodesIdVec[2] = 29 * (y + 1) + x + 1;
+            nodesIdVec[3] = 29 * (y + 1) + x + 0;
+            new TPZGeoElRefPattern(nodesIdVec, porousMediaMatId, *gmesh);
+        }
+    }
+
+    nodesIdVec.resize(2);
+    for (int x = 0; x < 28; x++) {
+        nodesIdVec[0] = x;
+        nodesIdVec[1] = x + 1;
+        new TPZGeoElRefPattern(nodesIdVec, bcMatId1, *gmesh);
+        nodesIdVec[0] = x + 8 * 29;
+        nodesIdVec[1] = x + 8 * 29 + 1;
+        new TPZGeoElRefPattern(nodesIdVec, bcMatId1, *gmesh);
+    }
+
+    for (int y = 0; y < 8; y++) {
+        nodesIdVec[0] = y * 29;
+        nodesIdVec[1] = (y + 1) * 29;
+        new TPZGeoElRefPattern(nodesIdVec, bcMatId1, *gmesh);
+        nodesIdVec[0] = y * 29 + 28;
+        nodesIdVec[1] = (y + 1) * 29 + 28;
+        new TPZGeoElRefPattern(nodesIdVec, bcMatId2, *gmesh);
+    }
+
+    //for (int64_t i = 0; i < 6; i++) {
+    //    nodesIdVec[0] = 0;
+    //    nodesIdVec[1] = 1 + 2 * i;
+    //    nodesIdVec[2] = 3 + 2 * i;
+    //    new TPZGeoElRefPattern>(nodesIdVec, matIdTriangle, *gmesh);
+    //}
+    //// Inserts arc elements
+    //for (int64_t i = 0; i < 6; i++) {
+    //    nodesIdVec[0] = 1 + 2 * i;
+    //    nodesIdVec[1] = 3 + 2 * i;
+    //    nodesIdVec[2] = 2 + 2 * i;
+    //    new TPZGeoElRefPattern(nodesIdVec, matIdArc, *gmesh);
+    //}
+    //// Finally, inserts line elements to complete boundary
+    //nodesIdVec.Resize(2);
+    //nodesIdVec[0] = 0;
+    //nodesIdVec[1] = 1;
+    //new TPZGeoElRefPattern(nodesIdVec, matIdArc, *gmesh);
+
+    //nodesIdVec[0] = 0;
+    //nodesIdVec[1] = 13;
+    //new TPZGeoElRefPattern(nodesIdVec, matIdArc, *gmesh);
+
+    gmesh->BuildConnectivity();
+    return gmesh;
+}
diff --git a/Projects/SPE10/ToolsSPE10.h b/Projects/SPE10/ToolsSPE10.h
new file mode 100644
index 00000000..4b100bd9
--- /dev/null
+++ b/Projects/SPE10/ToolsSPE10.h
@@ -0,0 +1,16 @@
+//
+// Created by Gustavo Batistela on 10/26/21.
+//
+
+#ifndef TOOLSSPE10_H
+#define TOOLSSPE10_H
+
+#include "pzgmesh.h"
+
+namespace SPE10 {
+[[maybe_unused]] [[maybe_unused]] TPZGeoMesh *CreateFineGridGeoMesh();
+[[maybe_unused]] TPZGeoMesh *CreateMHMGeoMesh();
+
+}
+
+#endif // TOOLSSPE10_H
diff --git a/Projects/SPE10/mainSPE10.cpp b/Projects/SPE10/mainSPE10.cpp
index 1cd6abba..dac713f6 100644
--- a/Projects/SPE10/mainSPE10.cpp
+++ b/Projects/SPE10/mainSPE10.cpp
@@ -12,6 +12,7 @@
 #include 
 #include 
 #include 
+#include "ToolsSPE10.h"
 
 typedef _2D::BicubicInterpolator Interpolator;
 
@@ -28,9 +29,19 @@ void SolveMHMProblem(TPZMHMixedMeshControl &mhm, int adaptivity_step);
 void EstimateError(TPZMHMixedMeshControl &mhm, TPZMHMHDivErrorEstimator &estimator);
 void MHMAdaptivity(TPZMHMixedMeshControl *mhm, TPZCompMesh *postProcMesh, std::vector &skelsToRefine);
 
+constexpr int adaptivity_steps = 4;
 int main() {
 
-    constexpr int adaptivity_steps = 3;
+    auto * gmesh = SPE10::CreateFineGridGeoMesh();
+    auto * gmeshMHM = SPE10::CreateMHMGeoMesh();
+
+    {
+        std::string fileName = "GMeshMHM.vtk";
+        std::ofstream file(fileName);
+        TPZVTKGeoMesh::PrintGMeshVTK(gmeshMHM, file);
+    }
+
+    return 0;
     constexpr int layer = 36;
     constexpr int nx = 220;
     constexpr int ny = 60;
@@ -152,7 +163,7 @@ void CreateSPE10MHMCompMesh(TPZMHMixedMeshControl &mhm, const std::vector coarse_indexes;
     ComputeCoarseIndices(gmesh, coarse_indexes);
 
-    int nInternalRef = 3;
+    int nInternalRef = adaptivity_steps;
     Tools::UniformRefinement(nInternalRef, 2, gmesh);
     Tools::DivideLowerDimensionalElements(gmesh);
 
@@ -169,7 +180,7 @@ void CreateSPE10MHMCompMesh(TPZMHMixedMeshControl &mhm, const std::vector
Date: Wed, 3 Nov 2021 09:33:05 -0300
Subject: [PATCH 147/187] Add CreateRefinementGeoMesh function

---
 Projects/SPE10/ToolsSPE10.cpp | 61 ++++++++++++++++++++++-------------
 Projects/SPE10/ToolsSPE10.h   |  1 +
 2 files changed, 40 insertions(+), 22 deletions(-)

diff --git a/Projects/SPE10/ToolsSPE10.cpp b/Projects/SPE10/ToolsSPE10.cpp
index 88eadc97..bde86fb3 100644
--- a/Projects/SPE10/ToolsSPE10.cpp
+++ b/Projects/SPE10/ToolsSPE10.cpp
@@ -85,28 +85,45 @@
         new TPZGeoElRefPattern(nodesIdVec, bcMatId2, *gmesh);
     }
 
-    //for (int64_t i = 0; i < 6; i++) {
-    //    nodesIdVec[0] = 0;
-    //    nodesIdVec[1] = 1 + 2 * i;
-    //    nodesIdVec[2] = 3 + 2 * i;
-    //    new TPZGeoElRefPattern>(nodesIdVec, matIdTriangle, *gmesh);
-    //}
-    //// Inserts arc elements
-    //for (int64_t i = 0; i < 6; i++) {
-    //    nodesIdVec[0] = 1 + 2 * i;
-    //    nodesIdVec[1] = 3 + 2 * i;
-    //    nodesIdVec[2] = 2 + 2 * i;
-    //    new TPZGeoElRefPattern(nodesIdVec, matIdArc, *gmesh);
-    //}
-    //// Finally, inserts line elements to complete boundary
-    //nodesIdVec.Resize(2);
-    //nodesIdVec[0] = 0;
-    //nodesIdVec[1] = 1;
-    //new TPZGeoElRefPattern(nodesIdVec, matIdArc, *gmesh);
-
-    //nodesIdVec[0] = 0;
-    //nodesIdVec[1] = 13;
-    //new TPZGeoElRefPattern(nodesIdVec, matIdArc, *gmesh);
+    gmesh->BuildConnectivity();
+    return gmesh;
+}
+
+[[maybe_unused]] TPZGeoMesh *SPE10::CreateRefinementGeoMesh(const int nx, const int ny) {
+    auto* gmesh = new TPZGeoMesh();
+    gmesh->SetDimension(2);
+    TPZManVector coord(3, 0.);
+
+    for (int y = 0; y <= ny; y++) {
+        for (int x = 0; x <= nx; x++) {
+            coord = {static_cast(x), static_cast(y), 0.};
+            // Create new node
+            const auto newID = gmesh->NodeVec().AllocateNewElement();
+            gmesh->NodeVec()[newID].Initialize(coord, *gmesh);
+        }
+    }
+
+    constexpr int matId = 1;
+
+    // Inserts quad elements
+    TPZManVector nodesIdVec(4, 0);
+    nodesIdVec[1] = nx;
+    nodesIdVec[2] = (ny + 1) * (nx + 1) - 1;
+    nodesIdVec[3] = ny * (nx + 1);
+    auto * father_gel = new TPZGeoElRefPattern(nodesIdVec, matId, *gmesh);
+
+    int nelem = 0;
+    for (int y = 0; y < ny; y++) {
+        for (int x = 0; x < nx; x++) {
+            nodesIdVec[0] = (nx + 1) * y + x;
+            nodesIdVec[1] = (nx + 1) * y + x + 1;
+            nodesIdVec[2] = (nx + 1) * (y + 1) + x + 1;
+            nodesIdVec[3] = (nx + 1) * (y + 1) + x + 0;
+            auto * gel = new TPZGeoElRefPattern(nodesIdVec, matId, *gmesh);
+            gel->SetFather(father_gel);
+            nelem++;
+        }
+    }
 
     gmesh->BuildConnectivity();
     return gmesh;
diff --git a/Projects/SPE10/ToolsSPE10.h b/Projects/SPE10/ToolsSPE10.h
index 4b100bd9..7bf8516a 100644
--- a/Projects/SPE10/ToolsSPE10.h
+++ b/Projects/SPE10/ToolsSPE10.h
@@ -10,6 +10,7 @@
 namespace SPE10 {
 [[maybe_unused]] [[maybe_unused]] TPZGeoMesh *CreateFineGridGeoMesh();
 [[maybe_unused]] TPZGeoMesh *CreateMHMGeoMesh();
+[[maybe_unused]] TPZGeoMesh *CreateRefinementGeoMesh(int nx, int ny);
 
 }
 

From 7636485560b982b243be3396bc786bb3eb1699fc Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 4 Nov 2021 09:22:33 -0300
Subject: [PATCH 148/187] Work on creation of new SPE10 gmesh

---
 Projects/SPE10/ToolsSPE10.cpp | 35 +++++++++++++++++++++++++++++------
 1 file changed, 29 insertions(+), 6 deletions(-)

diff --git a/Projects/SPE10/ToolsSPE10.cpp b/Projects/SPE10/ToolsSPE10.cpp
index bde86fb3..b5ea68da 100644
--- a/Projects/SPE10/ToolsSPE10.cpp
+++ b/Projects/SPE10/ToolsSPE10.cpp
@@ -35,8 +35,19 @@
     auto* gmesh = new TPZGeoMesh();
     gmesh->SetDimension(2);
 
-    TPZManVector coord(3, 0.);
+    auto * gmesh2x1 = CreateRefinementGeoMesh(2, 1);
+    TPZRefPattern ref_pat2x1(*gmesh2x1);
+    TPZAutoPointer ref2x1(&ref_pat2x1);
+
+    auto * gmesh1x2 = CreateRefinementGeoMesh(1, 2);
+    TPZRefPattern ref_pat1x2(*gmesh1x2);
+    TPZAutoPointer ref1x2(&ref_pat1x2);
 
+    auto * gmesh1x1 = CreateRefinementGeoMesh(1, 1);
+    TPZRefPattern ref_pat1x1(*gmesh1x1);
+    TPZAutoPointer ref1x1(&ref_pat1x1);
+
+    TPZManVector coord(3, 0.);
     for (int y = 0; y <= 8; y++) {
         for (int x = 0; x <= 28; x++) {
             coord = {8.0 * x, 8.0 * y, 0};
@@ -45,7 +56,6 @@
 
             // Create new node
             const auto newID = gmesh->NodeVec().AllocateNewElement();
-            std::cout << newID << ": " << coord[0] << ", " << coord[1] << ", " << coord[2] << '\n';
             gmesh->NodeVec()[newID].Initialize(coord, *gmesh);
         }
     }
@@ -62,7 +72,10 @@
             nodesIdVec[1] = 29 * y + x + 1;
             nodesIdVec[2] = 29 * (y + 1) + x + 1;
             nodesIdVec[3] = 29 * (y + 1) + x + 0;
-            new TPZGeoElRefPattern(nodesIdVec, porousMediaMatId, *gmesh);
+            auto * gel = new TPZGeoElRefPattern(nodesIdVec, porousMediaMatId, *gmesh);
+            if (x == 27 && y != 7) gel->SetRefPattern(ref1x2);
+            if (x != 27 && y == 7) gel->SetRefPattern(ref2x1);
+            if (x == 27 && y == 7) gel->SetRefPattern(ref1x1);
         }
     }
 
@@ -86,6 +99,18 @@
     }
 
     gmesh->BuildConnectivity();
+
+    TPZManVector sons;
+    for (int div = 0; div < 3; div++) {
+        auto nelem = gmesh->NElements();
+        for (int64_t i = 0; i < nelem; i++) {
+            auto * gel = gmesh->ElementVec()[i];
+            const int has_sub = gel->HasSubElement();
+            if (has_sub == 0) {
+                gel->Divide(sons);
+            }
+        }
+    }
     return gmesh;
 }
 
@@ -112,7 +137,6 @@
     nodesIdVec[3] = ny * (nx + 1);
     auto * father_gel = new TPZGeoElRefPattern(nodesIdVec, matId, *gmesh);
 
-    int nelem = 0;
     for (int y = 0; y < ny; y++) {
         for (int x = 0; x < nx; x++) {
             nodesIdVec[0] = (nx + 1) * y + x;
@@ -121,10 +145,9 @@
             nodesIdVec[3] = (nx + 1) * (y + 1) + x + 0;
             auto * gel = new TPZGeoElRefPattern(nodesIdVec, matId, *gmesh);
             gel->SetFather(father_gel);
-            nelem++;
         }
     }
 
     gmesh->BuildConnectivity();
     return gmesh;
-}
+}
\ No newline at end of file

From 23f1546f3caa68021394dcbb4aafdd7c8525ba89 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 4 Nov 2021 09:47:06 -0300
Subject: [PATCH 149/187] Clean ToolsMHM functions

---
 Projects/Tools/ToolsMHM.cpp | 415 ++----------------------------------
 Projects/Tools/ToolsMHM.h   | 149 +------------
 2 files changed, 16 insertions(+), 548 deletions(-)

diff --git a/Projects/Tools/ToolsMHM.cpp b/Projects/Tools/ToolsMHM.cpp
index 6c5ff179..584c182d 100644
--- a/Projects/Tools/ToolsMHM.cpp
+++ b/Projects/Tools/ToolsMHM.cpp
@@ -1,123 +1,24 @@
 //
 //  ToolsMHM.cpp
-//  AdaptivityTest
 //
 //  Created by Denise De Siqueira on 01/11/19.
 //
 
 #include "ToolsMHM.h"
-#include 
 #include "pzvec.h"
 #include "pzstack.h"
-#include "pzfmatrix.h"
 #include "pzreal.h"
 #include "pzgmesh.h"
-#include "pzcmesh.h"
-#include "pzcompel.h"
-#include "pzgeoelside.h"
-#include "tpzgeoelrefpattern.h"
-#include "tpzautopointer.h"
-#include "TPZBndCond.h"
-#include "TPZNullMaterial.h"
-
-#include "TPZSSpStructMatrix.h"
-#include "pzstepsolver.h"
-#include "TPZStructMatrix.h"
-
-#include "tpzarc3d.h"
 #include "tpzgeoblend.h"
-
-#include "pzbuildmultiphysicsmesh.h"
-#include "TPZCompMeshTools.h"
-
-#include "TPZVTKGeoMesh.h"
-
 #include "TPZHybridizeHDiv.h"
 #include "TPZGenGrid2D.h"
 
-#include 
 #include 
 #include 
-#include 
-#include "TPZPersistenceManager.h"
-
-#include "TPZMHMHDivErrorEstimator.h"
-
-TPZCompMesh *CMeshFlux(TPZGeoMesh * gmesh,int pOrder){
-    
-    int impervious_mat = 1;
-    int permeable_mat = 2;
-    int dim = gmesh->Dimension();
-    
-    TPZVec convdir(dim,0.0);
-    
-    TPZCompMesh *cmesh = new TPZCompMesh(gmesh);
-    cmesh->SetDimModel(dim);
-    cmesh->SetDefaultOrder(pOrder); //Default polynomial order of the approximation
-    
-    //Definition of the approximation space:
-    
-    auto *mat_0 = new TPZNullMaterial(impervious_mat);
-    auto *mat_1 = new TPZNullMaterial(permeable_mat);
-    
-    //  inserting volumetric materials objects
-    cmesh->InsertMaterialObject(mat_0);
-    cmesh->InsertMaterialObject(mat_1);
-    
-    cmesh->SetAllCreateFunctionsHDiv(); //Creating H(div) functions
-    
-    
-    int type_D = 0;
-    int type_N = 1;
-    TPZFMatrix val1(1, 1, 0.);
-    TPZManVector val2(1, 0.);
-    
-    // Insert boundary conditions
-    //Neumann boundary conditions (flux = 0)
-    int right_bc_id = -2;
-    auto * right_bc = mat_0->CreateBC(mat_0, right_bc_id, type_N, val1, val2);
-    cmesh->InsertMaterialObject(right_bc);
-    
-    int left_bc_id = -4;
-    auto * left_bc = mat_0->CreateBC(mat_0, left_bc_id, type_N, val1, val2);
-    cmesh->InsertMaterialObject(left_bc);
-    
-    int bottom_bc_1id = -1;
-    auto * bottom_bc_1 = mat_0->CreateBC(mat_0, bottom_bc_1id, type_N, val1, val2);
-    cmesh->InsertMaterialObject(bottom_bc_1);
-    
-    int top_bc_1id = -3;
-    auto * top_bc_1 = mat_0->CreateBC(mat_0, top_bc_1id, type_N, val1, val2);
-    cmesh->InsertMaterialObject(top_bc_1);
-
-    //Dirichlet Conditions (p=1 in, p=0 out)
-    int bottom_bc_id = -5;
-    auto * bottom_bc = mat_0->CreateBC(mat_0, bottom_bc_id, type_D, val1, val2);
-    cmesh->InsertMaterialObject(bottom_bc);
-    
-    int top_bc_id = -6;
-    auto * top_bc = mat_0->CreateBC(mat_0, top_bc_id, type_D, val1, val2);
-    cmesh->InsertMaterialObject(top_bc);
-    
-    cmesh->SetName("LaberintoTest");
-    cmesh->AutoBuild();
-    
-#ifdef PZDEBUG
-    std::ofstream file("cmesh_flux.txt");
-    cmesh->Print(file);
-#endif
-    
-    return cmesh;
-    
-}
 
 // compute the coarse indices of the geometric mesh
 void ComputeCoarseIndices(TPZGeoMesh *gmesh, TPZVec &coarseindices)
 {
-    //    {
-    //        std::ofstream out("gmeshref.txt");
-    //        gmesh->Print(out);
-    //    }
     coarseindices.Resize(gmesh->NElements());
     int count = 0;
     for (int64_t el=0; elNElements(); el++) {
@@ -130,203 +31,23 @@ void ComputeCoarseIndices(TPZGeoMesh *gmesh, TPZVec &coarseindices)
     coarseindices.Resize(count);
 }
 
-
-std::map> IdentifyChanel(TPZCompMesh *cmesh){
-    
-    int nelements = cmesh->NElements();
-    TPZGeoElSide first_gelside;
-    for(int iel=0; iel<=nelements; iel++){
-        TPZCompEl *cel = cmesh->Element(iel);
-        if(!cel){continue;}
-        TPZGeoEl *gel = cel->Reference();
-        TPZGeoElSide gelside(gel,4);
-        TPZGeoEl *neig = gelside.Neighbour().Element();
-        if(neig->MaterialId()==-5){
-            first_gelside.SetElement(gel);
-            first_gelside.SetSide(4);
-            break;
-        }
-    }
-    
-    int count=0;
-    int count_chain=0;
-    double Flux_Max = 0.0;
-    std::map> chain;
-    bool exit=false;
-    
-    while(exit==false){
-        
-        TPZGeoElSide exit_test = first_gelside;
-        exit_test.SetSide(6);
-        TPZGeoElSide candidate_exist =exit_test.Neighbour();
-        if(candidate_exist.Element()->MaterialId()==-6){
-            std::cout<<"Cadena encontrada con exito";
-            exit = true;
-            break;
-        }
-        
-        
-        //    while(candidate.Element()->Dimension()!=2){
-        //
-        //            candidate=candidate.Neighbour();
-        //
-        //    }
-        int side_in = first_gelside.Side();
-        for(int ican=4; ican<8; ican++){
-            first_gelside.SetSide(ican);
-            TPZGeoElSide candidate = first_gelside.Neighbour();
-            while(candidate.Element()->Dimension()!=2){
-                
-                candidate=candidate.Neighbour();
-            }
-            if(side_in == ican ){continue;}
-            
-            //calcula los 3 geoelement side y el fluxo
-            TPZVec qsi(2);
-            qsi[0]=0;
-            qsi[1]=0;
-            int var=31;
-            TPZVec sol;
-            TPZCompEl *cel = candidate.Element()->Reference();
-            cel->Solution(qsi, var,sol);
-            double Flux_can_Mag = sqrt(sol[0]*sol[0] + sol[1]*sol[1]);
-            
-            if(Flux_can_Mag > Flux_Max){
-                Flux_Max =Flux_can_Mag;
-                first_gelside.SetSide(ican);
-                chain[count].first= first_gelside;
-                chain[count].second =candidate;
-            }
-        }
-        Flux_Max=0.0;
-        first_gelside =chain[count].second;
-        count++;
-    }
-    
-    //here
-    
-    cmesh->LoadReferences();
-    TPZGeoMesh *gmesh =cmesh->Reference();
-    for(auto it:gmesh->ElementVec()){
-        int father_index = it->FatherIndex();
-        int element = it->Index();
-        std::cout<<"Element: "<> skelchanel;
-    int count_skel_chanel=0;
-    int matId_skel_chanel = 10;
-    count =0;
-    for(auto it : chain){
-        TPZGeoEl *first_element = it.second.first.Element();
-        TPZGeoEl *second_element = it.second.second.Element();
-        
-        int first_father_index = first_element->LowestFather()->Index();
-        int second_father_index = second_element->LowestFather()->Index();
-        
-        if(first_father_index!=second_father_index){
-            TPZGeoElBC(it.second.first, matId_skel_chanel);
-            skelchanel[count_skel_chanel] = it.second;
-            count_skel_chanel++;
-        }
-        
-    }
-    std::ofstream out("TestMesh.vtk");
-    TPZVTKGeoMesh::PrintGMeshVTK(gmesh, out, true);
-    
-    return skelchanel;
-    
-}
-
-TPZGeoMesh *CreateCircleGeoMesh() {
-
-    TPZGeoMesh *gmesh = new TPZGeoMesh();
-    gmesh->SetDimension(2);
-
-    TPZVec coord(3, 0.);
-
-    // Inserts node at origin
-    gmesh->NodeVec().AllocateNewElement();
-    gmesh->NodeVec()[0].Initialize(coord, *gmesh);
-
-    // Inserts circumference nodes
-    for (int64_t i = 0; i < 16; i++) {
-        const REAL step = M_PI / 8;
-        coord[0] = cos(i * step);
-        coord[1] = sin(i * step);
-        std::cout<<"{"<NodeVec().AllocateNewElement();
-        gmesh->NodeVec()[newID].Initialize(coord, *gmesh);
-    }
-
-    int matIdTriangle = 1, matIdArc = 2;
-
-    // Inserts triangle elements
-    TPZManVector nodesIdVec(3);
-    for (int64_t i = 0; i < 7; i++) {
-        nodesIdVec[0] = 0;
-        nodesIdVec[1] = 1 + 2 * i;
-        nodesIdVec[2] = 3 + 2 * i;
-        std::cout<<"{"<>(nodesIdVec, matIdTriangle, *gmesh);
-    }
-    nodesIdVec[0] = 0;
-    nodesIdVec[1] = 15;
-    nodesIdVec[2] = 1;
-
-    new TPZGeoElRefPattern>(nodesIdVec, matIdTriangle, *gmesh);
-    // Inserts arc elements
-    for (int64_t i = 0; i < 7; i++) {
-        nodesIdVec[0] = 1 + 2 * i;
-        nodesIdVec[1] = 3 + 2 * i;
-        nodesIdVec[2] = 2 + 2 * i;
-        new TPZGeoElRefPattern(nodesIdVec, matIdArc, *gmesh);
-    }
-
-    nodesIdVec[0] = 15;
-    nodesIdVec[1] = 1;
-    nodesIdVec[2] = 16;
-    //para o broblema do douglas matIdArc=3
-    new TPZGeoElRefPattern(nodesIdVec, 3, *gmesh);
-    //    // Finally, inserts line elements to complete boundary
-    //    nodesIdVec.Resize(2);
-    //    nodesIdVec[0] = 0;
-    //    nodesIdVec[1] = 1;
-    //    new TPZGeoElRefPattern(nodesIdVec, matIdArc, *gmesh);
-    //
-    //    nodesIdVec[0] = 0;
-    //    nodesIdVec[1] = 14;
-    //    new TPZGeoElRefPattern(nodesIdVec, matIdArc, *gmesh);
-
-    gmesh->BuildConnectivity();
-
-    return gmesh;
-}
-
 TPZGeoMesh *CreateLMHMMesh(int nDiv, TPZVec& coarseIndexes) {
+
+    int factor = static_cast(lround(pow(2, nDiv) + 0.5));
     
-    int factor = (int)(pow(2, nDiv) + 0.5);
-    
-    int xElements = factor * 6;
-    int yElements = factor * 4;
+    auto xElements = factor * 6;
+    auto yElements = factor * 4;
     
-    TPZManVector nx(2);
+    TPZManVector nx(2);
     nx[0] = xElements;
     nx[1] = yElements;
     
     TPZManVector x0(3,0.), x1(3,1.);
     x1[2] = 0.;
     
-    
     TPZGenGrid2D gen(nx, x0, x1, 1, 0);
     
-    TPZGeoMesh *gmesh = new TPZGeoMesh();
+    auto *gmesh = new TPZGeoMesh();
     gen.Read(gmesh);
     gen.SetBC(gmesh, 4, -1);
     gen.SetBC(gmesh, 5, -1);
@@ -348,12 +69,12 @@ TPZGeoMesh *CreateLMHMMesh(int nDiv, TPZVec& coarseIndexes) {
             TPZGeoEl *gel = gmesh->ElementVec()[elem];
             if (gel->Dimension() != 2) DebugStop();
             
-            int lineInPattern = elem / nx[0] % 4;
-            int colInPattern = elem % nx[0] % 6;
+            auto lineInPattern = elem / nx[0] % 4;
+            auto colInPattern = elem % nx[0] % 6;
             
             // IDs of elements in the neighbourhood to which a coarse index has been already assigned
-            int leftEl = elem - 1;
-            int bottomEl = elem - nx[0];
+            auto leftEl = elem - 1;
+            auto bottomEl = elem - nx[0];
             
             if (lineInPattern == 0) {
                 if (colInPattern % 2 == 0) {
@@ -391,118 +112,6 @@ TPZGeoMesh *CreateLMHMMesh(int nDiv, TPZVec& coarseIndexes) {
             }
         }
     }
-    
-//    for(int ilinha =0 ; ilinha & cmesh, const TPZVec> &compmeshes,
-                  TPZAnalyticSolution *analytic, const std::string &prefix, TRunConfig config) {
-    //calculo solution
-    bool shouldrenumber = true;
-    TPZLinearAnalysis an(cmesh,shouldrenumber);
-#ifdef PZ_USING_MKL
-    TPZSSpStructMatrix strmat(cmesh.operator->());
-    strmat.SetNumThreads(0/*config.n_threads*/);
-#else
-    TPZSkylineStructMatrix strmat(cmesh.operator->());
-    strmat.SetNumThreads(config.n_threads);
-#endif
-
-
-#ifdef PZDEBUG
-    if(0)
-    {
-        std::ofstream file("MeshToSolveProblem.txt");
-        cmesh->Print(file);
-    }
-#endif
-
-
-    an.SetStructuralMatrix(strmat);
-    TPZStepSolver step;
-    step.SetDirect(ELDLt);
-    an.SetSolver(step);
-    std::cout << "Assembling\n";
-    an.Assemble();
-
-    std::cout << "Solving\n";
-    an.Solve();
-    std::cout << "Finished\n";
-    an.LoadSolution(); // compute internal dofs
-
-
-    TPZMFSolutionTransfer transfer;
-    transfer.BuildTransferData(cmesh.operator->());
-//    TPZBuildMultiphysicsMesh::TransferFromMultiPhysics(compmeshes, cmesh);
-    transfer.TransferFromMultiphysics();
-
-    if(0)
-    {
-        std::ofstream out1("mfmesh.txt");
-        cmesh->Print(out1);
-        std::ofstream out2("flux.txt");
-        compmeshes[0]->Print(out2);
-        std::ofstream out3("pressure.txt");
-        compmeshes[1]->Print(out3);
-        std::ofstream out4("transfer.txt");
-        transfer.Print(out4);
-    }
-
-    TPZStack scalnames,vecnames;
-    TPZMaterial *mat = cmesh->FindMaterial(1);
-    if (!mat) {
-        DebugStop();
-    }
-    if (analytic)
-    {
-        an.SetExact(analytic->ExactSolution());
-        scalnames.Push("ExactPressure");
-        vecnames.Push("ExactFlux");
-    }
-    {
-        scalnames.Push("Pressure");
-        //  scalnames.Push("Permeability");
-        vecnames.Push("Flux");
-        //   vecnames.Push("Derivative");
-    }
-
-
-    std::string plotname;
-    {
-        std::stringstream out;
-        out << "MHMHdiv"<<"_kin" <Dimension() , scalnames, vecnames, plotname);
-    an.PostProcess(resolution,cmesh->Dimension() );
 
-
-    if(analytic)
-    {
-        TPZManVector errors(4,0.);
-        an.SetThreadsForError(config.n_threads);
-        an.SetExact(analytic->ExactSolution());
-        an.PostProcessError(errors,false);
-
-        //Erro
-
-        std::ofstream myfile;
-        myfile.open("ArquivosErrosMHM.txt", std::ios::app);
-        myfile << "\n\n Error for MHM formulation " ;
-        myfile << "\n-------------------------------------------------- \n";
-        myfile << "Ndiv = " << config.numHDivisions << " Order Internal= " << config.pOrderInternal <<" Order Skeleton= " << config.pOrderSkeleton <<"\n";
-        myfile << "DOF Total = " << cmesh->NEquations() << "\n";
-        myfile << "Energy norm = " << errors[0] << "\n";//norma energia
-        myfile << "error norm L2 = " << errors[1] << "\n";//norma L2
-        myfile << "Semi norm H1 = " << errors[2] << "\n";//norma L2
-        myfile.close();
-
-    }
-
-}
+    return gmesh;
+}
\ No newline at end of file
diff --git a/Projects/Tools/ToolsMHM.h b/Projects/Tools/ToolsMHM.h
index 06a45ef4..b27f34c0 100644
--- a/Projects/Tools/ToolsMHM.h
+++ b/Projects/Tools/ToolsMHM.h
@@ -1,159 +1,18 @@
 //
 //  ToolsMHM.hpp
-//  AdaptivityTest
 //
 //  Created by Denise De Siqueira on 01/11/19.
 //
 
-#ifndef ToolsMHM_hpp
-#define ToolsMHM_hpp
+#ifndef TOOLSMHM_H
+#define TOOLSMHM_H
 
-#include 
-
-#endif /* ToolsMHM_hpp */
-
-
-#ifdef HAVE_CONFIG_H
-#include 
-#endif
-
-#include 
-#include 
 #include "pzvec.h"
-#include "pzstack.h"
-#include "pzfmatrix.h"
-#include "pzfstrmatrix.h"
-#include "pzlog.h"
-#include "pzreal.h"
 #include "pzgmesh.h"
-#include "pzcmesh.h"
-#include "pzcompel.h"
-#include "TPZInterfaceEl.h"
-#include "pzgeoelside.h"
-#include "TPZGeoLinear.h"
-#include "pzgeopoint.h"
-
-#include "TPZRefPattern.h"
-#include "tpzgeoelrefpattern.h"
-#include "tpzautopointer.h"
-
-#include "TPZSSpStructMatrix.h"
-#include "pzstepsolver.h"
-#include "pzfstrmatrix.h"
-#include "TPZFrontNonSym.h"
-#include "TPZFrontSym.h"
-#include "TPZSpStructMatrix.h"
-#include "pzbstrmatrix.h"
-
-#include "tpzarc3d.h"
-#include "tpzgeoblend.h"
-#include "TPZGeoLinear.h"
-
-//#include "TPZMatLaplacianHybrid.h"
-#include "TPZLagrangeMultiplier.h"
-
-#include "pzbuildmultiphysicsmesh.h"
-#include "pzelementgroup.h"
-#include "TPZCompMeshTools.h"
-#include "pzcondensedcompel.h"
-#include "pzfunction.h"
-#include "pzgraphmesh.h"
-#include "pzfmatrix.h"
-
-#include "pzlog.h"
-
-#include "TPZVTKGeoMesh.h"
-#include "pzvisualmatrix.h"
-
-//#include "pzgengrid.h"
-
-#include "TPZGenGrid2D.h"
-#include "TPZExtendGridDimension.h"
-#include "pzcheckgeom.h"
-
-#include "TPZMHMeshControl.h"
-#include "TPZMHMixedMeshControl.h"
-#include "TPZMHMixedMeshChannelControl.h"
-
-#include "TPZMHMixedHybridMeshControl.h"
-#include "TPZHybridizeHDiv.h"
-//#include "ConfigCasesMaze.h"
-#include 
-#include 
-#include 
-#include 
-
-#include "TPZPersistenceManager.h"
-
-#include "TPZMHMHDivErrorEstimator.h"
-#include "Tools.h"
-#include "TPZGenGrid2D.h"
-
-struct TRunConfig
-{
-    int nelxcoarse = -1;
-    int nelycoarse = -1;
-    int numHDivisions = 0;
-    int pOrderInternal = 1;
-    int hdivmaismais = 1;
-    int numDivSkeleton = 0;
-    int pOrderSkeleton = 1;
-    int Hybridize = 0;
-    int Condensed = 1;
-    int LagrangeMult = 0;
-    int newline = 0;
-    int n_threads = 0;
-    bool MHM_HDiv_Elast = false;
-
-    /// number of equations when not condensing anything
-    int64_t fGlobalSystemSize = -1;
-    /// number of equations considering local condensation
-    int64_t fGlobalSystemWithLocalCondensationSize = -1;
-    /// number of equations of the global system
-    int64_t fNumeq = -1;
-
-    REAL fDeltaT = 1.;
-
-    /// number of timesteps
-    int64_t nTimeSteps = 10;
-
-    std::ostream &InlinePrint(std::ostream &out)
-    {
-//        out << "nelxCoarse " << nelxcoarse << " nelyCoarse " << nelycoarse << " numHDiv " << numHDivisions << " porderInternal " << pOrderInternal << " numDivSkeleton " << numDivSkeleton
-//        << " porderSkeleton " << pOrderSkeleton << " Hybridize " << Hybridize << " Condensed " << Condensed << " LagrangeMult " << LagrangeMult
-//        << " sysnocondense " << fGlobalSystemSize << " syslocalcondense " << fGlobalSystemWithLocalCondensationSize << " neq " << fNumeq;
-        // : n_dx n_dy k_skeleton m_div k_subelement
-        out << "n_dx " << nelxcoarse << " n_dy " << nelycoarse  << " k_skeleton " << pOrderSkeleton << " m_div " << numHDivisions << " k_subelement " << pOrderInternal << " upscaling_dof " << fNumeq << " total_dof " << fGlobalSystemSize;
-        return out;
-    }
-    std::ostream &MathematicaInlinePrint(std::ostream &out)
-    {
-        out << "nelxCoarse, " << nelxcoarse << ", nelyCoarse, " << nelycoarse << " ,numHDiv, " << numHDivisions << " ,porderInternal, " << pOrderInternal << " ,numDivSkeleton, " << numDivSkeleton
-            << " ,porderSkeleton, " << pOrderSkeleton << " ,Hybridize, " << Hybridize << " ,Condensed, " << Condensed << " ,LagrangeMult, " << LagrangeMult
-            << " ,sysnocondense, " << fGlobalSystemSize << " ,syslocalcondense, " << fGlobalSystemWithLocalCondensationSize << " ,neq, " << fNumeq;
-        return out;
-    }
-
-    std::ostream &ConfigPrint(std::ostream &out)
-    {
-        out << nelxcoarse << "x" << nelycoarse << "_HSkel" << numDivSkeleton << "_pSkel" << pOrderSkeleton << "_HDiv" << numHDivisions << "_pInt" << pOrderInternal;
-        return out;
-    }
-};
-// Creating the computational flux mesh
-TPZCompMesh *CMeshFlux(TPZGeoMesh * gmesh,int pOrder);
-
-// Create a geometric mesh with the given parameters, nx and ny are the coarse elements number. The total number of elements are defined by the image read.
-TPZGeoMesh *GenerateGeoMesh(std::string name, int nx, int ny);
-
-// Create a geoElSide map to be open because it has flux.
-// cmesh is the flux mesh obtained from a Hdiv previus simulation.
-std::map> IdentifyChanel (TPZCompMesh *cmesh);
 
 // Compute the geometric mesh coarse indices
 void ComputeCoarseIndices(TPZGeoMesh *gmesh, TPZVec &coarseindices);
 
-TPZGeoMesh *CreateLMHMMesh(int nDiv, TPZVec& coarseIndexes);
+TPZGeoMesh *CreateLMHMMesh(int nDiv, TPZVec &coarseIndexes);
 
-/// Solve the problem composed of a multiphysics mesh composed of compmeshes - applies to MHM and MHM-H(div)
-void SolveProblem(const TPZAutoPointer& cmesh, const TPZVec >& compmeshes, TPZAnalyticSolution *analytic, const std::string& prefix, TRunConfig config);
+#endif // TOOLSMHM_H

From ff68be2d3ddad224f289b0396e5bd525a0580513 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 4 Nov 2021 12:01:44 -0300
Subject: [PATCH 150/187] Fix cast type

---
 Projects/SPE10/ToolsSPE10.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/Projects/SPE10/ToolsSPE10.cpp b/Projects/SPE10/ToolsSPE10.cpp
index b5ea68da..8cd049b5 100644
--- a/Projects/SPE10/ToolsSPE10.cpp
+++ b/Projects/SPE10/ToolsSPE10.cpp
@@ -121,7 +121,7 @@
 
     for (int y = 0; y <= ny; y++) {
         for (int x = 0; x <= nx; x++) {
-            coord = {static_cast(x), static_cast(y), 0.};
+            coord = {static_cast(x), static_cast(y), 0.};
             // Create new node
             const auto newID = gmesh->NodeVec().AllocateNewElement();
             gmesh->NodeVec()[newID].Initialize(coord, *gmesh);

From 6ece8a1245a28fccaa85a837ea5b352497d58542 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 4 Nov 2021 12:10:06 -0300
Subject: [PATCH 151/187] Create CreateLineRefinementGeoMesh function

---
 Projects/SPE10/ToolsSPE10.cpp | 32 +++++++++++++++++++++++++++++++-
 Projects/SPE10/ToolsSPE10.h   |  2 +-
 2 files changed, 32 insertions(+), 2 deletions(-)

diff --git a/Projects/SPE10/ToolsSPE10.cpp b/Projects/SPE10/ToolsSPE10.cpp
index 8cd049b5..7e54dc20 100644
--- a/Projects/SPE10/ToolsSPE10.cpp
+++ b/Projects/SPE10/ToolsSPE10.cpp
@@ -150,4 +150,34 @@
 
     gmesh->BuildConnectivity();
     return gmesh;
-}
\ No newline at end of file
+}
+
+[[maybe_unused]] TPZGeoMesh *SPE10::CreateLineRefinementGeoMesh(const int nx) {
+    auto *gmesh = new TPZGeoMesh();
+    gmesh->SetDimension(1);
+
+    TPZManVector coord(3, 0.);
+    for (int x = 0; x <= nx; x++) {
+        coord = {static_cast(x), 0, 0.};
+        // Create new node
+        const auto newID = gmesh->NodeVec().AllocateNewElement();
+        gmesh->NodeVec()[newID].Initialize(coord, *gmesh);
+    }
+
+    constexpr int matId = 1;
+
+    // Inserts line elements
+    TPZManVector nodesIdVec(2, 0);
+    nodesIdVec[1] = nx;
+    auto *father_gel = new TPZGeoElRefPattern(nodesIdVec, matId, *gmesh);
+
+    for (int x = 0; x < nx; x++) {
+        nodesIdVec[0] = x;
+        nodesIdVec[1] = x + 1;
+        auto *gel = new TPZGeoElRefPattern(nodesIdVec, matId, *gmesh);
+        gel->SetFather(father_gel);
+    }
+
+    gmesh->BuildConnectivity();
+    return gmesh;
+}
diff --git a/Projects/SPE10/ToolsSPE10.h b/Projects/SPE10/ToolsSPE10.h
index 7bf8516a..1a79ef27 100644
--- a/Projects/SPE10/ToolsSPE10.h
+++ b/Projects/SPE10/ToolsSPE10.h
@@ -11,7 +11,7 @@ namespace SPE10 {
 [[maybe_unused]] [[maybe_unused]] TPZGeoMesh *CreateFineGridGeoMesh();
 [[maybe_unused]] TPZGeoMesh *CreateMHMGeoMesh();
 [[maybe_unused]] TPZGeoMesh *CreateRefinementGeoMesh(int nx, int ny);
-
+[[maybe_unused]] TPZGeoMesh *CreateLineRefinementGeoMesh(int nx);
 }
 
 #endif // TOOLSSPE10_H

From bea21ca39b2ca17a04cb449c4e65a360452b70dd Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 4 Nov 2021 12:10:32 -0300
Subject: [PATCH 152/187] Remove duplicated attribute

---
 Projects/SPE10/ToolsSPE10.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/Projects/SPE10/ToolsSPE10.h b/Projects/SPE10/ToolsSPE10.h
index 1a79ef27..384314ab 100644
--- a/Projects/SPE10/ToolsSPE10.h
+++ b/Projects/SPE10/ToolsSPE10.h
@@ -8,7 +8,7 @@
 #include "pzgmesh.h"
 
 namespace SPE10 {
-[[maybe_unused]] [[maybe_unused]] TPZGeoMesh *CreateFineGridGeoMesh();
+[[maybe_unused]] TPZGeoMesh *CreateFineGridGeoMesh();
 [[maybe_unused]] TPZGeoMesh *CreateMHMGeoMesh();
 [[maybe_unused]] TPZGeoMesh *CreateRefinementGeoMesh(int nx, int ny);
 [[maybe_unused]] TPZGeoMesh *CreateLineRefinementGeoMesh(int nx);

From 1d1854541779d717074dc6c2c3917d2f5346f9be Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 4 Nov 2021 12:10:59 -0300
Subject: [PATCH 153/187] Fix indentation

---
 Projects/SPE10/ToolsSPE10.cpp | 20 ++++++++++----------
 1 file changed, 10 insertions(+), 10 deletions(-)

diff --git a/Projects/SPE10/ToolsSPE10.cpp b/Projects/SPE10/ToolsSPE10.cpp
index 7e54dc20..b07f892f 100644
--- a/Projects/SPE10/ToolsSPE10.cpp
+++ b/Projects/SPE10/ToolsSPE10.cpp
@@ -32,18 +32,18 @@
 
 [[maybe_unused]] TPZGeoMesh *SPE10::CreateMHMGeoMesh() {
 
-    auto* gmesh = new TPZGeoMesh();
+    auto *gmesh = new TPZGeoMesh();
     gmesh->SetDimension(2);
 
-    auto * gmesh2x1 = CreateRefinementGeoMesh(2, 1);
+    auto *gmesh2x1 = CreateRefinementGeoMesh(2, 1);
     TPZRefPattern ref_pat2x1(*gmesh2x1);
     TPZAutoPointer ref2x1(&ref_pat2x1);
 
-    auto * gmesh1x2 = CreateRefinementGeoMesh(1, 2);
+    auto *gmesh1x2 = CreateRefinementGeoMesh(1, 2);
     TPZRefPattern ref_pat1x2(*gmesh1x2);
     TPZAutoPointer ref1x2(&ref_pat1x2);
 
-    auto * gmesh1x1 = CreateRefinementGeoMesh(1, 1);
+    auto *gmesh1x1 = CreateRefinementGeoMesh(1, 1);
     TPZRefPattern ref_pat1x1(*gmesh1x1);
     TPZAutoPointer ref1x1(&ref_pat1x1);
 
@@ -72,7 +72,7 @@
             nodesIdVec[1] = 29 * y + x + 1;
             nodesIdVec[2] = 29 * (y + 1) + x + 1;
             nodesIdVec[3] = 29 * (y + 1) + x + 0;
-            auto * gel = new TPZGeoElRefPattern(nodesIdVec, porousMediaMatId, *gmesh);
+            auto *gel = new TPZGeoElRefPattern(nodesIdVec, porousMediaMatId, *gmesh);
             if (x == 27 && y != 7) gel->SetRefPattern(ref1x2);
             if (x != 27 && y == 7) gel->SetRefPattern(ref2x1);
             if (x == 27 && y == 7) gel->SetRefPattern(ref1x1);
@@ -100,11 +100,11 @@
 
     gmesh->BuildConnectivity();
 
-    TPZManVector sons;
+    TPZManVector sons;
     for (int div = 0; div < 3; div++) {
         auto nelem = gmesh->NElements();
         for (int64_t i = 0; i < nelem; i++) {
-            auto * gel = gmesh->ElementVec()[i];
+            auto *gel = gmesh->ElementVec()[i];
             const int has_sub = gel->HasSubElement();
             if (has_sub == 0) {
                 gel->Divide(sons);
@@ -115,7 +115,7 @@
 }
 
 [[maybe_unused]] TPZGeoMesh *SPE10::CreateRefinementGeoMesh(const int nx, const int ny) {
-    auto* gmesh = new TPZGeoMesh();
+    auto *gmesh = new TPZGeoMesh();
     gmesh->SetDimension(2);
     TPZManVector coord(3, 0.);
 
@@ -135,7 +135,7 @@
     nodesIdVec[1] = nx;
     nodesIdVec[2] = (ny + 1) * (nx + 1) - 1;
     nodesIdVec[3] = ny * (nx + 1);
-    auto * father_gel = new TPZGeoElRefPattern(nodesIdVec, matId, *gmesh);
+    auto *father_gel = new TPZGeoElRefPattern(nodesIdVec, matId, *gmesh);
 
     for (int y = 0; y < ny; y++) {
         for (int x = 0; x < nx; x++) {
@@ -143,7 +143,7 @@
             nodesIdVec[1] = (nx + 1) * y + x + 1;
             nodesIdVec[2] = (nx + 1) * (y + 1) + x + 1;
             nodesIdVec[3] = (nx + 1) * (y + 1) + x + 0;
-            auto * gel = new TPZGeoElRefPattern(nodesIdVec, matId, *gmesh);
+            auto *gel = new TPZGeoElRefPattern(nodesIdVec, matId, *gmesh);
             gel->SetFather(father_gel);
         }
     }

From e20e427e5ba781484a790045158db06654eadd50 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 4 Nov 2021 12:12:50 -0300
Subject: [PATCH 154/187] Fix refinement level of BC elems

---
 Projects/SPE10/ToolsSPE10.cpp | 20 ++++++++++++++++----
 1 file changed, 16 insertions(+), 4 deletions(-)

diff --git a/Projects/SPE10/ToolsSPE10.cpp b/Projects/SPE10/ToolsSPE10.cpp
index b07f892f..5ef4a599 100644
--- a/Projects/SPE10/ToolsSPE10.cpp
+++ b/Projects/SPE10/ToolsSPE10.cpp
@@ -79,23 +79,35 @@
         }
     }
 
+    auto *gmesh1x1line = CreateLineRefinementGeoMesh(1);
+    TPZRefPattern ref_pat1x1line(*gmesh1x1line);
+    TPZAutoPointer ref1x1line(&ref_pat1x1line);
+
     nodesIdVec.resize(2);
     for (int x = 0; x < 28; x++) {
         nodesIdVec[0] = x;
         nodesIdVec[1] = x + 1;
-        new TPZGeoElRefPattern(nodesIdVec, bcMatId1, *gmesh);
+        auto *bc1 = new TPZGeoElRefPattern(nodesIdVec, bcMatId1, *gmesh);
         nodesIdVec[0] = x + 8 * 29;
         nodesIdVec[1] = x + 8 * 29 + 1;
-        new TPZGeoElRefPattern(nodesIdVec, bcMatId1, *gmesh);
+        auto *bc2 = new TPZGeoElRefPattern(nodesIdVec, bcMatId1, *gmesh);
+        if (x == 27) {
+            bc1->SetRefPattern(ref1x1line);
+            bc2->SetRefPattern(ref1x1line);
+        }
     }
 
     for (int y = 0; y < 8; y++) {
         nodesIdVec[0] = y * 29;
         nodesIdVec[1] = (y + 1) * 29;
-        new TPZGeoElRefPattern(nodesIdVec, bcMatId1, *gmesh);
+        auto *bc1 = new TPZGeoElRefPattern(nodesIdVec, bcMatId1, *gmesh);
         nodesIdVec[0] = y * 29 + 28;
         nodesIdVec[1] = (y + 1) * 29 + 28;
-        new TPZGeoElRefPattern(nodesIdVec, bcMatId2, *gmesh);
+        auto *bc2 = new TPZGeoElRefPattern(nodesIdVec, bcMatId2, *gmesh);
+        if (y == 7) {
+            bc1->SetRefPattern(ref1x1line);
+            bc2->SetRefPattern(ref1x1line);
+        }
     }
 
     gmesh->BuildConnectivity();

From dbe6f45abacc31b40955cafa0c8b7178923cb4a1 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 5 Nov 2021 11:07:00 -0300
Subject: [PATCH 155/187] Fix included headers

---
 Projects/SPE10/mainSPE10.cpp | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/Projects/SPE10/mainSPE10.cpp b/Projects/SPE10/mainSPE10.cpp
index dac713f6..61445736 100644
--- a/Projects/SPE10/mainSPE10.cpp
+++ b/Projects/SPE10/mainSPE10.cpp
@@ -3,16 +3,18 @@
 //
 
 #include "Tools.h"
+#include "ToolsSPE10.h"
 #include 
 #include 
 #include 
 #include 
+#include 
+#include 
 #include 
 #include 
 #include 
 #include 
 #include 
-#include "ToolsSPE10.h"
 
 typedef _2D::BicubicInterpolator Interpolator;
 

From 9e72522e05938f3331ebd6d39287e760ce541f26 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 5 Nov 2021 11:07:33 -0300
Subject: [PATCH 156/187] Add new perm function

---
 Projects/SPE10/mainSPE10.cpp | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)

diff --git a/Projects/SPE10/mainSPE10.cpp b/Projects/SPE10/mainSPE10.cpp
index 61445736..7b1bcb36 100644
--- a/Projects/SPE10/mainSPE10.cpp
+++ b/Projects/SPE10/mainSPE10.cpp
@@ -20,11 +20,16 @@ typedef _2D::BicubicInterpolator Interpolator;
 
 // Global variables
 Interpolator interpolator;
+constexpr int nx = 220;
+constexpr int ny = 60;
+constexpr int n_cells = nx * ny;
+TPZManVector perm_vec(n_cells, 1);
 
 // Function declarations
 void ReadSPE10CellPermeabilities(TPZVec*perm_vec, int layer);
 TPZGeoMesh *CreateSPE10GeoMesh();
 STATE PermeabilityFunction(const TPZVec &x);
+STATE NewPermeabilityFunction(const TPZVec &x);
 void InsertMaterials(TPZCompMesh *cmesh);
 void CreateSPE10MHMCompMesh(TPZMHMixedMeshControl &mhm, const std::vector &skelsToDivide);
 void SolveMHMProblem(TPZMHMixedMeshControl &mhm, int adaptivity_step);
@@ -159,6 +164,19 @@ STATE PermeabilityFunction(const TPZVec &x) {
     return perm;
 }
 
+STATE NewPermeabilityFunction(const TPZVec &x) {
+    const auto rounded_x = static_cast(x[0]);
+    const auto rounded_y = static_cast(x[1]);
+
+    auto perm = perm_vec[rounded_x * 60 + rounded_y];
+    if (perm <= 1) {
+        perm = 1;
+    } else {
+        perm += 1;
+    }
+    return perm;
+}
+
 void CreateSPE10MHMCompMesh(TPZMHMixedMeshControl &mhm, const std::vector &skelsToDivide) {
 
     TPZGeoMesh *gmesh = mhm.GMesh().operator->();
@@ -247,7 +265,7 @@ void SolveMHMProblem(TPZMHMixedMeshControl &mhm, const int adaptivity_step) {
 void InsertMaterials(TPZCompMesh *cmesh) {
 
     auto *mix = new TPZMixedDarcyFlow(1, cmesh->Dimension());
-    std::function &coord)> func = PermeabilityFunction;
+    std::function &coord)> func = NewPermeabilityFunction;
     mix->SetPermeabilityFunction(func);
 
     TPZFNMatrix<1, REAL> val1(1, 1, 0.);

From 7158fd86fd46c7220640523ca0fccfdc1c301b55 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Fri, 5 Nov 2021 11:08:19 -0300
Subject: [PATCH 157/187] Add changes to run updated problem

---
 Projects/SPE10/mainSPE10.cpp | 34 +++++++++++++++-------------------
 1 file changed, 15 insertions(+), 19 deletions(-)

diff --git a/Projects/SPE10/mainSPE10.cpp b/Projects/SPE10/mainSPE10.cpp
index 7b1bcb36..0baf3644 100644
--- a/Projects/SPE10/mainSPE10.cpp
+++ b/Projects/SPE10/mainSPE10.cpp
@@ -39,7 +39,8 @@ void MHMAdaptivity(TPZMHMixedMeshControl *mhm, TPZCompMesh *postProcMesh, std::v
 constexpr int adaptivity_steps = 4;
 int main() {
 
-    auto * gmesh = SPE10::CreateFineGridGeoMesh();
+    gRefDBase.InitializeAllUniformRefPatterns();
+
     auto * gmeshMHM = SPE10::CreateMHMGeoMesh();
 
     {
@@ -48,33 +49,28 @@ int main() {
         TPZVTKGeoMesh::PrintGMeshVTK(gmeshMHM, file);
     }
 
-    return 0;
     constexpr int layer = 36;
-    constexpr int nx = 220;
-    constexpr int ny = 60;
-    constexpr int n_cells = nx * ny;
 
-    auto perm_vec = TPZManVector(n_cells, 1);
     ReadSPE10CellPermeabilities(&perm_vec, layer);
 
     std::vector skelsToRefine;
     for (int step = 0; step < adaptivity_steps; step++) {
 
-        TPZGeoMesh *gmesh = CreateSPE10GeoMesh();
+        TPZGeoMesh *gmesh = SPE10::CreateMHMGeoMesh();
         std::cout << "SPE10 initial grid created. NElem: " << gmesh->NElements() << "\n";
 
-        std::vector x, y, perm;
-        for (int i = 0; i < nx; i++) {
-            for (int j = 0; j < ny; j++) {
-                const int cell_id = ny * i + j;
-                const double cell_perm = perm_vec[cell_id];
-                x.push_back(0.5 + i);
-                y.push_back(0.5 + j);
-                perm.push_back(cell_perm);
-            }
-        }
-
-        interpolator.setData(x.size(), x.data(), y.data(), perm.data());
+        //std::vector x, y, perm;
+        //for (int i = 0; i < nx; i++) {
+        //    for (int j = 0; j < ny; j++) {
+        //        const int cell_id = ny * i + j;
+        //        const double cell_perm = perm_vec[cell_id];
+        //        x.push_back(0.5 + i);
+        //        y.push_back(0.5 + j);
+        //        perm.push_back(cell_perm);
+        //    }
+        //}
+
+        //interpolator.setData(x.size(), x.data(), y.data(), perm.data());
 
         TPZMHMixedMeshControl mhm(gmesh);
         CreateSPE10MHMCompMesh(mhm, skelsToRefine);

From b0826b9d87c69ac815d636cd373e11a120f14920 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Mon, 8 Nov 2021 10:33:23 -0300
Subject: [PATCH 158/187] Fix included headers

---
 Projects/ErrorEstimationMHM/main_Journal.cpp       | 14 +++++++++++---
 Projects/ErrorEstimationMHM/main_MHM.cpp           | 11 +++++++++--
 .../ErrorEstimationMHM/main_RefSolValidation.cpp   |  9 ++++++++-
 3 files changed, 28 insertions(+), 6 deletions(-)

diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp
index 97b7bccf..0f96c9fe 100644
--- a/Projects/ErrorEstimationMHM/main_Journal.cpp
+++ b/Projects/ErrorEstimationMHM/main_Journal.cpp
@@ -1,14 +1,22 @@
 //
 // Created by Gustavo Batistela on 3/31/21.
 //
+#include "ProblemConfig.h"
+#include "TPZMHMHDivErrorEstimator.h"
+#include "ToolsMHM.h"
 #include "pzgmesh.h"
+#include 
 #include 
 #include 
+#include 
+#include 
 #include 
-//#include 
-#include 
-#include 
+#include 
+#include 
+#include 
 #include 
+#include 
+#include 
 
 struct ErrorResult {
     ErrorResult(const std::string &s, const int nIntRef, const int nCoarseDiv, const int kOrder, const int nOrder,
diff --git a/Projects/ErrorEstimationMHM/main_MHM.cpp b/Projects/ErrorEstimationMHM/main_MHM.cpp
index dadeb744..52df1181 100644
--- a/Projects/ErrorEstimationMHM/main_MHM.cpp
+++ b/Projects/ErrorEstimationMHM/main_MHM.cpp
@@ -2,14 +2,21 @@
 // Created by Gustavo A. Batistela on 06/07/2020.
 //
 
+#include 
 #include 
 #include 
 #include 
+#include 
+#include 
 #include 
-//#include 
+#include 
+#include 
+#include 
+#include 
 #include 
 #include 
-#include 
+#include 
+#include 
 
 void RunSmoothProblem();
 void RunHighGradientProblem();
diff --git a/Projects/ErrorEstimationMHM/main_RefSolValidation.cpp b/Projects/ErrorEstimationMHM/main_RefSolValidation.cpp
index 46274df1..37f0843b 100644
--- a/Projects/ErrorEstimationMHM/main_RefSolValidation.cpp
+++ b/Projects/ErrorEstimationMHM/main_RefSolValidation.cpp
@@ -2,12 +2,19 @@
 // Created by Gustavo Batistela on 25/08/21.
 //
 #include "pzgmesh.h"
+#include 
 #include 
 #include 
+#include 
+#include 
 #include 
-#include 
+#include 
+#include 
+#include 
 #include 
 #include 
+#include 
+#include 
 
 void RunReferenceSolutionValidationProblem();
 

From 54a5fcee23ab41e12d079eed0a1117e97739b764 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Tue, 9 Nov 2021 15:36:14 -0300
Subject: [PATCH 159/187] Add TPZMultiscaleGridGen2D files

---
 Projects/SPE10/CMakeLists.txt             |  2 +-
 Projects/SPE10/TPZMultiscaleGridGen2D.cpp |  3 +++
 Projects/SPE10/TPZMultiscaleGridGen2D.h   | 25 +++++++++++++++++++++++
 3 files changed, 29 insertions(+), 1 deletion(-)
 create mode 100644 Projects/SPE10/TPZMultiscaleGridGen2D.cpp
 create mode 100644 Projects/SPE10/TPZMultiscaleGridGen2D.h

diff --git a/Projects/SPE10/CMakeLists.txt b/Projects/SPE10/CMakeLists.txt
index fbcbb1b6..ee291f25 100644
--- a/Projects/SPE10/CMakeLists.txt
+++ b/Projects/SPE10/CMakeLists.txt
@@ -1,4 +1,4 @@
-add_executable(SPE10 mainSPE10.cpp ToolsSPE10.cpp ToolsSPE10.h)
+add_executable(SPE10 mainSPE10.cpp ToolsSPE10.cpp ToolsSPE10.h TPZMultiscaleGridGen2D.cpp TPZMultiscaleGridGen2D.h)
 target_link_libraries(SPE10 PRIVATE Tools ErrorEstimationLib)
 
 find_package(libInterpolate REQUIRED)
diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
new file mode 100644
index 00000000..2e3a1913
--- /dev/null
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
@@ -0,0 +1,3 @@
+//
+// Created by Gustavo Batistela on 11/8/21.
+//
diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.h b/Projects/SPE10/TPZMultiscaleGridGen2D.h
new file mode 100644
index 00000000..96b222cc
--- /dev/null
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.h
@@ -0,0 +1,25 @@
+//
+// Created by Gustavo Batistela on 11/8/21.
+//
+
+#ifndef TPZMULTISCALEGRIDGEN2D_H
+#define TPZMULTISCALEGRIDGEN2D_H
+
+#include 
+
+class TPZMultiscaleGridGen2D {
+
+private:
+    // Member variables
+    const TPZManVector fNDivFineGrid{0};
+    const int fNElemCoarseGrid{0};
+    const TPZManVector fMinX{0};
+    const TPZManVector fMaxX{0};
+
+    std::map> fRefPatterns;
+
+    TPZGeoMesh *fGeoMesh = nullptr;
+
+};
+
+#endif // TPZMULTISCALEGRIDGEN2D_H

From fc5ec4fb4339df1e8ca7b87b1fe1e5b1727e08f4 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Tue, 9 Nov 2021 15:36:53 -0300
Subject: [PATCH 160/187] Add RefTree struct and member var

---
 Projects/SPE10/TPZMultiscaleGridGen2D.h | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)

diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.h b/Projects/SPE10/TPZMultiscaleGridGen2D.h
index 96b222cc..7146b854 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.h
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.h
@@ -7,6 +7,27 @@
 
 #include 
 
+struct RefTree {
+    int fActualNumber{0};
+    RefTree *fChildLeft = nullptr;
+    RefTree *fChildRight = nullptr;
+
+    RefTree() = default;
+
+    explicit RefTree(const int actual_number) {
+        fActualNumber = actual_number;
+        FillRefTree();
+    }
+
+    void FillRefTree() {
+        std::div_t division = std::div(fActualNumber, 2);
+        if (fActualNumber != 1) {
+            fChildLeft = new RefTree(division.quot);
+            fChildRight = new RefTree(division.quot + division.rem);
+        }
+    }
+};
+
 class TPZMultiscaleGridGen2D {
 
 private:
@@ -16,6 +37,7 @@ class TPZMultiscaleGridGen2D {
     const TPZManVector fMinX{0};
     const TPZManVector fMaxX{0};
 
+    RefTree fRefTree;
     std::map> fRefPatterns;
 
     TPZGeoMesh *fGeoMesh = nullptr;

From 19aa852da41ac213a4d58215f66f457a5b3c063d Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Tue, 9 Nov 2021 15:37:52 -0300
Subject: [PATCH 161/187] Add CreateNonUniformLineRefPattern method

---
 Projects/SPE10/TPZMultiscaleGridGen2D.cpp | 36 +++++++++++++++++++++++
 Projects/SPE10/TPZMultiscaleGridGen2D.h   |  3 ++
 2 files changed, 39 insertions(+)

diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
index 2e3a1913..2b76a65c 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
@@ -1,3 +1,39 @@
 //
 // Created by Gustavo Batistela on 11/8/21.
 //
+
+#include "TPZMultiscaleGridGen2D.h"
+#include 
+
+TPZRefPattern TPZMultiscaleGridGen2D::CreateNonUniformLineRefPattern(const int a, const int b) {
+
+    auto *gmesh = new TPZGeoMesh();
+    gmesh->SetDimension(1);
+
+    TPZManVector coord(3, 0.);
+
+    gmesh->NodeVec().Resize(3);
+    gmesh->NodeVec()[0].Initialize(coord, *gmesh);
+
+    coord[0] = a;
+    gmesh->NodeVec()[1].Initialize(coord, *gmesh);
+    coord[0] = a + b;
+    gmesh->NodeVec()[2].Initialize(coord, *gmesh);
+
+    constexpr int mat_id = 1;
+
+    // Inserts line elements
+    TPZManVector nodes_id_vec(2, 0);
+    nodes_id_vec[1] = 2;
+    new TPZGeoElRefPattern(nodes_id_vec, mat_id, *gmesh);
+
+    nodes_id_vec[0] = 0;
+    nodes_id_vec[1] = 1;
+    new TPZGeoElRefPattern(nodes_id_vec, mat_id, *gmesh);
+    nodes_id_vec[0] = 1;
+    nodes_id_vec[1] = 2;
+    new TPZGeoElRefPattern(nodes_id_vec, mat_id, *gmesh);
+
+    gmesh->BuildConnectivity();
+    return TPZRefPattern(*gmesh);
+}
\ No newline at end of file
diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.h b/Projects/SPE10/TPZMultiscaleGridGen2D.h
index 7146b854..76f184d8 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.h
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.h
@@ -42,6 +42,9 @@ class TPZMultiscaleGridGen2D {
 
     TPZGeoMesh *fGeoMesh = nullptr;
 
+    // Private member functions
+    static TPZRefPattern CreateNonUniformLineRefPattern(int a, int b);
+
 };
 
 #endif // TPZMULTISCALEGRIDGEN2D_H

From 7e3e9e38ba1504dda03aef9c7fafef755fc8e29c Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Tue, 9 Nov 2021 17:55:54 -0300
Subject: [PATCH 162/187] Change var name to make it more expressive

---
 Projects/SPE10/TPZMultiscaleGridGen2D.h | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.h b/Projects/SPE10/TPZMultiscaleGridGen2D.h
index 76f184d8..1218d0be 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.h
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.h
@@ -8,20 +8,20 @@
 #include 
 
 struct RefTree {
-    int fActualNumber{0};
+    int fActualSize{0};
     RefTree *fChildLeft = nullptr;
     RefTree *fChildRight = nullptr;
 
     RefTree() = default;
 
     explicit RefTree(const int actual_number) {
-        fActualNumber = actual_number;
+        fActualSize = actual_number;
         FillRefTree();
     }
 
     void FillRefTree() {
-        std::div_t division = std::div(fActualNumber, 2);
-        if (fActualNumber != 1) {
+        std::div_t division = std::div(fActualSize, 2);
+        if (fActualSize != 1) {
             fChildLeft = new RefTree(division.quot);
             fChildRight = new RefTree(division.quot + division.rem);
         }

From 0b6d291c57ac2082550b87c3cc0a53976a8ad28e Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 10 Nov 2021 14:25:07 -0300
Subject: [PATCH 163/187] Improve TPZMultiscaleGridGen2D data structure

---
 Projects/SPE10/TPZMultiscaleGridGen2D.h | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.h b/Projects/SPE10/TPZMultiscaleGridGen2D.h
index 1218d0be..689d1185 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.h
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.h
@@ -37,8 +37,10 @@ class TPZMultiscaleGridGen2D {
     const TPZManVector fMinX{0};
     const TPZManVector fMaxX{0};
 
-    RefTree fRefTree;
-    std::map> fRefPatterns;
+    RefTree *fRefTreeDesiredSize = nullptr;
+    RefTree *fRefTreeRemainderX = nullptr;
+    RefTree *fRefTreeRemainderY = nullptr;
+    std::map, TPZRefPattern> fRefPatterns;
 
     TPZGeoMesh *fGeoMesh = nullptr;
 

From 1b4dc2a947d9789c29d84d63433b02700325dcf2 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 10 Nov 2021 14:25:37 -0300
Subject: [PATCH 164/187] Add GenerateRefPatterns method

---
 Projects/SPE10/TPZMultiscaleGridGen2D.cpp | 30 +++++++++++++++++++++++
 Projects/SPE10/TPZMultiscaleGridGen2D.h   |  1 +
 2 files changed, 31 insertions(+)

diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
index 2b76a65c..1774f951 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
@@ -36,4 +36,34 @@ TPZRefPattern TPZMultiscaleGridGen2D::CreateNonUniformLineRefPattern(const int a
 
     gmesh->BuildConnectivity();
     return TPZRefPattern(*gmesh);
+}
+
+void TPZMultiscaleGridGen2D::GenerateRefPatterns() {
+    std::set> ref_levels;
+
+    std::function VisitNode = [&](RefTree *node) -> void {
+        if (node->fActualSize != 1) {
+            const auto left_size = node->fChildLeft->fActualSize;
+            const auto right_size = node->fChildRight->fActualSize;
+            if (left_size != right_size) {
+                ref_levels.insert({node->fChildLeft->fActualSize, node->fChildRight->fActualSize});
+            } else {
+                ref_levels.insert({1, 1});
+            }
+            VisitNode(node->fChildLeft);
+            VisitNode(node->fChildRight);
+        }
+    };
+
+    VisitNode(fRefTreeDesiredSize);
+    if (fRefTreeRemainderX) VisitNode(fRefTreeRemainderX);
+    if (fRefTreeRemainderY) VisitNode(fRefTreeRemainderY);
+
+    for (auto it : ref_levels) {
+        const auto a = it.first;
+        const auto b = it.second;
+
+        TPZRefPattern refPattern = CreateNonUniformLineRefPattern(a, b);
+        fRefPatterns.insert({{it.first, it.second}, refPattern});
+    }
 }
\ No newline at end of file
diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.h b/Projects/SPE10/TPZMultiscaleGridGen2D.h
index 689d1185..e48fa64d 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.h
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.h
@@ -47,6 +47,7 @@ class TPZMultiscaleGridGen2D {
     // Private member functions
     static TPZRefPattern CreateNonUniformLineRefPattern(int a, int b);
 
+    void GenerateRefPatterns();
 };
 
 #endif // TPZMULTISCALEGRIDGEN2D_H

From 6fddc207e93977b390eb58dd3418238e458a27d2 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 10 Nov 2021 14:26:15 -0300
Subject: [PATCH 165/187] Add constructors

---
 Projects/SPE10/TPZMultiscaleGridGen2D.cpp | 17 +++++++++++++++++
 Projects/SPE10/TPZMultiscaleGridGen2D.h   |  7 +++++++
 2 files changed, 24 insertions(+)

diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
index 1774f951..e88d388c 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
@@ -5,6 +5,23 @@
 #include "TPZMultiscaleGridGen2D.h"
 #include 
 
+TPZMultiscaleGridGen2D::TPZMultiscaleGridGen2D(const TPZVec &minX, const TPZVec &maxX,
+                                               const TPZVec &NDivFineGrid, int NElemCoarseGrid)
+    : fMinX(minX), fMaxX(maxX), fNDivFineGrid(NDivFineGrid), fNElemCoarseGrid(NElemCoarseGrid) {
+
+    if (NDivFineGrid[0] < NElemCoarseGrid || NDivFineGrid[1] < NElemCoarseGrid) DebugStop();
+
+    fRefTreeDesiredSize = new RefTree(NElemCoarseGrid);
+
+    std::div_t div_x = std::div(NDivFineGrid[0], NElemCoarseGrid);
+    std::div_t div_y = std::div(NDivFineGrid[1], NElemCoarseGrid);
+    if (div_x.rem != 0) fRefTreeRemainderX = new RefTree(div_x.rem);
+    if (div_y.rem != 0) fRefTreeRemainderY = new RefTree(div_y.rem);
+
+    GenerateRefPatterns();
+
+}
+
 TPZRefPattern TPZMultiscaleGridGen2D::CreateNonUniformLineRefPattern(const int a, const int b) {
 
     auto *gmesh = new TPZGeoMesh();
diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.h b/Projects/SPE10/TPZMultiscaleGridGen2D.h
index e48fa64d..a7560a20 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.h
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.h
@@ -30,6 +30,13 @@ struct RefTree {
 
 class TPZMultiscaleGridGen2D {
 
+public:
+    // Constructors
+    TPZMultiscaleGridGen2D() = delete;
+
+    TPZMultiscaleGridGen2D(const TPZVec &minX, const TPZVec &maxX, const TPZVec &NDivFineGrid,
+                           int NElemCoarseGrid);
+
 private:
     // Member variables
     const TPZManVector fNDivFineGrid{0};

From 2bbcb4442f48fb0aacba7235c501b6f17415cfa9 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 11 Nov 2021 18:09:34 -0300
Subject: [PATCH 166/187] Add CreateFineGridMesh method

---
 Projects/SPE10/TPZMultiscaleGridGen2D.cpp | 21 ++++++++++++++++++++-
 Projects/SPE10/TPZMultiscaleGridGen2D.h   |  2 ++
 2 files changed, 22 insertions(+), 1 deletion(-)

diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
index e88d388c..411fd630 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
@@ -3,6 +3,7 @@
 //
 
 #include "TPZMultiscaleGridGen2D.h"
+#include 
 #include 
 
 TPZMultiscaleGridGen2D::TPZMultiscaleGridGen2D(const TPZVec &minX, const TPZVec &maxX,
@@ -83,4 +84,22 @@ void TPZMultiscaleGridGen2D::GenerateRefPatterns() {
         TPZRefPattern refPattern = CreateNonUniformLineRefPattern(a, b);
         fRefPatterns.insert({{it.first, it.second}, refPattern});
     }
-}
\ No newline at end of file
+}
+
+void TPZMultiscaleGridGen2D::CreateFineGridMesh() {
+
+    const TPZManVector bcIDs = {-2, -1, -2, -2};
+
+    TPZGenGrid2D gen(fNDivFineGrid, fMinX, fMaxX, 1, 0);
+    gen.SetRefpatternElements(true);
+
+    fGeoMesh = new TPZGeoMesh;
+    gen.Read(fGeoMesh);
+
+    gen.SetBC(fGeoMesh, 4, bcIDs[0]);
+    gen.SetBC(fGeoMesh, 5, bcIDs[1]);
+    gen.SetBC(fGeoMesh, 6, bcIDs[2]);
+    gen.SetBC(fGeoMesh, 7, bcIDs[3]);
+
+    fGeoMesh->SetDimension(2);
+}
diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.h b/Projects/SPE10/TPZMultiscaleGridGen2D.h
index a7560a20..df222267 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.h
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.h
@@ -55,6 +55,8 @@ class TPZMultiscaleGridGen2D {
     static TPZRefPattern CreateNonUniformLineRefPattern(int a, int b);
 
     void GenerateRefPatterns();
+
+    void CreateFineGridMesh();
 };
 
 #endif // TPZMULTISCALEGRIDGEN2D_H

From c234dc6e049edeec7f60dc0e6a0efaad487d9d07 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Tue, 16 Nov 2021 12:09:49 -0300
Subject: [PATCH 167/187] Add CreateSkeletonEelements method

---
 Projects/SPE10/TPZMultiscaleGridGen2D.cpp | 54 +++++++++++++++++++++++
 Projects/SPE10/TPZMultiscaleGridGen2D.h   |  2 +
 2 files changed, 56 insertions(+)

diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
index 411fd630..7be849ff 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
@@ -103,3 +103,57 @@ void TPZMultiscaleGridGen2D::CreateFineGridMesh() {
 
     fGeoMesh->SetDimension(2);
 }
+
+void TPZMultiscaleGridGen2D::CreateSkeletonElements() {
+
+    const auto node_vec = fGeoMesh->NodeVec();
+
+    const std::div_t div_x = std::div(fNDivFineGrid[0], fNElemCoarseGrid);
+    const std::div_t div_y = std::div(fNDivFineGrid[1], fNElemCoarseGrid);
+
+    const int n_full_size_x = div_x.quot;
+    const int n_full_size_y = div_x.quot;
+
+    const int ny_correction = div_y.rem == 0 ? 1 : 0;
+    const int nx_correction = div_x.rem == 0 ? 1 : 0;
+
+    const int n_nodes_x = fNDivFineGrid[0] + 1;
+
+    TPZManVector node_id_vec(2, 0);
+    int node0, node1;
+    for (auto iy = 0; iy < n_full_size_y - ny_correction; iy++) {
+        for (auto ix = 0; ix < n_full_size_x; ix++) {
+            node0 =
+                fNElemCoarseGrid * fNDivFineGrid[0] + (ix + 1) * fNElemCoarseGrid + fNElemCoarseGrid * n_nodes_x * iy;
+            node1 = node0 + fNElemCoarseGrid;
+            node_id_vec[0] = node0;
+            node_id_vec[1] = node1;
+            new TPZGeoElRefPattern(node_id_vec, 666, *fGeoMesh);
+        }
+        if (div_x.rem != 0) {
+            node0 = fNElemCoarseGrid * fNDivFineGrid[0] + (n_full_size_x + 1) * fNElemCoarseGrid +
+                    fNElemCoarseGrid * n_nodes_x * iy;
+            node1 = node0 + div_x.rem;
+            node_id_vec[0] = node0;
+            node_id_vec[1] = node1;
+            new TPZGeoElRefPattern(node_id_vec, 666, *fGeoMesh);
+        }
+    }
+
+    for (auto ix = 0; ix < n_full_size_x - nx_correction; ix++) {
+        for (auto iy = 0; iy < n_full_size_y; iy++) {
+            node0 = (fNElemCoarseGrid) * (ix + 1) + n_nodes_x * iy * fNElemCoarseGrid;
+            node1 = node0 + n_nodes_x * fNElemCoarseGrid;
+            node_id_vec[0] = node0;
+            node_id_vec[1] = node1;
+            new TPZGeoElRefPattern(node_id_vec, 666, *fGeoMesh);
+        }
+        if (div_y.rem != 0) {
+            node0 = (fNElemCoarseGrid) * (ix + 1) + n_nodes_x * n_full_size_y * fNElemCoarseGrid;
+            node1 = node0 + n_nodes_x * div_y.rem;
+            node_id_vec[0] = node0;
+            node_id_vec[1] = node1;
+            new TPZGeoElRefPattern(node_id_vec, 666, *fGeoMesh);
+        }
+    }
+}
diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.h b/Projects/SPE10/TPZMultiscaleGridGen2D.h
index df222267..74d473af 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.h
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.h
@@ -57,6 +57,8 @@ class TPZMultiscaleGridGen2D {
     void GenerateRefPatterns();
 
     void CreateFineGridMesh();
+
+    void CreateSkeletonElements();
 };
 
 #endif // TPZMULTISCALEGRIDGEN2D_H

From bb9d279315c6f6322abd8fc09532c59874b06f29 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Tue, 16 Nov 2021 12:10:37 -0300
Subject: [PATCH 168/187] Call CreateFineGridMesh and CreateSkeletonElements
 from constructor

---
 Projects/SPE10/TPZMultiscaleGridGen2D.cpp | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
index 7be849ff..d32dfe2e 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
@@ -20,6 +20,8 @@ TPZMultiscaleGridGen2D::TPZMultiscaleGridGen2D(const TPZVec &minX, const T
     if (div_y.rem != 0) fRefTreeRemainderY = new RefTree(div_y.rem);
 
     GenerateRefPatterns();
+    CreateFineGridMesh();
+    CreateSkeletonElements();
 
 }
 

From 02566493053f10adee0f404291164ddfe22ac508 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 17 Nov 2021 11:33:52 -0300
Subject: [PATCH 169/187] Fix value assigned to variable

'n_full_size_y' was receveing a value with respect to 'x' instead of 'y'
---
 Projects/SPE10/TPZMultiscaleGridGen2D.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
index d32dfe2e..938173b2 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
@@ -114,7 +114,7 @@ void TPZMultiscaleGridGen2D::CreateSkeletonElements() {
     const std::div_t div_y = std::div(fNDivFineGrid[1], fNElemCoarseGrid);
 
     const int n_full_size_x = div_x.quot;
-    const int n_full_size_y = div_x.quot;
+    const int n_full_size_y = div_y.quot;
 
     const int ny_correction = div_y.rem == 0 ? 1 : 0;
     const int nx_correction = div_x.rem == 0 ? 1 : 0;

From 35c7d1ae83da4eb0573fa7a16c95330affb41c49 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 17 Nov 2021 17:50:21 -0300
Subject: [PATCH 170/187] Add skelid/reftree map to data structure and fill its
 content

---
 Projects/SPE10/TPZMultiscaleGridGen2D.cpp | 12 ++++++++----
 Projects/SPE10/TPZMultiscaleGridGen2D.h   |  1 +
 2 files changed, 9 insertions(+), 4 deletions(-)

diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
index 938173b2..fb36378a 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
@@ -130,7 +130,8 @@ void TPZMultiscaleGridGen2D::CreateSkeletonElements() {
             node1 = node0 + fNElemCoarseGrid;
             node_id_vec[0] = node0;
             node_id_vec[1] = node1;
-            new TPZGeoElRefPattern(node_id_vec, 666, *fGeoMesh);
+            auto * gel = new TPZGeoElRefPattern(node_id_vec, 666, *fGeoMesh);
+            fSkelIdToRefTree.insert({gel->Id(), fRefTreeDesiredSize});
         }
         if (div_x.rem != 0) {
             node0 = fNElemCoarseGrid * fNDivFineGrid[0] + (n_full_size_x + 1) * fNElemCoarseGrid +
@@ -138,7 +139,8 @@ void TPZMultiscaleGridGen2D::CreateSkeletonElements() {
             node1 = node0 + div_x.rem;
             node_id_vec[0] = node0;
             node_id_vec[1] = node1;
-            new TPZGeoElRefPattern(node_id_vec, 666, *fGeoMesh);
+            auto * gel = new TPZGeoElRefPattern(node_id_vec, 666, *fGeoMesh);
+            fSkelIdToRefTree.insert({gel->Id(), fRefTreeRemainderX});
         }
     }
 
@@ -148,14 +150,16 @@ void TPZMultiscaleGridGen2D::CreateSkeletonElements() {
             node1 = node0 + n_nodes_x * fNElemCoarseGrid;
             node_id_vec[0] = node0;
             node_id_vec[1] = node1;
-            new TPZGeoElRefPattern(node_id_vec, 666, *fGeoMesh);
+            auto * gel = new TPZGeoElRefPattern(node_id_vec, 666, *fGeoMesh);
+            fSkelIdToRefTree.insert({gel->Id(), fRefTreeDesiredSize});
         }
         if (div_y.rem != 0) {
             node0 = (fNElemCoarseGrid) * (ix + 1) + n_nodes_x * n_full_size_y * fNElemCoarseGrid;
             node1 = node0 + n_nodes_x * div_y.rem;
             node_id_vec[0] = node0;
             node_id_vec[1] = node1;
-            new TPZGeoElRefPattern(node_id_vec, 666, *fGeoMesh);
+            auto * gel = new TPZGeoElRefPattern(node_id_vec, 666, *fGeoMesh);
+            fSkelIdToRefTree.insert({gel->Id(), fRefTreeRemainderY});
         }
     }
 }
diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.h b/Projects/SPE10/TPZMultiscaleGridGen2D.h
index 74d473af..aaebd80c 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.h
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.h
@@ -48,6 +48,7 @@ class TPZMultiscaleGridGen2D {
     RefTree *fRefTreeRemainderX = nullptr;
     RefTree *fRefTreeRemainderY = nullptr;
     std::map, TPZRefPattern> fRefPatterns;
+    std::map fSkelIdToRefTree;
 
     TPZGeoMesh *fGeoMesh = nullptr;
 

From c0da89d58d3c4d798d476ce05ed890ba5c4b1348 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Wed, 17 Nov 2021 17:52:00 -0300
Subject: [PATCH 171/187] Create RefineSkeletonElements method

---
 Projects/SPE10/TPZMultiscaleGridGen2D.cpp | 30 +++++++++++++++++++++++
 Projects/SPE10/TPZMultiscaleGridGen2D.h   |  2 ++
 2 files changed, 32 insertions(+)

diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
index fb36378a..59e3550b 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
@@ -22,6 +22,7 @@ TPZMultiscaleGridGen2D::TPZMultiscaleGridGen2D(const TPZVec &minX, const T
     GenerateRefPatterns();
     CreateFineGridMesh();
     CreateSkeletonElements();
+    RefineSkeletonElements();
 
 }
 
@@ -163,3 +164,32 @@ void TPZMultiscaleGridGen2D::CreateSkeletonElements() {
         }
     }
 }
+
+void TPZMultiscaleGridGen2D::RefineSkeletonElements() {
+
+    std::function)> RefineSkeleton = [&](std::pair data) -> void {
+        auto * node = data.second;
+        if (node->fActualSize != 1) {
+
+            auto right_size = node->fChildRight->fActualSize;
+            auto left_size = node->fChildLeft->fActualSize;
+
+            if (right_size == left_size) {
+                right_size = 1;
+                left_size = 1;
+            }
+            const auto ref_pattern = fRefPatterns.find({left_size, right_size});
+            if (ref_pattern == fRefPatterns.end()) DebugStop();
+            TPZAutoPointer ref_pattern_ptr(&ref_pattern->second);
+            auto * skel = fGeoMesh->Element(data.first);
+            skel->SetRefPattern(ref_pattern_ptr);
+            TPZManVector sons(2, nullptr);
+            skel->Divide(sons);
+
+            RefineSkeleton({sons[0]->Id(), node->fChildLeft});
+            RefineSkeleton({sons[1]->Id(), node->fChildRight});
+        }
+    };
+
+    std::for_each(fSkelIdToRefTree.begin(), fSkelIdToRefTree.end(), RefineSkeleton);
+}
diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.h b/Projects/SPE10/TPZMultiscaleGridGen2D.h
index aaebd80c..3f98b781 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.h
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.h
@@ -60,6 +60,8 @@ class TPZMultiscaleGridGen2D {
     void CreateFineGridMesh();
 
     void CreateSkeletonElements();
+
+    void RefineSkeletonElements();
 };
 
 #endif // TPZMULTISCALEGRIDGEN2D_H

From ccb63e6f5e8a9232a15ddd588be5dab4c9f40a31 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Mon, 22 Nov 2021 11:02:11 -0300
Subject: [PATCH 172/187] Add fGeoMesh getter

---
 Projects/SPE10/TPZMultiscaleGridGen2D.h | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.h b/Projects/SPE10/TPZMultiscaleGridGen2D.h
index 3f98b781..e072e1b9 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.h
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.h
@@ -37,6 +37,8 @@ class TPZMultiscaleGridGen2D {
     TPZMultiscaleGridGen2D(const TPZVec &minX, const TPZVec &maxX, const TPZVec &NDivFineGrid,
                            int NElemCoarseGrid);
 
+    [[nodiscard]] auto* GeoMesh() const { return fGeoMesh; }
+
 private:
     // Member variables
     const TPZManVector fNDivFineGrid{0};

From 97923ebbf083e954363497b0eb7cf8a7528094cf Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Mon, 22 Nov 2021 11:04:43 -0300
Subject: [PATCH 173/187] Add variable to handle the mat id of skels

---
 Projects/SPE10/TPZMultiscaleGridGen2D.h | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.h b/Projects/SPE10/TPZMultiscaleGridGen2D.h
index e072e1b9..57792332 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.h
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.h
@@ -41,6 +41,8 @@ class TPZMultiscaleGridGen2D {
 
 private:
     // Member variables
+    const int fSkeletonMatId{-99};
+
     const TPZManVector fNDivFineGrid{0};
     const int fNElemCoarseGrid{0};
     const TPZManVector fMinX{0};

From 77738c7ede5dd96a6c80ef16a7f037a3f3065ec7 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Mon, 22 Nov 2021 11:08:55 -0300
Subject: [PATCH 174/187] Create SwapSkeletonNodes method

---
 Projects/SPE10/TPZMultiscaleGridGen2D.cpp | 30 +++++++++++++++++++++++
 Projects/SPE10/TPZMultiscaleGridGen2D.h   |  2 ++
 2 files changed, 32 insertions(+)

diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
index 59e3550b..3a7d464d 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
@@ -193,3 +193,33 @@ void TPZMultiscaleGridGen2D::RefineSkeletonElements() {
 
     std::for_each(fSkelIdToRefTree.begin(), fSkelIdToRefTree.end(), RefineSkeleton);
 }
+
+void TPZMultiscaleGridGen2D::SwapSkeletonNodes() {
+
+    const auto x_step = (fMaxX[0] - fMinX[0]) / fNDivFineGrid[0];
+    const auto y_step = (fMaxX[1] - fMinX[1]) / fNDivFineGrid[1];
+
+    auto CoordToNodeId = [&](const auto &coord) {
+        return std::lround(coord[0] / x_step) + (fNDivFineGrid[0] + 1) * std::lround(coord[1] / y_step);
+    };
+
+    for (auto i = 0; i < fGeoMesh->NElements(); i++) {
+        const auto * gel = fGeoMesh->Element(i);
+        if (!gel) continue;
+        if (gel->MaterialId() != fSkeletonMatId) continue;
+        if (!gel->Father()) continue;
+        TPZManVector coord0(3), coord1(3);
+        auto node0 = gel->Node(0);
+        auto node1 = gel->Node(1);
+
+        node0.GetCoordinates(coord0);
+        node1.GetCoordinates(coord1);
+
+        auto node0_id = CoordToNodeId(coord0);
+        auto node1_id = CoordToNodeId(coord1);
+
+        //std::cout << "Old nodes: " << node0.Id() << ", " << node1.Id() << '\n';
+        //std::cout << "New nodes: " << node0_id << ", " << node1_id << '\n';
+
+    }
+}
diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.h b/Projects/SPE10/TPZMultiscaleGridGen2D.h
index 57792332..76c1ed6d 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.h
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.h
@@ -66,6 +66,8 @@ class TPZMultiscaleGridGen2D {
     void CreateSkeletonElements();
 
     void RefineSkeletonElements();
+
+    void SwapSkeletonNodes();
 };
 
 #endif // TPZMULTISCALEGRIDGEN2D_H

From c8994a5b3073aa616abfc657deae844d78c68de2 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Mon, 22 Nov 2021 11:09:57 -0300
Subject: [PATCH 175/187]  Call SwapSkeletonNodes from constructor

---
 Projects/SPE10/TPZMultiscaleGridGen2D.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
index 3a7d464d..5efdd0bf 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
@@ -23,7 +23,7 @@ TPZMultiscaleGridGen2D::TPZMultiscaleGridGen2D(const TPZVec &minX, const T
     CreateFineGridMesh();
     CreateSkeletonElements();
     RefineSkeletonElements();
-
+    SwapSkeletonNodes();
 }
 
 TPZRefPattern TPZMultiscaleGridGen2D::CreateNonUniformLineRefPattern(const int a, const int b) {

From 0a1e3f3ea818fe74372fff7ef7c056f7d135ff05 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Mon, 22 Nov 2021 11:10:20 -0300
Subject: [PATCH 176/187] Rename vars

---
 Projects/SPE10/TPZMultiscaleGridGen2D.cpp | 34 +++++++++++------------
 1 file changed, 17 insertions(+), 17 deletions(-)

diff --git a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
index 5efdd0bf..5a96820a 100644
--- a/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
+++ b/Projects/SPE10/TPZMultiscaleGridGen2D.cpp
@@ -123,23 +123,23 @@ void TPZMultiscaleGridGen2D::CreateSkeletonElements() {
     const int n_nodes_x = fNDivFineGrid[0] + 1;
 
     TPZManVector node_id_vec(2, 0);
-    int node0, node1;
+    int node0_id, node1_id;
     for (auto iy = 0; iy < n_full_size_y - ny_correction; iy++) {
         for (auto ix = 0; ix < n_full_size_x; ix++) {
-            node0 =
+            node0_id =
                 fNElemCoarseGrid * fNDivFineGrid[0] + (ix + 1) * fNElemCoarseGrid + fNElemCoarseGrid * n_nodes_x * iy;
-            node1 = node0 + fNElemCoarseGrid;
-            node_id_vec[0] = node0;
-            node_id_vec[1] = node1;
+            node1_id = node0_id + fNElemCoarseGrid;
+            node_id_vec[0] = node0_id;
+            node_id_vec[1] = node1_id;
             auto * gel = new TPZGeoElRefPattern(node_id_vec, 666, *fGeoMesh);
             fSkelIdToRefTree.insert({gel->Id(), fRefTreeDesiredSize});
         }
         if (div_x.rem != 0) {
-            node0 = fNElemCoarseGrid * fNDivFineGrid[0] + (n_full_size_x + 1) * fNElemCoarseGrid +
+            node0_id = fNElemCoarseGrid * fNDivFineGrid[0] + (n_full_size_x + 1) * fNElemCoarseGrid +
                     fNElemCoarseGrid * n_nodes_x * iy;
-            node1 = node0 + div_x.rem;
-            node_id_vec[0] = node0;
-            node_id_vec[1] = node1;
+            node1_id = node0_id + div_x.rem;
+            node_id_vec[0] = node0_id;
+            node_id_vec[1] = node1_id;
             auto * gel = new TPZGeoElRefPattern(node_id_vec, 666, *fGeoMesh);
             fSkelIdToRefTree.insert({gel->Id(), fRefTreeRemainderX});
         }
@@ -147,18 +147,18 @@ void TPZMultiscaleGridGen2D::CreateSkeletonElements() {
 
     for (auto ix = 0; ix < n_full_size_x - nx_correction; ix++) {
         for (auto iy = 0; iy < n_full_size_y; iy++) {
-            node0 = (fNElemCoarseGrid) * (ix + 1) + n_nodes_x * iy * fNElemCoarseGrid;
-            node1 = node0 + n_nodes_x * fNElemCoarseGrid;
-            node_id_vec[0] = node0;
-            node_id_vec[1] = node1;
+            node0_id = (fNElemCoarseGrid) * (ix + 1) + n_nodes_x * iy * fNElemCoarseGrid;
+            node1_id = node0_id + n_nodes_x * fNElemCoarseGrid;
+            node_id_vec[0] = node0_id;
+            node_id_vec[1] = node1_id;
             auto * gel = new TPZGeoElRefPattern(node_id_vec, 666, *fGeoMesh);
             fSkelIdToRefTree.insert({gel->Id(), fRefTreeDesiredSize});
         }
         if (div_y.rem != 0) {
-            node0 = (fNElemCoarseGrid) * (ix + 1) + n_nodes_x * n_full_size_y * fNElemCoarseGrid;
-            node1 = node0 + n_nodes_x * div_y.rem;
-            node_id_vec[0] = node0;
-            node_id_vec[1] = node1;
+            node0_id = (fNElemCoarseGrid) * (ix + 1) + n_nodes_x * n_full_size_y * fNElemCoarseGrid;
+            node1_id = node0_id + n_nodes_x * div_y.rem;
+            node_id_vec[0] = node0_id;
+            node_id_vec[1] = node1_id;
             auto * gel = new TPZGeoElRefPattern(node_id_vec, 666, *fGeoMesh);
             fSkelIdToRefTree.insert({gel->Id(), fRefTreeRemainderY});
         }

From 96554e3c445ffcbed8ae3e05fbe9ea51a4a168d4 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 20 Jan 2022 11:42:14 -0300
Subject: [PATCH 177/187] Work on SPE10 and new SPE10RefSol target

---
 Projects/CMakeLists.txt            |   6 +-
 Projects/SPE10/CMakeLists.txt      |   8 +-
 Projects/SPE10/ToolsSPE10.cpp      | 227 +++++++++++++++++++++++++++++
 Projects/SPE10/ToolsSPE10.h        |  27 +++-
 Projects/SPE10/mainSPE10.cpp       | 101 +++++--------
 Projects/SPE10/mainSPE10RefSol.cpp | 164 +++++++++++++++++++++
 6 files changed, 460 insertions(+), 73 deletions(-)
 create mode 100644 Projects/SPE10/mainSPE10RefSol.cpp

diff --git a/Projects/CMakeLists.txt b/Projects/CMakeLists.txt
index 5df72e5e..b7ea9ac5 100644
--- a/Projects/CMakeLists.txt
+++ b/Projects/CMakeLists.txt
@@ -19,9 +19,5 @@ if(BUILD_UNISIM_PROJECT)
     #add_subdirectory(UNISIM)
 endif()
 
-# This project is marked as optional since it requires libInterpolate external library
-option(BUILD_SPE10_PROJECT "Whether to build estimation on SPE10 mesh" OFF)
-if(BUILD_SPE10_PROJECT)
-    add_subdirectory(SPE10)
-endif()
+add_subdirectory(SPE10)
 
diff --git a/Projects/SPE10/CMakeLists.txt b/Projects/SPE10/CMakeLists.txt
index ee291f25..d20d4c76 100644
--- a/Projects/SPE10/CMakeLists.txt
+++ b/Projects/SPE10/CMakeLists.txt
@@ -1,7 +1,7 @@
-add_executable(SPE10 mainSPE10.cpp ToolsSPE10.cpp ToolsSPE10.h TPZMultiscaleGridGen2D.cpp TPZMultiscaleGridGen2D.h)
-target_link_libraries(SPE10 PRIVATE Tools ErrorEstimationLib)
+add_executable(SPE10Adaptivity mainSPE10.cpp ToolsSPE10.cpp ToolsSPE10.h TPZMultiscaleGridGen2D.cpp TPZMultiscaleGridGen2D.h)
+target_link_libraries(SPE10Adaptivity PRIVATE Tools ErrorEstimationLib)
 
-find_package(libInterpolate REQUIRED)
-target_link_libraries(SPE10 PRIVATE libInterpolate::Interpolate)
+add_executable(SPE10RefSol mainSPE10RefSol.cpp ToolsSPE10.cpp ToolsSPE10.h TPZMultiscaleGridGen2D.cpp TPZMultiscaleGridGen2D.h)
+target_link_libraries(SPE10RefSol PRIVATE Tools ErrorEstimationLib)
 
 configure_file(InputData/spe_perm.dat InputData/spe_perm.dat COPYONLY)
diff --git a/Projects/SPE10/ToolsSPE10.cpp b/Projects/SPE10/ToolsSPE10.cpp
index 5ef4a599..48b3a0c6 100644
--- a/Projects/SPE10/ToolsSPE10.cpp
+++ b/Projects/SPE10/ToolsSPE10.cpp
@@ -2,9 +2,16 @@
 // Created by Gustavo Batistela on 10/26/21.
 //
 
+#include "Tools.h"
+#include "ToolsMHM.h"
 #include "ToolsSPE10.h"
+#include 
 #include 
+#include 
+#include 
+#include 
 #include 
+#include 
 #include 
 
 [[maybe_unused]] TPZGeoMesh *SPE10::CreateFineGridGeoMesh() {
@@ -193,3 +200,223 @@
     gmesh->BuildConnectivity();
     return gmesh;
 }
+
+STATE SPE10::PermeabilityFunction(const TPZVec &x) {
+    auto rounded_x = static_cast(x[0]);
+    auto rounded_y = static_cast(x[1]);
+    if (rounded_x == 220) rounded_x = 219;
+    if (rounded_y == 60) rounded_y = 59;
+    return perm_vec->operator[](rounded_x * 60 + rounded_y);
+}
+
+void SPE10::ReadSPE10CellPermeabilities() {
+
+    std::cout << "Reading permeability data...\n";
+
+    std::ifstream perm_file("InputData/spe_perm.dat", std::ios::in);
+    if (!perm_file) {
+        std::cerr << "Unable to open input file\n";
+        DebugStop();
+    }
+
+    perm_vec = new TPZManVector(n_cells, 0);
+
+    int cell_id = 0;
+    const auto start_line = 1 + n_cells * (layer - 1) / 6;
+
+    int line_num = 0;
+    int line_num2 = 0;
+    while (perm_file) {
+        line_num++;
+        line_num2++;
+        std::string line;
+        std::getline(perm_file, line, '\n');
+
+        if (line_num < start_line) continue;
+
+        std::stringstream stream(line);
+        for (int i = 0; i < 6; i++) {
+            stream >> perm_vec->operator[](cell_id);
+            cell_id++;
+        }
+        if (cell_id == n_cells) break;
+    }
+    std::cout << "Finished reading permeability data from input file!\n";
+}
+
+void SPE10::InsertMaterials(TPZCompMesh *cmesh) {
+
+    auto *mix = new TPZMixedDarcyFlow(1, cmesh->Dimension());
+    std::function &coord)> func = PermeabilityFunction;
+    mix->SetPermeabilityFunction(func);
+
+    TPZFNMatrix<1, REAL> val1(1, 1, 0.);
+    TPZManVector val2(1, 0.);
+    constexpr int dirichlet_bc = 0;
+    constexpr int neumann_bc = 1;
+
+    // Pressure at reservoir boundary
+    val2[0] = 10;
+    TPZBndCond *pressure_left = mix->CreateBC(mix, -1, dirichlet_bc, val1, val2);
+    val2[0] = 0;
+    TPZBndCond *pressure_general = mix->CreateBC(mix, -2, neumann_bc, val1, val2);
+
+    cmesh->InsertMaterialObject(mix);
+    cmesh->InsertMaterialObject(pressure_left);
+    cmesh->InsertMaterialObject(pressure_general);
+}
+
+void SPE10::EstimateError(TPZMHMixedMeshControl &mhm, TPZMHMHDivErrorEstimator &estimator) {
+
+    std::cout << "\nError Estimation processing for MHM-Hdiv problem " << std::endl;
+
+    // Error estimation
+    TPZMultiphysicsCompMesh *originalMesh = dynamic_cast(mhm.CMesh().operator->());
+    if (!originalMesh) DebugStop();
+
+    estimator.PotentialReconstruction();
+
+    std::string command = "mkdir SPE10";
+    system(command.c_str());
+
+    TPZManVector errors;
+    TPZManVector elementerrors;
+    std::stringstream plotname;
+    plotname << "CroppedSPE10-Errors-Step" << estimator.AdaptivityStep() << ".vtk";
+    auto plotname_str = plotname.str();
+    estimator.ComputeErrors(errors, elementerrors, plotname_str);
+    std::cout << "Finished computing errors!\n";
+}
+
+void SPE10::EstimateError(TPZMHMixedMeshControl &mhm, TPZMHMHDivErrorEstimator &estimator, TPZMultiphysicsCompMesh * ref_sol) {
+
+    std::cout << "\nError Estimation processing for MHM-Hdiv problem " << std::endl;
+
+    // Error estimation
+    TPZMultiphysicsCompMesh *originalMesh = dynamic_cast(mhm.CMesh().operator->());
+    if (!originalMesh) DebugStop();
+
+    estimator.SetReferenceSolution(true);
+    estimator.SetReferenceSolutionMeshes(ref_sol->MeshVector()[1], ref_sol->MeshVector()[1]);
+
+    estimator.PotentialReconstruction();
+
+
+    std::string command = "mkdir SPE10";
+    system(command.c_str());
+
+    TPZManVector errors;
+    TPZManVector elementerrors;
+    std::stringstream plotname;
+    plotname << "CroppedSPE10-Errors-Step" << estimator.AdaptivityStep() << ".vtk";
+    auto plotname_str = plotname.str();
+    estimator.ComputeErrors(errors, elementerrors, plotname_str);
+    std::cout << "Finished computing errors!\n";
+}
+
+void SPE10::SolveMHMProblem(TPZMHMixedMeshControl &mhm, const int adaptivity_step) {
+
+    TPZAutoPointer cmesh = mhm.CMesh();
+
+    bool should_renumber = true;
+    TPZLinearAnalysis an(cmesh, should_renumber);
+
+#ifdef PZ_USING_MKL
+    TPZSSpStructMatrix strmat(cmesh.operator->());
+    strmat.SetNumThreads(0);
+#else
+    TPZSkylineStructMatrix strmat(cmesh.operator->());
+    strmat.SetNumThreads(8);
+#endif
+
+    an.SetStructuralMatrix(strmat);
+    TPZStepSolver step;
+    step.SetDirect(ELDLt);
+    an.SetSolver(step);
+
+    std::cout << "Assembling\n";
+    an.Assemble();
+
+    std::cout << "Solving\n";
+    an.Solve();
+    std::cout << "Finished\n";
+    an.LoadSolution();
+
+    TPZMFSolutionTransfer transfer;
+    transfer.BuildTransferData(cmesh.operator->());
+    transfer.TransferFromMultiphysics();
+
+    TPZStack scalnames, vecnames;
+    TPZMaterial *mat = cmesh->FindMaterial(1);
+    if (!mat) {
+        DebugStop();
+    }
+
+    scalnames.Push("Pressure");
+    scalnames.Push("Permeability");
+    vecnames.Push("Flux");
+
+    int resolution = 0;
+    std::stringstream plotname;
+    plotname << "CroppedSPE10-Results-Step" << adaptivity_step << ".vtk";
+    an.DefineGraphMesh(cmesh->Dimension(), scalnames, vecnames, plotname.str());
+    an.PostProcess(resolution, cmesh->Dimension());
+}
+
+TPZGeoMesh *SPE10::CreateSPE10CoarseGeoMesh() {
+    std::cout << "Creating SPE10 initial grid...\n";
+
+    const TPZManVector x0 = {0, 0, 0};
+    const TPZManVector x1 = {208., 48., 0.};
+    const TPZManVector ndiv = {13, 3, 0};
+
+    TPZGenGrid2D gen(ndiv, x0, x1);
+
+    gen.SetRefpatternElements(true);
+    auto gmesh = new TPZGeoMesh;
+    gen.Read(gmesh);
+
+    gen.SetBC(gmesh, 5, -1);
+    gen.SetBC(gmesh, 6, -2);
+    gen.SetBC(gmesh, 7, -2);
+    // gen.SetBC(gmesh, 4, -2);
+
+    std::cout << "SPE10 initial grid created. NElem: " << gmesh->NElements() << "\n";
+
+    return gmesh;
+}
+
+void SPE10::CreateSPE10MHMCompMesh(TPZMHMixedMeshControl &mhm, const std::vector &skelsToDivide, const int nInternalRef) {
+
+    TPZGeoMesh *gmesh = mhm.GMesh().operator->();
+    TPZManVector coarse_indexes;
+    ComputeCoarseIndices(gmesh, coarse_indexes);
+
+    Tools::UniformRefinement(nInternalRef, 2, gmesh);
+    Tools::DivideLowerDimensionalElements(gmesh);
+
+    mhm.DefinePartitionbyCoarseIndices(coarse_indexes);
+
+    // Indicate material indices to the MHM control structure
+    mhm.fMaterialIds = {1};
+    mhm.fMaterialBCIds = {-1, -2, -3};
+
+    // Insert the material objects in the multiphysics mesh
+    TPZCompMesh *cmesh = mhm.CMesh().operator->();
+    SPE10::InsertMaterials(cmesh);
+
+    // General approximation order settings
+    mhm.SetInternalPOrder(1);
+    mhm.SetSkeletonPOrder(1);
+    mhm.SetHdivmaismaisPOrder(2);
+
+    // Refine skeleton elements
+    for (auto skelid : skelsToDivide) {
+        mhm.DivideSkeletonElement(skelid);
+    }
+    mhm.DivideBoundarySkeletonElements();
+
+    // Creates MHM mesh
+    bool substructure = true;
+    mhm.BuildComputationalMesh(substructure);
+}
diff --git a/Projects/SPE10/ToolsSPE10.h b/Projects/SPE10/ToolsSPE10.h
index 384314ab..33f911bf 100644
--- a/Projects/SPE10/ToolsSPE10.h
+++ b/Projects/SPE10/ToolsSPE10.h
@@ -6,12 +6,37 @@
 #define TOOLSSPE10_H
 
 #include "pzgmesh.h"
+#include 
+#include 
 
 namespace SPE10 {
+
+constexpr int nx = 220;
+constexpr int ny = 60;
+constexpr int layer = 36;
+constexpr int n_cells = nx * ny;
+static TPZManVector *perm_vec;
+
 [[maybe_unused]] TPZGeoMesh *CreateFineGridGeoMesh();
 [[maybe_unused]] TPZGeoMesh *CreateMHMGeoMesh();
 [[maybe_unused]] TPZGeoMesh *CreateRefinementGeoMesh(int nx, int ny);
 [[maybe_unused]] TPZGeoMesh *CreateLineRefinementGeoMesh(int nx);
-}
+
+STATE PermeabilityFunction(const TPZVec &x);
+
+void ReadSPE10CellPermeabilities();
+
+void InsertMaterials(TPZCompMesh *cmesh);
+
+void EstimateError(TPZMHMixedMeshControl &mhm, TPZMHMHDivErrorEstimator &estimator);
+void EstimateError(TPZMHMixedMeshControl &mhm, TPZMHMHDivErrorEstimator &estimator, TPZMultiphysicsCompMesh * ref_sol);
+
+void SolveMHMProblem(TPZMHMixedMeshControl &mhm, int adaptivity_step);
+
+TPZGeoMesh *CreateSPE10CoarseGeoMesh();
+
+void CreateSPE10MHMCompMesh(TPZMHMixedMeshControl &mhm, const std::vector &skelsToDivide, int nInternalRef);
+
+} // namespace SPE10
 
 #endif // TOOLSSPE10_H
diff --git a/Projects/SPE10/mainSPE10.cpp b/Projects/SPE10/mainSPE10.cpp
index 0baf3644..be8cc715 100644
--- a/Projects/SPE10/mainSPE10.cpp
+++ b/Projects/SPE10/mainSPE10.cpp
@@ -12,43 +12,32 @@
 #include 
 #include 
 #include 
-#include 
 #include 
 #include 
 
-typedef _2D::BicubicInterpolator Interpolator;
-
 // Global variables
-Interpolator interpolator;
 constexpr int nx = 220;
 constexpr int ny = 60;
 constexpr int n_cells = nx * ny;
 TPZManVector perm_vec(n_cells, 1);
 
+std::map neq_error;
+
 // Function declarations
 void ReadSPE10CellPermeabilities(TPZVec*perm_vec, int layer);
-TPZGeoMesh *CreateSPE10GeoMesh();
+TPZGeoMesh *CreateSPE10CoarseGeoMesh();
 STATE PermeabilityFunction(const TPZVec &x);
-STATE NewPermeabilityFunction(const TPZVec &x);
 void InsertMaterials(TPZCompMesh *cmesh);
 void CreateSPE10MHMCompMesh(TPZMHMixedMeshControl &mhm, const std::vector &skelsToDivide);
 void SolveMHMProblem(TPZMHMixedMeshControl &mhm, int adaptivity_step);
 void EstimateError(TPZMHMixedMeshControl &mhm, TPZMHMHDivErrorEstimator &estimator);
 void MHMAdaptivity(TPZMHMixedMeshControl *mhm, TPZCompMesh *postProcMesh, std::vector &skelsToRefine);
 
-constexpr int adaptivity_steps = 4;
+constexpr int adaptivity_steps = 5;
 int main() {
 
     gRefDBase.InitializeAllUniformRefPatterns();
 
-    auto * gmeshMHM = SPE10::CreateMHMGeoMesh();
-
-    {
-        std::string fileName = "GMeshMHM.vtk";
-        std::ofstream file(fileName);
-        TPZVTKGeoMesh::PrintGMeshVTK(gmeshMHM, file);
-    }
-
     constexpr int layer = 36;
 
     ReadSPE10CellPermeabilities(&perm_vec, layer);
@@ -56,26 +45,13 @@ int main() {
     std::vector skelsToRefine;
     for (int step = 0; step < adaptivity_steps; step++) {
 
-        TPZGeoMesh *gmesh = SPE10::CreateMHMGeoMesh();
+        TPZGeoMesh *gmesh = CreateSPE10CoarseGeoMesh();
         std::cout << "SPE10 initial grid created. NElem: " << gmesh->NElements() << "\n";
 
-        //std::vector x, y, perm;
-        //for (int i = 0; i < nx; i++) {
-        //    for (int j = 0; j < ny; j++) {
-        //        const int cell_id = ny * i + j;
-        //        const double cell_perm = perm_vec[cell_id];
-        //        x.push_back(0.5 + i);
-        //        y.push_back(0.5 + j);
-        //        perm.push_back(cell_perm);
-        //    }
-        //}
-
-        //interpolator.setData(x.size(), x.data(), y.data(), perm.data());
-
         TPZMHMixedMeshControl mhm(gmesh);
         CreateSPE10MHMCompMesh(mhm, skelsToRefine);
         std::stringstream filename;
-        filename << "SPE10GeoMesh-Step" << step;
+        filename << "FineCroppedSPE10GeoMesh-Step" << step;
         Tools::PrintGeometry(gmesh, filename.str(), false, true);
 
         SolveMHMProblem(mhm, step);
@@ -92,16 +68,19 @@ int main() {
 
         MHMAdaptivity(&mhm, postprocmesh, skelsToRefine);
     }
+    for (auto it: neq_error) {
+        std::cout << "(" << it.first << ", " << it.second << ")\n";
+    }
 
     return 0;
 }
 
-TPZGeoMesh *CreateSPE10GeoMesh() {
+TPZGeoMesh *CreateSPE10CoarseGeoMesh() {
     std::cout << "Creating SPE10 initial grid...\n";
 
     const TPZManVector x0 = {0, 0, 0};
-    const TPZManVector x1 = {220., 60., 0.};
-    const TPZManVector ndiv = {22, 6, 0};
+    const TPZManVector x1 = {208., 48., 0.};
+    const TPZManVector ndiv = {13, 3, 0};
 
     TPZGenGrid2D gen(ndiv, x0, x1);
 
@@ -110,6 +89,9 @@ TPZGeoMesh *CreateSPE10GeoMesh() {
     gen.Read(gmesh);
 
     gen.SetBC(gmesh, 5, -1);
+    gen.SetBC(gmesh, 6, -2);
+    gen.SetBC(gmesh, 7, -2);
+    //gen.SetBC(gmesh, 4, -2);
 
     std::cout << "SPE10 initial grid created. NElem: " << gmesh->NElements() << "\n";
 
@@ -151,26 +133,11 @@ void ReadSPE10CellPermeabilities(TPZVec *perm_vec, const int layer) {
 }
 
 STATE PermeabilityFunction(const TPZVec &x) {
-    auto perm = interpolator(x[0], x[1]);
-    if (perm <= 1) {
-        perm = 1;
-    } else {
-        perm += 1;
-    }
-    return perm;
-}
-
-STATE NewPermeabilityFunction(const TPZVec &x) {
-    const auto rounded_x = static_cast(x[0]);
-    const auto rounded_y = static_cast(x[1]);
-
-    auto perm = perm_vec[rounded_x * 60 + rounded_y];
-    if (perm <= 1) {
-        perm = 1;
-    } else {
-        perm += 1;
-    }
-    return perm;
+    auto rounded_x = static_cast(x[0]);
+    auto rounded_y = static_cast(x[1]);
+    if (rounded_x == 220) rounded_x = 219;
+    if (rounded_y == 60) rounded_y = 59;
+    return perm_vec[rounded_x * 60 + rounded_y];
 }
 
 void CreateSPE10MHMCompMesh(TPZMHMixedMeshControl &mhm, const std::vector &skelsToDivide) {
@@ -179,7 +146,7 @@ void CreateSPE10MHMCompMesh(TPZMHMixedMeshControl &mhm, const std::vector coarse_indexes;
     ComputeCoarseIndices(gmesh, coarse_indexes);
 
-    int nInternalRef = adaptivity_steps;
+    int nInternalRef = adaptivity_steps - 1;
     Tools::UniformRefinement(nInternalRef, 2, gmesh);
     Tools::DivideLowerDimensionalElements(gmesh);
 
@@ -196,7 +163,7 @@ void CreateSPE10MHMCompMesh(TPZMHMixedMeshControl &mhm, const std::vector cmesh = mhm.CMesh();
-
+    std::cout << "*** NEQ: ," << mhm.CMesh()->NEquations() << '\n';
     bool should_renumber = true;
     TPZLinearAnalysis an(cmesh, should_renumber);
 
@@ -253,7 +220,7 @@ void SolveMHMProblem(TPZMHMixedMeshControl &mhm, const int adaptivity_step) {
 
     int resolution = 0;
     std::stringstream plotname;
-    plotname << "SPE10-Results-Step" << adaptivity_step << ".vtk";
+    plotname << "FineCroppedSPE10-Results-Step" << adaptivity_step << ".vtk";
     an.DefineGraphMesh(cmesh->Dimension(), scalnames, vecnames, plotname.str());
     an.PostProcess(resolution, cmesh->Dimension());
 }
@@ -261,19 +228,23 @@ void SolveMHMProblem(TPZMHMixedMeshControl &mhm, const int adaptivity_step) {
 void InsertMaterials(TPZCompMesh *cmesh) {
 
     auto *mix = new TPZMixedDarcyFlow(1, cmesh->Dimension());
-    std::function &coord)> func = NewPermeabilityFunction;
+    std::function &coord)> func = PermeabilityFunction;
     mix->SetPermeabilityFunction(func);
 
     TPZFNMatrix<1, REAL> val1(1, 1, 0.);
     TPZManVector val2(1, 0.);
     constexpr int dirichlet_bc = 0;
+    constexpr int neumann_bc = 1;
 
     // Pressure at reservoir boundary
-    val2[0] = 1;
+    val2[0] = 10;
     TPZBndCond *pressure_left = mix->CreateBC(mix, -1, dirichlet_bc, val1, val2);
+    val2[0] = 0;
+    TPZBndCond *pressure_general = mix->CreateBC(mix, -2, neumann_bc, val1, val2);
 
     cmesh->InsertMaterialObject(mix);
     cmesh->InsertMaterialObject(pressure_left);
+    cmesh->InsertMaterialObject(pressure_general);
 }
 
 void EstimateError(TPZMHMixedMeshControl &mhm, TPZMHMHDivErrorEstimator &estimator) {
@@ -292,10 +263,14 @@ void EstimateError(TPZMHMixedMeshControl &mhm, TPZMHMHDivErrorEstimator &estimat
     TPZManVector errors;
     TPZManVector elementerrors;
     std::stringstream plotname;
-    plotname << "SPE10-Errors-Step" << estimator.AdaptivityStep() << ".vtk";
+    plotname << "FineCroppedSPE10-Errors-Step" << estimator.AdaptivityStep() << ".vtk";
     auto plotname_str = plotname.str();
     estimator.ComputeErrors(errors, elementerrors, plotname_str);
-    std::cout << "Finished computing errors!";
+    Tools::PrintErrors(std::cout, errors);
+
+    neq_error.insert({mhm.CMesh()->NEquations(), errors[3]});
+
+    std::cout << "Finished computing errors!\n";
 }
 
 void MHMAdaptivity(TPZMHMixedMeshControl *mhm, TPZCompMesh *postProcMesh, std::vector &skelsToRefine) {
@@ -322,7 +297,6 @@ void MHMAdaptivity(TPZMHMixedMeshControl *mhm, TPZCompMesh *postProcMesh, std::v
         }
     }
 
-    std::cout << "Max error: " << maxError << "\n";
 
     // Refines elements which error are bigger than 30% of the maximum error
     REAL threshold = 0.5 * maxError;
@@ -336,9 +310,10 @@ void MHMAdaptivity(TPZMHMixedMeshControl *mhm, TPZCompMesh *postProcMesh, std::v
 
         STATE submeshError = sol(iel, fluxErrorEstimateCol);
         if (submeshError > threshold) {
+        //if (true) {
             TPZGeoEl * gel = submesh->Element(0)->Reference();
             const auto submesh_id = geoToMHM[gel->Index()];
-            std::cout << "Refining submesh " << submesh_id << " which error is " << submeshError << ".\n";
+            //std::cout << "Refining submesh " << submesh_id << " which error is " << submeshError << ".\n";
             for (auto interface : interfaces) {
                 if (interface.second.first == submesh_id || interface.second.second == submesh_id) {
                     interfacesToRefine.insert(interface.first);
diff --git a/Projects/SPE10/mainSPE10RefSol.cpp b/Projects/SPE10/mainSPE10RefSol.cpp
new file mode 100644
index 00000000..c3da0b0e
--- /dev/null
+++ b/Projects/SPE10/mainSPE10RefSol.cpp
@@ -0,0 +1,164 @@
+//
+// Created by Gustavo Batistela on 4/5/21.
+//
+
+#include "Tools.h"
+#include "ToolsSPE10.h"
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+#include 
+
+constexpr int porder = 1;
+constexpr int korder = 2;
+constexpr int nInternalRef = 5;
+
+TPZMultiphysicsCompMesh RunFineScaleProblem();
+
+int main() {
+
+    gRefDBase.InitializeAllUniformRefPatterns();
+
+    SPE10::ReadSPE10CellPermeabilities();
+
+    auto fine_cmesh = RunFineScaleProblem();
+    // Create geomesh
+    TPZGeoMesh *gmesh = SPE10::CreateSPE10CoarseGeoMesh();
+    std::cout << "SPE10 initial grid created. NElem: " << gmesh->NElements() << "\n";
+
+    // Create compmesh
+    TPZMHMixedMeshControl mhm(gmesh);
+
+    std::vector skelsToRefine;
+    SPE10::CreateSPE10MHMCompMesh(mhm, skelsToRefine, nInternalRef);
+    constexpr int step = 0;
+    std::stringstream filename;
+    filename << "CroppedSPE10GeoMesh-Step" << step;
+    Tools::PrintGeometry(gmesh, filename.str(), false, true);
+
+    SPE10::SolveMHMProblem(mhm, step);
+
+    // Estimate error
+    bool postProcWithHDiv = false;
+    TPZMultiphysicsCompMesh *originalMesh = dynamic_cast(mhm.CMesh().operator->());
+    if (!originalMesh) DebugStop();
+
+    TPZMHMHDivErrorEstimator estimator(*originalMesh, &mhm, postProcWithHDiv);
+    estimator.SetAdaptivityStep(step);
+    SPE10::EstimateError(mhm, estimator, &fine_cmesh);
+
+    return 0;
+}
+
+TPZMultiphysicsCompMesh RunFineScaleProblem() {
+    // Create geomesh
+    TPZGeoMesh *gmesh = SPE10::CreateSPE10CoarseGeoMesh();
+    std::cout << "SPE10 initial grid created. NElem: " << gmesh->NElements() << "\n";
+
+    Tools::UniformRefinement(nInternalRef, 2, gmesh);
+    Tools::DivideLowerDimensionalElements(gmesh);
+    const int dim = gmesh->Dimension();
+
+    TPZMultiphysicsCompMesh mixed_cmesh(gmesh);
+
+    SPE10::InsertMaterials(&mixed_cmesh);
+    mixed_cmesh.ApproxSpace().SetAllCreateFunctionsMultiphysicElem();
+
+    TPZManVector active(2, 1);
+    TPZManVector meshvector(2, 0);
+
+    auto* cmesh_flux = new TPZCompMesh(gmesh);
+    gmesh->ResetReference();
+    auto *null_mat = new TPZNullMaterial(1);
+    null_mat->SetDimension(dim);
+    cmesh_flux->InsertMaterialObject(null_mat);
+
+    for (auto matid : {-1, -2}) {
+        TPZFNMatrix<1, REAL> val1(1, 1, 0.);
+        TPZManVector val2(1, 1.);
+        const int bctype = 0;
+        auto * bc = null_mat->CreateBC(null_mat, matid, bctype, val1, val2);
+        cmesh_flux->InsertMaterialObject(bc);
+    }
+    cmesh_flux->SetDefaultOrder(porder);
+    cmesh_flux->ApproxSpace().SetAllCreateFunctionsHDiv(dim);
+    cmesh_flux->AutoBuild();
+
+    cmesh_flux->InitializeBlock();
+
+    auto *cmesh_pressure = new TPZCompMesh(gmesh);
+    auto *null_mat_p = new TPZNullMaterial(1);
+    null_mat_p->SetDimension(cmesh_pressure->Dimension());
+    cmesh_pressure->InsertMaterialObject(null_mat_p);
+
+    cmesh_pressure->SetDefaultOrder(porder + korder);
+    // cmesh_pressure->SetDefaultOrder(problem.porder);
+    cmesh_pressure->ApproxSpace().SetAllCreateFunctionsContinuous();
+    cmesh_pressure->ApproxSpace().CreateDisconnectedElements(true);
+    cmesh_pressure->AutoBuild();
+    int64_t n_connects = cmesh_pressure->NConnects();
+    for (int64_t i = 0; i < n_connects; ++i) {
+        cmesh_pressure->ConnectVec()[i].SetLagrangeMultiplier(1);
+    }
+
+    meshvector[0] = cmesh_flux;
+    meshvector[1] = cmesh_pressure;
+
+    TPZCompMeshTools::AdjustFluxPolynomialOrders(meshvector[0], korder);
+    TPZCompMeshTools::SetPressureOrders(meshvector[0], meshvector[1]);
+
+    mixed_cmesh.BuildMultiphysicsSpace(active, meshvector);
+    mixed_cmesh.LoadReferences();
+    bool keepmatrix = false;
+    bool keeponelagrangian = true;
+    TPZCompMeshTools::CreatedCondensedElements(&mixed_cmesh, keeponelagrangian, keepmatrix);
+    mixed_cmesh.InitializeBlock();
+
+    TPZHybridizeHDiv hybridizer;
+    TPZMultiphysicsCompMesh* hybridMesh = hybridizer.Hybridize(&mixed_cmesh);
+    hybridMesh->CleanUpUnconnectedNodes();
+    hybridMesh->AdjustBoundaryElements();
+
+    TPZLinearAnalysis an(hybridMesh);
+
+#ifdef PZ_USING_MKL
+    TPZSSpStructMatrix strmat(hybridMesh);
+    strmat.SetNumThreads(0);
+#else
+    TPZSkylineStructMatrix strmat(Hybridmesh);
+    strmat.SetNumThreads(0);
+#endif
+
+    std::set matIds = {1, -1, -2, hybridizer.fInterfaceMatid.first, hybridizer.fInterfaceMatid.second};
+    strmat.SetMaterialIds(matIds);
+
+    an.SetStructuralMatrix(strmat);
+
+    auto *direct = new TPZStepSolver;
+    direct->SetDirect(ELDLt);
+    an.SetSolver(*direct);
+    delete direct;
+    direct = nullptr;
+    an.Assemble();
+    an.Solve();
+
+    TPZStack scalnames, vecnames;
+    scalnames.Push("ExactPressure");
+    scalnames.Push("Pressure");
+    scalnames.Push("Permeability");
+    vecnames.Push("ExactFlux");
+    vecnames.Push("Flux");
+
+    std::stringstream sout;
+    sout << "SPE10FINE-Results.vtk";
+    an.DefineGraphMesh(2, scalnames, vecnames, sout.str());
+    constexpr int resolution = 0;
+    an.PostProcess(resolution, hybridMesh->Dimension());
+    return mixed_cmesh;
+}

From 53f54c9adeae58d54028a489c52213112b8066ea Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 20 Jan 2022 11:50:11 -0300
Subject: [PATCH 178/187] Move ref sol code to base class

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp    | 28 ++++++++++++++------
 ErrorEstimation/TPZHDivErrorEstimator.h      |  5 +++-
 ErrorEstimation/TPZMHMHDivErrorEstimator.cpp |  9 +++++--
 ErrorEstimation/TPZMHMHDivErrorEstimator.h   |  6 -----
 4 files changed, 31 insertions(+), 17 deletions(-)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index 3fbba652..ff0e3a26 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -301,8 +301,8 @@ void TPZHDivErrorEstimator::CreatePostProcessingMesh() {
     int dim = fOriginal->Dimension();
     // switch the material from mixed to TPZMixedHdivErrorEstimate...
     InsertPostProcMaterials();
-    
-    TPZManVector meshvec(4, 0);
+
+    auto & meshvec = fPostProcMesh.MeshVector();
     meshvec[0] = 0;
     meshvec[2] = fOriginal->MeshVector()[0];//flux
     meshvec[3] = fOriginal->MeshVector()[1];//potential
@@ -344,8 +344,7 @@ void TPZHDivErrorEstimator::CreatePostProcessingMesh() {
     }
 #endif
     
-    
-    TPZManVector active(4, 0);
+    auto & active = fPostProcMesh.GetActiveApproximationSpaces();
     active[1] = 1;
     
     if(fPostProcesswithHDiv)
@@ -1628,7 +1627,7 @@ bool TPZHDivErrorEstimator::IsDirichletCondition(const TPZGeoElSide& gelside) {
 
 void TPZHDivErrorEstimator::PotentialReconstruction() {
     
-    if (fPostProcMesh.MeshVector().size()) {
+    if (fPostProcMesh.MeshVector().size() && !fHasReferenceSolution) {
         DebugStop();
     }
 
@@ -2450,13 +2449,26 @@ std::set TPZHDivErrorEstimator::GetBCMatIDs(const TPZCompMesh* cmesh) {
     return bc_mat_ids;
 }
 
+void TPZHDivErrorEstimator::SetReferenceSolution(bool hasRefSol) {
+    fHasReferenceSolution = hasRefSol;
+
+    auto mat_vec = fPostProcMesh.MaterialVec();
+    for (auto &mat : mat_vec) {
+        auto *material = mat.second;
+        auto *error_mat = dynamic_cast(material);
+        if (error_mat) {
+            error_mat->SetReferenceSolution(true);
+        }
+    }
+}
+
 void TPZHDivErrorEstimator::SetReferenceSolutionMeshes(TPZCompMesh* ref_pressure, TPZCompMesh* ref_flux) {
     fHasReferenceSolution = true;
     auto &mesh_vec = fPostProcMesh.MeshVector();
-    auto active_spaces = fPostProcMesh.GetActiveApproximationSpaces();
+    auto &active_spaces = fPostProcMesh.GetActiveApproximationSpaces();
 
-    mesh_vec.resize(6);
-    active_spaces.resize(6);
+    mesh_vec.Resize(6, nullptr);
+    active_spaces.Resize(6, 0);
 
     mesh_vec[4] = ref_pressure;
     mesh_vec[5] = ref_flux;
diff --git a/ErrorEstimation/TPZHDivErrorEstimator.h b/ErrorEstimation/TPZHDivErrorEstimator.h
index 925f7763..66f29750 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.h
+++ b/ErrorEstimation/TPZHDivErrorEstimator.h
@@ -93,6 +93,10 @@ class TPZHDivErrorEstimator {
     TPZMultiphysicsCompMesh *PostProcMesh() { return &fPostProcMesh; }
     TPZGeoMesh *GMesh() { return fOriginal->Reference(); }
 
+    void SetReferenceSolution(bool hasRefSol);
+
+    void SetReferenceSolutionMeshes(TPZCompMesh* ref_pressure, TPZCompMesh* ref_flux);
+
 protected:
 
     /// compute the pressure weights and material weights
@@ -187,7 +191,6 @@ class TPZHDivErrorEstimator {
 
     static std::set GetBCMatIDs(const TPZCompMesh* cmesh);
 
-    void SetReferenceSolutionMeshes(TPZCompMesh* ref_pressure, TPZCompMesh* ref_flux);
 };
 
 #endif /* TPZHybridHDivErrorEstimator_hpp */
diff --git a/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp b/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
index ebb6736c..2c53948f 100644
--- a/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
@@ -27,8 +27,13 @@ void TPZMHMHDivErrorEstimator::CreatePostProcessingMesh()
     // Switch the material from mixed to TPZMHMHDivErrorEstimationMaterial
     InsertPostProcMaterials();
 
-    TPZManVector meshvec(4);
-    TPZManVector active(4,0);
+    auto & meshvec = fPostProcMesh.MeshVector();
+    auto & active = fPostProcMesh.GetActiveApproximationSpaces();
+    if (!fHasReferenceSolution){
+        meshvec.Resize(4, nullptr);
+        active.Resize(4, 0);
+    }
+
     active[1] = 1;
 
     meshvec[0] = 0;
diff --git a/ErrorEstimation/TPZMHMHDivErrorEstimator.h b/ErrorEstimation/TPZMHMHDivErrorEstimator.h
index 23cb4818..af2cc5eb 100644
--- a/ErrorEstimation/TPZMHMHDivErrorEstimator.h
+++ b/ErrorEstimation/TPZMHMHDivErrorEstimator.h
@@ -32,18 +32,12 @@ class TPZMHMHDivErrorEstimator : public TPZHDivErrorEstimator {
 
     virtual ~TPZMHMHDivErrorEstimator() = default;
 
-    void SetReferenceSolution(bool hasRefSol) {
-        fHasReferenceSolution = hasRefSol;
-    }
-
 private:
     // material id of the dim-1 multiphysic inerface and wrap elements
     // (only used for HDiv reconstruction)
     int fMultiPhysicsInterfaceMatId = 0;
     int fHDivWrapMatId = 0;
 
-    bool fHasReferenceSolution = false;
-
     /// a pointer to the datastructure used to generate the MHM mesh
     TPZMHMixedMeshControl *fMHM = nullptr;
     // a method for generating the HDiv mesh

From 4d6da2e59cf86de302ef3987f17de68372062b37 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 20 Jan 2022 11:51:44 -0300
Subject: [PATCH 179/187] Add new print errors function

---
 Projects/Tools/Tools.cpp | 13 +++++++++++++
 Projects/Tools/Tools.h   |  1 +
 2 files changed, 14 insertions(+)

diff --git a/Projects/Tools/Tools.cpp b/Projects/Tools/Tools.cpp
index 10b54f5d..c6779bbc 100644
--- a/Projects/Tools/Tools.cpp
+++ b/Projects/Tools/Tools.cpp
@@ -1081,3 +1081,16 @@ void Tools::PrintErrors(std::ofstream& out, const ProblemConfig& config, const T
     out << ss.str();
     std::cout << ss.str();
 }
+
+void Tools::PrintErrors(std::ostream& out, const TPZVec& error_vec) {
+
+    std::stringstream ss;
+    ss << '\n';
+    ss << "Global estimator = " << error_vec[3] << "\n";
+    ss << "|ufem-urec| = " << error_vec[1] << "\n";
+    ss << "Residual Error L2 = " << error_vec[4] << "\n";
+    ss << "[Unknown exact solution and errors]\n";
+
+    out << ss.str();
+    std::cout << ss.str();
+}
diff --git a/Projects/Tools/Tools.h b/Projects/Tools/Tools.h
index d6bf0be4..aa0b613e 100644
--- a/Projects/Tools/Tools.h
+++ b/Projects/Tools/Tools.h
@@ -94,6 +94,7 @@ namespace Tools {
     TPZGeoMesh* CreateGeoMesh(int nelem, TPZVec& bcids, int dim, bool isOriginCentered, int topologyMode);
 
     void PrintErrors(std::ofstream& out, const ProblemConfig& config, const TPZVec& error_vec);
+    void PrintErrors(std::ostream& out, const TPZVec& error_vec);
 }
 
 #endif

From fd636c58fb5f0aa3abe9659c24ecaae7f438817e Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 20 Jan 2022 11:52:57 -0300
Subject: [PATCH 180/187] Use refsol in material when needed

---
 .../Material/TPZHDivErrorEstimateMaterial.cpp            | 9 +++++++++
 1 file changed, 9 insertions(+)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index eb21ea1d..90f56607 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -286,6 +286,15 @@ void TPZHDivErrorEstimateMaterial::Errors(const TPZVec>
             flux_exact(i, 0) = -perm * flux_exact(i, 0);
             flux_error_exact += (fluxfem[i] - flux_exact(i, 0)) * (fluxfem[i] - flux_exact(i, 0)) / perm;
         }
+    } else if (this->fHasReferenceSolution) {
+
+        const auto u_ref = data[5].sol[0][0];
+        const auto &flux_ref = data[4].sol[0];
+
+        pressure_error_exact = (pressurefem - u_ref) * (pressurefem - u_ref);
+        for (int i = 0; i < 3; i++) {
+            flux_error_exact += (fluxfem[i] - flux_ref[i]) * (fluxfem[i] - flux_ref[i]) / perm;
+        }
     }
 
     // Calculate residual component

From 5030741818ecd07a6ae146f5c7de5a24961508a1 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 20 Jan 2022 12:59:39 -0300
Subject: [PATCH 181/187] Check if PZ_LOG is define before using it

---
 Projects/ErrorEstimationMHM/main_Journal.cpp          | 2 ++
 Projects/ErrorEstimationMHM/main_RefSolValidation.cpp | 2 ++
 2 files changed, 4 insertions(+)

diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp
index 0f96c9fe..25a56b66 100644
--- a/Projects/ErrorEstimationMHM/main_Journal.cpp
+++ b/Projects/ErrorEstimationMHM/main_Journal.cpp
@@ -87,7 +87,9 @@ void RunInnerSingularityProblemSuite(const std::set &nCoarseDiv, const std:
 
 
 int main() {
+#ifdef PZ_LOG
     TPZLogger::InitializePZLOG();
+#endif
     gRefDBase.InitializeAllUniformRefPatterns();
 
     const std::set nCoarseDiv = {8};
diff --git a/Projects/ErrorEstimationMHM/main_RefSolValidation.cpp b/Projects/ErrorEstimationMHM/main_RefSolValidation.cpp
index 37f0843b..fe0bfcdc 100644
--- a/Projects/ErrorEstimationMHM/main_RefSolValidation.cpp
+++ b/Projects/ErrorEstimationMHM/main_RefSolValidation.cpp
@@ -35,7 +35,9 @@ void SolveMHMProblem(TPZMHMixedMeshControl *mhm, const ProblemConfig &config);
 void EstimateError(ProblemConfig &config, TPZMHMixedMeshControl *mhm);
 
 int main() {
+#ifdef PZ_LOG
     TPZLogger::InitializePZLOG();
+#endif
     gRefDBase.InitializeAllUniformRefPatterns();
 
     RunReferenceSolutionValidationProblem();

From 247885e26c34097821c2395f7678fce4ceb53bc8 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 20 Jan 2022 13:00:07 -0300
Subject: [PATCH 182/187] Simplify inheritance from TPZMixedDarcyFlow in
 material classes

---
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp | 2 +-
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h   | 3 +--
 ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h      | 5 ++---
 3 files changed, 4 insertions(+), 6 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
index 90f56607..e827a48f 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.cpp
@@ -19,7 +19,7 @@ TPZHDivErrorEstimateMaterial::TPZHDivErrorEstimateMaterial(int matid, int dim) :
 TPZHDivErrorEstimateMaterial::TPZHDivErrorEstimateMaterial() : TPZMixedDarcyFlow() {}
 
 TPZHDivErrorEstimateMaterial::TPZHDivErrorEstimateMaterial(const TPZMixedDarcyFlow ©)
-    : TBase(copy), TPZMixedDarcyFlow(copy) {}
+    : TPZMixedDarcyFlow(copy) {}
 
 TPZHDivErrorEstimateMaterial::TPZHDivErrorEstimateMaterial(const TPZHDivErrorEstimateMaterial ©)
         : TPZMixedDarcyFlow(copy) {}
diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
index 6e72926a..e1f05189 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
@@ -15,8 +15,7 @@
 #include "DarcyFlow/TPZMixedDarcyFlow.h"
 #include "TPZMaterialDataT.h"
 
-class TPZHDivErrorEstimateMaterial: public virtual TPZMatBase,
-        TPZMatErrorCombinedSpaces, TPZIsotropicPermeability>, public virtual TPZMixedDarcyFlow {
+class TPZHDivErrorEstimateMaterial: public virtual TPZMixedDarcyFlow {
 
     // type alias to improve constructor readability
     using TBase = TPZMatBase,
diff --git a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
index 7f7ff552..1186b939 100644
--- a/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
+++ b/ErrorEstimation/Material/TPZMixedHdivErrorEstimate.h
@@ -14,8 +14,7 @@
 #include "pzreal.h"
 
 
-class TPZMixedHDivErrorEstimate : public virtual TPZMatBase,
-        TPZMatErrorCombinedSpaces, TPZIsotropicPermeability>, public TPZMixedDarcyFlow {
+class TPZMixedHDivErrorEstimate :  public TPZMixedDarcyFlow {
 
 public:
     
@@ -41,7 +40,7 @@ class TPZMixedHDivErrorEstimate : public virtual TPZMatBase> &data, TPZVec &errors) override;
 
-    int NEvalErrors() override { return 5; }
+    [[nodiscard]] int NEvalErrors() const override { return 5; }
     
     [[nodiscard]] int VariableIndex(const std::string &name) const override;
     

From ee742915248df7ec6d10aae5f971ad9ce57a95c3 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 20 Jan 2022 13:00:34 -0300
Subject: [PATCH 183/187] Add const to method

---
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
index e1f05189..5a137985 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
@@ -51,7 +51,7 @@ class TPZHDivErrorEstimateMaterial: public virtual TPZMixedDarcyFlow {
         fNeumannLocalProblem = neumannProblem;
     }
 
-    int NEvalErrors() override { return 5; }
+    [[nodiscard]] int NEvalErrors() const override { return 5; }
 
     /// Compute the error and error estimate
     // error[0] - error computed with exact pressure

From 7a5d467c79c10945156e03cb2ff575a4a01ddde5 Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 20 Jan 2022 16:05:28 -0300
Subject: [PATCH 184/187] Set smooth problem to be run

---
 Projects/ErrorEstimationMHM/main_Journal.cpp | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/Projects/ErrorEstimationMHM/main_Journal.cpp b/Projects/ErrorEstimationMHM/main_Journal.cpp
index 25a56b66..f429106d 100644
--- a/Projects/ErrorEstimationMHM/main_Journal.cpp
+++ b/Projects/ErrorEstimationMHM/main_Journal.cpp
@@ -93,15 +93,15 @@ int main() {
     gRefDBase.InitializeAllUniformRefPatterns();
 
     const std::set nCoarseDiv = {8};
-    const std::set nInternalRef = {1};
+    const std::set nInternalRef = {3};
     const std::set kOrder = {1};
     const std::set nOrder = {2};
 
-    //RunSmoothProblemSuite(nCoarseDiv, nInternalRef, kOrder, nOrder);
+    RunSmoothProblemSuite(nCoarseDiv, nInternalRef, kOrder, nOrder);
 
     //RunInnerSingularityProblemSuite(nCoarseDiv, nInternalRef, kOrder, nOrder);
 
-    RunHighGradientAdaptivityProblem(4);
+    //RunHighGradientAdaptivityProblem(4);
 
     //RunNonConvexProblem();
     //std::ofstream out_latex("LatexGraphs.txt", std::ios::trunc);
@@ -594,7 +594,7 @@ void SolveMHMProblem(TPZMHMixedMeshControl *mhm, const ProblemConfig &config) {
     plotname << config.dir_name << "/" << config.problemname << "-" << config.ndivisions << "-" << config.ninternalref
              << "-Results.vtk";
     an.DefineGraphMesh(cmesh->Dimension(), scalnames, vecnames, plotname.str());
-    an.PostProcess(resolution, cmesh->Dimension());
+    //an.PostProcess(resolution, cmesh->Dimension());
 }
 
 void EstimateError(ProblemConfig &config, TPZMHMixedMeshControl *mhm) {

From 915fe73975fec15f522ac3fc0821dce95d9412fa Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 20 Jan 2022 16:06:02 -0300
Subject: [PATCH 185/187] Set type of createfunctions in postproc mesh

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp    | 1 +
 ErrorEstimation/TPZMHMHDivErrorEstimator.cpp | 1 +
 2 files changed, 2 insertions(+)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index ff0e3a26..fd07a218 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -298,6 +298,7 @@ void TPZHDivErrorEstimator::CreatePostProcessingMesh() {
     
     // initialize the post processing mesh
     fPostProcMesh.SetReference(fOriginal->Reference());
+    fPostProcMesh.ApproxSpace().SetAllCreateFunctionsMultiphysicElem();
     int dim = fOriginal->Dimension();
     // switch the material from mixed to TPZMixedHdivErrorEstimate...
     InsertPostProcMaterials();
diff --git a/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp b/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
index 2c53948f..ca204593 100644
--- a/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZMHMHDivErrorEstimator.cpp
@@ -70,6 +70,7 @@ void TPZMHMHDivErrorEstimator::CreatePostProcessingMesh()
     }
 
     RemoveMaterialObjects(fPostProcMesh.MaterialVec());
+    fPostProcMesh.ApproxSpace().SetAllCreateFunctionsMultiphysicElem();
     fPostProcMesh.BuildMultiphysicsSpace(active, meshvec);
 
     if(fPostProcesswithHDiv) {

From ec3bf3c7ec8bce8c9e4a2519419c81cebd27ee0a Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 20 Jan 2022 16:06:15 -0300
Subject: [PATCH 186/187] Resize mesh vec and active spaces

---
 ErrorEstimation/TPZHDivErrorEstimator.cpp | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/ErrorEstimation/TPZHDivErrorEstimator.cpp b/ErrorEstimation/TPZHDivErrorEstimator.cpp
index fd07a218..2c42b8ac 100644
--- a/ErrorEstimation/TPZHDivErrorEstimator.cpp
+++ b/ErrorEstimation/TPZHDivErrorEstimator.cpp
@@ -304,6 +304,7 @@ void TPZHDivErrorEstimator::CreatePostProcessingMesh() {
     InsertPostProcMaterials();
 
     auto & meshvec = fPostProcMesh.MeshVector();
+    meshvec.resize(4);
     meshvec[0] = 0;
     meshvec[2] = fOriginal->MeshVector()[0];//flux
     meshvec[3] = fOriginal->MeshVector()[1];//potential
@@ -346,6 +347,7 @@ void TPZHDivErrorEstimator::CreatePostProcessingMesh() {
 #endif
     
     auto & active = fPostProcMesh.GetActiveApproximationSpaces();
+    active.Resize(4, 0);
     active[1] = 1;
     
     if(fPostProcesswithHDiv)

From a4613f5c1d7f98ae73aef84338afa10f6764100d Mon Sep 17 00:00:00 2001
From: gustavobat 
Date: Thu, 20 Jan 2022 16:08:09 -0300
Subject: [PATCH 187/187] Remove type alias and virtual inheritance

---
 ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h | 5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)

diff --git a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
index 5a137985..a567af24 100644
--- a/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
+++ b/ErrorEstimation/Material/TPZHDivErrorEstimateMaterial.h
@@ -15,11 +15,8 @@
 #include "DarcyFlow/TPZMixedDarcyFlow.h"
 #include "TPZMaterialDataT.h"
 
-class TPZHDivErrorEstimateMaterial: public virtual TPZMixedDarcyFlow {
+class TPZHDivErrorEstimateMaterial: public TPZMixedDarcyFlow {
 
-    // type alias to improve constructor readability
-    using TBase = TPZMatBase,
-        TPZMatErrorCombinedSpaces, TPZIsotropicPermeability>;
 public:
     TPZHDivErrorEstimateMaterial(int matid, int dim);