main.cpp 38.5 KB
Newer Older
thomaskummer's avatar
thomaskummer committed
1
2
3
4
5
6
7
8
9
10
11
12
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
//============================================//
// Includes
//============================================//

#include <lifev/core/LifeV.hpp>

// Passive material
#include <lifev/electrophysiology/solver/ElectroETAMonodomainSolver.hpp>
#include <lifev/electrophysiology/util/HeartUtility.hpp>
#include <lifev/structure/solver/StructuralConstitutiveLawData.hpp>
#include <lifev/em/solver/mechanics/EMStructuralOperator.hpp>
#include <lifev/em/solver/mechanics/EMStructuralConstitutiveLaw.hpp>
#include <lifev/bc_interface/3D/bc/BCInterface3D.hpp>

// Solver
#include <lifev/em/solver/EMSolver.hpp>

// Exporter
#include <lifev/core/filter/ExporterEnsight.hpp>
#include <lifev/core/filter/ExporterVTK.hpp>
#ifdef HAVE_HDF5
#include <lifev/core/filter/ExporterHDF5.hpp>
#endif
#include <lifev/core/filter/ExporterEmpty.hpp>

// Resize mesh
#include <lifev/core/mesh/MeshUtility.hpp>

// B.C. modification
#include <lifev/core/fem/BCVector.hpp>

// Circulation
#include <lifev/em/solver/circulation/Circulation.hpp>

// Volume computation
#include <lifev/em/solver/circulation/CirculationVolumeIntegrator.hpp>

thomaskummer's avatar
thomaskummer committed
38
39
// Heart solver
#include <lifev/em/solver/HeartSolver.hpp>
thomaskummer's avatar
thomaskummer committed
40

thomaskummer's avatar
thomaskummer committed
41
// PatchBC
thomaskummer's avatar
thomaskummer committed
42
#include <lifev/em/examples/example_EMHeart/PatchBC.hpp>
thomaskummer's avatar
thomaskummer committed
43

thomaskummer's avatar
thomaskummer committed
44
45
46
47
48
49
50
51
52
53
54
// Track nan
// #include <fenv.h>



using namespace LifeV;


