Source

pflotran-dev / src / pflotran / mfd.F90

   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
  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
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 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
 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
 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
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 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
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 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
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 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
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 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
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 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
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 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
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 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
 688
 689
 690
 691
 692
 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
 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
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
module MFD_module


  use Connection_module
  use Grid_module
  use MFD_Aux_module
  implicit none
  
  private 

#include "definitions.h"
#include "finclude/petscvec.h"
#include "finclude/petscvec.h90"
#include "finclude/petscis.h"
#include "finclude/petscis.h90"
#include "finclude/petscmat.h"
#include "finclude/petscmat.h90"
#include "finclude/petscviewer.h"
#include "finclude/petsclog.h"


  public :: MFDCreateJacobian, &
            MFDInitializeMassMatrices, MFDAuxGenerateStiffMatrix,&
            MFDAuxGenerateRhs, MFDAuxReconstruct, MFDAuxFluxes, MFDComputeDensity,&
            MFDAuxJacobianLocal, MFDAuxUpdateCellPressure, MFDCreateJacobianLP, &
            MFDAuxGenerateRhs_LP, MFDAuxJacobianLocal_LP

contains

! ************************************************************************** !
!
! MFDCreateJacobian: Creates a Jacobian matrix for  the faced based dof
! author: Daniil Svyatskiy 
! date: 05/14/10
!
! ************************************************************************** !
subroutine MFDCreateJacobian(grid, mfd_aux, mat_type, J, option)

 use Option_module
 use Grid_module
 use MFD_Aux_module

  implicit none

#include "finclude/petscvec.h"
#include "finclude/petscvec.h90"
#include "finclude/petscmat.h"
#include "finclude/petscmat.h90"
#include "finclude/petscdm.h"
#include "finclude/petscdm.h90"
#include "finclude/petscis.h"
#include "finclude/petscis.h90"
#include "finclude/petscviewer.h"

  type(grid_type) :: grid
  type(mfd_type) :: mfd_aux
  type(option_type) :: option
  MatType :: mat_type
  Mat :: J


  type(mfd_auxvar_type), pointer :: aux_var
  PetscInt, allocatable :: d_nnz(:), o_nnz(:)
  PetscInt :: icell, iface
  PetscInt :: ghost_face_id, local_face_id, ghost_face_id_n, local_face_id_n
  PetscInt :: icount, jcount
  PetscInt :: ndof_local
  PetscErrorCode :: ierr

  allocate(d_nnz(grid%nlmax_faces))
  allocate(o_nnz(grid%nlmax_faces))

  d_nnz = 1 ! start 1 since diagonal connection to self
  o_nnz = 0

  do icell = 1, grid%nlmax
    aux_var => MFD_aux%aux_vars(icell)
    do icount = 1, aux_var%numfaces
      ghost_face_id = aux_var%face_id_gh(icount)
      local_face_id = grid%fG2L(ghost_face_id)
      if (local_face_id > 0) then
        do jcount = 1, aux_var%numfaces
          if (icount == jcount) cycle
          ghost_face_id_n = aux_var%face_id_gh(jcount)
          local_face_id_n = grid%fG2L(ghost_face_id_n)
          if (local_face_id_n > 0) then
             d_nnz(local_face_id) = d_nnz(local_face_id) + 1
          else
             o_nnz(local_face_id) = o_nnz(local_face_id) + 1
          endif
        enddo
      endif
    enddo
  enddo

  ndof_local = mfd_aux%ndof * grid%nlmax_faces

  if (option%mycommsize > 1) then
    select case(mat_type)
      case(MATAIJ)
        d_nnz = d_nnz*mfd_aux%ndof
        o_nnz = o_nnz*mfd_aux%ndof
        call MatCreateAIJ(option%mycomm,ndof_local,ndof_local, &
                             PETSC_DETERMINE,PETSC_DETERMINE, &
                             PETSC_NULL_INTEGER,d_nnz, &
                             PETSC_NULL_INTEGER,o_nnz,J,ierr)
        call MatSetLocalToGlobalMapping(J,mfd_aux%mapping_ltog_faces, mfd_aux%mapping_ltog_faces, ierr)
        call MatSetLocalToGlobalMappingBlock(J,mfd_aux%mapping_ltogb_faces, mfd_aux%mapping_ltogb_faces, ierr)


      case(MATBAIJ)
        call MatCreateBAIJ(option%mycomm,mfd_aux%ndof,ndof_local,ndof_local, &
                             PETSC_DETERMINE,PETSC_DETERMINE, &
                             PETSC_NULL_INTEGER,d_nnz, &
                             PETSC_NULL_INTEGER,o_nnz,J,ierr)
        call MatSetLocalToGlobalMapping(J,mfd_aux%mapping_ltog_faces,mfd_aux%mapping_ltog_faces,ierr)
        call MatSetLocalToGlobalMappingBlock(J,mfd_aux%mapping_ltogb_faces, mfd_aux%mapping_ltogb_faces, ierr)
        
      case default
        option%io_buffer = 'MatType not recognized in MFDCreateJacobian'
        call printErrMsg(option)
    end select
  else
    select case(mat_type)
      case(MATAIJ)
        d_nnz = d_nnz*mfd_aux%ndof
        call MatCreateSeqAIJ(option%mycomm,ndof_local,ndof_local, &
                             PETSC_NULL_INTEGER,d_nnz,J,ierr)
        call MatSetLocalToGlobalMapping(J,mfd_aux%mapping_ltog_faces, mfd_aux%mapping_ltog_faces, ierr)
        call MatSetLocalToGlobalMappingBlock(J,mfd_aux%mapping_ltogb_faces, mfd_aux%mapping_ltogb_faces, ierr)
      case(MATBAIJ)
        call MatCreateSeqBAIJ(option%mycomm,mfd_aux%ndof,ndof_local,ndof_local, &
                             PETSC_NULL_INTEGER,d_nnz,J,ierr)
        call MatSetLocalToGlobalMapping(J,mfd_aux%mapping_ltog_faces,mfd_aux%mapping_ltog_faces,ierr)
        call MatSetLocalToGlobalMappingBlock(J,mfd_aux%mapping_ltogb_faces,mfd_aux%mapping_ltogb_faces, ierr)
      case default
        option%io_buffer = 'MatType not recognized in MFDCreateJacobian'
        call printErrMsg(option)
    end select
  endif

  deallocate(d_nnz)
  deallocate(o_nnz)

end subroutine MFDCreateJacobian

! ************************************************************************** !
! ************************************************************************** !
subroutine MFDCreateJacobianLP(grid, mfd_aux, mat_type, J, option)

  use Option_module
  use Grid_module
  use MFD_Aux_module
  use Connection_module
  use Unstructured_Grid_Aux_module
  use Unstructured_Cell_module

  implicit none

