main.cpp 20 KB
Newer Older
Kirill Terekhov's avatar
Kirill Terekhov 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
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

#include "inmost.h"
using namespace INMOST;

#ifndef M_PI
#define M_PI 3.141592653589
#endif

#if defined(USE_MPI)
#define BARRIER MPI_Barrier(MPI_COMM_WORLD);
#else
#define BARRIER
#endif

//shortcuts
typedef Storage::real real;
typedef Storage::integer integer;
typedef Storage::enumerator enumerator;
typedef Storage::real_array real_array;
typedef Storage::var_array var_array;

const real reg_abs = 1.0e-12; //regularize abs(x) as sqrt(x*x+reg_abs)
const real reg_div = 1.0e-15; //regularize (|x|+reg_div)/(|x|+|y|+2*reg_div) to reduce to 1/2 when |x| ~= |y| ~= 0


Kirill Terekhov's avatar
Kirill Terekhov committed
30
#define OPTIMIZATION
Kirill Terekhov's avatar
Kirill Terekhov committed
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
94
95
96
97
98
99

int main(int argc,char ** argv)
{
	Solver::Initialize(&argc,&argv,""); // Initialize the solver and MPI activity
#if defined(USE_PARTITIONER)
	Partitioner::Initialize(&argc,&argv); // Initialize the partitioner activity
#endif
	if( argc > 1 )
	{
    double ttt; // Variable used to measure timing
    bool repartition = false; // Is it required to redistribute the mesh?
		Mesh * m = new Mesh(); // Create an empty mesh
    { // Load the mesh
		  ttt = Timer();
		  m->SetCommunicator(INMOST_MPI_COMM_WORLD); // Set the MPI communicator for the mesh
      if( m->GetProcessorRank() == 0 ) std::cout << "Processors: " << m->GetProcessorsNumber() << std::endl;
		  if( m->isParallelFileFormat(argv[1]) ) //The format is 
		  {
			  m->Load(argv[1]); // Load mesh from the parallel file format
			  repartition = true; // Ask to repartition the mesh
		  }
		  else if( m->GetProcessorRank() == 0 ) m->Load(argv[1]); // Load mesh from the serial file format
		  BARRIER
		  if( m->GetProcessorRank() == 0 ) std::cout << "Load the mesh: " << Timer()-ttt << std::endl;
    }
		
		
#if defined(USE_PARTITIONER)
    if (m->GetProcessorsNumber() > 1 && !repartition) // Currently only non-distributed meshes are supported by Inner_RCM partitioner
    {
      { // Compute mesh partitioning
			  ttt = Timer();
			  Partitioner p(m); //Create Partitioning object
			  p.SetMethod(Partitioner::Inner_RCM,repartition ? Partitioner::Repartition : Partitioner::Partition); // Specify the partitioner
			  p.Evaluate(); // Compute the partitioner and store new processor ID in the mesh
			  BARRIER
			  if( m->GetProcessorRank() == 0 ) std::cout << "Evaluate: " << Timer()-ttt << std::endl;
      }

      { //Distribute the mesh
			  ttt = Timer();
			  m->Redistribute(); // Redistribute the mesh data
			  m->ReorderEmpty(CELL|FACE|EDGE|NODE); // Clean the data after reordring
			  BARRIER
			  if( m->GetProcessorRank() == 0 ) std::cout << "Redistribute: " << Timer()-ttt << std::endl;
      }
		}
#endif

    { // prepare geometrical data on the mesh
      ttt = Timer();
		  Mesh::GeomParam table;
		  table[CENTROID]    = CELL | FACE; //Compute averaged center of mass
		  table[NORMAL]      = FACE;        //Compute normals
		  table[ORIENTATION] = FACE;        //Check and fix normal orientation
		  table[MEASURE]     = CELL | FACE; //Compute volumes and areas
		  //table[BARYCENTER]  = CELL | FACE; //Compute volumetric center of mass
		  m->PrepareGeometricData(table); //Ask to precompute the data
		  BARRIER
		  if( m->GetProcessorRank() == 0 ) std::cout << "Prepare geometric data: " << Timer()-ttt << std::endl;
    }
		
    // data tags for
		Tag tag_P;  // Pressure
		Tag tag_K;  // Diffusion tensor
    Tag tag_F;  // Forcing term
    Tag tag_BC; // Boundary conditions
    Tag tag_W;  // Gradient matrix acting on harmonic points on faces and returning gradient on faces

Kirill Terekhov's avatar
Kirill Terekhov committed
100
    
Kirill Terekhov's avatar
Kirill Terekhov committed
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
    if( m->GetProcessorsNumber() > 1 ) //skip for one processor job
    { // Exchange ghost cells
		  ttt = Timer();
		  m->ExchangeGhost(1,FACE); // Produce layer of ghost cells
		  BARRIER
		  if( m->GetProcessorRank() == 0 ) std::cout << "Exchange ghost: " << Timer()-ttt << std::endl;
    }
    
    { //initialize data
		  if( m->HaveTag("PERM") ) // is diffusion tensor already defined on the mesh? (PERM from permeability)
        tag_K = m->GetTag("PERM"); // get the diffusion tensor
      
      if( !tag_K.isValid() || !tag_K.isDefined(CELL) ) // diffusion tensor was not initialized or was not defined on cells.
      {
        tag_K = m->CreateTag("PERM",DATA_REAL,CELL,NONE,6); // create a new tag for symmetric diffusion tensor K
Kirill Terekhov's avatar
Kirill Terekhov committed
116
        for( int q = 0; q < m->CellLastLocalID(); ++q ) if( m->isValidCell(q) ) // loop over mesh cells
Kirill Terekhov's avatar
Kirill Terekhov committed
117
        {
Kirill Terekhov's avatar
Kirill Terekhov committed
118
          Cell cell = m->CellByLocalID(q);
Kirill Terekhov's avatar
Kirill Terekhov committed
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
          real_array K = cell->RealArray(tag_K);
          // assign a symmetric positive definite tensor K
				  K[0] = 1.0; //XX
          K[1] = 0.0; //XY
          K[2] = 0.0; //XZ
          K[3] = 1.0; //YY
          K[4] = 0.0; //YZ
          K[5] = 1.0; //ZZ
        }

        m->ExchangeData(tag_K,CELL,0); //Exchange diffusion tensor
      }

      if( m->HaveTag("PRESSURE") ) //Is there a pressure on the mesh?
        tag_P = m->GetTag("PRESSURE"); //Get the pressure
      
      if( !tag_P.isValid() || !tag_P.isDefined(CELL) ) // Pressure was not initialized or was not defined on nodes
      {
        srand(1); // Randomization
Kirill Terekhov's avatar
Kirill Terekhov committed
138
139
        tag_P = m->CreateTag("PRESSURE",DATA_REAL,CELL|FACE,NONE,1); // Create a new tag for the pressure
        for(Mesh::iteratorElement e = m->BeginElement(CELL|FACE); e != m->EndElement(); ++e) //Loop over mesh cells
Kirill Terekhov's avatar
Kirill Terekhov committed
140
            e->Real(tag_P) = 0;//(rand()*1.0)/(RAND_MAX*1.0); // Prescribe random value in [0,1]
Kirill Terekhov's avatar
Kirill Terekhov committed
141
142
      }

Kirill Terekhov's avatar
Kirill Terekhov committed
143
144
145
146
      if( !tag_P.isDefined(FACE) )
      {
        tag_P = m->CreateTag("PRESSURE",DATA_REAL,FACE,NONE,1);
        for(Mesh::iteratorElement e = m->BeginElement(FACE); e != m->EndElement(); ++e) //Loop over mesh cells
Kirill Terekhov's avatar
Kirill Terekhov committed
147
            e->Real(tag_P) = 0;//(rand()*1.0)/(RAND_MAX*1.0); // Prescribe random value in [0,1]
Kirill Terekhov's avatar
Kirill Terekhov committed
148
149
150
      }


Kirill Terekhov's avatar
Kirill Terekhov committed
151
152
153
154
155
156
157
      
      if( m->HaveTag("BOUNDARY_CONDITION") ) //Is there boundary condition on the mesh?
      {
        tag_BC = m->GetTag("BOUNDARY_CONDITION");
        //initialize unknowns at boundary
      }
      m->ExchangeData(tag_P,CELL|FACE,0); //Synchronize initial solution with boundary unknowns
Kirill Terekhov's avatar
Kirill Terekhov committed
158
159
      tag_W = m->CreateTag("nKGRAD",DATA_REAL,CELL,NONE);
      ttt = Timer();
Kirill Terekhov's avatar
Kirill Terekhov committed
160
      //Assemble gradient matrix W on cells
Kirill Terekhov's avatar
Kirill Terekhov committed
161
#if defined(USE_OMP)
Kirill Terekhov's avatar
Kirill Terekhov committed
162
//#pragma omp parallel for
Kirill Terekhov's avatar
Kirill Terekhov committed
163
#endif
Kirill Terekhov's avatar
Kirill Terekhov committed
164
      for( int q = 0; q < m->CellLastLocalID(); ++q ) if( m->isValidCell(q) )
Kirill Terekhov's avatar
Kirill Terekhov committed
165
      {
Kirill Terekhov's avatar
Kirill Terekhov committed
166
        Cell cell = m->CellByLocalID(q);
Kirill Terekhov's avatar
Kirill Terekhov committed
167
        real xP[3]; //center of the cell
Kirill Terekhov's avatar
Kirill Terekhov committed
168
        real yF[3]; //center of the face
Kirill Terekhov's avatar
Kirill Terekhov committed
169
        real nF[3]; //normal to the face
Kirill Terekhov's avatar
Kirill Terekhov committed
170
171
        real aF; //area of the face
        real vP = cell->Volume(); //volume of the cell
Kirill Terekhov's avatar
Kirill Terekhov committed
172
173
        cell->Centroid(xP);
        ElementArray<Face> faces = cell->getFaces(); //obtain faces of the cell
Kirill Terekhov's avatar
Kirill Terekhov committed
174
        int NF = (int)faces.size(); //number of faces;
175
        rMatrix K = rMatrix::FromTensor(cell->RealArrayDF(tag_K).data(),cell->RealArrayDF(tag_K).size()); //get permeability for the cell
Kirill Terekhov's avatar
Kirill Terekhov committed
176
177
178
179
        //rMatrix U,S,V;
        //K0.SVD(U,S,V);
        //for(int k = 0; k < 3; ++k) S(k,k) = sqrt(S(k,k));
        //rMatrix K = U*S*V;
Kirill Terekhov's avatar
Kirill Terekhov committed
180
        rMatrix nKGRAD(NF,NF), NK(NF,3), R(NF,3), D(NF,NF), U(NF,NF), Areas(NF,1); //big gradient matrix, co-normals, directions
Kirill Terekhov's avatar
Kirill Terekhov committed
181
        for(int k = 0; k < NF; ++k) //loop over faces
Kirill Terekhov's avatar
Kirill Terekhov committed
182
        {
Kirill Terekhov's avatar
Kirill Terekhov committed
183
184
185
          aF = faces[k].Area();
          faces[k].Centroid(yF);
          faces[k].OrientedUnitNormal(cell->self(),nF);
Kirill Terekhov's avatar
Kirill Terekhov committed
186
          // assemble matrix of directions
Kirill Terekhov's avatar
Kirill Terekhov committed
187
188
189
          R(k,0) = (yF[0]-xP[0])*aF;
          R(k,1) = (yF[1]-xP[1])*aF;
          R(k,2) = (yF[2]-xP[2])*aF;
Kirill Terekhov's avatar
Kirill Terekhov committed
190
          // assemble matrix of co-normals 
191
          rMatrix nK = rMatrix::FromVector(nF,3).Transpose()*K;
Kirill Terekhov's avatar
Kirill Terekhov committed
192
193
194
195
          NK(k,0) = nK(0,0);
          NK(k,1) = nK(0,1);
          NK(k,2) = nK(0,2);
        } //end of loop over faces
Kirill Terekhov's avatar
Kirill Terekhov committed
196
          rMatrix SU,SS,SV;
Kirill Terekhov's avatar
Kirill Terekhov committed
197
        nKGRAD = NK*(NK.Transpose()*R).Invert(true).first*NK.Transpose(); //stability part
Kirill Terekhov's avatar
Kirill Terekhov committed
198
199
200
201
202
203
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
        /*
          std::cout << "W" << std::endl;
          nKGRAD.Print();
          nKGRAD.SVD(SU,SS,SV);
          std::cout << "U" << std::endl;
          SU.Print();
          std::cout << "S" << std::endl;
          SS.Print();
          std::cout << "V" << std::endl;
          SV.Print();
          std::cout << "Check " << (nKGRAD - SU*SS*SV.Transpose()).FrobeniusNorm() << std::endl;
        */
          
          int rank = 0; //size of matrix U
          
          { //Retrive orthogonal to R matrix D
              //Symmetric orthogonal matrix
              rMatrix DUD = (rMatrix::Unit(NF) - R*(R.Transpose()*R).Invert(true).first*R.Transpose());
              //perfrom singular value decomposition
              //S should be unity matrix with rank NF-3
              rMatrix DUD_U,DUD_S,DUD_V;
              DUD.SVD(DUD_U,DUD_S,DUD_V);
              //compute the rank
              for(int q = 0; q < NF; ++q)
                  if( DUD_S(q,q) > 1.0e-2 )
                      rank++;
              rank = NF-3;
              if( rank != NF-3)
              {
                  std::cout << "rank: " << rank << " expected " << NF-3 << std::endl;
                  DUD_S.Print();
              }
              //chop matrix to the full rank
              DUD_S.RemoveSubset(rank,NF,rank,NF);
              DUD_V.RemoveColumns(rank,NF);
              //assign the matrix
              D = DUD_V;
              U = DUD_S;
          }
          //std::cout << "D" << std::endl;
          //D.Print();
          //std::cout << "U" << std::endl;
          //U.Print();
          //std::cout << "DtR" << std::endl;
          //(D.Transpose()*R).Print();
          
          U *=(2.0/(static_cast<real>(NF)*vP)*(NK*K.Invert(true).first*NK.Transpose()).Trace());
Kirill Terekhov's avatar
Kirill Terekhov committed
245
#if defined(OPTIMIZATION)
Kirill Terekhov's avatar
Kirill Terekhov committed
246
          { //Make W a Z-matrix
Kirill Terekhov's avatar
Kirill Terekhov committed
247
              vMatrix vL(rank,rank), vD(rank,rank), vW(NF,NF);
Kirill Terekhov's avatar
Kirill Terekhov committed
248
              int unk = 0;
Kirill Terekhov's avatar
Kirill Terekhov committed
249
250
251
              // U = L*D*L^T
              vD.Zero();
              //diagonal D
Kirill Terekhov's avatar
Kirill Terekhov committed
252
              for(int i = 0; i < rank; ++i)
Kirill Terekhov's avatar
Kirill Terekhov committed
253
254
255
256
257
258
259
260
261
262
              {
                  vD(i,i) = unknown(U(i,i),unk);
                  unk++;
              }
              //off-diagonal 
              vL.Zero();
              for(int i = 0; i < rank; ++i) 
                vL(i,i) = 1.0;
              for(int i = 1; i < rank; ++i)
                  for(int j = 0; j < i; ++j)
Kirill Terekhov's avatar
Kirill Terekhov committed
263
                  {
Kirill Terekhov's avatar
Kirill Terekhov committed
264
                      vL(i,j) = unknown(0.0,unk);
Kirill Terekhov's avatar
Kirill Terekhov committed
265
266
267
268
                      unk++;
                  }
              //std::cout << "unknowns: " << unk << std::endl;
              variable phi,s;
Kirill Terekhov's avatar
Kirill Terekhov committed
269
270
271
272
273
              //std::cout << "vD" << std::endl;
              //vD.Print();
              //std::cout << "vL" << std::endl;
              //vL.Print();

Kirill Terekhov's avatar
Kirill Terekhov committed
274
275
276
              int iter = 0;
              do
              { //Optimize U matrix
Kirill Terekhov's avatar
Kirill Terekhov committed
277
                  vW = nKGRAD + D*vL*vD*vL.Transpose()*D.Transpose();
Kirill Terekhov's avatar
Kirill Terekhov committed
278
279
280
281
                  //construct minimization functional phi(W)
                  phi = 0.0;
                  for(int i = 0; i < NF; ++i)
                  {
Kirill Terekhov's avatar
Kirill Terekhov committed
282
                      //phi += 1.0 / (vW(i,i)*vW(i,i));
Kirill Terekhov's avatar
Kirill Terekhov committed
283
284
285
286
                      s = vW(i,i)*faces[i].Area();
                      for(int j = 0; j < NF; ++j) if( i != j )
                      {
                          s += vW(i,j)*faces[j].Area();
Kirill Terekhov's avatar
Kirill Terekhov committed
287
                          phi += (vW(i,j)+fabs(vW(i,j)))*(vW(i,j)+fabs(vW(i,j)));
Kirill Terekhov's avatar
Kirill Terekhov committed
288
                      }
Kirill Terekhov's avatar
Kirill Terekhov committed
289
                      phi += (s - fabs(s))*(s - fabs(s));
Kirill Terekhov's avatar
Kirill Terekhov committed
290
291
292
293
294
295
296
                  }
                  Sparse::Row & der = phi.GetRow(); //row of derivatives
                  //std::sort(der.Begin(),der.End());
                  //for(int i = 0; i < der.Size(); ++i)
                  //    std::cout << "(" << der.GetIndex(i) << "," << der.GetValue(i) << ") ";
                  //std::cout<<std::endl;
                  int q = 0;
Kirill Terekhov's avatar
Kirill Terekhov committed
297
298
299
                  real a = 0.00005;
                  real minvD = 1.0e20;
                  //diagonal
Kirill Terekhov's avatar
Kirill Terekhov committed
300
                  for(int i = 0; i < rank; ++i)
Kirill Terekhov's avatar
Kirill Terekhov committed
301
302
303
304
305
306
307
308
309
310
                  {
                    real d = a*der[q++];
                    //if( vD(i,i)-d > 0.0 ) 
                      vD(i,i) -= d;
                    if( vD(i,i) < minvD ) minvD = get_value(vD(i,i));
                  }
                  std::cout << "[" << iter << "] phi: " << get_value(phi) << " minD " << minvD << std::endl;
                  //off-diagonal
                  for(int i = 1; i < rank; ++i)
                      for(int j = 0; j < i; ++j)
Kirill Terekhov's avatar
Kirill Terekhov committed
311
312
                      {
                          real d = a*der[q++];
Kirill Terekhov's avatar
Kirill Terekhov committed
313
                          vL(i,j) -= d;
Kirill Terekhov's avatar
Kirill Terekhov committed
314
315
                      }
                  iter++;
Kirill Terekhov's avatar
Kirill Terekhov committed
316
317
318
319
320
321
322
323
324
325
                  //std::cout << "vD" << std::endl;
                  //vD.Print();
                  //std::cout << "vL" << std::endl;
                  //vL.Print();
              } while(iter < 100 && phi > 1.0e-3);
              {
                vMatrix vU = vL*vD*vL.Transpose();
                for(int i = 0; i < rank; ++i)
                    for(int j = 0; j < rank; ++j)
                        U(i,j) = get_value(vU(i,j));
Kirill Terekhov's avatar
Kirill Terekhov committed
326
327
328
329
330
331
              }
              //std::cout << "U: " << std::endl;
              //U.Print();
              
              
          }
Kirill Terekhov's avatar
Kirill Terekhov committed
332
#endif
Kirill Terekhov's avatar
Kirill Terekhov committed
333
334
335
336
337
338
339
340
341
          //std::cout << "UDtR" << std::endl;
          //(U*D.Transpose()*R).Print();

        nKGRAD += D*U*D.Transpose();
          
          //std::cout << "W: " << std::endl;
          //nKGRAD.Print();

          real_array W = cell->RealArrayDV(tag_W); //access data structure for gradient matrix in mesh
Kirill Terekhov's avatar
Kirill Terekhov committed
342
        W.resize(NF*NF); //resize the structure
Kirill Terekhov's avatar
Kirill Terekhov committed
343
        std::copy(nKGRAD.data(),nKGRAD.data()+NF*NF,W.data()); //write down the gradient matrix
Kirill Terekhov's avatar
Kirill Terekhov committed
344
      } //end of loop over cells
Kirill Terekhov's avatar
Kirill Terekhov committed
345
      std::cout << "Construct W matrix: " << Timer() - ttt << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
346
347
348

      if( m->HaveTag("FORCE") ) //Is there force on the mesh?
      {
Kirill Terekhov's avatar
Kirill Terekhov committed
349
350
        tag_F = m->GetTag("FORCE"); //initial force
        assert(tag_F.isDefined(CELL)); //assuming it was defined on cells
Kirill Terekhov's avatar
Kirill Terekhov committed
351
352
353
354
355
      } // end of force
    } //end of initialize data

   
		
Kirill Terekhov's avatar
Kirill Terekhov committed
356
357
    integer nit = 0;
    ttt = Timer();
Kirill Terekhov's avatar
Kirill Terekhov committed
358
359
360

    { //Main loop for problem solution
      Automatizator aut(m); // declare class to help manage unknowns
Kirill Terekhov's avatar
Kirill Terekhov committed
361
      Automatizator::MakeCurrent(&aut);
Kirill Terekhov's avatar
Kirill Terekhov committed
362
      dynamic_variable P(aut,aut.RegisterDynamicTag(tag_P,CELL|FACE)); //register pressure as primary unknown
Kirill Terekhov's avatar
Kirill Terekhov committed
363
      variable calc; //declare variable that helps calculating the value with variations
Kirill Terekhov's avatar
Kirill Terekhov committed
364
365
366
      aut.EnumerateDynamicTags(); //enumerate all primary variables

     
Kirill Terekhov's avatar
Kirill Terekhov committed
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
      Residual R("",aut.GetFirstIndex(),aut.GetLastIndex());
      Sparse::Vector Update  ("",aut.GetFirstIndex(),aut.GetLastIndex()); //vector for update
      
      {//Annotate matrix
        for( int q = 0; q < m->CellLastLocalID(); ++q ) if( m->isValidCell(q) )
        {
          Cell cell = m->CellByLocalID(q);
          R.GetJacobian().Annotation(P.Index(cell)) = "Cell-centered pressure value";
        }
        for( int q = 0; q < m->FaceLastLocalID(); ++q ) if( m->isValidFace(q) )
        {
          Face face = m->FaceByLocalID(q);
          if( tag_BC.isValid() && face.HaveData(tag_BC) )
            R.GetJacobian().Annotation(P.Index(face)) = "Pressure guided by boundary condition";
          else
            R.GetJacobian().Annotation(P.Index(face)) = "Interface pressure";
        }
      }
Kirill Terekhov's avatar
Kirill Terekhov committed
385

Kirill Terekhov's avatar
Kirill Terekhov committed
386
387
      
      
Kirill Terekhov's avatar
Kirill Terekhov committed
388
389
      do
      {
Kirill Terekhov's avatar
Kirill Terekhov committed
390
        R.Clear(); //clean up the residual
Kirill Terekhov's avatar
Kirill Terekhov committed
391
        //First we need to evaluate the gradient at each cell for scaling matrix D
Kirill Terekhov's avatar
Kirill Terekhov committed
392
393
394
#if defined(USE_OMP)
#pragma omp parallel for
#endif
Kirill Terekhov's avatar
Kirill Terekhov committed
395
        for( int q = 0; q < m->CellLastLocalID(); ++q ) if( m->isValidCell(q) ) //loop over cells
Kirill Terekhov's avatar
Kirill Terekhov committed
396
        {
Kirill Terekhov's avatar
Kirill Terekhov committed
397
          Cell cell = m->CellByLocalID(q);
Kirill Terekhov's avatar
Kirill Terekhov committed
398
          ElementArray<Face> faces = cell->getFaces(); //obtain faces of the cell
Kirill Terekhov's avatar
Kirill Terekhov committed
399
          int NF = (int)faces.size();
Kirill Terekhov's avatar
Kirill Terekhov committed
400
          rMatrix nKGRAD(cell->RealArrayDV(tag_W).data(),NF,NF); //Matrix for gradient
Kirill Terekhov's avatar
Kirill Terekhov committed
401
          vMatrix pF(NF,1); //vector of pressure differences on faces
Kirill Terekhov's avatar
Kirill Terekhov committed
402
          vMatrix FLUX(NF,1); //computed flux on faces
Kirill Terekhov's avatar
Kirill Terekhov committed
403
          for(int k = 0; k < NF; ++k)
Kirill Terekhov's avatar
Kirill Terekhov committed
404
405
            pF(k,0) = (P(faces[k]) - P(cell))*faces[k].Area();
          FLUX = nKGRAD*pF; //fluxes on faces
Kirill Terekhov's avatar
Kirill Terekhov committed
406
          for(int k = 0; k < NF; ++k) //loop over faces of current cell
Kirill Terekhov's avatar
Kirill Terekhov committed
407
            R[P.Index(cell)] += FLUX(k,0)*faces[k].Area();
Kirill Terekhov's avatar
Kirill Terekhov committed
408
          for(int k = 0; k < NF; ++k) //loop over faces of current cell
Kirill Terekhov's avatar
Kirill Terekhov committed
409
          {
Kirill Terekhov's avatar
Kirill Terekhov committed
410
            int index = P.Index(faces[k]);
Kirill Terekhov's avatar
Kirill Terekhov committed
411
            R[index].Lock();
Kirill Terekhov's avatar
Kirill Terekhov committed
412
            if( tag_BC.isValid() && faces[k].HaveData(tag_BC) )
Kirill Terekhov's avatar
Kirill Terekhov committed
413
            {
Kirill Terekhov's avatar
Kirill Terekhov committed
414
              real_array BC = faces[k].RealArray(tag_BC);
Kirill Terekhov's avatar
Kirill Terekhov committed
415
              R[index] -= BC[0]*P(faces[k]) + BC[1]*FLUX(k,0) - BC[2];
Kirill Terekhov's avatar
Kirill Terekhov committed
416
            }
Kirill Terekhov's avatar
Kirill Terekhov committed
417
            else
Kirill Terekhov's avatar
Kirill Terekhov committed
418
419
              R[index] -= FLUX(k,0);
            R[index].Unlock();
Kirill Terekhov's avatar
Kirill Terekhov committed
420
          }
Kirill Terekhov's avatar
Kirill Terekhov committed
421
422
        } //end of loop over cells

Kirill Terekhov's avatar
Kirill Terekhov committed
423
424
425

        if( tag_F.isValid() )
        {
Kirill Terekhov's avatar
Kirill Terekhov committed
426
427
428
#if defined(USE_OMP)
#pragma omp parallel for
#endif
Kirill Terekhov's avatar
Kirill Terekhov committed
429
430
431
          for( int q = 0; q < m->CellLastLocalID(); ++q ) if( m->isValidCell(q) )
          {
            Cell cell = m->CellByLocalID(q);
Kirill Terekhov's avatar
Kirill Terekhov committed
432
            if( cell->HaveData(tag_F) ) R[P.Index(cell)] += cell->Real(tag_F)*cell->Volume();
Kirill Terekhov's avatar
Kirill Terekhov committed
433
          }
Kirill Terekhov's avatar
Kirill Terekhov committed
434
        }
Kirill Terekhov's avatar
Kirill Terekhov committed
435
436
437


        R.Rescale();
Kirill Terekhov's avatar
Kirill Terekhov committed
438
439
        R.GetJacobian().Save("jacobian.mtx");
        R.GetResidual().Save("residual.mtx");
Kirill Terekhov's avatar
Kirill Terekhov committed
440
441


Kirill Terekhov's avatar
Kirill Terekhov committed
442
443
444
        std::cout << "Nonlinear residual: " << R.Norm() << "\t\t" << std::endl;

        if( R.Norm() < 1.0e-4 ) break;
Kirill Terekhov's avatar
Kirill Terekhov committed
445

Kirill Terekhov's avatar
Kirill Terekhov committed
446
        Solver S(Solver::INNER_ILU2);
Kirill Terekhov's avatar
Kirill Terekhov committed
447
        S.SetMatrix(R.GetJacobian());
Kirill Terekhov's avatar
Kirill Terekhov committed
448
449
        S.SetParameterReal("relative_tolerance", 1.0e-14);
        S.SetParameterReal("absolute_tolerance", 1.0e-12);
Kirill Terekhov's avatar
Kirill Terekhov committed
450
        S.SetParameterReal("drop_tolerance", 1.0e-3);
Kirill Terekhov's avatar
Kirill Terekhov committed
451
        S.SetParameterReal("reuse_tolerance", 1.0e-4);
Kirill Terekhov's avatar
Kirill Terekhov committed
452
        //std::fill(Update.Begin(),Update.End(),0.0);
Kirill Terekhov's avatar
Kirill Terekhov committed
453
        if( S.Solve(R.GetResidual(),Update) )
Kirill Terekhov's avatar
Kirill Terekhov committed
454
        {
Kirill Terekhov's avatar
Kirill Terekhov committed
455
456
457
#if defined(USE_OMP)
#pragma omp parallel for
#endif
Kirill Terekhov's avatar
Kirill Terekhov committed
458
459
460
461
462
          for( int q = 0; q < m->CellLastLocalID(); ++q ) if( m->isValidCell(q) )
          {
            Cell cell = m->CellByLocalID(q);
            cell->Real(tag_P) -= Update[P.Index(cell)];
          }
Kirill Terekhov's avatar
Kirill Terekhov committed
463
464
465
#if defined(USE_OMP)
#pragma omp parallel for
#endif
Kirill Terekhov's avatar
Kirill Terekhov committed
466
467
468
469
470
          for( int q = 0; q < m->FaceLastLocalID(); ++q ) if( m->isValidFace(q) )
          {
            Face face = m->FaceByLocalID(q);
            face->Real(tag_P) -= Update[P.Index(face)];
          }
Kirill Terekhov's avatar
Kirill Terekhov committed
471
472
473
474
475
          {
            std::stringstream str;
            str << "iter" << nit << ".vtk";
            m->Save(str.str());
          }
Kirill Terekhov's avatar
Kirill Terekhov committed
476
477
478
479
        }
        else
        {
          std::cout << "Unable to solve: " << S.GetReason() << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
480
            break;
Kirill Terekhov's avatar
Kirill Terekhov committed
481
        }
Kirill Terekhov's avatar
Kirill Terekhov committed
482
483
484
485
        ++nit;
      } while( R.Norm() > 1.0e-4 && nit < 10); //check the residual norm
    }
    std::cout << "Solved problem in " << Timer() - ttt << " seconds with " << nit << " iterations " << std::endl;
Kirill Terekhov's avatar
Kirill Terekhov committed
486
487
488
489
490
491
492
493
494
495
496
497
    
    if( m->HaveTag("REFERENCE_SOLUTION") )
    {
      Tag tag_E = m->CreateTag("ERRROR",DATA_REAL,CELL,NONE,1);
      Tag tag_R = m->GetTag("REFERENCE_SOLUTION");
      real C, L2, volume;
      C = L2 = volume = 0.0;
      for( int q = 0; q < m->CellLastLocalID(); ++q ) if( m->isValidCell(q) )
      {
        Cell cell = m->CellByLocalID(q);
        real err = cell->Real(tag_P) - cell->Real(tag_R);
        real vol = cell->Volume();
Kirill Terekhov's avatar
Kirill Terekhov committed
498
        if( C < fabs(err) ) C = fabs(err);
Kirill Terekhov's avatar
Kirill Terekhov committed
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
        L2 += err*err*vol;
        volume += vol;
        cell->Real(tag_E) = err;
      }
      L2 = sqrt(L2/volume);
      std::cout << "Error on cells, C-norm " << C << " L2-norm " << L2 << std::endl;
      C = L2 = volume = 0.0;
      if( tag_R.isDefined(FACE) )
      {
        tag_E = m->CreateTag("ERRROR",DATA_REAL,FACE,NONE,1);
        for( int q = 0; q < m->FaceLastLocalID(); ++q ) if( m->isValidFace(q) )
        {
          Face face = m->FaceByLocalID(q);
          real err = face->Real(tag_P) - face->Real(tag_R);
          real vol = (face->BackCell()->Volume() + (face->FrontCell().isValid() ? face->FrontCell()->Volume() : 0))*0.5;
Kirill Terekhov's avatar
Kirill Terekhov committed
514
          if( C < fabs(err) ) C = fabs(err);
Kirill Terekhov's avatar
Kirill Terekhov committed
515
516
517
518
519
520
521
522
523
524
525
526
          L2 += err*err*vol;
          volume += vol;
          face->Real(tag_E) = err;
        }
        L2 = sqrt(L2/volume);
        std::cout << "Error on faces, C-norm " << C << " L2-norm " << L2 << std::endl;
      }
      else std::cout << "Reference solution was not defined on faces" << std::endl;
    }

    m->Save("out.gmv");
    m->Save("out.vtk");
Kirill Terekhov's avatar
Kirill Terekhov committed
527
528
529
530
531
532
533
534
535
536
537
538
539
540

		delete m; //clean up the mesh
	}
	else
	{
		std::cout << argv[0] << " mesh_file" << std::endl;
	}

#if defined(USE_PARTITIONER)
	Partitioner::Finalize(); // Finalize the partitioner activity
#endif
	Solver::Finalize(); // Finalize solver and close MPI activity
	return 0;
}