FormulationQSRemeshAniso.cc 24.9 KB
Newer Older
1 2 3 4 5 6
/* 
    This file is a part of eXlibris C++ Library
    under the GNU General Public License:
    See the LICENSE.md files for terms and 
    conditions.
*/
7
#include "Export.h"
8
#include "FormulationQSRemeshAniso.h"
9 10
#include "Import.h"
#include "Observer.h"
11 12
#include "TLSGeom.h"
#include "TLSSolver.h"
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include "Util.h"
#include "LinearSystem.h"
#include "options.h"

#include "xAlgorithm.h"
#include "xAssembler.h"
#include "xData.h"
#include "xParseData.h"
#include "xMaterialSensitivity.h"
#include "xSpaceFactory.h"
#include "xSpace.h"
#include "xFieldStorage.h"
#include "xLevelSetOperators.h"
#include "xSubMesh.h"

#include "xCSRVector.h"
#include "xCSRMatrix.h"
// #include "xDenseMatrix.h"

#include "xData.h"
#include "MaterialCommand.h"
#include "NonUniformMaterialSensitivity.h"

//xtls
#include "TLSEnrichment.h"
#include "TLSGeomInterface.h"


#include "mAOMD.h"
#include "mEntity.h"
#include "mFace.h"
#include "mTet.h"
#include "mVertex.h"

//For ICI...
#include "xPostProVTU.h"
#include <boost/lexical_cast.hpp>
#include <stdlib.h>

52 53 54 55 56 57
//For FastMarching
#ifdef HAVE_FASTMARCHING
//#include "gmshinputoutput.h"
#include "meshinterfacexRegion.h"
//#include "FastMarching.h"
#include "FM.h"
58
#include "FMEntityStorage.h"
59 60
#endif

61 62 63 64 65
using namespace xfem;

QSFormulRemeshAniso::QSFormulRemeshAniso(TLSGeom& geom, TLSSolver& tls_solver,
                                         const xData& data, const xParseData& parse_data,
                                         PreProcessing& pre_pro, PostProcessing& post_pro, std::function<void (xMesh&)> tagger) :
66
    QSFormulation(geom, tls_solver, data, parse_data, pre_pro, post_pro),
67 68 69
      tagger(tagger), doRestart(pre_pro.doRestart()){
    backupMesh = new xMesh();
}
70

71 72 73 74

QSFormulRemeshAniso::~QSFormulRemeshAniso() {}

void QSFormulRemeshAniso::updateLevelSetField() {
75 76 77 78 79 80 81 82 83 84 85 86 87 88
  std::cout<<"Coucou"<<std::endl;

  if(Observer::tell<int>("step") == 150 || doRestart){
      delete backupMesh;
      backupMesh = new xMesh();
      //if(!doRestart) xCopyMesh(&geom.getMesh(), backupMesh);
      //else AOMD::AOMD_Util::Instance()->import("backupMesh_save.msh", backupMesh);

      xCopyMesh(&geom.getMesh(), backupMesh);

      backupMesh->modifyAllState();
      doRestart = false;
  }

89
  tls_solver.updateLevelSetField();
90
  tls_solver.exportMeanField("delta_phi",Observer::tell<int>("step"));
91 92 93
  tls_solver.delocalizeLevelSetField();
  if(tls_solver.isDelocalized()) {
    tls_solver.reinitLevelSetField();
94 95 96 97
    if(parse_data.getInt("remesh_aniso") == 1){
       remesh();
       tls_solver.reinitLevelSetField();
    }
98 99 100



101
    if(tls_solver.isCrackable()) {
102 103 104 105 106 107 108
      clearDispMeasField();
      geom.buildFullyDamagedSupport(tls_solver.getPhiMinusLcEval());
      deleteMaterialVariables("fds");
      tls_solver.cutCrack();
      tls_solver.transferLevelSetField();
      transferDispField();
      transferMaterialVariables();
109
      updateMaterialVariables(tls_solver.getDamageEval(),"duplicated");
110
      declareDispMeasField();
111 112 113
    }
    tls_solver.delocalizeMeanField();
  }
114 115 116 117 118 119 120 121 122 123 124
else{
 // std::cout<<"iscrack"<<geom.isCracked()<<endl;
     //if(Observer::tell<int>("step") >= 15){
      if(parse_data.getInt("remesh_aniso") == 1){
       remesh();
      }
 // std::cout<<"iscrack"<<geom.isCracked()<<endl;
   //  }
   }
  if(is_nonlinear) {
    geom.buildLinearAndNonLinear(tls_solver.getPhiEval());
125 126 127
  }
}