#include "finclude/petscvec.h"
#include "finclude/petscvec.h90"
#include "finclude/petscmat.h"
#include "finclude/petscmat.h90"
#include "finclude/petscdm.h"
#include "finclude/petscdm.h90"
#include "finclude/petscis.h"
#include "finclude/petscis.h90"
#include "finclude/petscviewer.h"

  type(grid_type) :: grid
  type(mfd_type) :: mfd_aux
  type(option_type) :: option
  MatType :: mat_type
  Mat :: J


  type(mfd_auxvar_type), pointer :: aux_var
  PetscInt, allocatable :: d_nnz(:), o_nnz(:)
  type(connection_set_type), pointer :: conn
  PetscInt :: icell, iface, i
  PetscInt :: ghost_face_id, local_face_id, ghost_face_id_n, local_face_id_n
  PetscInt :: icount, jcount, jface, loc_id_up, loc_id_dn
  PetscInt :: ndof_local
  PetscErrorCode :: ierr
  PetscInt :: local_id
  PetscInt :: ghosted_id
  type(unstructured_grid_type),pointer :: ugrid

  allocate(d_nnz(grid%nlmax_faces + grid%nlmax))
  allocate(o_nnz(grid%nlmax_faces + grid%nlmax))

  ugrid => grid%unstructured_grid

  d_nnz = 1 ! start 1 since diagonal connection to self
  o_nnz = 0

  if (grid%itype == STRUCTURED_GRID_MIMETIC) then

    !
    ! Structured grid
    !

    do icell = 1, grid%nlmax
      aux_var => MFD_aux%aux_vars(icell)
      do icount = 1, aux_var%numfaces
        ghost_face_id = aux_var%face_id_gh(icount)
        local_face_id = grid%fG2L(ghost_face_id)
        if (local_face_id > 0) then
          do jcount = 1, aux_var%numfaces
            if (icount == jcount) cycle
            ghost_face_id_n = aux_var%face_id_gh(jcount)
            local_face_id_n = grid%fG2L(ghost_face_id_n)
            if (local_face_id_n > 0) then
              d_nnz(local_face_id) = d_nnz(local_face_id) + 1
            else
              o_nnz(local_face_id) = o_nnz(local_face_id) + 1
            endif
          enddo
          d_nnz(local_face_id) = d_nnz(local_face_id) + 1   ! connection to cell-centered dof
        endif

        conn => grid%faces(ghost_face_id)%conn_set_ptr
        jface = grid%faces(ghost_face_id)%id
        if (conn%itype == INTERNAL_CONNECTION_TYPE) then
          loc_id_dn = grid%nG2L(conn%id_dn(jface))
          loc_id_up = grid%nG2L(conn%id_up(jface))
          if ((loc_id_dn > 0).and.(loc_id_up > 0)) then
            d_nnz(grid%nlmax_faces + icell) = d_nnz(grid%nlmax_faces + icell) + 1
          else
            o_nnz(grid%nlmax_faces + icell) = o_nnz(grid%nlmax_faces + icell) + 1
            if (local_face_id > 0) then
              o_nnz(local_face_id) = o_nnz(local_face_id) + 6
            endif
          endif
        else
          d_nnz(grid%nlmax_faces + icell) = d_nnz(grid%nlmax_faces + icell) + 1
        endif

        if (local_face_id > 0) then
          d_nnz(grid%nlmax_faces + icell) = d_nnz(grid%nlmax_faces + icell) + 1
        else
          o_nnz(grid%nlmax_faces + icell) = o_nnz(grid%nlmax_faces + icell) + 1
        endif
      enddo
    enddo

  else
    !
    ! Unstructured grid
    !

    ! 1) For Pressre at cell-faces
    do ghost_face_id = 1,grid%ngmax_faces

      local_face_id = grid%fG2L(ghost_face_id)
      conn => grid%faces(ghost_face_id)%conn_set_ptr
      jface = grid%faces(ghost_face_id)%id

      if (conn%itype == INTERNAL_CONNECTION_TYPE) then

        ! Interal connection

        loc_id_dn = grid%nG2L(conn%id_dn(jface))
        loc_id_up = grid%nG2L(conn%id_up(jface))

        d_nnz(local_face_id) = 1

        ! Check if downstream cell is local
        if(loc_id_dn>0) then
          d_nnz(local_face_id) = d_nnz(local_face_id) + &
                      UCellGetNFaces(ugrid%cell_type(conn%id_dn(jface)),option)
        else
          if(local_face_id>0) then
          o_nnz(local_face_id) = o_nnz(local_face_id) + &
                      UCellGetNFaces(ugrid%cell_type(conn%id_dn(jface)),option)
          endif
          o_nnz(grid%nlmax_faces+loc_id_up)=o_nnz(grid%nlmax_faces+loc_id_up)+1
        endif

        ! Check if upstream cell is local
        if(loc_id_up>0) then
          d_nnz(local_face_id) = d_nnz(local_face_id) + &
                      UCellGetNFaces(ugrid%cell_type(conn%id_up(jface)),option)
        else
          if(local_face_id>0) then
          o_nnz(local_face_id) = o_nnz(local_face_id) + &
                      UCellGetNFaces(ugrid%cell_type(conn%id_up(jface)),option)
          endif
          o_nnz(grid%nlmax_faces+loc_id_dn)=o_nnz(grid%nlmax_faces+loc_id_dn)+1
        endif

        ! GB: This is a temporary fix
        o_nnz(local_face_id) = 6*2
        d_nnz(local_face_id) = 13

      else

        loc_id_dn = grid%nG2L(conn%id_dn(jface))

        ! External connection
        d_nnz(local_face_id) = &
                  UCellGetNFaces(ugrid%cell_type(conn%id_dn(jface)),option) + 1
        o_nnz(local_face_id) = 6
        o_nnz(grid%nlmax_faces+loc_id_dn)=o_nnz(grid%nlmax_faces+loc_id_dn)+1

        ! GB: This is a temporary fix
        o_nnz(local_face_id) = 6*2
        d_nnz(local_face_id) = 13
      endif
    enddo

    ! 1) For Pressre at cell-centers
    do local_id = 1,grid%nlmax

      ghosted_id = grid%nL2G(local_id)
      d_nnz(grid%nlmax_faces+local_id) = &
                          UCellGetNFaces(ugrid%cell_type(ghosted_id),option) + 1

      do icount = 1,ugrid%cell_neighbors_local_ghosted(0,local_id)
        if(ugrid%cell_neighbors_local_ghosted(icount,local_id)>0) then
          d_nnz(grid%nlmax_faces+local_id) = d_nnz(grid%nlmax_faces+local_id) + 1
        else
          o_nnz(grid%nlmax_faces+local_id) = o_nnz(grid%nlmax_faces+local_id) + 1
        endif
      enddo

        ! GB: This is a temporary fix
        o_nnz(grid%nlmax_faces+local_id) = 6*2
        d_nnz(grid%nlmax_faces+local_id) = 13
    enddo
  endif


  ndof_local = mfd_aux%ndof * (grid%nlmax_faces + grid%nlmax)

  if (option%mycommsize > 1) then
    select case(mat_type)
      case(MATAIJ)
        d_nnz = d_nnz*mfd_aux%ndof
        o_nnz = o_nnz*mfd_aux%ndof
        call MatCreateAIJ(option%mycomm,ndof_local,ndof_local, &
                             PETSC_DETERMINE,PETSC_DETERMINE, &
                             PETSC_NULL_INTEGER,d_nnz, &
                             PETSC_NULL_INTEGER,o_nnz,J,ierr)
        call MatSetLocalToGlobalMapping(J,mfd_aux%mapping_ltog_LP, mfd_aux%mapping_ltog_LP, ierr)
        call MatSetLocalToGlobalMappingBlock(J,mfd_aux%mapping_ltogb_LP, mfd_aux%mapping_ltogb_LP, ierr)


      case(MATBAIJ)
        call MatCreateBAIJ(option%mycomm,mfd_aux%ndof,ndof_local,ndof_local, &
                             PETSC_DETERMINE,PETSC_DETERMINE, &
                             PETSC_NULL_INTEGER,d_nnz, &
                             PETSC_NULL_INTEGER,o_nnz,J,ierr)
        call MatSetLocalToGlobalMapping(J,mfd_aux%mapping_ltog_LP,mfd_aux%mapping_ltog_LP,ierr)
        call MatSetLocalToGlobalMappingBlock(J,mfd_aux%mapping_ltogb_LP, mfd_aux%mapping_ltogb_LP, ierr)
        
      case default
        option%io_buffer = 'MatType not recognized in MFDCreateJacobianLP'
        call printErrMsg(option)
    end select
  else
    select case(mat_type)
      case(MATAIJ)
        d_nnz = d_nnz*mfd_aux%ndof
        call MatCreateSeqAIJ(option%mycomm,ndof_local,ndof_local, &
                             PETSC_NULL_INTEGER,d_nnz,J,ierr)
        call MatSetLocalToGlobalMapping(J,mfd_aux%mapping_ltog_LP, mfd_aux%mapping_ltog_LP, ierr)
        call MatSetLocalToGlobalMappingBlock(J,mfd_aux%mapping_ltogb_LP, mfd_aux%mapping_ltogb_LP, ierr)
      case(MATBAIJ)
        call MatCreateSeqBAIJ(option%mycomm,mfd_aux%ndof,ndof_local,ndof_local, &
                             PETSC_NULL_INTEGER,d_nnz,J,ierr)
        call MatSetLocalToGlobalMapping(J,mfd_aux%mapping_ltog_LP, mfd_aux%mapping_ltog_LP,ierr)
        call MatSetLocalToGlobalMappingBlock(J,mfd_aux%mapping_ltogb_LP, mfd_aux%mapping_ltogb_LP, ierr)
      case default
        option%io_buffer = 'MatType not recognized in MFDCreateJacobianLP'
        call printErrMsg(option)
    end select
  endif

  deallocate(d_nnz)
  deallocate(o_nnz)