int main (int argc, char** argv)
{

thomaskummer's avatar
thomaskummer committed
55
//    feenableexcept(FE_INVALID | FE_OVERFLOW);
thomaskummer's avatar
thomaskummer committed
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
    
    //============================================//
    // Typedefs
    //============================================//
    
    typedef RegionMesh<LinearTetra>                         mesh_Type;
    typedef boost::shared_ptr<mesh_Type>                    meshPtr_Type;
    
    typedef boost::function < Real (const Real & t,
                                    const Real &   x,
                                    const Real &   y,
                                    const Real & z,
                                    const ID&   /*i*/ ) >   function_Type;
    
    typedef VectorEpetra                                    vector_Type;
    typedef boost::shared_ptr<vector_Type>                  vectorPtr_Type;
    
    typedef BCVector                                        bcVector_Type;
    typedef boost::shared_ptr<bcVector_Type>                bcVectorPtr_Type;
    
    typedef EMMonodomainSolver<mesh_Type>                   monodomain_Type;

    typedef FESpace< mesh_Type, MapEpetra >                 solidFESpace_Type;
    typedef boost::shared_ptr<solidFESpace_Type>            solidFESpacePtr_Type;
    
    typedef ETFESpace< mesh_Type, MapEpetra, 3, 3 >         solidETFESpace_Type;
    typedef boost::shared_ptr<solidETFESpace_Type>          solidETFESpacePtr_Type;
    
    typedef StructuralConstitutiveLawData                   constitutiveLaw_Type;
    typedef boost::shared_ptr<constitutiveLaw_Type>         constitutiveLawPtr_Type;
    
    typedef BCHandler                                       bc_Type;
    typedef StructuralOperator< mesh_Type >                 physicalSolver_Type;
    typedef BCInterface3D< bc_Type, physicalSolver_Type >   bcInterface_Type;
    typedef boost::shared_ptr< bcInterface_Type >           bcInterfacePtr_Type;
    

    //============================================//
thomaskummer's avatar
thomaskummer committed
94
    // Communicator and displayer
thomaskummer's avatar
thomaskummer committed
95
96
97
98
99
100
101
    //============================================//
#ifdef HAVE_MPI
    MPI_Init ( &argc, &argv );
#endif

    boost::shared_ptr<Epetra_Comm>  comm ( new Epetra_MpiComm (MPI_COMM_WORLD) );
    Displayer displayer ( comm );
thomaskummer's avatar
thomaskummer committed
102
103
    
    displayer.leaderPrint("\n\nEMHeart running ...\n\n");
thomaskummer's avatar
thomaskummer committed
104
    
thomaskummer's avatar
thomaskummer committed
105
106
107
108
109
110
111
112
    //============================================//
    // Read data file and create output folder
    //============================================//
    GetPot command_line (argc, argv);
    const std::string data_file_name = command_line.follow ("data", 2, "-f", "--file");
    GetPot dataFile (data_file_name);
    std::string problemFolder = EMUtility::createOutputFolder (command_line, *comm);

thomaskummer's avatar
thomaskummer committed
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
    
    //============================================//
    // Electromechanic solver
    //============================================//
    EMSolver<mesh_Type, monodomain_Type> solver(comm);
    
    
    //============================================//
    // Body circulation
    //============================================//
    const std::string circulationInputFile = command_line.follow ("circulation", 2, "-cif", "--cifile");
    const std::string circulationOutputFile = command_line.follow ( (problemFolder + "solution.dat").c_str(), 2, "-cof", "--cofile");
    
    Circulation circulationSolver( circulationInputFile );
    
    // Flow rate between two vertices
    auto Q = [&circulationSolver] (const std::string& N1, const std::string& N2) { return circulationSolver.solution ( std::vector<std::string> {N1, N2} ); };
    auto p = [&circulationSolver] (const std::string& N1) { return circulationSolver.solution ( N1 ); };
    
    
    //============================================//
    // Heart solver
    //============================================//
thomaskummer's avatar
thomaskummer committed
136
    HeartSolver<EMSolver<mesh_Type, monodomain_Type> > heartSolver (solver, circulationSolver);
thomaskummer's avatar
thomaskummer committed
137
    
thomaskummer's avatar
thomaskummer committed
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
    
    //============================================//
    // Setup material data
    //============================================//
    EMData emdata;
    emdata.setup (dataFile);
    
    
    //============================================//
    // Load mesh
    //============================================//
    std::string meshName = dataFile("solid/space_discretization/mesh_file", "cube4.mesh");
    std::string meshPath = dataFile("solid/space_discretization/mesh_dir", "./");
    
    solver.loadMesh (meshName, meshPath);
    
    
    //============================================//
    // Resize mesh
    //============================================//
thomaskummer's avatar
thomaskummer committed
158
159
    if ( 0 == comm->MyPID() ) std::cout << "\nResizing mesh ... " << '\r' << std::flush;

thomaskummer's avatar
thomaskummer committed
160
161
162
163
164
165
166
167
168
169
    std::vector<Real> scale (3, dataFile("solid/space_discretization/mesh_scaling", 1.0));
    std::vector<Real> rotate { dataFile("solid/space_discretization/mesh_rotation_0", 0.0) , dataFile("solid/space_discretization/mesh_rotation_1", 0.0) , dataFile("solid/space_discretization/mesh_rotation_2", 0.0) };
    std::vector<Real> translate { dataFile("solid/space_discretization/mesh_translation_0", 0.0) , dataFile("solid/space_discretization/mesh_translation_1", 0.0) , dataFile("solid/space_discretization/mesh_translation_2", 0.0) };
    
    MeshUtility::MeshTransformer<mesh_Type> transformerFull (* (solver.fullMeshPtr() ) );
    MeshUtility::MeshTransformer<mesh_Type> transformerLocal (* (solver.localMeshPtr() ) );
    
    transformerFull.transformMesh (scale, rotate, translate);
    transformerLocal.transformMesh (scale, rotate, translate);
    
thomaskummer's avatar
thomaskummer committed
170
    if ( 0 == comm->MyPID() ) std::cout << "Resizing mesh done" << '\r' << std::flush;
thomaskummer's avatar
thomaskummer committed
171
    if ( 0 == comm->MyPID() ) solver.fullMeshPtr()->showMe();
thomaskummer's avatar
thomaskummer committed
172

thomaskummer's avatar
thomaskummer committed
173
174
175
176
    
    //============================================//
    // Setup solver (including fe-spaces & b.c.)
    //============================================//
thomaskummer's avatar
thomaskummer committed
177
    EMAssembler::quadRule.setQuadRule( dataFile ( "solid/space_discretization/quad_rule", "4pt") );
thomaskummer's avatar
thomaskummer committed
178
179
    solver.setup (dataFile);
    
thomaskummer's avatar
thomaskummer committed
180
181
182
    auto& disp = solver.structuralOperatorPtr() -> displacement();
    auto FESpace = solver.structuralOperatorPtr() -> dispFESpacePtr();
    auto dETFESpace = solver.electroSolverPtr() -> displacementETFESpacePtr();
thomaskummer's avatar
thomaskummer committed
183
    auto ETFESpace = solver.electroSolverPtr() -> ETFESpacePtr();
thomaskummer's avatar
thomaskummer committed
184
    
thomaskummer's avatar
thomaskummer committed
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
    
    //============================================//
    // Setup anisotropy vectors
    //============================================//
    bool anisotropy = dataFile ( "solid/space_discretization/anisotropic", false );

    if ( anisotropy )
    {
        std::string fiberFileName  =  dataFile ( "solid/space_discretization/fiber_name", "FiberDirection");
        std::string sheetFileName  =  dataFile ( "solid/space_discretization/sheet_name", "SheetsDirection");
        std::string fiberFieldName =  dataFile ( "solid/space_discretization/fiber_fieldname", "fibers");
        std::string sheetFieldName =  dataFile ( "solid/space_discretization/sheet_fieldname", "sheets");
        std::string fiberDir       =  meshPath; //dataFile ( "solid/space_discretization/fiber_dir", "./");
        std::string sheetDir       =  meshPath; //dataFile ( "solid/space_discretization/sheet_dir", "./");
        std::string elementOrder   =  dataFile ( "solid/space_discretization/order", "P1");

        solver.setupFiberVector ( fiberFileName, fiberFieldName, fiberDir, elementOrder );
        solver.setupMechanicalSheetVector ( sheetFileName, sheetFieldName, sheetDir, elementOrder );
    }
    else
    {
        solver.setupFiberVector (1., 0., 0.);
        solver.setupSheetVector (0., 1., 0.);
    }
    
    
    //============================================//
    // Initialize electrophysiology
    //============================================//
    solver.initialize();
    
    
    //============================================//
    // Building Matrices
    //============================================//
thomaskummer's avatar
thomaskummer committed
220
    solver.oneWayCoupling();
thomaskummer's avatar
thomaskummer committed
221
222
223
224
225
226
227
228
    solver.structuralOperatorPtr()->setNewtonParameters(dataFile);
    solver.buildSystem();
    
    
    //============================================//
    // Setup exporters for EMSolver
    //============================================//
    solver.setupExporters (problemFolder);
thomaskummer's avatar
thomaskummer committed
229
        
thomaskummer's avatar
thomaskummer committed
230
231
232
233
    
    //============================================//
    // Electric stimulus function
    //============================================//
thomaskummer's avatar
thomaskummer committed
234
    function_Type stim = &HeartSolver<EMSolver<mesh_Type, monodomain_Type> >::Iapp;
thomaskummer's avatar
thomaskummer committed
235

thomaskummer's avatar
thomaskummer committed
236
    
thomaskummer's avatar
thomaskummer committed
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
//    //============================================//
//    // Create displacement patch b.c.
//    //============================================//
//    std::vector<Real> patchDisplacement;
//    std::vector<Vector3D> patchDirection;
//
//    std::vector<vectorPtr_Type> patchDispVecPtr;
//    std::vector<bcVectorPtr_Type> patchDispBCVecPtr;
//
//    UInt nPatchBC = dataFile.vector_variable_size ( ( "solid/boundary_conditions/listPatchBC" ) );
//
//    for ( UInt i (0) ; i < nPatchBC ; ++i )
//    {
//        std::string patchName = dataFile ( ( "solid/boundary_conditions/listPatchBC" ), " ", i );
//        Real patchFlag = dataFile ( ("solid/boundary_conditions/" + patchName + "/flag").c_str(), 0 );
//        Real patchRadius = dataFile ( ("solid/boundary_conditions/" + patchName + "/radius").c_str(), 1.0 );
//        patchDisplacement.push_back( dataFile ( ("solid/boundary_conditions/" + patchName + "/displacement").c_str(), 1.0 ) );
//
//        Vector3D patchCenter;
//        for ( UInt j (0); j < 3; ++j )
//        {
//            patchCenter[j] = dataFile ( ("solid/boundary_conditions/" + patchName + "/center").c_str(), 0, j );
//        }
//
//        Vector3D pd;
//        for ( UInt j (0); j < 3; ++j )
//        {
//            pd[j] = dataFile ( ("solid/boundary_conditions/" + patchName + "/direction").c_str(), 0, j );
//        }
//        patchDirection.push_back(pd);
//
//        UInt componentSize = dataFile.vector_variable_size ( ("solid/boundary_conditions/" + patchName + "/component").c_str() );
//        std::vector<ID> patchComponent (componentSize);
//        for ( UInt j (0); j < componentSize; ++j )
//        {
//            patchComponent[j] = dataFile ( ("solid/boundary_conditions/" + patchName + "/component").c_str(), 0, j );
//        }
//        
//        createPatch(solver, patchCenter, patchRadius, patchFlag, (900+i));
//
//        patchDispVecPtr.push_back ( vectorPtr_Type ( directionalVectorField(FESpace, patchDirection[i], 1e-10) ) );
//        patchDispBCVecPtr.push_back ( bcVectorPtr_Type( new bcVector_Type( *patchDispVecPtr[i], solver.structuralOperatorPtr() -> dispFESpacePtr() -> dof().numTotalDof(), 1 ) ) );
//        solver.bcInterfacePtr() -> handler()->addBC (patchName, (900+i),  Essential, Component, *patchDispBCVecPtr[i], patchComponent);
//    }
//
//
//    Real tmax = dataFile ( "solid/patches/tmax", 0. );
//    Real tduration = dataFile ( "solid/patches/tduration", 0. );
//
//    auto modifyPatchBC = [&] (const Real& time)
//    {
//        for ( UInt i (0) ; i < nPatchBC ; ++i )
//        {
//            Real currentPatchDisp = sinSquared(time, patchDisplacement[i], tmax, tduration);
//            patchDispVecPtr[i] = directionalVectorField(FESpace, patchDirection[i], currentPatchDisp);
//            patchDispBCVecPtr[i].reset( new bcVector_Type( *patchDispVecPtr[i], FESpace->dof().numTotalDof(), 1 ) );
//            solver.bcInterfacePtr()->handler()->modifyBC((900+i), *patchDispBCVecPtr[i]);
//        }
//    };
thomaskummer's avatar
thomaskummer committed
296
    
thomaskummer's avatar
thomaskummer committed
297

thomaskummer's avatar
thomaskummer committed
298
    //============================================//
thomaskummer's avatar
thomaskummer committed
299
    // Pressure b.c. on endocardia
thomaskummer's avatar
thomaskummer committed
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
    //============================================//
    std::vector<vectorPtr_Type> pVecPtrs;
    std::vector<bcVectorPtr_Type> pBCVecPtrs;

    std::vector<ID> flagsBC;
    std::vector<UInt> ventIdx;

    // Endocardia
    UInt nVarBC = dataFile.vector_variable_size ( ( "solid/boundary_conditions/listVariableBC" ) );
    for ( UInt i (0) ; i < nVarBC ; ++i )
    {
        std::string varBCSection = dataFile ( ( "solid/boundary_conditions/listVariableBC" ), " ", i );
        flagsBC.push_back( dataFile ( ("solid/boundary_conditions/" + varBCSection + "/flag").c_str(), 0 ) );
        ventIdx.push_back ( dataFile ( ("solid/boundary_conditions/" + varBCSection + "/index").c_str(), 0 ) );
        
        pVecPtrs.push_back ( vectorPtr_Type ( new vector_Type ( solver.structuralOperatorPtr() -> displacement().map(), Repeated ) ) );
        pBCVecPtrs.push_back ( bcVectorPtr_Type( new bcVector_Type( *pVecPtrs[i], solver.structuralOperatorPtr() -> dispFESpacePtr() -> dof().numTotalDof(), 1 ) ) );
        solver.bcInterfacePtr() -> handler() -> addBC(varBCSection, flagsBC[i], Natural, Full, *pBCVecPtrs[i], 3);
    }
    
thomaskummer's avatar
thomaskummer committed
320
321

    // Functions to modify b.c.
thomaskummer's avatar
thomaskummer committed
322
    auto modifyPressureBC = [&] (const std::vector<Real>& bcValues)
thomaskummer's avatar
thomaskummer committed
323
324
325
    {
        for ( UInt i (0) ; i < nVarBC ; ++i )
        {
thomaskummer's avatar
thomaskummer committed
326
            *pVecPtrs[i] = - bcValues[ ventIdx[i] ] * 1333.224;
thomaskummer's avatar
thomaskummer committed
327
328
329
330
331
            pBCVecPtrs[i].reset ( ( new bcVector_Type (*pVecPtrs[i], solver.structuralOperatorPtr() -> dispFESpacePtr() -> dof().numTotalDof(), 1) ) );
            solver.bcInterfacePtr() -> handler() -> modifyBC(flagsBC[i], *pBCVecPtrs[i]);
        }
    };

thomaskummer's avatar
thomaskummer committed
332
333
334
335
336
337
    
    //============================================//
    // Update and print bcHandler
    //============================================//
    solver.bcInterfacePtr() -> handler() -> bcUpdate( *solver.structuralOperatorPtr() -> dispFESpacePtr() -> mesh(), solver.structuralOperatorPtr() -> dispFESpacePtr() -> feBd(), solver.structuralOperatorPtr() -> dispFESpacePtr() -> dof() );
    
thomaskummer's avatar
thomaskummer committed
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
    if ( 0 == comm->MyPID() ) solver.bcInterfacePtr() -> handler() -> showMe();
    
    
    //============================================//
    // Volume integrators
    //============================================//
    std::vector<int> LVFlags;
    std::vector<int> RVFlags;

    for ( UInt i (0) ; i < nVarBC ; ++i )
    {
        std::string varBCSection = dataFile ( ( "solid/boundary_conditions/listVariableBC" ), " ", i );
        ID flag  =  dataFile ( ("solid/boundary_conditions/" + varBCSection + "/flag").c_str(), 0 );
        ID index =  dataFile ( ("solid/boundary_conditions/" + varBCSection + "/index").c_str(), 0 );
        switch ( index )
        {
            case 0: LVFlags.push_back ( flag );
                break;
            case 1: RVFlags.push_back ( flag );
                break;
            default:
                break;
        }
    }
    
    VolumeIntegrator LV (LVFlags, "Left Ventricle", solver.fullMeshPtr(), solver.localMeshPtr(), ETFESpace, FESpace);
    VolumeIntegrator RV (RVFlags, "Right Ventricle", solver.fullMeshPtr(), solver.localMeshPtr(), ETFESpace, FESpace);

    
    //============================================//
    // Set variables and functions
    //============================================//
thomaskummer's avatar
thomaskummer committed
370
    const Real dt_activation = solver.data().electroParameter<Real>("timestep");
thomaskummer's avatar
thomaskummer committed
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
    const Real dt_loadstep =  dataFile ( "solid/time_discretization/dt_loadstep", 1.0 );
    const Real activationLimit_loadstep =  dataFile ( "solid/time_discretization/activation_limit_loadstep", 0.0 );
    const Real dt_mechanics = solver.data().solidParameter<Real>("timestep");
    const Real dt_save = dataFile ( "exporter/save", 10. );
    const Real endtime = solver.data().electroParameter<Real>("endtime");
    const UInt mechanicsLoadstepIter = static_cast<UInt>( dt_loadstep / dt_activation );
    const UInt mechanicsCouplingIter = static_cast<UInt>( dt_mechanics / dt_activation );
    const UInt maxiter = static_cast<UInt>( endtime / dt_activation ) ;
    
    const Real pPerturbationFe = dataFile ( "solid/coupling/pPerturbationFe", 1e-2 );
    const Real pPerturbationCirc = dataFile ( "solid/coupling/pPerturbationCirc", 1e-3 );
    const Real couplingError = dataFile ( "solid/coupling/couplingError", 1e-6 );
    const UInt couplingJFeSubIter = dataFile ( "solid/coupling/couplingJFeSubIter", 1 );
    const UInt couplingJFeSubStart = dataFile ( "solid/coupling/couplingJFeSubStart", 1 );
    const UInt couplingJFeIter = dataFile ( "solid/coupling/couplingJFeIter", 1 );
thomaskummer's avatar
thomaskummer committed
386
387
    
    const Real dpMax = dataFile ( "solid/coupling/dpMax", 0.1 );
thomaskummer's avatar
thomaskummer committed
388
    
thomaskummer's avatar
thomaskummer committed
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
    std::vector<std::vector<std::string> > bcNames { { "lv" , "p" } , { "rv" , "p" } };
    std::vector<double> bcValues { p ( "lv" ) , p ( "rv") };
    std::vector<double> bcValuesPre ( bcValues );

    VectorSmall<2> VCirc, VCircNew, VCircPert, VFe, VFeNew, VFePert, R, dp;
    MatrixSmall<2,2> JFe, JCirc, JR;

    UInt iter (0);
    Real t (0);
    
    auto printCoupling = [&] ( std::string label ) { if ( 0 == comm->MyPID() )
    {
        std::cout << "\n===============================================================";
        std::cout << "\nCoupling: " << label;
        std::cout << "\nNewton iteration nr. " << iter << " at time " << t;
        std::cout << "\nLV - Pressure: \t\t\t" << bcValues[0];
        std::cout << "\nLV - FE-Volume: \t\t" << VFeNew[0];
        std::cout << "\nLV - Circulation-Volume: \t" << VCircNew[0];
        std::cout << "\nLV - Residual: \t\t\t" << std::abs(VFeNew[0] - VCircNew[0]);
        std::cout << "\nRV - Pressure: \t\t\t" << bcValues[1];
        std::cout << "\nRV - FE-Volume : \t\t" << VFeNew[1];
        std::cout << "\nRV - Circulation-Volume: \t" << VCircNew[1];
        std::cout << "\nRV - Residual: \t\t\t" << std::abs(VFeNew[1] - VCircNew[1]);
        //std::cout << "\nJFe   = " << JFe;
        //std::cout << "\nJCirc = " << JCirc;
        //std::cout << "\nJR    = " << JR;
thomaskummer's avatar
thomaskummer committed
415
        std::cout << "\n===============================================================\n"; }
thomaskummer's avatar
thomaskummer committed
416
    };
thomaskummer's avatar
thomaskummer committed
417
    
thomaskummer's avatar
thomaskummer committed
418
419
420
421
422
    
    //============================================//
    // Load restart file
    //============================================//
    
thomaskummer's avatar
thomaskummer committed
423
424
425
    std::string restartInput = command_line.follow ("noRestart", 2, "-r", "--restart");
    const bool restart ( restartInput != "noRestart" );

thomaskummer's avatar
b    
thomaskummer committed
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
    if ( restart )
    {
        const std::string restartDir = command_line.follow (problemFolder.c_str(), 2, "-rd", "--restartDir");
        
        Real dtExport = 10.;
        
        // Set time variable
        const unsigned int restartInputStr = std::stoi(restartInput);
        const unsigned int nIter = (restartInputStr - 1) * dtExport / dt_mechanics;
        t = nIter * dt_mechanics;

        // Set time exporter time index
        solver.setTimeIndex(restartInputStr + 1);

        // Load restart solutions from output files
        std::string polynomialDegree = dataFile ( "solid/space_discretization/order", "P2");

        ElectrophysiologyUtility::importVectorField ( solver.structuralOperatorPtr() -> displacementPtr(), "MechanicalSolution" , "displacement", solver.localMeshPtr(), restartDir, polynomialDegree, restartInput );

        for ( unsigned int i = 0; i < solver.electroSolverPtr()->globalSolution().size() ; ++i )
        {
            ElectrophysiologyUtility::importScalarField (solver.electroSolverPtr()->globalSolution().at(i), "ElectroSolution" , ("Variable" + std::to_string(i)), solver.localMeshPtr(), restartDir, polynomialDegree, restartInput );
        }

        ElectrophysiologyUtility::importScalarField (solver.activationModelPtr() -> fiberActivationPtr(), "ActivationSolution" , "Activation", solver.localMeshPtr(), restartDir, polynomialDegree, restartInput );
        //ElectrophysiologyUtility::importScalarField (solver.activationTimePtr(), "ActivationTimeSolution" , "Activation Time", solver.localMeshPtr(), restartDir, polynomialDegree, restartInput );

        circulationSolver.restartFromFile ( restartDir + "solution.dat" , nIter );
        
        // Set boundary mechanics conditions
        bcValues = { p ( "lv" ) , p ( "rv" ) };
        bcValuesPre = { p ( "lv" ) , p ( "rv" ) };
thomaskummer's avatar
thomaskummer committed
458
        modifyPressureBC(bcValues);
thomaskummer's avatar
b    
thomaskummer committed
459
    }
thomaskummer's avatar
thomaskummer committed
460
461
462
463
464
465

    
    //============================================//
    // Preload
    //============================================//
    
thomaskummer's avatar
c    
thomaskummer committed
466
467
    if ( ! restart )
    {
thomaskummer's avatar
thomaskummer committed
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
        solver.structuralOperatorPtr() -> data() -> dataTime() -> setTime(0.0);
        
        const int preloadSteps = dataFile ( "solid/boundary_conditions/numPreloadSteps", 0);
        
        auto preloadPressure = [] (std::vector<double> p, const int& step, const int& steps)
        {
            for (auto& i : p) {i *= double(step) / double(steps);}
            return p;
        };
        
        LifeChrono chronoSave;
        chronoSave.start();

        solver.saveSolution (-1.0);
        
        if ( 0 == comm->MyPID() )
        {
            std::cout << "\n*****************************************************************";
            std::cout << "\nData stored in " << chronoSave.diff() << " s";
            std::cout << "\n*****************************************************************\n";
        }
        
        LifeChrono chronoPreload;
        chronoPreload.start();
        
thomaskummer's avatar
thomaskummer committed
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
        for (int i (1); i <= preloadSteps; i++)
        {
            if ( 0 == comm->MyPID() )
            {
                std::cout << "\n*****************************************************************";
                std::cout << "\nPreload step: " << i << " / " << preloadSteps;
                std::cout << "\n*****************************************************************\n";
            }

            // Update pressure b.c.
            modifyPressureBC(preloadPressure(bcValues, i, preloadSteps));

            // Solve mechanics
            solver.bcInterfacePtr() -> updatePhysicalSolverVariables();
            solver.solveMechanics();
            // solver.saveSolution (i-1);
        }
thomaskummer's avatar
thomaskummer committed
510

thomaskummer's avatar
thomaskummer committed
511
        auto maxI4fValue ( solver.activationModelPtr()->I4f().maxValue() );
thomaskummer's avatar
thomaskummer committed
512
        auto minI4fValue ( solver.activationModelPtr()->I4f().minValue() );
thomaskummer's avatar
thomaskummer committed
513
        
thomaskummer's avatar
thomaskummer committed
514
        if ( 0 == comm->MyPID() ) std::cout << "\nI4fmax/I4fmin = " << maxI4fValue << "/" << minI4fValue << std::endl;
thomaskummer's avatar
thomaskummer committed
515

thomaskummer's avatar
thomaskummer committed
516
517
518
519
520
521
522
        if ( 0 == comm->MyPID() )
        {
            std::cout << "\n*****************************************************************";
            std::cout << "\nPreload done in: " << chronoPreload.diff();
            std::cout << "\n*****************************************************************\n";
        }

thomaskummer's avatar
c    
thomaskummer committed
523
524
    }

thomaskummer's avatar
thomaskummer committed
525
    
thomaskummer's avatar
thomaskummer committed
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
    //============================================//
    // Create displacement patch b.c.
    //============================================//
    std::vector<Real> patchDisplacement;
    std::vector<Vector3D> patchDirection;
    
    std::vector<vectorPtr_Type> patchDispVecPtr;
    std::vector<bcVectorPtr_Type> patchDispBCVecPtr;
    
    UInt nPatchBC = dataFile.vector_variable_size ( ( "solid/boundary_conditions/listPatchBC" ) );
    
    for ( UInt i (0) ; i < nPatchBC ; ++i )
    {
        std::string patchName = dataFile ( ( "solid/boundary_conditions/listPatchBC" ), " ", i );
        Real patchFlag = dataFile ( ("solid/boundary_conditions/" + patchName + "/flag").c_str(), 0 );
        Real patchRadius = dataFile ( ("solid/boundary_conditions/" + patchName + "/radius").c_str(), 1.0 );
        patchDisplacement.push_back( dataFile ( ("solid/boundary_conditions/" + patchName + "/displacement").c_str(), 1.0 ) );
        
        Vector3D patchCenter;
        for ( UInt j (0); j < 3; ++j )
        {
            patchCenter[j] = dataFile ( ("solid/boundary_conditions/" + patchName + "/center").c_str(), 0, j );
        }
        
        Vector3D pd;
        for ( UInt j (0); j < 3; ++j )
        {
            pd[j] = dataFile ( ("solid/boundary_conditions/" + patchName + "/direction").c_str(), 0, j );
        }
        patchDirection.push_back(pd);
        
        UInt componentSize = dataFile.vector_variable_size ( ("solid/boundary_conditions/" + patchName + "/component").c_str() );
        std::vector<ID> patchComponent (componentSize);
        for ( UInt j (0); j < componentSize; ++j )
        {
            patchComponent[j] = dataFile ( ("solid/boundary_conditions/" + patchName + "/component").c_str(), 0, j );
        }
        
        createPatch(solver, patchCenter, patchRadius, patchFlag, (900+i));
        
thomaskummer's avatar
thomaskummer committed
566
        patchDispVecPtr.push_back ( vectorPtr_Type ( heartSolver.directionalVectorField(FESpace, patchDirection[i], 1e-10) ) );
thomaskummer's avatar
thomaskummer committed
567
568
569
570
571
572
573
574
575
576
577
578
        patchDispBCVecPtr.push_back ( bcVectorPtr_Type( new bcVector_Type( *patchDispVecPtr[i], solver.structuralOperatorPtr() -> dispFESpacePtr() -> dof().numTotalDof(), 1 ) ) );
        solver.bcInterfacePtr() -> handler()->addBC (patchName, (900+i),  Essential, Component, *patchDispBCVecPtr[i], patchComponent);
    }
    
    
    Real tmax = dataFile ( "solid/patches/tmax", 0. );
    Real tduration = dataFile ( "solid/patches/tduration", 0. );
    
    auto modifyPatchBC = [&] (const Real& time)
    {
        for ( UInt i (0) ; i < nPatchBC ; ++i )
        {
thomaskummer's avatar
thomaskummer committed
579
            Real currentPatchDisp = heartSolver.sinSquared(time, patchDisplacement[i], tmax, tduration);
thomaskummer's avatar
thomaskummer committed
580
            patchDispVecPtr[i] = heartSolver.directionalVectorField(FESpace, patchDirection[i], currentPatchDisp);
thomaskummer's avatar
thomaskummer committed
581
582
583
584
585
586
587
588
589
            patchDispBCVecPtr[i].reset( new bcVector_Type( *patchDispVecPtr[i], FESpace->dof().numTotalDof(), 1 ) );
            solver.bcInterfacePtr()->handler()->modifyBC((900+i), *patchDispBCVecPtr[i]);
        }
    };

    solver.bcInterfacePtr() -> handler() -> bcUpdate( *solver.structuralOperatorPtr() -> dispFESpacePtr() -> mesh(), solver.structuralOperatorPtr() -> dispFESpacePtr() -> feBd(), solver.structuralOperatorPtr() -> dispFESpacePtr() -> dof() );
    
    if ( 0 == comm->MyPID() ) solver.bcInterfacePtr() -> handler() -> showMe();
    
thomaskummer's avatar
thomaskummer committed
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
    //============================================//
    // Time loop
    //============================================//
    
    VFe[0] = LV.volume(disp, dETFESpace, - 1);
    VFe[1] = RV.volume(disp, dETFESpace, 1);
    VCirc = VFe;
    
    VectorEpetra dispPre ( disp );
    VectorEpetra dispCurrent ( disp );
    ID bdPowerFlag  =  dataFile ( ("solid/boundary_conditions/LVEndo/flag") , 0 );
    
    printCoupling("Initial values");
    
    auto perturbedPressure = [] (std::vector<double> p, const double& dp)
    {
        for (auto& i : p) {i += dp;}
        return p;
    };
    
    auto perturbedPressureComp = [] (std::vector<double> p, const double& dp, int comp)
    {
        p[comp] += dp;
        return p;
    };
thomaskummer's avatar
thomaskummer committed
615
616
617

    if ( ! restart )
    {
thomaskummer's avatar
thomaskummer committed
618
619
        solver.saveSolution (t);
        circulationSolver.exportSolution( circulationOutputFile );
thomaskummer's avatar
thomaskummer committed
620
    }
thomaskummer's avatar
thomaskummer committed
621

thomaskummer's avatar
thomaskummer committed
622
    for (int k (1); k <= maxiter; k++)
thomaskummer's avatar
thomaskummer committed
623
624
625
626
    {
        if ( 0 == comm->MyPID() )
        {
            std::cout << "\n*****************************************************************";
thomaskummer's avatar
thomaskummer committed
627
            std::cout << "\nTIME = " << t+dt_activation;
thomaskummer's avatar
thomaskummer committed
628
629
630
            std::cout << "\n*****************************************************************\n";
        }

thomaskummer's avatar
thomaskummer committed
631
        t = t + dt_activation;
thomaskummer's avatar
thomaskummer committed
632
633
634
635
636

        //============================================//
        // Solve electrophysiology and activation
        //============================================//

thomaskummer's avatar
thomaskummer committed
637
        auto maxI4fValue ( solver.activationModelPtr()->I4f().maxValue() );
thomaskummer's avatar
thomaskummer committed
638
        auto minI4fValue ( solver.activationModelPtr()->I4f().minValue() );
thomaskummer's avatar
thomaskummer committed
639
        
thomaskummer's avatar
thomaskummer committed
640
        if ( 0 == comm->MyPID() ) std::cout << "\nI4fmax/I4fmin = " << maxI4fValue << "/" << minI4fValue << std::endl;
thomaskummer's avatar
thomaskummer committed
641
        
thomaskummer's avatar
thomaskummer committed
642
643
        solver.solveElectrophysiology (stim, t);
        solver.solveActivation (dt_activation);
thomaskummer's avatar
thomaskummer committed
644

thomaskummer's avatar
thomaskummer committed
645
646
647
648
        //============================================//
        // Load steps mechanics (activation & b.c.)
        //============================================//

thomaskummer's avatar
thomaskummer committed
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
        auto minActivationValue ( solver.activationModelPtr() -> fiberActivationPtr() -> minValue() );

        if ( k % mechanicsLoadstepIter == 0 && k % mechanicsCouplingIter != 0 && minActivationValue < activationLimit_loadstep )
        {
            if ( 0 == comm->MyPID() )
            {
                std::cout << "\n*****************************************************************";
                std::cout << "\nLoad step at time = " << t;
                std::cout << "\nMinimal activation value = " << minActivationValue;
                std::cout << "\n*****************************************************************\n";
            }

            // Linear b.c. extrapolation
            auto bcValuesLoadstep ( bcValues );
            bcValuesLoadstep[0] = bcValues[0] + ( bcValues[0] - bcValuesPre[0] ) * ( k % mechanicsCouplingIter ) / mechanicsCouplingIter;
            bcValuesLoadstep[1] = bcValues[1] + ( bcValues[1] - bcValuesPre[1] ) * ( k % mechanicsCouplingIter ) / mechanicsCouplingIter;

            if ( 0 == comm->MyPID() )
            {
                std::cout << "\n***************************************************************";
                std::cout << "\nLV-Pressure extrapolation from " <<  bcValues[0] << " to " <<  bcValuesLoadstep[0];
                std::cout << "\nRV-Pressure extrapolation from " <<  bcValues[1] << " to " <<  bcValuesLoadstep[1];
                std::cout << "\n***************************************************************\n\n";
            }

            // Load step mechanics
            solver.structuralOperatorPtr() -> data() -> dataTime() -> setTime(t);
            modifyPressureBC(bcValuesLoadstep);
thomaskummer's avatar
thomaskummer committed
677
            modifyPatchBC(t);
thomaskummer's avatar
thomaskummer committed
678
679
680
            solver.bcInterfacePtr() -> updatePhysicalSolverVariables();
            solver.solveMechanics();
        }
thomaskummer's avatar
thomaskummer committed
681
682
683
684
685
686
        
        
        //============================================//
        // Iterate mechanics / circulation
        //============================================//
        
thomaskummer's avatar
thomaskummer committed
687
        if ( k % mechanicsCouplingIter == 0 )
thomaskummer's avatar
thomaskummer committed
688
689
        {
            iter = 0;
thomaskummer's avatar
thomaskummer committed
690
            const double dt_circulation ( dt_mechanics / 1000 );
thomaskummer's avatar
thomaskummer committed
691
692
            solver.structuralOperatorPtr() -> data() -> dataTime() -> setTime(t);
            
thomaskummer's avatar
thomaskummer committed
693
694
            modifyPatchBC(t);

thomaskummer's avatar
thomaskummer committed
695
696
697
698
            //============================================//
            // 4th order Adam-Bashforth pressure extrapol.
            //============================================//
            
thomaskummer's avatar
thomaskummer committed
699
            heartSolver.extrapolate4thOrderAdamBashforth(bcValues, bcValuesPre, dpMax);
thomaskummer's avatar
thomaskummer committed
700
            
thomaskummer's avatar
thomaskummer committed
701
702
703
704
705
706
707
708
            if ( 0 == comm->MyPID() )
            {
                std::cout << "\n***************************************************************";
                std::cout << "\nMinimal activation value = " << minActivationValue;
                std::cout << "\nLV-Pressure extrapolation from " <<  bcValuesPre[0] << " to " <<  bcValues[0];
                std::cout << "\nRV-Pressure extrapolation from " <<  bcValuesPre[1] << " to " <<  bcValues[1];
                std::cout << "\n***************************************************************\n\n";
            }
thomaskummer's avatar
thomaskummer committed
709
710
711
712
713

            
            //============================================//
            // Solve mechanics
            //============================================//
thomaskummer's avatar
thomaskummer committed
714
            modifyPressureBC(bcValues);
thomaskummer's avatar
thomaskummer committed
715
716
717
            solver.bcInterfacePtr() -> updatePhysicalSolverVariables();
            solver.solveMechanics();
            
thomaskummer's avatar
thomaskummer committed
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
            VFeNew[0] = LV.volume(disp, dETFESpace, - 1);
            VFeNew[1] = RV.volume(disp, dETFESpace, 1);

            //============================================//
            // Solve circlation
            //============================================//
            circulationSolver.iterate(dt_circulation, bcNames, bcValues, iter);
            VCircNew[0] = VCirc[0] + dt_circulation * ( Q("la", "lv") - Q("lv", "sa") );
            VCircNew[1] = VCirc[1] + dt_circulation * ( Q("ra", "rv") - Q("rv", "pa") );

            //============================================//
            // Residual computation
            //============================================//
            R = VFeNew - VCircNew;
            printCoupling("Residual Computation");

            //============================================//
            // Newton iterations
            //============================================//
            while ( R.norm() > couplingError )
            {
                ++iter;

                //============================================//
                // Jacobian circulation
                //============================================//

                // Left ventricle
                circulationSolver.iterate(dt_circulation, bcNames, perturbedPressureComp(bcValues, pPerturbationCirc, 0), iter);
                VCircPert[0] = VCirc[0] + dt_circulation * ( Q("la", "lv") - Q("lv", "sa") );
                VCircPert[1] = VCirc[1] + dt_circulation * ( Q("ra", "rv") - Q("rv", "pa") );

                JCirc(0,0) = ( VCircPert[0] - VCircNew[0] ) / pPerturbationCirc;
                JCirc(1,0) = ( VCircPert[1] - VCircNew[1] ) / pPerturbationCirc;

                // Right ventricle
                circulationSolver.iterate(dt_circulation, bcNames, perturbedPressureComp(bcValues, pPerturbationCirc, 1), iter);
                VCircPert[0] = VCirc[0] + dt_circulation * ( Q("la", "lv") - Q("lv", "sa") );
                VCircPert[1] = VCirc[1] + dt_circulation * ( Q("ra", "rv") - Q("rv", "pa") );

                JCirc(0,1) = ( VCircPert[0] - VCircNew[0] ) / pPerturbationCirc;
                JCirc(1,1) = ( VCircPert[1] - VCircNew[1] ) / pPerturbationCirc;


                //============================================//
                // Jacobian fe
                //============================================//

                const bool jFeIter ( ! ( k % (couplingJFeIter * mechanicsCouplingIter) ) );
                const bool jFeSubIter ( ! ( (iter - couplingJFeSubStart) % couplingJFeSubIter) && iter >= couplingJFeSubStart );
                const bool jFeEmpty ( JFe.norm() == 0 );

                if ( jFeIter || jFeSubIter || jFeEmpty )
                {
                    JFe *= 0.0;
                    dispCurrent = disp;

                    // Left ventricle
                    modifyPressureBC(perturbedPressureComp(bcValues, pPerturbationFe, 0));
                    solver.bcInterfacePtr() -> updatePhysicalSolverVariables();
                    solver.solveMechanicsLin();

                    VFePert[0] = LV.volume(disp, dETFESpace, - 1);
                    VFePert[1] = RV.volume(disp, dETFESpace, 1);

                    JFe(0,0) = ( VFePert[0] - VFeNew[0] ) / pPerturbationFe;
                    JFe(1,0) = ( VFePert[1] - VFeNew[1] ) / pPerturbationFe;

                    disp = dispCurrent;

                    // Right ventricle
                    modifyPressureBC(perturbedPressureComp(bcValues, pPerturbationFe, 1));
                    solver.bcInterfacePtr() -> updatePhysicalSolverVariables();
                    solver.solveMechanicsLin();

                    VFePert[0] = LV.volume(disp, dETFESpace, - 1);
                    VFePert[1] = RV.volume(disp, dETFESpace, 1);

                    JFe(0,1) = ( VFePert[0] - VFeNew[0] ) / pPerturbationFe;
                    JFe(1,1) = ( VFePert[1] - VFeNew[1] ) / pPerturbationFe;

                    disp = dispCurrent;
                }

                //============================================//
                // Update pressure b.c.
                //============================================//
                JR = JFe - JCirc;

                if ( JR.determinant() != 0 )
                {
                    dp = ( JR | R );
                    if ( iter > 5 ) dp *= 0.7;
                    if ( iter > 20 ) dp *= 0.5;
                    bcValues[0] -= std::min( std::max( dp(0) , - dpMax ) , dpMax );
                    bcValues[1] -= std::min( std::max( dp(1) , - dpMax ) , dpMax );
                }

                printCoupling("Pressure Update");

                //============================================//
                // Solve circulation
                //============================================//
                circulationSolver.iterate(dt_circulation, bcNames, bcValues, iter);
                VCircNew[0] = VCirc[0] + dt_circulation * ( Q("la", "lv") - Q("lv", "sa") );
                VCircNew[1] = VCirc[1] + dt_circulation * ( Q("ra", "rv") - Q("rv", "pa") );

                //============================================//
                // Solve mechanics
                //============================================//
                modifyPressureBC(bcValues);
                solver.bcInterfacePtr() -> updatePhysicalSolverVariables();
                solver.solveMechanics();

                VFeNew[0] = LV.volume(disp, dETFESpace, - 1);
                VFeNew[1] = RV.volume(disp, dETFESpace, 1);

                //============================================//
                // Residual update
                //============================================//
                R = VFeNew - VCircNew;
                printCoupling("Residual Update");
            }
thomaskummer's avatar
thomaskummer committed
841
842
843
844
845
846
847
848
849
850
851
852
853
854
 
            if ( 0 == comm->MyPID() )
            {
                std::cout << "\n*****************************************************************";
                std::cout << "\nCoupling converged after " << iter << " iteration" << ( iter > 1 ? "s" : "" );
                std::cout << "\n*****************************************************************\n\n";
            }
            
            //============================================//
            // Update volume variables
            //============================================//
            VCirc = VCircNew;
            VFe = VFeNew;
            
thomaskummer's avatar
thomaskummer committed
855
856
857
858
859
            //============================================//
            // Export circulation solution
            //============================================//
            if ( 0 == comm->MyPID() ) circulationSolver.exportSolution( circulationOutputFile );
            
thomaskummer's avatar
thomaskummer committed
860
        }
thomaskummer's avatar
thomaskummer committed
861
862
863
864
        
        //============================================//
        // Export FE-solution
        //============================================//
thomaskummer's avatar
thomaskummer committed
865
        bool save ( std::abs(std::remainder(t, dt_save)) < 0.01 );
thomaskummer's avatar
thomaskummer committed
866
        if ( save ) solver.saveSolution(t);
thomaskummer's avatar
thomaskummer committed
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881

    }

    
    //============================================//
    // Close all exporters
    //============================================//
    solver.closeExporters();
    

#ifdef HAVE_MPI
    MPI_Finalize();
#endif
    return 0;
}