128
void QSFormulRemeshAniso::xReadFromParaview(string fName, string targetData, xField<> &field,  xMesh& mesh){
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202

  const bool debug{false};
  const char * line_c;
  string line;
  int LocalistionNodes{0}, LocalistionConnec{0}, LocalistionTarget{0} ;
  int NbNodes, NbElements, Dim;
  unsigned long Position, PositionMaillage ;
  Dim = 1;

  std::ifstream f(fName);

  if(!f.is_open()){
    cout<<"ERROR Unable to open vtu postpro file\n";
    exit(1);
  }


  //First, parse in order to get the position of the different parts of the file...
  //Indeed, there no specific order for the nodes and element parts with VTU format...
  //Inspired by ICITech code...
  while(!(f.eof())) {
    Position = f.tellg() ;
    getline(f,line);

    line_c=line.c_str();


    //Extract number of nodes and elements : NbNodes, NbElements
    if(line.find("NumberOfPoints")!=string::npos){
      // Extraction Nb noeuds et Nb elements
      long a,b ;
      a = line.find("\"") ;
      b = line.find("\"",a+1) ;
      sscanf(&(line_c[a+1]),"%d",&NbNodes);//ch_val.value_type

      a = line.find("\"",b+1) ;
      sscanf(&(line_c[a+1]),"%d",&NbElements);

      PositionMaillage = Position ;
    }

      if(line.find(targetData+"\""+" NumberOfComponents")!=string::npos){
      // Extraction Nb noeuds et Nb elements
      long c,d;
      c = line.find("\"") ;
      d = line.find("\"",c+1) ;
      sscanf(&(line_c[c+1]),"%d",&Dim);//ch_val.value_type

      c = line.find("\"",d+1) ;
      d = line.find("\"",c+1) ;
      sscanf(&(line_c[c+1]),"%d",&Dim);

      c = line.find("\"",d+1) ;
      sscanf(&(line_c[c+1]),"%d",&Dim);

      PositionMaillage = Position ;
    }

    //Extraction of targetData
    if(line.find(targetData)!=string::npos){
      LocalistionTarget = f.tellg() ;
      getline(f,line);
      cout<<"line= "<<line<<endl;

      break;
    }

  }

  //Then, use the positions in order to fill the mesh
  //First, consider nodes
  f.clear();// Whooooooo tricky ! If eof was raised, seekg can't go enywhere. We must clear f before or re-open it...
  f.seekg(LocalistionTarget);

203
  xValueManagerDist<double>* double_manager=field.getValueManager();
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309

  double val;

  for(int j=1; j<NbNodes+1; ++j) {
      AOMD::mEntity* e = mesh.getVertex(j);
      xFiniteElement FEM;
      FEM.setKeys(e, field.begin(), field.end());
      vector < xValKey >* keys = FEM.getKeys();
      std::vector<int>::size_type nb_keys_trial = keys->size();
     // cout<<"test keys size "<<nb_keys_trial<<endl;

      std::vector<xValue<double>*> vals;
      double_manager->getValPtr(FEM.beginKey(), FEM.endKey(), vals);

     for(int iKey = 0; iKey < nb_keys_trial; ++iKey)
      {
        f >> val;
        vals[iKey]->setVal(val);
       // cout<<(*keys)[iKey]<<endl;
      }

      if(nb_keys_trial==2) f >> val;
  }

  f.close();
  return;
}