end subroutine MFDCreateJacobianLP

! ************************************************************************** !
! ************************************************************************** !
subroutine MFDInitializeMassMatrices(grid, field, &
                                             mfd_aux, option)

 use Option_module
 use Grid_module
 use MFD_Aux_module
 use Field_module

  implicit none

#include "finclude/petscvec.h"
#include "finclude/petscvec.h90"
#include "finclude/petscmat.h"
#include "finclude/petscmat.h90"
#include "finclude/petscdm.h"
#include "finclude/petscdm.h90"
#include "finclude/petscis.h"
#include "finclude/petscis.h90"
#include "finclude/petscviewer.h"

  type(grid_type) :: grid
  type(field_type) :: field
  type(mfd_type) :: mfd_aux
  type(option_type) :: option


  type(mfd_auxvar_type), pointer :: aux_var
  PetscInt :: ghosted_cell_id, icell, i, j
  PetscErrorCode :: ierr
  PetscReal :: PermTensor(3,3) 
  PetscReal, pointer :: volume_p(:), perm_xx_loc_p(:), perm_yy_loc_p(:), perm_zz_loc_p(:)
  PetscReal, pointer :: perm_xz_loc_p(:), perm_xy_loc_p(:), perm_yz_loc_p(:)

  call VecGetArrayF90(field%volume, volume_p, ierr)
  call VecGetArrayF90(field%perm_xx_loc, perm_xx_loc_p, ierr)
  call VecGetArrayF90(field%perm_yy_loc, perm_yy_loc_p, ierr)
  call VecGetArrayF90(field%perm_zz_loc, perm_zz_loc_p, ierr)
  call VecGetArrayF90(field%perm_xz_loc, perm_xz_loc_p, ierr)
  call VecGetArrayF90(field%perm_xy_loc, perm_xy_loc_p, ierr)
  call VecGetArrayF90(field%perm_yz_loc, perm_yz_loc_p, ierr)

  do icell = 1, grid%nlmax

    ghosted_cell_id = grid%nL2G(icell)

    PermTensor = 0.
    PermTensor(1,1) = perm_xx_loc_p(ghosted_cell_id)
    PermTensor(2,2) = perm_yy_loc_p(ghosted_cell_id)
    PermTensor(3,3) = perm_zz_loc_p(ghosted_cell_id)
    PermTensor(1,3) = perm_xz_loc_p(ghosted_cell_id)
    PermTensor(1,2) = perm_xy_loc_p(ghosted_cell_id)
    PermTensor(2,3) = perm_yz_loc_p(ghosted_cell_id)
    PermTensor(2,1) = PermTensor(1,2)
    PermTensor(3,1) = PermTensor(1,3)
    PermTensor(3,2) = PermTensor(2,3)

    aux_var => mfd_aux%aux_vars(icell)
    call MFDAuxGenerateMassMatrixInv(grid, ghosted_cell_id, aux_var, volume_p(icell), PermTensor, option)
    call MFDAuxInitResidDerivArrays(aux_var, option)
    call MFDAuxComputeGeometricValues (grid, ghosted_cell_id, aux_var, PermTensor, option)
  enddo

  call VecRestoreArrayF90(field%volume, volume_p, ierr)
  call VecRestoreArrayF90(field%perm_xx_loc, perm_xx_loc_p, ierr)
  call VecRestoreArrayF90(field%perm_yy_loc, perm_yy_loc_p, ierr)
  call VecRestoreArrayF90(field%perm_zz_loc, perm_zz_loc_p, ierr)
  call VecRestoreArrayF90(field%perm_xz_loc, perm_xz_loc_p, ierr)
  call VecRestoreArrayF90(field%perm_xy_loc, perm_xy_loc_p, ierr)
  call VecRestoreArrayF90(field%perm_yz_loc, perm_yz_loc_p, ierr)

end subroutine MFDInitializeMassMatrices

! ************************************************************************** !
! ************************************************************************** !
subroutine MFDAuxGenerateStiffMatrix(aux_var, rich_aux_var, global_aux_var,  &
                                       sq_faces, option)

  use Option_module
  use Richards_Aux_module
  use Global_Aux_module

  implicit none

  type(mfd_auxvar_type), pointer :: aux_var
  type(richards_auxvar_type) :: rich_aux_var
  type(global_auxvar_type) :: global_aux_var
  PetscScalar, pointer :: sq_faces(:)
  type(option_type) :: option
  PetscScalar, pointer :: StiffMatrix(:,:)

  PetscInt :: iface, jface, i,j
  PetscScalar :: E
  PetscScalar, pointer :: MB(:)

  allocate(MB(aux_var%numfaces))

  E = 0
  do iface = 1, aux_var%numfaces
    MB(iface) = 0.
    do jface = 1, aux_var%numfaces
       MB(iface) = MB(iface) + aux_var%MassMatrixInv(iface,jface)*sq_faces(jface)
    enddo
    E = E + MB(iface)*sq_faces(iface)
  enddo

  do iface = 1, aux_var%numfaces
    do jface = 1, aux_var%numfaces
        aux_var%StiffMatrix(iface,jface) = sq_faces(iface)*sq_faces(jface)*    &
                                        (aux_var%MassMatrixInv(iface,jface) - &
                                        (1./E)*MB(iface)*MB(jface))
    enddo
  enddo


  deallocate(MB)

end subroutine MFDAuxGenerateStiffMatrix


! ************************************************************************** !
! ************************************************************************** !
subroutine MFDAuxGenerateRhs(patch, grid, ghosted_cell_id, PermTensor, bc_g, source_f,  bc_h, aux_var, &
                                       rich_aux_var, global_aux_var, Accum, &
                                       porosity, volume, pres, face_pres, bnd,&
                                       sq_faces, neig_den, neig_kvr, neig_dkvr_dp, option, rhs)

  use Option_module
  use Richards_Aux_module
  use Global_Aux_module
  use Patch_module

  implicit none

  type(patch_type) :: patch
  type(grid_type) :: grid
  type(mfd_auxvar_type), pointer :: aux_var
  type(richards_auxvar_type) :: rich_aux_var
  type(global_auxvar_type) :: global_aux_var
  PetscScalar :: sq_faces(:), neig_den(:), neig_kvr(:), neig_dkvr_dp(:)
  type(option_type) :: option
  PetscScalar :: bc_g(:), rhs(:), bc_h(:), face_pres(:), bnd(:)
  PetscScalar :: Accum(1:option%nflowdof),source_f(1:option%nflowdof), pres(1:option%nflowdof)
  PetscScalar :: PermTensor(3,3), sat
  PetscInt :: ghosted_cell_id, bound_id

  PetscScalar :: Kg(3), dir_norm(3)
  PetscInt :: i, j, ghost_face_id, local_face_id
  type(connection_set_type), pointer :: conn
  PetscInt, parameter :: numfaces = 6

  PetscInt :: iface, jface
  PetscScalar :: E, den_gWB, den_BWB, den_BWCl , div_grav_term
  PetscScalar :: ukvr(6), dukvr_dp(6), ds_dp, porosity, volume, den_cntr, dden_cntr_dp
  PetscScalar :: PorVol_dt
  PetscScalar :: norm_len
  PetscScalar :: Wg(6), WClm(6), CWCl(6), f(6), dden_dp(6), dir, v_darcy(6)
  PetscScalar :: dbeta_dp(6), den(6), beta(6), denB(6), Clm(6), Rgr(6), BAR(6), BdARdp(6)
  PetscScalar :: BARWB, BARWClm, BdARdpWB, BdARdpWClm
  PetscScalar :: upweight, delta_p

  ukvr = 0. !rich_aux_var%kvr_x
  dukvr_dp = 0.!rich_aux_var%dkvr_x_dp
  den_cntr = global_aux_var%den(1)
  dden_cntr_dp =  rich_aux_var%dden_dp

  upweight = 0.5

  do i = 1 , numfaces
    if (bnd(i)==1) then 
        call MFDComputeDensity(global_aux_var, face_pres(i) + bc_g(i)/sq_faces(i), den(i), dden_dp(i), option)
    else  
        den(i) =  upweight*den_cntr + (1.D0-upweight)*neig_den(i)
        dden_dp(i) = dden_cntr_dp

    endif

#ifdef USE_ANISOTROPIC_MOBILITY
        if (rich_aux_var%kvr_x < 1e-10) then
            ukvr(i) = 1e-10
        else 
            ukvr(i) = rich_aux_var%kvr_x
        endif
        dukvr_dp(i) = rich_aux_var%dkvr_x_dp 
#else
        ukvr(i) = rich_aux_var%kvr
        dukvr_dp(i) = rich_aux_var%dkvr_dp 
#endif

     beta(i) = ukvr(i)*den(i)
     dbeta_dp(i) = dukvr_dp(i)*den(i) + ukvr(i)*dden_dp(i)

     denB(i) = sq_faces(i)*den(i)
     BAR(i) = sq_faces(i)*ukvr(i)*den(i)
     BdARdp(i) = sq_faces(i)*dbeta_dp(i)
  enddo

#ifdef DASVYAT_DEBUG
   if (ghosted_cell_id==1) then
     write(*,*) "cntr pressure", pres(1)
     write(*,*) "sq ", (sq_faces(iface),iface=1,6)
     write(*,*) "p ", (face_pres(iface) + bc_g(iface)/sq_faces(iface),iface=1,6)
     write(*,*) "den ", (den(iface),iface=1,6)
     write(*,*) "den_dp ", (dden_dp(iface),iface=1,6)
     write(*,*) "dbeta_dp ", ( dbeta_dp(i),i=1,6)
     write(*,*) "Accum ", Accum(1)
  endif
#endif

  sat = global_aux_var%sat(1)
  ds_dp = rich_aux_var%dsat_dp
  PorVol_dt = porosity*volume/option%flow_dt

  E = 0.
  f(1) = Accum(1) - source_f(1)
  Wg = 0.

  do iface = 1, numfaces
     Clm(iface) = sq_faces(iface)*face_pres(iface) + bc_g(iface)
     Rgr(iface) = den(iface)*aux_var%gr(iface)
  enddo 

  Wg = matmul(aux_var%MassMatrixInv, bc_g)
  WClm = matmul(aux_var%MassMatrixInv, Clm)

  BARWB = dot_product(aux_var%WB, BAR)
  BARWClm = dot_product(WClm, BAR)
  BdARdpWB = dot_product(aux_var%WB, BdARdp)
  BdARdpWClm = dot_product(WClm, BdARdp)
  div_grav_term = dot_product(Rgr, BAR)

   aux_var%Rp = BARWB*pres(1) - BARWClm  + f(1) + div_grav_term

   aux_var%dRp_dp = BARWB + pres(1) * BdARdpWB - BdARdpWClm
   do iface = 1, numfaces
     
     aux_var%dRp_dp = aux_var%dRp_dp + & 
       sq_faces(iface)* &
     ( dukvr_dp(iface)*den(iface)*den(iface) + 2*den(iface)*ukvr(iface)*dden_dp(iface) ) &
     * aux_var%gr(iface) 

   enddo
   aux_var%dRp_dp = aux_var%dRp_dp  + PorVol_dt*sat*dden_cntr_dp + PorVol_dt*den_cntr*ds_dp      

   do iface = 1, aux_var%numfaces
          aux_var%dRp_dl(iface) = 0.
         do jface = 1, aux_var%numfaces
            aux_var%dRp_dl(iface) = aux_var%dRp_dl(iface) - & 
              BAR(jface) * aux_var%MassMatrixInv(iface,jface) * sq_faces(iface)
         enddo
   enddo
    
    aux_var%Rl = 0
    aux_var%dRl_dp = 0
    CWCl = 0

   do iface = 1, aux_var%numfaces
     do jface = 1, aux_var%numfaces
       CWCl(iface) = CWCl(iface) + sq_faces(iface)*aux_var%MassMatrixInv(iface, jface) * &
                                   sq_faces(jface)*face_pres(jface)
     enddo
   enddo

   do iface = 1, aux_var%numfaces

     aux_var%Rl(iface) = -sq_faces(iface)*aux_var%WB(iface)*pres(1) &       
                                   + CWCl(iface)  & 
                                   + sq_faces(iface)*Wg(iface) & 
                                   - sq_faces(iface)*den(iface)*aux_var%gr(iface)&
                                   - bc_h(iface)/ukvr(iface)

     aux_var%dRl_dp(iface) = -sq_faces(iface)*aux_var%WB(iface) - sq_faces(iface)*dden_dp(iface)*aux_var%gr(iface)

   enddo

  do iface = 1, aux_var%numfaces
      rhs(iface) = -aux_var%dRl_dp(iface)*aux_var%Rp/aux_var%dRp_dp + aux_var%Rl(iface)
  enddo


end subroutine MFDAuxGenerateRhs