void QSFormulRemeshAniso:: xReadFromParaviewxLevelSet(string fName, string targetData, xLevelSet &ls){

  const bool debug{false};
  const char * line_c;
  string line;
  int LocalistionNodes{0}, LocalistionConnec{0}, LocalistionTarget{0} ;
  int NbNodes, NbElements;
  unsigned long Position, PositionMaillage ;


  std::ifstream f(fName);

  if(!f.is_open()){
    cout<<"ERROR Unable to open vtu postpro file\n";
    exit(1);
  }


  //First, parse in order to get the position of the different parts of the file...
  //Indeed, there no specific order for the nodes and element parts with VTU format...
  //Inspired by ICITech code...
  while(!(f.eof())) {
    Position = f.tellg() ;
    getline(f,line);

    line_c=line.c_str();


    //Extract number of nodes and elements : NbNodes, NbElements
    if(line.find("NumberOfPoints")!=string::npos){
      // Extraction Nb noeuds et Nb elements
      long a,b ;
      a = line.find("\"") ;
      b = line.find("\"",a+1) ;
      sscanf(&(line_c[a+1]),"%d",&NbNodes);//ch_val.value_type

      a = line.find("\"",b+1) ;
      sscanf(&(line_c[a+1]),"%d",&NbElements);

      PositionMaillage = Position ;
    }


    //Extraction of targetData
    if(line.find(targetData)!=string::npos){
      LocalistionTarget = f.tellg() ;
      getline(f,line);
      cout<<"line= "<<line<<endl;

      break;
    }

  }

  xMesh *m = ls.getSupport().getMesh();

  //Then, use the positions in order to fill the mesh
  //First, consider nodes
  f.clear();// Whooooooo tricky ! If eof was raised, seekg can't go enywhere. We must clear f before or re-open it...
  f.seekg(LocalistionTarget);

  for(int j=1; j<NbNodes+1; ++j) {
    double val;
    f >> val;

//    cout<<"val="<<val<<endl;
    ls(m->getVertex(j)) = val;
  }


  f.close();

  return;
}

void QSFormulRemeshAniso::buildLSAdaptationField(){

    //1- Recuperer le bord de Omega_NL
310
    xSubMesh& sm_bnd_nonlocal=geom.getMesh().getSubMesh("bnd_nonlocal");
311 312
    sm_bnd_nonlocal.exportGmsh("bnd_nonlocal.msh");

313
    xSubMesh& sm_int_nonlocal=geom.getMesh().getSubMesh("int_nonlocal");
314 315 316 317 318
    sm_int_nonlocal.exportGmsh("int_nonlocal.msh");


    //2- Faire un fast-marching par rapport au bord pour construire le champ distance
    xRegion targetRegion = geom.getRegion();
Kévin Moreau's avatar
Kévin Moreau committed
319

320 321 322 323
//    xEvalConstant<double> one(1.);


//    xRegion targetRegion = geom.getRegion("nonlocal");
324 325
    xfastmarching::meshinterfacexRegion mi(targetRegion);
    xfastmarching::entitystorage<xfastmarching::meshinterfacexRegion, AOMD::mVertex, double> ls(mi);
326

327 328
    xfastmarching::entitytovertexiteratorconvertor<xIter> known_conv_begin(sm_bnd_nonlocal.begin(0));
    xfastmarching::entitytovertexiteratorconvertor<xIter> known_conv_end(sm_bnd_nonlocal.end(0));
329 330 331 332

//    entitytovertexiteratorconvertor<xIter> tofind_conv_begin(geom.begin(0));
//    entitytovertexiteratorconvertor<xIter> tofind_conv_end(geom.end(0));

333 334
    xfastmarching::entitytovertexiteratorconvertor<xIter> tofind_conv_begin(geom.begin(0, "local"));
    xfastmarching::entitytovertexiteratorconvertor<xIter> tofind_conv_end(geom.end(0, "local"));
335 336 337 338 339 340 341 342

    std::function<double (const AOMD::mVertex&)> fmFunction = [](const mEntity& v) { return 1.; };

    for(xIter it=sm_bnd_nonlocal.begin(0); it!=sm_bnd_nonlocal.end(0); ++it) {
      auto v=*it;
      std::vector<double> vals;
      tls_solver.getField().getVals(v, vals);

343 344
      //ls.set(*static_cast<AOMD::mVertex*>(v), vals[0]);
      ls.set(*static_cast<AOMD::mVertex*>(v), 0);
345 346 347 348 349 350

      //v->print();
//      double val_;
//      ls.get(*static_cast<AOMD::mVertex*>(v), val_);
      //cout<<"set known val as "<<val_<<endl;
    }
351 352
    //TODO
    //fmeik(mi, ls, known_conv_begin, known_conv_end, tofind_conv_begin, tofind_conv_end, fmFunction);
353 354

    std::cout<<"size of int_nonlocal "<<std::distance(geom.begin(0, "int_nonlocal"), geom.end(0, "int_nonlocal"))<<std::endl;
355 356
    xfastmarching::entitytovertexiteratorconvertor<xIter> tofind_conv_begin2(geom.begin(0, "int_nonlocal"));
    xfastmarching::entitytovertexiteratorconvertor<xIter> tofind_conv_end2(geom.end(0, "int_nonlocal"));
357 358 359
    
    //TODO
    //    fmeik(mi, ls, known_conv_begin, known_conv_end, tofind_conv_begin2, tofind_conv_end2, fmFunction);
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381

    lsetAdapt.setSupport(targetRegion);

    for(xIter it = geom.begin(0, "local"); it != geom.end(0, "local"); ++it){
        auto v=*it;
        double val;
        ls.get(*static_cast<AOMD::mVertex*>(v), val);
        lsetAdapt(v) = -val;
    }
    for(xIter it = geom.begin(0, "int_nonlocal"); it != geom.end(0, "int_nonlocal"); ++it){
        auto v=*it;
        double val;
        ls.get(*static_cast<AOMD::mVertex*>(v), val);
        lsetAdapt(v) = val;
    }

    post_pro.exportOnSpace("lsAdapt",Observer::tell<int>("step"),lsetAdapt);
    return ;   
}