! ************************************************************************** !
! ************************************************************************** !
subroutine MFDAuxGenerateRhs_LP(patch, grid, ghosted_cell_id, PermTensor, bc_g, source_f,  bc_h, aux_var, &
                                       rich_aux_var, global_aux_var, Accum, &
                                       porosity, volume, pres, face_pres, bnd,&
                                       sq_faces, neig_den, neig_kvr, neig_dkvr_dp, neig_pres, option, rhs)

 use Option_module
 use Richards_Aux_module
 use Global_Aux_module
 use Patch_module

  implicit none

  type(patch_type) :: patch
  type(grid_type) :: grid
  type(mfd_auxvar_type), pointer :: aux_var
  type(richards_auxvar_type) :: rich_aux_var
  type(global_auxvar_type) :: global_aux_var
  PetscScalar :: sq_faces(:), neig_den(:), neig_kvr(:), neig_dkvr_dp(:), neig_pres(:)
  type(option_type) :: option
  PetscScalar :: bc_g(:), rhs(:), bc_h(:), face_pres(:), bnd(:)
  PetscScalar :: Accum(1:option%nflowdof),source_f(1:option%nflowdof), pres(1:option%nflowdof)
  PetscScalar :: PermTensor(3,3), sat
  PetscInt :: ghosted_cell_id, bound_id



  PetscScalar :: Kg(3), dir_norm(3)
  PetscInt :: i, j, ghost_face_id, local_face_id
  type(connection_set_type), pointer :: conn
  PetscInt, parameter :: numfaces = 6



  PetscInt :: iface, jface
  PetscScalar :: E, den_gWB, den_BWB, den_BWCl , div_grav_term
  PetscScalar :: ukvr(6), dukvr_dp(6), ds_dp, porosity, volume, den_cntr, dden_cntr_dp
  PetscScalar :: PorVol_dt
  PetscScalar :: norm_len, gravity, dphi, distance_gravity
  PetscScalar :: Wg(6), WClm(6), CWCl(6), f(6), dden_dp(6), dir, v_darcy(6), dkvr_dp_neig(6)
  PetscScalar :: dbeta_dp(6), den(6), beta(6), denB(6), Clm(6), Rgr(6), BAR(6), BdARdp(6)
  PetscScalar :: BARWB, BARWClm, BdARdpWB, BdARdpWClm
  PetscScalar :: upweight, delta_p

  ukvr = 0. 
  dukvr_dp = 0.
  dkvr_dp_neig = 0.
  den_cntr = global_aux_var%den(1)
  dden_cntr_dp =  rich_aux_var%dden_dp 

  upweight = 0.5
 
  do i = 1 , numfaces
    ghost_face_id = aux_var%face_id_gh(i)
    conn => grid%faces(ghost_face_id)%conn_set_ptr
    iface = grid%faces(ghost_face_id)%id

    if (bnd(i)==1) then 
      call MFDComputeDensity(global_aux_var, face_pres(i) + bc_g(i)/sq_faces(i), den(i), dden_dp(i), option)
    else
      den(i) =  upweight*den_cntr + (1.D0-upweight)*neig_den(i)
      dden_dp(i) = dden_cntr_dp
    endif

!   UPWIND
    distance_gravity = conn%dist(0,iface) * &
                       dot_product(option%gravity, &
                                     conn%dist(1:3,iface))
    gravity = den(i) * FMWH2O * distance_gravity
    if (aux_var%gr(i) * gravity < 0) gravity = -gravity
    dphi = pres(1) - neig_pres(i) + gravity
 
    if (aux_var%gr(i) >=0 )  then
#ifdef USE_ANISOTROPIC_MOBILITY
      if (rich_aux_var%kvr_x < 1e-10 ) then
        ukvr(i) = 1e-10
      else
        ukvr(i) = rich_aux_var%kvr_x
      endif
      dukvr_dp(i) = rich_aux_var%dkvr_x_dp
#else
      if (rich_aux_var%kvr < 1e-10 ) then
        ukvr(i) = 1e-10
      else
        ukvr(i) = rich_aux_var%kvr
      endif
      dukvr_dp(i) = rich_aux_var%dkvr_dp
#endif

    else if (aux_var%gr(i) < 0)  then

      if (neig_kvr(i) < 1e-10) then
        ukvr(i) = 1e-10
      else
        ukvr(i) = neig_kvr(i)
      endif
      dkvr_dp_neig(i) = neig_dkvr_dp(i)
    endif

    beta(i) = ukvr(i)*den(i)
    dbeta_dp(i) = dukvr_dp(i)*den(i) + ukvr(i)*dden_dp(i)

    denB(i) = sq_faces(i)*den(i)
    BAR(i) = sq_faces(i)*ukvr(i)*den(i)
    BdARdp(i) = sq_faces(i)*dbeta_dp(i)
  enddo

  sat = global_aux_var%sat(1)
  ds_dp = rich_aux_var%dsat_dp
  PorVol_dt = porosity*volume/option%flow_dt

  E = 0.
  f(1) = Accum(1) - source_f(1)
  Wg = 0.

  do iface = 1, numfaces
    Clm(iface) = sq_faces(iface)*face_pres(iface) + bc_g(iface)
    Rgr(iface) = den(iface)*aux_var%gr(iface)
  enddo 

  Wg = matmul(aux_var%MassMatrixInv, bc_g)
  WClm = matmul(aux_var%MassMatrixInv, Clm)

  BARWB = dot_product(aux_var%WB, BAR)
  BARWClm = dot_product(WClm, BAR)
  BdARdpWB = dot_product(aux_var%WB, BdARdp)
  BdARdpWClm = dot_product(WClm, BdARdp)
  div_grav_term = dot_product(Rgr, BAR)

  aux_var%Rp = BARWB*pres(1) - BARWClm  + f(1) + div_grav_term
  aux_var%dRp_dp = BARWB + pres(1) * BdARdpWB - BdARdpWClm

  do iface = 1, numfaces
    aux_var%dRp_dp = aux_var%dRp_dp + &
       sq_faces(iface)* &
      (dukvr_dp(iface)*den(iface)*den(iface) + 2*den(iface)*ukvr(iface)*dden_dp(iface) ) &
      *aux_var%gr(iface)
  enddo
  aux_var%dRp_dp = aux_var%dRp_dp  + PorVol_dt*sat*dden_cntr_dp + PorVol_dt*den_cntr*ds_dp

  aux_var%dRp_dneig = 0

  do iface = 1, numfaces
    aux_var%dRp_dneig(iface)=aux_var%dRp_dneig(iface) + &
                             sq_faces(iface)*den(iface)* &
                              dkvr_dp_neig(iface)*aux_var%WB(iface)*pres(1)
    aux_var%dRp_dneig(iface)=aux_var%dRp_dneig(iface) - &
                             sq_faces(iface)*den(iface)* &
                              dkvr_dp_neig(iface)*WClm(iface)
    aux_var%dRp_dneig(iface)=aux_var%dRp_dneig(iface) + &
                             sq_faces(iface)*den(iface)*den(iface)* &
                              dkvr_dp_neig(iface)*aux_var%gr(iface)
  enddo

  do iface = 1, aux_var%numfaces
    aux_var%dRp_dl(iface) = 0.
    do jface = 1, aux_var%numfaces
      aux_var%dRp_dl(iface) = aux_var%dRp_dl(iface) - &
      BAR(jface) * aux_var%MassMatrixInv(iface,jface) * sq_faces(iface)
    enddo
  enddo
    
  aux_var%Rl = 0
  aux_var%dRl_dp = 0
  CWCl = 0

  do iface = 1, aux_var%numfaces
    do jface = 1, aux_var%numfaces
      CWCl(iface) = CWCl(iface) + sq_faces(iface)*aux_var%MassMatrixInv(iface, jface) * &
                                   sq_faces(jface)*face_pres(jface)
    enddo
  enddo

  do iface = 1, aux_var%numfaces
    aux_var%Rl(iface) = -sq_faces(iface)*aux_var%WB(iface)*pres(1) &
                        + CWCl(iface)  &
                        + sq_faces(iface)*Wg(iface) &
                        - sq_faces(iface)*den(iface)*aux_var%gr(iface)&
                        - bc_h(iface)/ukvr(iface)
    aux_var%dRl_dp(iface) = -sq_faces(iface)*aux_var%WB(iface) - sq_faces(iface)*dden_dp(iface)*aux_var%gr(iface)
  enddo

  do iface = 1, aux_var%numfaces
    rhs(iface) = aux_var%Rl(iface)
  enddo
  rhs(aux_var%numfaces + 1) = aux_var%Rp


end subroutine MFDAuxGenerateRhs_LP

! ************************************************************************** !
! ************************************************************************** !
subroutine MFDAuxJacobianLocal( grid, aux_var, &
                                       rich_aux_var, global_aux_var,  &
                                       sq_faces, option, J)

 use Option_module
 use Richards_Aux_module
 use Global_Aux_module

  implicit none

  type(grid_type) :: grid
  type(mfd_auxvar_type), pointer :: aux_var
  type(richards_auxvar_type) :: rich_aux_var
  type(global_auxvar_type) :: global_aux_var
  PetscScalar, pointer :: sq_faces(:)
  type(option_type) :: option
  PetscScalar, pointer :: J(:)

  PetscInt :: iface, jface
  PetscScalar :: ukvr

#ifdef USE_ANISOTROPIC_MOBILITY
  ukvr = rich_aux_var%kvr_x
#else
  ukvr = rich_aux_var%kvr
#endif

  J = 0.

   do iface = 1, aux_var%numfaces
     do jface = 1, aux_var%numfaces

!    J(jface + (iface - 1)*aux_var%numfaces) = -ukvr*sq_faces(iface)*aux_var%MassMatrixInv(iface,jface)*sq_faces(jface) - &
!                                                 aux_var%dRl_dp(iface)*aux_var%dRp_dl(jface)/aux_var%dRp_dp

!    J(jface + (iface - 1)*aux_var%numfaces) = -ukvr*sq_faces(iface)*aux_var%MassMatrixInv(iface,jface)*sq_faces(jface) - & !TEST
!                                                 aux_var%dRl_dp(iface)*aux_var%dRp_dl(jface)/aux_var%dRp_dp                     !TEST
    J(jface + (iface - 1)*aux_var%numfaces) = -aux_var%dRl_dp(iface)*aux_var%dRp_dl(jface)/aux_var%dRp_dp   &                  !TEST
                                               + sq_faces(iface)*aux_var%MassMatrixInv(iface,jface)*sq_faces(jface)  

    enddo
  enddo

  aux_var%dRp_dneig = 0

end subroutine MFDAuxJacobianLocal

! ************************************************************************** !
! ************************************************************************** !
subroutine MFDAuxJacobianLocal_LP( grid, aux_var, &
                                       rich_aux_var, global_aux_var,  &
                                       sq_faces, option, J)

  use Option_module
  use Richards_Aux_module
  use Global_Aux_module

  implicit none

  type(grid_type) :: grid
  type(mfd_auxvar_type), pointer :: aux_var
  type(richards_auxvar_type) :: rich_aux_var
  type(global_auxvar_type) :: global_aux_var
  PetscScalar, pointer :: sq_faces(:)
  type(option_type) :: option
  PetscScalar, pointer :: J(:)

  PetscInt :: iface, jface
  PetscScalar :: ukvr

#ifdef USE_ANISOTROPIC_MOBILITY
  ukvr = rich_aux_var%kvr_x
#else
  ukvr = rich_aux_var%kvr
#endif

  J = 0.
  do iface = 1, aux_var%numfaces
    do jface = 1, aux_var%numfaces
      J(iface + (jface - 1)*(aux_var%numfaces + 1)) = sq_faces(iface)*aux_var%MassMatrixInv(iface,jface)*sq_faces(jface)
    enddo
    J(aux_var%numfaces + 1 + (iface - 1)*(aux_var%numfaces + 1)) = aux_var%dRp_dl(iface)
    J(iface + aux_var%numfaces*(aux_var%numfaces + 1)) = aux_var%dRl_dp(iface)
  enddo

  J(aux_var%numfaces + 1 + aux_var%numfaces*(aux_var%numfaces + 1)) =  aux_var%dRp_dp

end subroutine MFDAuxJacobianLocal_LP


! ************************************************************************** !
! ************************************************************************** !
subroutine MFDAuxReconstruct(face_pr, source_f, aux_var, rich_aux_var, global_aux_var, Accum, &
                                       sq_faces, option, xx)

  use Option_module
  use Richards_Aux_module
  use Global_Aux_module

  implicit none

  type(mfd_auxvar_type), pointer :: aux_var
  type(richards_auxvar_type) :: rich_aux_var
  type(global_auxvar_type) :: global_aux_var
  PetscScalar, pointer :: sq_faces(:), face_pr(:)
  type(option_type) :: option
  PetscScalar :: Accum(1:option%nflowdof),source_f(1:option%nflowdof), xx(1:option%nflowdof)

  PetscInt :: iface, jface, i,j
  PetscScalar :: ukvr, E, gMB
  PetscScalar, pointer :: MB(:)

  allocate(MB(aux_var%numfaces))

  E = 0

#ifdef USE_ANISOTROPIC_MOBILITY
  ukvr = rich_aux_var%kvr_x
#else
  ukvr = rich_aux_var%kvr
#endif

  do iface = 1, aux_var%numfaces
    MB(iface) = 0.
    do jface = 1, aux_var%numfaces
       MB(iface) = MB(iface) + aux_var%MassMatrixInv(iface,jface)*sq_faces(jface)
    enddo
    E = E + MB(iface)*sq_faces(iface)
  enddo

  E = 1./E
  xx(1) = 0

  do iface = 1, aux_var%numfaces
    xx(1) = xx(1) + E*MB(iface)*sq_faces(iface)*face_pr(iface) 
  enddo 

  deallocate(MB)

end subroutine MFDAuxReconstruct


! ************************************************************************** !
! ************************************************************************** !
subroutine  MFDAuxUpdateCellPressure(face_pres, face_DELTA_pres, mfd_aux_var,&
                                option, pressure)

  use Option_module
  use Richards_Aux_module
  use Global_Aux_module

  implicit none

  type(mfd_auxvar_type), pointer :: mfd_aux_var
  type(option_type) :: option
  PetscScalar, pointer ::  face_pres(:), face_DELTA_pres(:)
  PetscScalar :: pressure(1:option%nflowdof)
  

  PetscScalar :: DELTA_pres
  PetscInt :: iface

  DELTA_pres = mfd_aux_var%Rp

  do iface = 1, mfd_aux_var%numfaces
    DELTA_pres = DELTA_pres + mfd_aux_var%dRp_dl(iface)*face_DELTA_pres(iface)
  enddo

  DELTA_pres = -DELTA_pres/mfd_aux_var%dRp_dp
  pressure(1) = pressure(1) + DELTA_pres

end subroutine MFDAuxUpdateCellPressure