void QSFormulRemeshAniso::projectPhiOnMesh(xMesh *mesh_new, std::map<mEntity *, double> &projectedValues){
    xMesh* mesh_old=&geom.getMesh("comp");
382
    xField<> &phi_field = tls_solver.getField();
383
    Trellis_Util::mPoint bbmin, bbmax;
384 385 386 387 388 389 390 391
    mesh_old->compute_bounding_box(bbmin, bbmax);

    //Works only in 2D for the moment
    assert(mesh_old->dim() <3);

    for(xIter it = mesh_new->begin(0); it != mesh_new->end(0); ++it ){
        mEntity *e = *it;
        mVertex *v = static_cast<mVertex*>(e);
392
        Trellis_Util::mPoint p = v->point();
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415

        //Find in which element v is lying
        std::set<mEntity*> elts_old;
        mesh_old->locateElement(v->point(),elts_old);
        //mesh_old->locateElementOctree(v->point(),elts_old);

        //Test "boundary cases"
        if(elts_old.empty()){

            double tol = 1.e-5;
            bool bndLeft = abs(bbmin(0)-p(0))<tol;
            bool bndRight = abs(bbmax(0)-p(0))<tol;
            bool bndTop = abs(bbmax(1)-p(1))<tol;
            bool bndBottom = abs(bbmin(1)-p(1))<tol;

            double move = 1.e-5;
            if(bndLeft) p(0)+= move;
            if(bndRight) p(0) -= move;
            if(bndTop) p(1) -= move;
            if(bndBottom) p(1) += move;

            if(!bndLeft && !bndRight && !bndTop && !bndBottom){
                mEntity *elt = e->get(2,0);
416 417
                xfem::xGeomElem geo(elt);
                Trellis_Util::mPoint CGD = geo.getCDGxyz();
418
                xtensor::xVector<> toCDG(p,CGD);
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
                //toCDG.norm();

                double epsi = 1.e-3;
                p(0) += epsi * toCDG(0);
                p(1) += epsi * toCDG(1);

                cout<<toCDG<<endl;
            }


            mesh_old->locateElement(p,elts_old);

            assert(!elts_old.empty());
        }



        //Get the value of the field at this location
        assert(!elts_old.empty());
438
        xfem::xGeomElem geo_old(*(elts_old.begin()));
439 440 441 442 443 444 445 446 447 448 449 450
        geo_old.setUVWForXYZ(p);
        double old_value{0};
        phi_field.getVal(&geo_old, &geo_old, old_value);

        //Set the value
        projectedValues[e] = old_value;
    }


    return;
}