! ************************************************************************** !
! ************************************************************************** !
subroutine MFDAuxFluxes(patch, grid, ghosted_cell_id, xx, face_pr, aux_var, PermTensor, rich_aux_var, global_aux_var, &
                                       sq_faces, bnd, neigh_den, neig_kvr,  neig_pres, option)

  use Option_module
  use Richards_Aux_module
  use Global_Aux_module
  use Grid_module
  use Connection_module
  use Patch_module

  implicit none 

  type(grid_type) :: grid
  type(patch_type) :: patch
  type(mfd_auxvar_type), pointer :: aux_var
  type(richards_auxvar_type) :: rich_aux_var
  type(global_auxvar_type) :: global_aux_var
  PetscScalar, pointer :: sq_faces(:), face_pr(:), neigh_den(:), neig_pres(:), neig_kvr(:), bnd(:)
  type(option_type) :: option
  PetscScalar :: xx(1:option%nflowdof),  PermTensor(3,3), Kg(3), real_tmp
  PetscInt :: ghosted_cell_id
  PetscScalar :: ukvr0, den0
  PetscInt, parameter :: numfaces = 6

  PetscInt :: iface, jface, i, j, ghost_face_id, local_face_id, local_id, bound_id, dir
  PetscScalar :: den(numfaces), dden_dp(numfaces) , ukvr(numfaces), den_cntr
  PetscScalar :: gravity, darcy_v, dir_norm(3), total_flux, upweight, DIV, dphi, distance_gravity
  type(connection_set_type), pointer :: conn

#ifdef USE_ANISOTROPIC_MOBILITY
  ukvr = rich_aux_var%kvr_x
#else
  ukvr = rich_aux_var%kvr
#endif
  upweight = 0.5


  do i = 1 , numfaces
    ghost_face_id = aux_var%face_id_gh(i)
    conn => grid%faces(ghost_face_id)%conn_set_ptr
    iface = grid%faces(ghost_face_id)%id
    if (bnd(i)==1) then  
      call MFDComputeDensity(global_aux_var, face_pr(i), den(i), dden_dp(i), option)
    else
      den(i) = global_aux_var%den(1)*upweight + (1 - upweight)*neigh_den(i)
    endif 

! UPWIND
    distance_gravity = conn%dist(0,iface) * &
                       dot_product(option%gravity, &
                                     conn%dist(1:3,iface))

    gravity = den(i) * FMWH2O * distance_gravity   

    if (aux_var%gr(i) * gravity < 0) gravity = -gravity 

    dphi = xx(1) - neig_pres(i) + gravity
    
    if (aux_var%gr(i) >= 0)  then

#ifdef USE_ANISOTROPIC_MOBILITY
      if (rich_aux_var%kvr_x < 1e-10 ) then
        ukvr(i) = 1e-10
      else
        ukvr(i) = rich_aux_var%kvr_x
      endif
#else
      if (rich_aux_var%kvr < 1e-10 ) then
        ukvr(i) = 1e-10
      else
        ukvr(i) = rich_aux_var%kvr
      endif
#endif

    else if (aux_var%gr(i) < 0)  then
      if (neig_kvr(i) < 1e-10 ) then
        ukvr(i) = 1e-10
      else
        ukvr(i) = neig_kvr(i)
      endif
   endif
 enddo
 
  do i = 1, aux_var%numfaces
    ghost_face_id = aux_var%face_id_gh(i)
    local_face_id = grid%fG2L(ghost_face_id)
    conn => grid%faces(ghost_face_id)%conn_set_ptr
    iface = grid%faces(ghost_face_id)%id
    if (conn%itype==INTERNAL_CONNECTION_TYPE) local_id = grid%nG2L(conn%id_up(iface))

    dir = 1
    if (conn%itype/=BOUNDARY_CONNECTION_TYPE.and.conn%id_dn(iface)==ghosted_cell_id) dir = -1

    darcy_v = 0.
    do j = 1, aux_var%numfaces
      darcy_v = darcy_v + ukvr(i)*aux_var%MassMatrixInv(i, j)* &
                                           (sq_faces(j)*(xx(1) - face_pr(j)))
    enddo

    darcy_v = darcy_v + den(i)*ukvr(i)*aux_var%gr(i)

    DIV = DIV + den(i)*darcy_v*sq_faces(i)

    if (conn%itype/=BOUNDARY_CONNECTION_TYPE.and.conn%id_dn(iface)==ghosted_cell_id.and.local_id>0) cycle
      if (conn%itype == BOUNDARY_CONNECTION_TYPE) then
        if (local_face_id > 0) then
          bound_id = grid%fL2B(local_face_id)
          if (bound_id>0) then
            patch%boundary_velocities(option%nphase, bound_id) = -darcy_v
          endif
        endif
    else if (conn%itype == INTERNAL_CONNECTION_TYPE) then
      patch%internal_velocities(option%nphase, iface) = darcy_v * dir
    endif
  enddo

end subroutine MFDAuxFluxes

! ************************************************************************** !
! ************************************************************************** !
subroutine MFDComputeDensity(global_aux_var, pres, den, dden_dp, option)

  use Option_module
  use Global_Aux_module
  use Water_EOS_module



  type(global_auxvar_type) :: global_aux_var
  PetscScalar :: pres
  type(option_type) :: option
  PetscReal, parameter :: tol = 1.d-3


  PetscInt :: numfaces, i
  PetscErrorCode :: ierr
  PetscReal :: den, dden_dp, pc, pw 
  PetscReal :: dw_kg, dw_mol, dw_dp, dw_dt, hw, hw_dp, hw_dt


  pc = option%reference_pressure - pres

  if (pc > 1.0) then
    pw = option%reference_pressure
  else 
    pw = pres
  endif

#ifndef DONT_USE_WATEOS
  call wateos(global_aux_var%temp(1),pw,dw_kg,dw_mol,dw_dp,dw_dt,hw, &
              hw_dp,hw_dt,option%scale,ierr)
#else
  call density(global_aux_var%temp(1),pw,dw_kg)
  pert = tol*pw
  pw_pert = pw + pert
  call density(global_aux_var%temp(1),pw_pert,dw_kg_pert)
  dw_dp = (dw_kg_pert-dw_kg)/pert
  ! dw_kg = kg/m^3
  ! dw_mol = kmol/m^3
  ! FMWH2O = kg/kmol h2o
  dw_mol = dw_kg/FMWH2O
  dw_dp = dw_dp/FMWH2O
#endif

  den = dw_mol
  dden_dp = dw_dp

end subroutine MFDComputeDensity

! ************************************************************************** !
! ************************************************************************** !
subroutine MFDAuxComputeGeometricValues (grid, ghosted_cell_id, aux_var, PermTensor, option)


 use Option_module
 use Richards_Aux_module
 use Global_Aux_module
 use Patch_module

  implicit none

  type(grid_type) :: grid
  type(mfd_auxvar_type), pointer :: aux_var
  type(option_type) :: option
  PetscScalar :: PermTensor(3,3)
  PetscInt :: ghosted_cell_id

  PetscScalar :: Kg(3), dir_norm(3)
  PetscScalar :: sq_faces(6), norm_len
  PetscInt :: i, j, ghost_face_id
  type(connection_set_type), pointer :: conn
  PetscInt, parameter :: numfaces = 6
  PetscInt :: iface, jface

  Kg = matmul(PermTensor, option%gravity)

  do i=1,3
    Kg(i) = Kg(i) * FMWH2O
  enddo

  do i = 1, numfaces
    ghost_face_id = aux_var%face_id_gh(i)
    conn => grid%faces(ghost_face_id)%conn_set_ptr
    iface = grid%faces(ghost_face_id)%id
    sq_faces(i) = conn%area(iface)

    dir_norm(1) = conn%cntr(1, iface) - grid%x(ghosted_cell_id)       !direction to define outward normal
    dir_norm(2) = conn%cntr(2, iface) - grid%y(ghosted_cell_id)
    dir_norm(3) = conn%cntr(3, iface) - grid%z(ghosted_cell_id)

    norm_len = sqrt(dir_norm(1)**2 + dir_norm(2)**2 + dir_norm(3)**2)

    aux_var%gr(i) = 0
    do j = 1,3
      dir_norm(j) = dir_norm(j)/norm_len
      aux_var%gr(i) = aux_var%gr(i) + dir_norm(j) * Kg(j)
    enddo
  enddo
  aux_var%WB = matmul(aux_var%MassMatrixInv, sq_faces)

end subroutine MFDAuxComputeGeometricValues

! ************************************************************************** !
!
! MFDAuxGenerateMassMatrixInv: Create a mass matrix for cell
! author: Daniil Svyatskiy
! date: 05/25/10
!
! ************************************************************************** !
subroutine MFDAuxGenerateMassMatrixInv(grid, ghosted_cell_id,  aux_var, volume, PermTensor, option)

 use Grid_module
 use Option_module
 use Connection_module

  implicit none

#include "finclude/petscvec.h"
#include "finclude/petscvec.h90"
#include "finclude/petscmat.h"
#include "finclude/petscmat.h90"
#include "finclude/petscdm.h"
#include "finclude/petscdm.h90"
#include "finclude/petscis.h"
#include "finclude/petscis.h90"
#include "finclude/petscviewer.h"


  type(grid_type) :: grid
  type(mfd_auxvar_type), pointer :: aux_var
  PetscScalar :: PermTensor(3,3), dir_norm(3), sq_faces(6)
  PetscScalar :: N(6,3), D(6,3), H(6,3),  W1(6,6), U(3,3), rx(6), ry(6), rz(6)   ! hex only
  PetscScalar :: volume, norm, area, a1, a2, u_parm
  PetscInt :: ghost_face_id, ghosted_cell_id
  type(option_type) :: option
  type(connection_set_type), pointer :: conn


  PetscInt :: iface, i,j,k

  if (volume==0.) then
    option%io_buffer = 'Cell volume iz zero'
    call printErrMsg(option)
  endif

  N = 0.
  u_parm  = (PermTensor(1,1) + PermTensor(2,2) +PermTensor(3,3))/volume

  do i = 1, aux_var%numfaces

    ghost_face_id = aux_var%face_id_gh(i)
    conn => grid%faces(ghost_face_id)%conn_set_ptr
    iface = grid%faces(ghost_face_id)%id
    area = conn%area(iface)
    sq_faces(i) = conn%area(iface)

    dir_norm(1) = conn%cntr(1, iface) - grid%x(ghosted_cell_id)       !direction to define outward normal
    dir_norm(2) = conn%cntr(2, iface) - grid%y(ghosted_cell_id)
    dir_norm(3) = conn%cntr(3, iface) - grid%z(ghosted_cell_id)

    norm = sqrt(dir_norm(1)**2 + dir_norm(2)**2 +dir_norm(3)**2)

    do j=1,3
      dir_norm(j) = dir_norm(j)/norm
    enddo

    rx(i) = ( conn%cntr(1, iface) - grid%x(ghosted_cell_id) )*area
    ry(i) = ( conn%cntr(2, iface) - grid%y(ghosted_cell_id) )*area
    rz(i) = ( conn%cntr(3, iface) - grid%z(ghosted_cell_id) )*area

    do j=1,3
      N(i,j) = dir_norm(j)
     enddo
  enddo

#if 0

  D = 0.

  norm = dot_product(rx(1:6), rx(1:6))
  norm = sqrt(norm)
  do i = 1, aux_var%numfaces
    D(i,1) = rx(i)/norm
  enddo
  a1 = -dot_product(D(1:6,1), ry)

 ! write(*,*) "a1", a1

  do i = 1, aux_var%numfaces
    D(i,2) = ry(i) + a1*D(i,1)
  enddo

  norm = dot_product(D(1:6,2),D(1:6,2))
  norm = sqrt(norm)

  do i = 1, aux_var%numfaces
    D(i,2) = D(i,2)/norm
  enddo

  a1 = -dot_product(D(1:6,1), rz(1:6))
  a2 = -dot_product(D(1:6,2), rz(1:6))

  do i = 1, aux_var%numfaces
    D(i,3) = rz(i) + a1*D(i,1) + a2*D(i,2)
  enddo
   
  norm = dot_product(D(1:6,3),D(1:6,3))
  norm = sqrt(norm)

  do i = 1, aux_var%numfaces
    D(i,3) = D(i,3)/norm
  enddo

  do i = 1, aux_var%numfaces
    do j = 1, aux_var%numfaces
      W1(i,j) = 0.
      do k = 1, 3
         W1(i,j) = W1(i,j) + D(i,k)*D(j,k)
      enddo
    enddo
  enddo

  do i = 1, aux_var%numfaces
    W1(i,i) = W1(i,i) - 1
  enddo

  do i = 1, aux_var%numfaces
     do j = 1, 3
       H(i,j) = 0
       do k = 1, 3
         H(i,j) = H(i,j) + N(i,k)*PermTensor(k,j)
       enddo
     enddo
  enddo

  allocate(aux_var%MassMatrixInv(aux_var%numfaces, aux_var%numfaces))

  do i = 1, aux_var%numfaces
    do j = 1, aux_var%numfaces
       aux_var%MassMatrixInv(i,j) = 0
       do k =1,3
         aux_var%MassMatrixInv(i,j) = aux_var%MassMatrixInv(i,j) + H(i,k) * N(j,k)
       enddo
       aux_var%MassMatrixInv(i,j) = aux_var%MassMatrixInv(i,j) / volume
       aux_var%MassMatrixInv(i,j) = aux_var%MassMatrixInv(i,j) - u_parm*W1(i,j)
     enddo
   enddo

#else

  do i = 1, aux_var%numfaces
     do j = 1, 3
       D(i,j) = abs(N(i,j))
     enddo
  enddo

  do i = 1,3
     U(i,i) = PermTensor(i,i)/volume
     do j = i+1, 3
        U(i,j) = -abs(PermTensor(i,j))/volume
        U(j,i) = U(i,j)
     enddo
  enddo 

  do i = 1, aux_var%numfaces
     do j = 1, 3
       H(i,j) = 0
       do k = 1, 3
         H(i,j) = H(i,j) + N(i,k)*PermTensor(k,j)
       enddo
     enddo
  enddo

  allocate(aux_var%MassMatrixInv(aux_var%numfaces, aux_var%numfaces))


  do i = 1, aux_var%numfaces
    do j = 1, aux_var%numfaces
       aux_var%MassMatrixInv(i,j) = 0
       do k =1,3
         aux_var%MassMatrixInv(i,j) = aux_var%MassMatrixInv(i,j) + H(i,k) * N(j,k)
       enddo
       aux_var%MassMatrixInv(i,j) = aux_var%MassMatrixInv(i,j) / volume
     enddo
   enddo

  do i = 1, aux_var%numfaces
     do j = 1, 3
       H(i,j) = 0
       do k = 1, 3
         H(i,j) = H(i,j) + D(i,k)*U(k,j)
       enddo
    enddo
  enddo

  do i = 1, aux_var%numfaces
    do j = 1, aux_var%numfaces
       do k =1,3
         aux_var%MassMatrixInv(i,j) = aux_var%MassMatrixInv(i,j) + H(i,k) * D(j,k)
       enddo
     enddo
   enddo

#endif

end subroutine MFDAuxGenerateMassMatrixInv


end module MFD_module