451
void  QSFormulRemeshAniso::xAssignPhiValues(xField<> &field, xMesh *mesh, std::map<mEntity *, double> &projectedValues){
452
    xValueManagerDist<double>* double_manager=field.getValueManager();
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474

    for(xIter it = mesh->begin(0); it != mesh->end(0); ++it ){
        mEntity *e = *it;

        xFiniteElement FEM;
        FEM.setKeys(e, field.begin(), field.end());
        vector < xValKey >* keys = FEM.getKeys();
        std::vector<int>::size_type nb_keys_trial = keys->size();

        std::vector<xValue<double>*> vals;
        double_manager->getValPtr(FEM.beginKey(), FEM.endKey(), vals);
        assert(nb_keys_trial==1);
        vals[0]->setVal(projectedValues[e]);
        //if(vals[0]->getVal()<1e-3 && vals[0]->getVal()>1e-13){
        if(vals[0]->getVal()<1e-3){
            vals[0]->setVal(0);
            }
    }

    return;
}

475
void QSFormulRemeshAniso::remesh() {
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
   xMesh* mesh=&geom.getMesh("comp");
//   // begin export
  string sfront_iter = boost::lexical_cast<string>(Observer::tell<int>("step")-1);

//  //cout<<"step is"<<front_iter<<endl;
//  AOMD::AOMD_Util::Instance()->ex_port("test_mesh1.msh", mesh);

  xEvalConstant<double> eval_one_before(1.);
  post_pro.exportOnSpace("sm_local_before_build",       Observer::tell<int>("step"), eval_one_before, geom.getIntegRuleBasic(0), geom.begin("local"),  geom.end("local"));
  post_pro.exportOnSpace("sm_nonlocal_before_build",       Observer::tell<int>("step"), eval_one_before, geom.getIntegRuleBasic(0), geom.begin("nonlocal"),  geom.end("nonlocal"));

  if(tls_solver.isDelocalized()){
    buildLSAdaptationField();
  }
  else{
      lsetAdapt.setSupport(mesh, -10.0);
  }
  post_pro.exportOnSpace("lsAdapt_after",Observer::tell<int>("step"),lsetAdapt);
494

495
  //Export vers ICItech
496 497 498 499 500
    xMesh *meshForRemeshing = backupMesh;
   // xMesh *meshForRemeshing = &geom.backupMesh;
  //xMesh* meshForRemeshing=&geom.getMesh();

    //Misc evaluators
501 502
    xEvalField<xtool::xIdentity<xtensor::xVector<>> > eval_disp(disp_field);
    xEvalGradField<xtensor::xSymmetrize<>> eval_strain(disp_field);
503
    xEvalLevelSet<xtool::xIdentity<double> > eval_lsetAdapt(lsetAdapt);
504 505 506 507

    //Adapters for the evaluators that are defined on geom.getMesh, but exported on meshForRemeshing (backupMesh)
    xEvalOnOtherMesh<double> eval_phi_on_backupMesh(tls_solver.getPhiEval(),geom.getMesh() );
    xEvalOnOtherMesh<double> eval_damage_on_backupMesh(tls_solver.getDamageEval(),geom.getMesh() );
508 509
    xEvalOnOtherMesh<xtensor::xVector<>> eval_disp_on_backupMesh(eval_disp,geom.getMesh() );
    xEvalOnOtherMesh<xtensor::xTensor2<>> eval_strain_on_backupMesh(eval_strain,geom.getMesh() );
510 511 512
    xEvalOnOtherMesh<double> eval_lsadapt_on_backupMesh(eval_lsetAdapt,geom.getMesh() );


513
    xexport::xPostProVTU postProVTU(meshForRemeshing);
514 515 516 517 518
    std::string str = "sortie_";
    str+=sfront_iter;
    str+= ".vtu";
    const char *sortie = str.c_str();
    postProVTU.openFile(sortie);
519 520 521 522
    postProVTU.exportScalarAtNode(eval_phi_on_backupMesh,"level-set");
    //postProVTU.exportLevelSet(eval_lsadapt_on_backupMesh,"lsadapt");
    postProVTU.exportScalarAtNode(eval_lsadapt_on_backupMesh,"lsadapt");
    postProVTU.exportScalarAtNode(eval_damage_on_backupMesh,"Endomagement");
523
    //SmoothNonUniformMaterialSensitivity_c<xtensor::xTensor2<>> eval("strain", variab_manager);
524 525 526 527

    //TODO
    //    postProVTU.exportVonMisesAtElem(eval_strain_on_backupMesh,"deformation");
    postProVTU.exportVectorAtNode(eval_disp_on_backupMesh,"deplacement");
528 529 530 531 532

    postProVTU.closeFile();

    // export the mesh

533
     AOMD::AOMD_Util::Instance()->exportICIFile("sortie.t", meshForRemeshing);
534 535 536 537 538
     std::string strt = "sortie_";
     strt+=sfront_iter;
     strt+= ".t";
     const char *sortiet = strt.c_str();

539
     AOMD::AOMD_Util::Instance()->exportICIFile(sortiet, meshForRemeshing);
540

541
    disp_field.getValueManager()->PrintForDebug("bef_clean_disp.dbg");
542 543 544

  // end export

545 546 547 548
   //  xMesh *old_mesh_adress = mesh;


  // call of ICI executable
549
    string iciTechCommand="/usr/mpi/gcc/mvapich2-2.0/bin/mpirun /glouton/struct/csarkis/icitech/buildIciplayer/iciplayer data/LectureMaillage_MultiRemaillage/mtc/main.mtc";
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    int ret = system(iciTechCommand.c_str());

  // create mesh_new
    xMesh *mesh_new = new xMesh();

  //read mesh
  cout<<"Open VTU-- file\n";
  std::string stre = "entree_";
  stre+=sfront_iter;
  stre+= ".vtu";
  const char *entree = stre.c_str();
  AOMD::AOMD_Util::Instance()->importVTUFile(entree, mesh_new);

  mesh_new->modifyAllState();
  mesh_new->bdryLinkSetup();
 // end read mesh_new

567 568 569 570 571 572 573 574 575 576 577 578 579
  //Clean backup mesh and refill
//    backupMesh.cleanup(2);
//    backupMesh.cleanup(1);
//    backupMesh.cleanup(0);
  delete backupMesh;
  backupMesh = new xMesh();
  xCopyMesh(mesh_new, backupMesh);
  backupMesh->modifyAllState();
  string nameMeshFile="backupMesh_"+boost::lexical_cast<string>(Observer::tell<int>("step")-1)+".msh";
  AOMD::AOMD_Util::Instance()->ex_port(nameMeshFile.c_str(), backupMesh);
  AOMD::AOMD_Util::Instance()->ex_port("backupMesh_save.msh", backupMesh);


580 581 582 583 584

  //Project old phi on the new mesh
  //std::map<mEntity *, double> projectedValues;
  //projectPhiOnMesh(mesh_new, projectedValues);

585
  // begin clean up
586 587
  deleteState();
  deleteDispField();
588
  disp_field.ResetStoragePolicy<xfem::xFieldStorageFull<double>>();
589
  deleteMaterialVariables();
590 591 592
  tls_solver.deleteState();
  tls_solver.deleteField("tls");   //tls_solver.clearField();
  clearDispMeasField();
593 594
  mesh->deleteAllSubMesh();
  delete mesh;
595

596 597
  //disp_field.getValueManager()->clear();
  disp_field.getValueManager()->PrintForDebug("aft_clean_disp.dbg");
598 599
  // end clean up

600 601 602 603 604 605 606 607 608 609
  //Set mesh pointer as mesh_new
  mesh = mesh_new;
  geom.setMesh("comp",mesh);
  //declareDispMeasField();
  geom.buildTLS();
  tls_solver.declareField();
  tls_solver.declareState();
  declareMaterialVariables();
  declareDispField();

610
  disp_field.getValueManager()->PrintForDebug("aft_recreate_disp.dbg");
611

612 613
  // read displacement
  xReadFromParaview(entree,"deplacement",disp_field,*mesh);
614
  disp_field.getValueManager()->PrintForDebug("aft_read_disp.dbg");
615

616
  xEvalField<xtool::xIdentity<xtensor::xVector<>> > eval_disp1(disp_field);
617 618
  //xEvalConstant<double> eval_disp_(1.);
  post_pro.exportOnSpace("read_disp", Observer::tell<int>("step"), eval_disp1, geom.getIntegRuleSmart(), geom.begin(), geom.end());
619

620 621
//applyEssentialEnv
   cout<<"After read disp\n";
622

623
//   xexport::xPostProVTU postProVTU2(mesh);
624
//   postProVTU2.openFile("DispRead.vtu");
625
//   xEvalField<xtool::xIdentity<xtensor::xVector<>> > eval_disp2(disp_field);
626 627
//   postProVTU2.exportVectorAtNode(eval_disp2,"deplacement");
//   postProVTU2.closeFile();
628 629

  // read phi
630 631 632 633 634 635 636 637 638

   xReadFromParaview(entree,"level-set",tls_solver.getField(),*mesh);
   //xAssignPhiValues(tls_solver.field, mesh, projectedValues);
   post_pro.exportOnSpace("readPHI", Observer::tell<int>("step"), tls_solver.getPhiEval(), geom.getIntegRuleSmart(), geom.begin(), geom.end());

 // read ls pour construire delocalized_list
    lsetAdapt.setSupport(mesh, -10.0);
    xReadFromParaviewxLevelSet(entree,"lsadapt",lsetAdapt);

639
// xexport::xPostProVTU postProVTU2(mesh);
640 641 642 643
// postProVTU2.openFile("phiRead.vtu");
// postProVTU2.exportScalarAtNode(tls_solver.getPhiEval(),"level-set");
// postProVTU2.closeFile();

644 645
  // end read phi

646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
 // create domains
  std::list<mEntity*> delocalized_list;
//   tls_solver.delocalized_list.clear();
   geom.buildNonlocal(delocalized_list);
   geom.buildLocal();

  //tls_solver.updateLevelSetField();

// updateLevelSetField();
// updateLevelSetFieldForced();

 //Construire la liste delocalized_list
//   tls_solver.delocalizeLevelSetField();
//   tls_solver.constructDelocalizedList(lsetAdapt);

   //Fill the new delocalized_list
   delocalized_list = constructDelocalizedList(lsetAdapt);//Pourrait etre remonte avant le geom.buildNonlocal(delocalized_list); ???
   //Assign it into geom
   geom.buildNonlocal(delocalized_list);


  // tls_solver.delocalizeLevelSetFieldForced();

  // get new h for new mesh
  //geom.updateElementSize();
  //xRegion all=geom.getRegion();
  //xRegion all=mesh;

  //Clear the info_manager (it is used inside getLength)
  //as it stores the pointer to the elements already used.

  //xElementInfoManager& info_manager = xElementInfoManagerSingleton::instance();
  //cout<<"clear info_manager\n";
  //info_manager.clear();
  //geom.h = xCFL::getLength(all);
  //geom.h = 0.01;
  //cout<<"minimal element size = "<<geom.h<<endl;


  // reseting thresold when vicinity algo based on distance
 // if (!vicinity_algo && re_init_ls_from_front_modifier) re_init_ls_from_front_modifier->setThreshold(0.4*geom.h);

688 689
   //TODO
   //  tls_solver.updateDomains();
690 691
  tls_solver.delocalizeMeanField();

692
  xEvalGradField<xtensor::xNorm<>> eval_norm_grad_phi_after(tls_solver.getField());
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
  post_pro.exportOnSpace("norm_grad_phi_after", Observer::tell<int>("step"), eval_norm_grad_phi_after, geom.getIntegRuleBasic(0), geom.begin(), geom.end());

// cout<<"delocalized list size"<<tls_solver.delocalized_list.size()<<endl;

 //xSubMesh& sm_nonlocal=mesh->getSubMesh("nonlocal");
 // xSubMesh& sm_local=mesh->getSubMesh("local");
 xEvalConstant<double> eval_one(1.);
 //xIntegrationRuleBasic integ_rule(0);

  //post_pro.exportOnSpace("sm_local_after_build",          Observer::tell<int>("step"), eval_one, integ_rule, sm_local.begin(),     sm_local.end());
  //post_pro.exportOnSpace("sm_local_nodes_after_build",    Observer::tell<int>("step"), eval_one, integ_rule, sm_local.begin(0),    sm_local.end(0));
    post_pro.exportOnSpace("sm_local_after_build",       Observer::tell<int>("step"), eval_one, geom.getIntegRuleBasic(0), geom.begin("local"),  geom.end("local"));
    post_pro.exportOnSpace("sm_local_nodes_after_build", Observer::tell<int>("step"), eval_one, geom.getIntegRuleBasic(0), geom.begin(0,"local"), geom.end(0,"local"));
    post_pro.exportOnSpace("sm_nonlocal_after_build",       Observer::tell<int>("step"), eval_one, geom.getIntegRuleBasic(0), geom.begin("nonlocal"),  geom.end("nonlocal"));
    post_pro.exportOnSpace("sm_nonlocal_nodes_after_build", Observer::tell<int>("step"), eval_one, geom.getIntegRuleBasic(0), geom.begin(0,"nonlocal"), geom.end(0,"nonlocal"));

// declare disp, declare and update material variables
  tagger(*mesh);


 //Re-classify mesh entities

//  for(std::tuple<std::function<bool (const Trellis_Util::mPoint&) >, int, int> bccurr : BCDEF){
//      auto filter = std::get<0>(bccurr);
//      int tagnum = std::get<1>(bccurr);
//      int dimBC = std::get<2>(bccurr);

//      //loop over Bnd entities
//     // for(xIter itBnd = data.mesh->begin(dimBC); itBnd != data.mesh->end(dimBC); ++itBnd){

//        for(xIter itBnd = geom.begin(dimBC); itBnd != geom.end(dimBC); ++itBnd){

//          //check filter
726
//          xfem::xGeomElem geo(*itBnd);
727 728 729 730 731 732 733 734

//          if(filter(geo.getCDGxyz())){
//              (*itBnd)->classify(mesh->getGEntity(tagnum,dimBC));
//                  (*itBnd)->print();
//                  printf("tag is %i , dim is %i\n",tagnum,dimBC);
//          }
//      }
//  }
735 736

  applyEssentialEnv(1.);
737
  disp_field.getValueManager()->PrintForDebug("aft_essenv_disp.dbg");
738
  declareDofs();
739
  disp_field.getValueManager()->PrintForDebug("yeah.dbg");
740 741 742
  geom.buildBndMeas();
  declareDispMeasField();
//  tls_solver.swapOldAndCurrentLevelSetField();
743
  updateMaterialVariables(tls_solver.getDamageEval());
744
  writeStrain("eps_ref");
745 746 747 748 749 750 751 752 753

  //export mesh in mesh_long.msh to read it in main for the restart in the case of the aniso
  //AOMD::AOMD_Util::Instance()->ex_port("mesh_long.msh", mesh);
 }



std::list<AOMD::mEntity*> QSFormulRemeshAniso::constructDelocalizedList(xLevelSet &lsetAdapt) {
  std::list<AOMD::mEntity*> delocalized_list;
754
  xEvalLevelSet<xtool::xIdentity<double> > eval_chi(lsetAdapt);
755 756 757 758 759 760 761
  post_pro.exportOnSpace("lsAdapt_computed_eval",Observer::tell<int>("step"),eval_chi,geom.getIntegRuleBasic(0), geom.begin("tls"), geom.end("tls"));
  LocateHotPointsCommand locate_hot_points(eval_chi, 0., delocalized_list);
  ApplyCommandOnIntegrationRule(locate_hot_points, geom.getIntegRuleBasic(0), geom.begin("tls"), geom.end("tls"));
  delocalized_list.sort();
  delocalized_list.unique();

  return delocalized_list;
762
}
763 764 765 766 767 768


//// for aniso
////void QSFormulRemeshAniso::setBCDefinition(std::vector<std::tuple<std::function<bool (const Trellis_Util::mPoint &)>, int, int> > &BCDEF_){
////    BCDEF = BCDEF_;
////}