File: cs_groundwater.c

package info (click to toggle)
code-saturne 4.3.3%2Brepack-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 77,992 kB
  • sloc: ansic: 281,257; f90: 122,305; python: 56,490; makefile: 3,915; xml: 3,285; cpp: 3,183; sh: 1,139; lex: 176; yacc: 101; sed: 16
file content (2197 lines) | stat: -rw-r--r-- 74,765 bytes parent folder | download
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
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
/*============================================================================
 * Main functions dedicated to groundwater flows
 *============================================================================*/

/* VERS */

/*
  This file is part of Code_Saturne, a general-purpose CFD tool.

  Copyright (C) 1998-2016 EDF S.A.

  This program is free software; you can redistribute it and/or modify it under
  the terms of the GNU General Public License as published by the Free Software
  Foundation; either version 2 of the License, or (at your option) any later
  version.

  This program is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
  details.

  You should have received a copy of the GNU General Public License along with
  this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
  Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

/*----------------------------------------------------------------------------*/

#include "cs_defs.h"

/*----------------------------------------------------------------------------
 * Standard C library headers
 *----------------------------------------------------------------------------*/

#include <assert.h>
#include <ctype.h>
#include <float.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>


/*----------------------------------------------------------------------------
 *  Local headers
 *----------------------------------------------------------------------------*/

#include <bft_mem.h>
#include <bft_printf.h>

#include "cs_post.h"
#include "cs_mesh_location.h"
#include "cs_field.h"
#include "cs_cdo.h"
#include "cs_math.h"
#include "cs_param.h"
#include "cs_reco.h"
#include "cs_hodge.h"

/*----------------------------------------------------------------------------
 * Header for the current file
 *----------------------------------------------------------------------------*/

#include "cs_groundwater.h"

/*----------------------------------------------------------------------------*/

BEGIN_C_DECLS

/*============================================================================
 * Local macro definitions
 *============================================================================*/

/* Tag dedicated to build a flag for the groundwater module */
/*   1: post the moisture content */
#define CS_GROUNDWATER_POST_MOISTURE  (1 <<  0)

/*============================================================================
 * Structure definitions
 *============================================================================*/

/* Set of parameters related to a tracer equation */
typedef struct {

  /* Bulk density times the distribution coefficient for each soil */
  double           rho_kd;

  /* Longitudinal and transversal dispersivity for each soil */
  double           alpha_l;
  double           alpha_t;

  /* Water molecular diffusivity */
  double           wmd;

  /* First order decay coefficient (related to the reaction term) */
  double           reaction_rate;

} cs_gw_tracer_t;

/* Set of parameters describing a type of soil */
typedef struct {

  int          ml_id;    /* id associated to a mesh location structure
                            The support entities are cells */

  /* Set of parameters for each tracer equation */
  cs_gw_tracer_t         *tracer_param;

  /* Physical modelling adopted for this soil */
  cs_groundwater_model_t  model;

  /* Parameters for predefined models */
  cs_gw_genuchten_t       genuchten_param; /* Van-Genuchten-Mualen law */
  cs_gw_tracy_t           tracy_param;     /* Tracy law */

  /* Main soil properties */
  double                  residual_moisture;       /* theta_r */
  double                  saturated_moisture;      /* theta_s */
  double                  delta_moisture;          /* theta_s - theta_r */
  cs_get_t                saturated_permeability;  /* k_s [m.s^-1] */

} cs_gw_soil_t;

/* Set of parameters related to the groundwater module */
struct _groundwater_t {

  cs_flag_t                flag;       /* Compact information */

  cs_groundwater_model_t   global_model;

  /* Physical parameters related to each kind of soil considered.
     If n_soils > 1, soil_id array stores the id giving access to the soil
     parameters related to each cell of the mesh */
  int            n_soils;
  int            n_max_soils;
  cs_gw_soil_t  *soil_param;
  cs_lnum_t      n_cells;     /* Number of cells (useful to get soil_id) */
  short int     *soil_id;     /* NULL or allocated to n_cells */

  /* Gravity effect */
  bool           with_gravitation;
  cs_real_3_t    gravity;

  /* Fields located at cells */
  cs_field_t    *hydraulic_head;  /* H (shared or owner according to the
                                     discretization space scheme) */
  cs_field_t    *pressure_head;   /* h = H - gravity_potential */

  /* Set of equations associated to this module */
  int            richards_eq_id;

  int            n_tracers;
  int            n_max_tracers;
  int           *tracer_eq_ids;

  /* Moisture content variable and attached quantities */
  cs_field_t          *moisture_content;

  /* Permeability is the diffusion property related to Richards equation but
     this property plays also a role in the diffusion of tracer equations */
  cs_property_t       *permeability;  /* shared with a cs_domain_t structure */

  /* Scan the c2e connectivity index to get the darcian flux related to
     each dual face when CDO vertex-based scheme is activated */
  cs_real_t           *darcian_flux;
  cs_adv_field_t      *adv_field;    /* shared with a cs_domain_t structure */

  /* Work buffer (allocated to n_max_ebyc) */
  cs_real_t  *work;

};

/*============================================================================
 * Static global variables
 *============================================================================*/

static const char _err_empty_gw[] =
  " Stop execution. The structure related to the groundwater module is empty.\n"
  " Please check your settings.\n";

/*============================================================================
 * Private function prototypes
 *============================================================================*/

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Set a cs_gw_tracer_t structure
 *
 * \param[in, out] tp              pointer to a cs_gw_tracer_t structure
 * \param[in]      wmd             value of the water molecular diffusivity
 * \param[in]      alpha_l         value of the longitudinal dispersivity
 * \param[in]      alpha_t         value of the transversal dispersivity
 * \param[in]      bulk_density    value of the bulk density
 * \param[in]      distrib_coef    value of the distribution coefficient
 * \param[in]      reaction_rate   value of the first order rate of reaction
 */
/*----------------------------------------------------------------------------*/

static void
_set_tracer_param(cs_gw_tracer_t     *tp,
                  double              wmd,
                  double              alpha_l,
                  double              alpha_t,
                  double              bulk_density,
                  double              distrib_coef,
                  double              reaction_rate)
{
  assert(tp != NULL); /* Sanity check */

  tp->wmd = wmd;
  tp->rho_kd = bulk_density * distrib_coef;
  tp->reaction_rate = reaction_rate;
  tp->alpha_l = alpha_l;
  tp->alpha_t = alpha_t;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Initialize a cs_gw_soil_t structure (already allocated)
 *
 * \param[in]      ml_name         name of the mesh location
 * \param[in]      model_kw        keyword related to the modelling
 * \param[in]      n_tracers       number of related tracer eqs
 * \param[in, out] soil            pointer to a cs_gw_soil_t structure
 */
/*----------------------------------------------------------------------------*/

static void
_init_soil(const char     *ml_name,
           const char     *model_kw,
           int             n_tracers,
           cs_gw_soil_t   *soil)
{
  if (soil == NULL)
    return;

  int  ml_id = cs_mesh_location_get_id_by_name(ml_name);

  if (ml_id == -1)
    bft_error(__FILE__, __LINE__, 0,
              _(" Invalid mesh location name %s.\n"
                " This mesh location is not already defined.\n"), ml_name);

  if (cs_mesh_location_get_type(ml_id) != CS_MESH_LOCATION_CELLS)
    bft_error(__FILE__, __LINE__, 0,
              _(" Invalid type of mesh location for mesh location  %s.\n"
                " The expected type is CS_MESH_LOCATION_CELLS.\n"), ml_name);

  soil->ml_id = ml_id;

  /* Set the model associated to this soil */
  if (strcmp(model_kw, "saturated") == 0) {

    soil->model = CS_GROUNDWATER_MODEL_SATURATED;
    soil->saturated_moisture = 1.0;
    soil->residual_moisture = 0.0;

  }
  else if (strcmp(model_kw, "genuchten") == 0) {

    soil->model = CS_GROUNDWATER_MODEL_GENUCHTEN;

    /* Default initialization */
    soil->saturated_moisture = 0.75;
    soil->residual_moisture = 0.15;

    const double  n = 1.56;
    soil->genuchten_param.n = n;
    soil->genuchten_param.m = 1 - 1/n;
    soil->genuchten_param.scale = 0.036;
    soil->genuchten_param.tortuosity = 0.5;

  }
  else if (strcmp(model_kw, "tracy") == 0) {

    soil->model = CS_GROUNDWATER_MODEL_TRACY;

    /* Default initialization */
    soil->saturated_moisture = 0.75;
    soil->residual_moisture = 0.15;
    soil->tracy_param.h_r = -100;
    soil->tracy_param.h_s = 0;

  }
  else
    bft_error(__FILE__, __LINE__, 0,
              " Incompatible model for a soil in the groundwater module.\n"
              " Value given: %s\n"
              " Availaible models: saturated, genuchten, tracy", model_kw);

  soil->delta_moisture = soil->saturated_moisture - soil->residual_moisture;

  /* Set of parameters for each tracer which are related to this soil */
  BFT_MALLOC(soil->tracer_param, n_tracers, cs_gw_tracer_t);

  for (int i = 0; i < n_tracers; i++) /* default initialization */
    _set_tracer_param(soil->tracer_param + i,
                      0.0,  /* water molecular diffusivity */
                      0.0,  /* alpha_l */
                      0.0,  /* alpha_t */
                      1.0,  /* bulk density */
                      0.0,  /* Kd (distribution coef.) */
                      0.0); /* reaction rate */

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Get the id in a cs_groundwater_t structure from the tracer
 *         equation id
 *
 * \param[in]   gw             pointer to a cs_groundwater_t structure
 * \param[in]   tracer_eq_id   tracer equation id
 *
 * \returns an id related to this tracer equation id
 */
/*----------------------------------------------------------------------------*/

static inline int
_get_tracer_id(const cs_groundwater_t   *gw,
               int                       tracer_eq_id)
{
  int  tracer_id = -1;

  for (int id = 0; id < gw->n_tracers; id++) {
    if (gw->tracer_eq_ids[id] == tracer_eq_id) {
      tracer_id = id;
      break;
    }
  }

  if (tracer_id == -1)
    bft_error(__FILE__, __LINE__, 0,
              " Stop setting a tracer equation. Its identification number has"
              " not been found in the groundwater flow module.\n"
              " Please check your settings.");

  return tracer_id;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Define the coefficient appearing in the diffusion term of the
 *         tracer equation
 *
 * \param[in]      theta          value of the moisture content
 * \param[in]      v              value of the local velocity
 * \param[in]      tracer_struc   pointer to a soil structure
 * \param[in, out] result         pointer to a cs_get_t structure
 */
/*----------------------------------------------------------------------------*/

static inline void
_get_tracer_diffusion_tensor(double          theta,
                             const double    v[],
                             const void     *tracer_struc,
                             cs_get_t       *result)
{
  const cs_gw_tracer_t  *tp = (const cs_gw_tracer_t *)tracer_struc;

  const double v2[3] = {v[0]*v[0], v[1]*v[1], v[2]*v[2]};
  const double  vnorm = sqrt(v2[0] + v2[1] + v2[2]);
  const double  coef1 = tp->wmd * theta + tp->alpha_t*vnorm;

  double  delta_coef = 0.;
  if (vnorm > cs_math_zero_threshold)
    delta_coef = (tp->alpha_l - tp->alpha_t)/vnorm;

  const double  dcv[3] = {delta_coef*v[0], delta_coef*v[1], delta_coef*v[2]};

  for (int ki = 0; ki < 3; ki++) {

    /* Diagonal terms */
    result->tens[ki][ki] = coef1 + delta_coef*v2[ki];

    /* Extra-diagonal terms */
    for (int kj = ki + 1; kj < 3; kj++)
      result->tens[ki][kj] = dcv[ki]*v[kj];
  }

  /* Diffusion tensor is symmetric by construction */
  result->tens[1][0] = result->tens[0][1];
  result->tens[2][0] = result->tens[0][2];
  result->tens[2][1] = result->tens[1][2];

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Define the coefficient appearing in time-dependent term of the
 *         simulation of tracer equations
 *
 * \param[in]      theta          value of the moisture content
 * \param[in]      tracer_struc   pointer to a soil structure
 * \param[in, out] result         pointer to a cs_get_t structure
 */
/*----------------------------------------------------------------------------*/

static inline void
_get_tracer_time_coeff(double        theta,
                       const void   *tracer_struc,
                       cs_get_t     *result)
{
  const cs_gw_tracer_t  *tracer = (const cs_gw_tracer_t  *)tracer_struc;

  result->val = theta + tracer->rho_kd;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Define the coefficient appearing in reaction term for the simulation
 *         of tracer equations
 *
 * \param[in]      theta          value of the moisture content
 * \param[in]      tracer_struc   pointer to a soil structure
 * \param[in, out] result         pointer to a cs_get_t structure
 */
/*----------------------------------------------------------------------------*/

static inline void
_get_tracer_reaction_coeff(double        theta,
                           const void   *tracer_struc,
                           cs_get_t     *result)
{
  const cs_gw_tracer_t  *tracer = (const cs_gw_tracer_t  *)tracer_struc;

  result->val = tracer->reaction_rate * (theta + tracer->rho_kd);
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Define the permeability (or hydraulic conductivity) using the
 *         van Genuchten-Mualen law
 *
 * \param[in]      h             value of the hydralic head
 * \param[in]      soil_struc    pointer to a soil structure
 * \param[in, out] result        pointer to a cs_get_t structure
 */
/*----------------------------------------------------------------------------*/

static inline void
_permeability_by_genuchten_law(double        h,
                               const void   *soil_struc,
                               cs_get_t     *result)
{
  const cs_gw_soil_t  *soil = (const cs_gw_soil_t  *)soil_struc;
  const cs_gw_genuchten_t  law = soil->genuchten_param;

  /* Up to now, only isotropic values are considered */
  double  isoval = soil->saturated_permeability.val;

  if (h < 0) {

    /* S_e(h) = [1 + |alpha*h|^n]^(-m) */
    const double  one_alpha_hn = 1 + pow(fabs(law.scale*h), law.n);
    const double  se = pow(one_alpha_hn, -law.m);
    const double  se_pow_L = pow(se, law.tortuosity);
    const double  se_pow_overm = pow(se, 1/law.m);
    const double  coef_base = 1 - pow(1 - se_pow_overm, law.m);

    isoval *= se_pow_L * coef_base*coef_base;

  }

  /* Build the related tensor (permeability is always defined as a tensor) */
  for (int k = 0; k < 3; k++) {
    result->tens[k][k] = isoval;
    for (int l = k+1; l < 3; l++) {
      result->tens[k][l] = result->tens[l][k] = 0;
    }
  }

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Define the moisture content using the Van Genuchten law
 *
 * \param[in]      h             value of the hydralic head
 * \param[in]      soil_struc    pointer to a soil structure
 * \param[in, out] result        pointer to a cs_get_t structure
 */
/*----------------------------------------------------------------------------*/

static void
_moisture_by_genuchten_law(double        h,
                           const void   *soil_struc,
                           cs_get_t     *result)
{
  const cs_gw_soil_t  *soil = (const cs_gw_soil_t  *)soil_struc;
  const cs_gw_genuchten_t  law = soil->genuchten_param;

  double  Se = 1; // dimensionless moisture

  if (h < 0) {
    double  tmp_coef = pow(fabs(law.scale * h), law.n);
    Se = pow(1 + tmp_coef, -law.m);
  }

  /* Return the computed moisture content */
  result->val = Se*soil->delta_moisture + soil->residual_moisture;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Define the moisture content using the Van Genuchten law
 *
 * \param[in]      h             value of the hydralic head
 * \param[in]      soil_struc    pointer to a soil structure
 * \param[in, out] result        pointer to a cs_get_t structure
 */
/*----------------------------------------------------------------------------*/

static void
_capacity_by_genuchten_law(double        h,
                           const void   *soil_struc,
                           cs_get_t     *result)
{
  const cs_gw_soil_t  *soil = (const cs_gw_soil_t  *)soil_struc;
  const cs_gw_genuchten_t  law = soil->genuchten_param;

  result->val = 0.; // default initialization for saturated soil

  if (h >= 0)
    return;

  const double  mult_coef = -law.n * law.m * soil->delta_moisture;
  const double  alpha_h_pow_n = pow(fabs(law.scale * h), law.n);
  const double  se_m1 = pow(1 + alpha_h_pow_n, -law.m-1);

  result->val = mult_coef * alpha_h_pow_n/h * se_m1;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Define the permeability (or hydraulic conductivity) using the
 *         Tracy law
 *
 * \param[in]      h             value of the hydralic head
 * \param[in]      soil_struc    pointer to a soil structure
 * \param[in, out] result        pointer to a cs_get_t structure
 */
/*----------------------------------------------------------------------------*/

static inline void
_permeability_by_tracy_law(double        h,
                           const void   *soil_struc,
                           cs_get_t     *result)
{
  const cs_gw_soil_t  *soil = (const cs_gw_soil_t  *)soil_struc;
  const cs_gw_tracy_t  law = soil->tracy_param;

  /* Up to now, only isotropic values are considered */
  const double  ks = soil->saturated_permeability.val;
  const double  isoval = ks * (h - law.h_r)/(law.h_s - law.h_r);

  /* Build the related tensor (in bottom laywer permeability is always defined
     as a tensor) */
  for (int k = 0; k < 3; k++) {
    result->tens[k][k] = isoval;
    for (int l = k+1; l < 3; l++) {
      result->tens[k][l] = result->tens[l][k] = 0;
    }
  }

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Define the moisture content using the Tracy law
 *
 * \param[in]      h             value of the hydralic head
 * \param[in]      soil_struc    pointer to a soil structure
 * \param[in, out] result        pointer to a cs_get_t structure
 */
/*----------------------------------------------------------------------------*/

static inline void
_moisture_by_tracy_law(double        h,
                       const void   *soil_struc,
                       cs_get_t     *result)
{
  const cs_gw_soil_t  *soil = (const cs_gw_soil_t  *)soil_struc;
  const cs_gw_tracy_t  law = soil->tracy_param;

  double  k_r = (h - law.h_r)/(law.h_s - law.h_r);
  double  moisture = k_r * soil->delta_moisture + soil->residual_moisture;

  result->val = moisture;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Update the pressure head from the value of the hydraulic head
 *
 * \param[in]      connect     pointer to a cs_cdo_connect_t structure
 * \param[in]      cdoq        pointer to a cs_cdo_quantities_t structure
 * \param[in]      richards    pointer to the Richards equation structure
 * \param[in, out] gw          pointer to a cs_groundwater_t structure
 */
/*----------------------------------------------------------------------------*/

static void
_update_head(const cs_cdo_connect_t      *connect,
             const cs_cdo_quantities_t   *cdoq,
             const cs_equation_t         *richards,
             cs_groundwater_t            *gw)
{
  /* Sanity checks */
  if (gw == NULL) bft_error(__FILE__, __LINE__, 0,  _err_empty_gw);
  if (richards == NULL)
    bft_error(__FILE__, __LINE__, 0," Richards eq. is not allocated.");

  cs_field_t  *h_head = gw->hydraulic_head;

  /* Sanity check */
  assert(h_head->location_id == cs_mesh_location_get_id_by_name(N_("cells")));

  switch (cs_equation_get_space_scheme(richards)) {
  case CS_SPACE_SCHEME_CDOVB:
    {
      /* Copy current field values to previous values */
      cs_field_current_to_previous(h_head);

      cs_field_t  *h_head_vtx = cs_equation_get_field(richards);

      /* Sanity check */
      assert(h_head_vtx->location_id ==
             cs_mesh_location_get_id_by_name(N_("vertices")));

      /* Reconstruct (or interpolate) values at the cell centers */
# pragma omp parallel for if (cdoq->n_cells > CS_THR_MIN)
      for (cs_lnum_t c_id = 0; c_id < cdoq->n_cells; c_id++)
        cs_reco_pv_at_cell_center(c_id, connect->c2v, cdoq, h_head_vtx->val,
                                  h_head->val + c_id);

    }
    break;

  case CS_SPACE_SCHEME_CDOVCB:
    {
      const cs_real_t  *hh_vals = cs_equation_get_cell_values(richards);

      /* Copy current field values to previous values */
      cs_field_current_to_previous(h_head);

      /* Copy values at cells center into this field */
      memcpy(h_head->val, hh_vals, sizeof(cs_real_t)*cdoq->n_cells);
    }
    break;

  case CS_SPACE_SCHEME_CDOFB:
    break; // Nothing to do (h_head is a pointer to richards field

  default:
    bft_error(__FILE__, __LINE__, 0, " Invalid space scheme.");

  } // Switch on space scheme

  if (gw->with_gravitation) {

    cs_field_t  *p_head = gw->pressure_head;

    /* Sanity checks */
    if (p_head == NULL)
      bft_error(__FILE__, __LINE__, 0,
                " The field related to the pressure head is not allocated.");

    /* Copy current field values to previous values */
    cs_field_current_to_previous(p_head);

# pragma omp parallel for if (cdoq->n_cells > CS_THR_MIN)
    for (cs_lnum_t c_id = 0; c_id < cdoq->n_cells; c_id++) {

      const cs_real_t  gpot = cs_math_3_dot_product(cdoq->cell_centers + 3*c_id,
                                                    gw->gravity);

      p_head->val[c_id] = h_head->val[c_id] - gpot;

    }

  } // Gravitation effect is activated

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Update the moisture content from the value of the hydraulic head
 *
 * \param[in]      cdoq        pointer to a cs_cdo_quantities_t structure
 * \param[in]      richards    pointer to the Richards equation structure
 * \param[in, out] gw          pointer to a cs_groundwater_t structure
 */
/*----------------------------------------------------------------------------*/

static void
_update_moisture_content(const cs_cdo_quantities_t   *cdoq,
                         const cs_equation_t         *richards,
                         cs_groundwater_t            *gw)
{
  /* Sanity checks */
  if (richards == NULL || gw == NULL)
    bft_error(__FILE__, __LINE__, 0,
              " Groundwater module or Richards eq. is not allocated.");

  cs_field_t  *moisture = gw->moisture_content;

  /* Sanity checks */
  if (moisture == NULL)
    bft_error(__FILE__, __LINE__, 0,
              " The field related to the moisture content is not allocated.");

  /* Copy current field values to previous values */
  cs_field_current_to_previous(moisture);

  /* Moisture content is define in each cell along with the hydraulic (or
     pressure head */

  const cs_field_t  *h;
  if (gw->with_gravitation)
    h = gw->pressure_head;
  else
    h = gw->hydraulic_head;

  for (int soil_id = 0; soil_id < gw->n_soils; soil_id++) {

    const cs_gw_soil_t  *soil = gw->soil_param + soil_id;
    const cs_lnum_t  *elt_ids = cs_mesh_location_get_elt_list(soil->ml_id);

    switch (soil->model) {

    case CS_GROUNDWATER_MODEL_GENUCHTEN:

      if (elt_ids == NULL) {
# pragma omp parallel for if (cdoq->n_cells > CS_THR_MIN)
        for (cs_lnum_t c_id = 0; c_id < cdoq->n_cells; c_id++) {

          cs_get_t  get;

          _moisture_by_genuchten_law(h->val[c_id], (const void *)soil, &get);
          moisture->val[c_id] = get.val;

        } // Loop on cells

      }
      else {

        const cs_lnum_t  *n_elts = cs_mesh_location_get_n_elts(soil->ml_id);

# pragma omp parallel for if (n_elts[0] > CS_THR_MIN)
        for (cs_lnum_t i = 0; i < n_elts[0]; i++) {

          cs_get_t  get;
          const cs_lnum_t  c_id = elt_ids[i];

          _moisture_by_genuchten_law(h->val[c_id], (const void *)soil, &get);
          moisture->val[c_id] = get.val;

        } // Loop on cells

      } // cell selection is a part of all cells
      break;

    case CS_GROUNDWATER_MODEL_TRACY:
      if (elt_ids == NULL) {

# pragma omp parallel for if (cdoq->n_cells > CS_THR_MIN)
        for (cs_lnum_t c_id = 0; c_id < cdoq->n_cells; c_id++) {

          cs_get_t  get;

          _moisture_by_tracy_law(h->val[c_id], (const void *)soil, &get);
          moisture->val[c_id] = get.val;

        } // Loop on cells

      }
      else {

        const cs_lnum_t  *n_elts = cs_mesh_location_get_n_elts(soil->ml_id);

# pragma omp parallel for if (n_elts[0] > CS_THR_MIN)
        for (cs_lnum_t i = 0; i < n_elts[0]; i++) {

          cs_get_t  get;
          const cs_lnum_t  c_id = elt_ids[i];

          _moisture_by_tracy_law(h->val[c_id], (const void *)soil, &get);
          moisture->val[c_id] = get.val;

        } // Loop on cells

      } // cell selection is a part of all cells
      break;

    case CS_GROUNDWATER_MODEL_SATURATED:
      if (elt_ids == NULL) {

# pragma omp parallel for if (cdoq->n_cells > CS_THR_MIN)
        for (cs_lnum_t c_id = 0; c_id <  cdoq->n_cells; c_id++)
          moisture->val[c_id] = soil->saturated_moisture;

      }
      else {

        const cs_lnum_t  *n_elts = cs_mesh_location_get_n_elts(soil->ml_id);

# pragma omp parallel for if (n_elts[0] > CS_THR_MIN)
        for (cs_lnum_t i = 0; i < n_elts[0]; i++)
          moisture->val[elt_ids[i]] = soil->saturated_moisture;

      } // cell selection is a part of all cells
      break;

    default:
      bft_error(__FILE__, __LINE__, 0,
                _(" Invalid type of model for estimating the moisture"
                  " content."));
      break; // Nothing to do

    } // Switch on the type of soil modelling

  } // Loop on soils

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Check if the setting is correct
 *
 * \param[in]  gw     pointer to a cs_groundwater_t struct.
 */
/*----------------------------------------------------------------------------*/

static void
_check_settings(const cs_groundwater_t  *gw)
{
  if (gw == NULL) bft_error(__FILE__, __LINE__, 0, _(_err_empty_gw));

  for (int i = 0; i < gw->n_max_tracers; i++)
    if (gw->tracer_eq_ids[i] == -1)
      bft_error(__FILE__, __LINE__, 0,
                " At least one tracer equation has not been set.\n"
                " %d tracer equations have heen initialy requested.\n"
                " Please check your settings.", gw->n_max_tracers);


  if (gw->n_soils < gw->n_max_soils)
    bft_error(__FILE__, __LINE__, 0,
              " %d soils are defined but %d have been initially requested."
              " Please check your settings.", gw->n_soils, gw->n_max_soils);

  if (gw->n_soils > 1) {

    cs_lnum_t  n_unset_cells = 0;
    int  cell_ml_id = cs_mesh_location_get_id_by_name(N_("cells"));
    const cs_lnum_t  *n_elts = cs_mesh_location_get_n_elts(cell_ml_id);

# pragma omp parallel reduction(+:n_unset_cells) if (n_elts[0] > CS_THR_MIN)
    for (cs_lnum_t i = 0; i < n_elts[0]; i++)
      if (gw->soil_id[i] == gw->n_max_soils) n_unset_cells++;

    if (n_unset_cells > 0)
      bft_error(__FILE__, __LINE__, 0,
                " %d cells are not associated to any soil.\n"
                " Please check your settings.", n_unset_cells);

  } // n_soils > 1

}

/*============================================================================
 * Public function prototypes
 *============================================================================*/

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Create a structure dedicated to manage groundwater flows
 *
 * \return a pointer to a new allocated cs_groundwater_t structure
 */
/*----------------------------------------------------------------------------*/

cs_groundwater_t *
cs_groundwater_create(void)
{
  cs_groundwater_t  *gw = NULL;

  BFT_MALLOC(gw, 1, cs_groundwater_t);

  /* Default initialization */
  gw->flag = 0;

  gw->n_soils = 0;
  gw->n_max_soils = 0;
  gw->soil_param = NULL;
  gw->soil_id = NULL;

  gw->global_model = CS_GROUNDWATER_N_MODELS;

  gw->with_gravitation = false;
  gw->gravity[0] = 0, gw->gravity[1] = 0, gw->gravity[2] = 0;
  gw->hydraulic_head = NULL;
  gw->pressure_head = NULL;

  gw->richards_eq_id = -1;
  gw->n_tracers = 0;
  gw->n_max_tracers = 0;
  gw->tracer_eq_ids = NULL;

  gw->darcian_flux = NULL;
  gw->adv_field = NULL;
  gw->work = NULL;

  return gw;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Free the main structure related to groundwater flows
 *
 * \param[in, out]  gw     pointer to a cs_groundwater_t struct. to free
 *
 * \return a NULL pointer
 */
/*----------------------------------------------------------------------------*/

cs_groundwater_t *
cs_groundwater_finalize(cs_groundwater_t   *gw)
{
  if (gw == NULL)
    return NULL;

  BFT_FREE(gw->tracer_eq_ids);
  BFT_FREE(gw->darcian_flux);
  BFT_FREE(gw->work);

  for (int i = 0; i < gw->n_soils; i++) {
    cs_gw_soil_t *soil = gw->soil_param + i;
    BFT_FREE(soil->tracer_param);
  }

  if (gw->n_soils > 1)
    BFT_FREE(gw->soil_id);

  BFT_FREE(gw->soil_param);

  BFT_FREE(gw);

  /* Fields, advection fields and properties are freed elsewhere */

  return NULL;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Get the number of requested soils
 *
 * \param[in]  gw        pointer to a cs_groundwater_t structure
 *
 * \return the number of requested soils
 */
/*----------------------------------------------------------------------------*/

int
cs_groundwater_get_n_soils(const cs_groundwater_t    *gw)
{
  if (gw == NULL)
    return 0;

  return gw->n_max_soils;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Set parameters related to a cs_groundwater_t structure
 *
 * \param[in, out]  gw        pointer to a cs_groundwater_t structure
 * \param[in]       key       key related to the member of gw to set
 * \param[in]       keyval    accessor to the value to set
 */
/*----------------------------------------------------------------------------*/

void
cs_groundwater_set_param(cs_groundwater_t      *gw,
                         cs_groundwater_key_t   key,
                         const char            *keyval)
{
  if (gw == NULL) bft_error(__FILE__, __LINE__, 0, _(_err_empty_gw));

  /* Conversion of the string to lower case */
  char val[CS_BASE_STRING_LEN];
  for (size_t i = 0; i < strlen(keyval); i++)
    val[i] = tolower(keyval[i]);
  val[strlen(keyval)] = '\0';

  switch(key) {

  case CS_GWKEY_GRAVITATION:
    gw->with_gravitation = true;
    gw->gravity[0] = gw->gravity[1] = gw->gravity[2] = 0.;
    if (strcmp(val, "x") == 0)       gw->gravity[0] =  1.;
    else if (strcmp(val, "-x") == 0) gw->gravity[0] = -1.;
    else if (strcmp(val, "y") == 0)  gw->gravity[1] =  1.;
    else if (strcmp(val, "-y") == 0) gw->gravity[1] = -1.;
    else if (strcmp(val, "z") == 0)  gw->gravity[2] =  1.;
    else if (strcmp(val, "-z") == 0) gw->gravity[2] = -1.;
    else
      bft_error(__FILE__, __LINE__, 0,
                _(" Invalid choice of gravitation axis: %s.\n"
                  " Available choices are 'x', 'y' and 'z'\n"
                  " Please check your settings."), val);
    break;

  case CS_GWKEY_OUTPUT_MOISTURE:
    if (strcmp(val, "false")) // not "false"
      gw->flag |= CS_GROUNDWATER_POST_MOISTURE;
    break;

  default:
    bft_error(__FILE__, __LINE__, 0, _(" Key not implemented yet."));

  } /* Switch on keys */

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Summary of a cs_groundwater_t structure
 *
 * \param[in]  gw     pointer to a cs_groundwater_t struct. to summarize
 */
/*----------------------------------------------------------------------------*/

void
cs_groundwater_summary(const cs_groundwater_t   *gw)
{
  if (gw == NULL)
    return;

  /* Sanity checks */
  _check_settings(gw);

  bft_printf("\n");
  bft_printf("%s", lsepline);
  bft_printf("\tSummary of the groundwater module\n");
  bft_printf("%s", lsepline);

  if (gw->with_gravitation)
    bft_printf("  <GW/Gravitation> true -- Axis = [%.2f %.2f %.2f]\n",
               gw->gravity[0], gw->gravity[1], gw->gravity[2]);
  else
    bft_printf("  <GW/Gravitation> false\n");

  bft_printf("  <GW/Tracer> n_tracer_equations %d\n", gw->n_tracers);
  bft_printf("  <GW/Soils>  n_soils %d\n", gw->n_soils);

  const cs_property_t  *permeability = gw->permeability;

  for (int i = 0; i < gw->n_soils; i++) {

    const cs_gw_soil_t  soil = gw->soil_param[i];
    const char *ml_name = cs_mesh_location_get_name(soil.ml_id);
    const cs_get_t  sat_perm = soil.saturated_permeability;

    bft_printf("  <GW/Soil %s>", ml_name);
    bft_printf(" residual_moisture %5.3e", soil.residual_moisture);
    bft_printf(" saturated_moisture %5.3e\n", soil.saturated_moisture);
    bft_printf("  <GW/Soil %s>", ml_name);

    switch (cs_property_get_type(permeability)) {

    case CS_PROPERTY_ISO:
      bft_printf(" saturated_permeability (iso) %5.3e\n", sat_perm.val);
      break;

    case CS_PROPERTY_ORTHO:
      bft_printf(" saturated_permeability (ortho) %5.3e %5.3e %5.3e\n",
                 sat_perm.vect[0], sat_perm.vect[1], sat_perm.vect[2]);
      break;

    case CS_PROPERTY_ANISO:
      bft_printf(" saturated_permeability (aniso) %-5.3e %5.3e %5.3e\n"
                 "                                %-5.3e %5.3e %5.3e\n"
                 "                                %-5.3e %5.3e %5.3e\n",
                 sat_perm.tens[0][0], sat_perm.tens[0][1], sat_perm.tens[0][2],
                 sat_perm.tens[1][0], sat_perm.tens[1][1], sat_perm.tens[1][2],
                 sat_perm.tens[2][0], sat_perm.tens[2][1], sat_perm.tens[2][2]);
      break;

    default:
      bft_error(__FILE__, __LINE__, 0,
                _(" Invalid type of property for %s."),
                cs_property_get_name(permeability));
      break;

    } // Switch on property type

    bft_printf("  <GW/Soil %s>", ml_name);
    switch (soil.model) {
    case CS_GROUNDWATER_MODEL_GENUCHTEN:
      bft_printf(" model VanGenuchten-Mualen\n");
      break;
    case CS_GROUNDWATER_MODEL_SATURATED:
      bft_printf(" model saturated\n");
      break;
    case CS_GROUNDWATER_MODEL_TRACY:
      bft_printf(" model Tracy\n");
      break;
    case CS_GROUNDWATER_MODEL_USER:
      bft_printf(" model User-defined\n");
      break;

    default:
      bft_error(__FILE__, __LINE__, 0,
                " Invalid model for a soil in the groundwater module.\n"
                " Please check your settings.");
    } // Switch model

  } // Loop on soils

  if (gw->n_soils > 1) {

    switch (gw->global_model) {
    case CS_GROUNDWATER_MODEL_COMPOSITE:
      bft_printf("  <GW/Global model> composite model\n");
      break;
    case CS_GROUNDWATER_MODEL_GENUCHTEN:
      bft_printf("  <GW/Global model> model VanGenuchten-Mualen\n");
      break;
    case CS_GROUNDWATER_MODEL_SATURATED:
      bft_printf("  <GW/Global model> model saturated\n");
      break;
    case CS_GROUNDWATER_MODEL_TRACY:
      bft_printf("  <GW/Global model> model Tracy\n");
      break;
    case CS_GROUNDWATER_MODEL_USER:
      bft_printf("  <GW/Global model> model User-defined\n");
      break;

    default:
      bft_error(__FILE__, __LINE__, 0,
                " Invalid model for groundwater module.\n"
                " Please check your settings.");
    } // Switch model

  }

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Initialize the module dedicated to groundwater flows
 *
 * \param[in]      connect          pointer to a cs_cdo_connect_t structure
 * \param[in]      richards_eq_id   id related to the Richards equation
 * \param[in]      n_soils          number of soils to consider
 * \param[in]      n_tracers        number of tracers to consider
 * \param[in, out] permeability     pointer to a property structure
 * \param[in, out] soil_capacity    pointer to a property structure
 * \param[in, out] adv_field        pointer to a cs_adv_field_t structure
 * \param[in, out] gw               pointer to a cs_groundwater_t structure
 *
 * \return a pointer to a new allocated equation structure (Richards eq.)
 */
/*----------------------------------------------------------------------------*/

cs_equation_t *
cs_groundwater_initialize(const cs_cdo_connect_t  *connect,
                          int                      richards_eq_id,
                          int                      n_soils,
                          int                      n_tracer_eqs,
                          cs_property_t           *permeability,
                          cs_property_t           *soil_capacity,
                          cs_adv_field_t          *adv_field,
                          cs_groundwater_t        *gw)
{
  cs_equation_t  *eq = NULL;

  const cs_connect_index_t  *c2e = connect->c2e;
  const cs_lnum_t  n_cells = connect->c_info->n_elts;

  /* Sanity check */
  assert(n_soils > 0);

  if (gw == NULL) bft_error(__FILE__, __LINE__, 0, _(_err_empty_gw));

  gw->richards_eq_id = richards_eq_id;

  /* Create a new equation structure for Richards' equation */
  eq = cs_equation_create("Richards",                   // equation name
                          "hydraulic_head",             // variable name
                          CS_EQUATION_TYPE_GROUNDWATER, // type of equation
                          CS_PARAM_VAR_SCAL,            // type of variable
                          CS_PARAM_BC_HMG_NEUMANN);     // default BC

  /* Associate soil_capacity to the unsteady term of the Richards eq. */
  if (soil_capacity != NULL)
    cs_equation_link(eq, "time", soil_capacity);

  /* Associate permeability to the diffusion property of the Richards eq. */
  gw->permeability = permeability;
  cs_equation_link(eq, "diffusion", permeability);

  /* Advection field induced by the hydraulic head */
  gw->adv_field = adv_field;

  /* Up to now Richards equation is only set with vertex-based schemes */
  BFT_MALLOC(gw->darcian_flux, c2e->idx[n_cells], cs_real_t);
# pragma omp parallel for if (n_cells > CS_THR_MIN)
  for (cs_lnum_t i = 0; i < c2e->idx[n_cells]; i++)
    gw->darcian_flux[i] = 0;

  /* Work (temporary) buffer */
  BFT_MALLOC(gw->work, connect->n_max_ebyc, cs_real_t);

  /* Quantities related to soils */
  gw->n_soils = 0;           /* No soil is set at the beginning */
  gw->n_max_soils = n_soils; /* Max. number of soils allocated */
  BFT_MALLOC(gw->soil_param, n_soils, cs_gw_soil_t);

  if (n_soils > 1) {
    BFT_MALLOC(gw->soil_id, n_cells, short int);

# pragma omp parallel for if (n_cells > CS_THR_MIN)
    for (cs_lnum_t i = 0; i < n_cells; i++)
      gw->soil_id[i] = n_soils; /* Default value => not set */
  }

  gw->n_tracers = 0;
  gw->n_max_tracers = n_tracer_eqs;
  BFT_MALLOC(gw->tracer_eq_ids, n_tracer_eqs, int);
  for (int i = 0; i < n_tracer_eqs; i++)
    gw->tracer_eq_ids[i] = -1; /* Default initialization = not set */

  return eq;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Add a new type of soil to consider in the groundwater module
 *
 * \param[in, out] gw         pointer to a cs_groundwater_t structure
 * \param[in]      ml_name    name of the mesh location related to this soil
 * \param[in]      model_kw   keyword related to the model used
 * \param[in]      ks         value(s) of the saturated permeability
 */
/*----------------------------------------------------------------------------*/

void
cs_groundwater_add_soil_by_value(cs_groundwater_t   *gw,
                                 const char         *ml_name,
                                 const char         *model_kw,
                                 const char         *pty_val)
{
  if (gw == NULL) bft_error(__FILE__, __LINE__, 0, _(_err_empty_gw));

  int  soil_id = gw->n_soils;

  gw->n_soils += 1;
  if (gw->n_soils > gw->n_max_soils)
    bft_error(__FILE__, __LINE__, 0,
              " Maximum number of soils is reached.\n"
              " Stop adding a new soil by value (mesh location: %s).\n"
              " Please modify your settings.", ml_name);

  cs_gw_soil_t  *soil = gw->soil_param + soil_id;

  _init_soil(ml_name, model_kw, gw->n_max_tracers, soil);

  /* Set the saturated permeability */
  switch (cs_property_get_type(gw->permeability)) {

  case CS_PROPERTY_ISO:
    cs_param_set_get(CS_PARAM_VAR_SCAL, (const void *)pty_val,
                     &(soil->saturated_permeability));
    break;

  case CS_PROPERTY_ORTHO:
    cs_param_set_get(CS_PARAM_VAR_VECT, (const void *)pty_val,
                     &(soil->saturated_permeability));
    break;

  case CS_PROPERTY_ANISO:
    cs_param_set_get(CS_PARAM_VAR_TENS, (const void *)pty_val,
                     &(soil->saturated_permeability));
    break;

  default:
    bft_error(__FILE__, __LINE__, 0,
              _(" Invalid type of property for %s."),
              cs_property_get_name(gw->permeability));
    break;

  } /* End of switch */

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Set parameters related to a cs_groundwater_t structure
 *
 * \param[in, out]  gw        pointer to a cs_groundwater_t structure
 * \param[in]       ml_name   name of the mesh location associated to this soil
 * \param[in]       key       key related to a member of the soil to set
 * \param[in]       keyval    accessor to the value to set
 */
/*----------------------------------------------------------------------------*/

void
cs_groundwater_set_soil_param(cs_groundwater_t          *gw,
                              const char                *ml_name,
                              cs_groundwater_soilkey_t   key,
                              const char                *keyval)
{
  if (gw == NULL) bft_error(__FILE__, __LINE__, 0, _(_err_empty_gw));

  int  ml_id = -1;
  if (ml_name != NULL) {
    ml_id = cs_mesh_location_get_id_by_name(ml_name);
    if (ml_id == -1)
      bft_error(__FILE__, __LINE__, 0,
                _(" Invalid mesh location name %s.\n"
                  " This mesh location is not already defined.\n"), ml_name);
  }

  /* Conversion of the string to lower case */
  char val[CS_BASE_STRING_LEN];
  for (size_t i = 0; i < strlen(keyval); i++)
    val[i] = tolower(keyval[i]);
  val[strlen(keyval)] = '\0';

  /* Set different available keys */
  switch(key) {

  case CS_SOILKEY_SAT_MOISTURE:
    {
      double  theta_s = atof(val);

      if (ml_id == -1) {

        for (int i = 0; i < gw->n_soils; i++) {
          gw->soil_param[i].saturated_moisture = theta_s;
          /* Update delta_moisture */
          gw->soil_param[i].delta_moisture =
            theta_s - gw->soil_param[i].residual_moisture;
        } // Loop on soils

      } // All soils are updated
      else {

        for (int i = 0; i < gw->n_soils; i++) {
          if (ml_id == gw->soil_param[i].ml_id) {
            gw->soil_param[i].saturated_moisture = theta_s;
            /* Update delta_moisture */
            gw->soil_param[i].delta_moisture =
              theta_s - gw->soil_param[i].residual_moisture;
          }
        } // Loop on soils

      }
    }
    break;

  case CS_SOILKEY_RES_MOISTURE:
    {
      double  theta_r = atof(val);

      if (ml_id == -1) {

        for (int i = 0; i < gw->n_soils; i++) {
          gw->soil_param[i].residual_moisture = theta_r;
          /* Update delta_moisture */
          gw->soil_param[i].delta_moisture =
            gw->soil_param[i].saturated_moisture - theta_r;
        } // Loop on soils

      }
      else {

        for (int i = 0; i < gw->n_soils; i++) {
          if (ml_id == gw->soil_param[i].ml_id) {
            gw->soil_param[i].residual_moisture = theta_r;
            /* Update delta_moisture */
            gw->soil_param[i].delta_moisture =
              gw->soil_param[i].saturated_moisture - theta_r;
          }
        } // Loop on soils

      }
    }
    break;

  case CS_SOILKEY_TRACY_SAT_H:
    {
      double  h_s = atof(val);

      if (ml_id == -1) {
        for (int i = 0; i < gw->n_soils; i++)
          if (gw->soil_param[i].model == CS_GROUNDWATER_MODEL_TRACY)
            gw->soil_param[i].tracy_param.h_s = h_s;
      }
      else {
        for (int i = 0; i < gw->n_soils; i++)
          if (ml_id == gw->soil_param[i].ml_id)
            gw->soil_param[i].tracy_param.h_s = h_s;
      }

    }
    break;

  case CS_SOILKEY_TRACY_RES_H:
    {
      double  h_r = atof(val);

      if (ml_id == -1) {

        for (int i = 0; i < gw->n_soils; i++)
          if (gw->soil_param[i].model == CS_GROUNDWATER_MODEL_TRACY)
            gw->soil_param[i].tracy_param.h_r = h_r;

      }
      else {

        for (int i = 0; i < gw->n_soils; i++)
          if (ml_id == gw->soil_param[i].ml_id)
            gw->soil_param[i].tracy_param.h_r = h_r;

      }
    }
    break;

  default:
    bft_error(__FILE__, __LINE__, 0, _(" Key not implemented"));

  } /* Switch on keys */

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Add a new equation related to the groundwater flow module
 *         This equation is a specific unsteady advection/diffusion/reaction eq.
 *         Tracer is advected thanks to the darcian velocity which is given
 *         by the resolution of the Richards equation.
 *         Diffusion and reaction parameters result from a physical modelling.
 *
 * \param[in, out] gw              pointer to a cs_groundwater_t structure
 * \param[in]      tracer_eq_id    id related to the tracer equation
 * \param[in]      eqname          name of the equation
 * \param[in]      varname         name of the related variable
 *
 * \return a pointer to a new allocated equation structure (Tracer eq.)
 */
/*----------------------------------------------------------------------------*/

cs_equation_t *
cs_groundwater_add_tracer(cs_groundwater_t    *gw,
                          int                  tracer_eq_id,
                          const char          *eqname,
                          const char          *varname)
{
  /* Sanity check */
  if (gw == NULL) bft_error(__FILE__, __LINE__, 0, _(_err_empty_gw));

  if (gw->n_soils != gw->n_max_soils)
    bft_error(__FILE__, __LINE__, 0,
              " Add a tracer but not all soils are defined (%d/%d).\n"
              " Stop adding a new tracer equation (%s).\n"
              " Please check your settings.",
              gw->n_soils, gw->n_max_soils, eqname);

  int  tracer_id = gw->n_tracers;
  cs_equation_t  *eq = NULL;

  eq = cs_equation_create(eqname,                       // equation name
                          varname,                      // variable name
                          CS_EQUATION_TYPE_GROUNDWATER, // type of equation
                          CS_PARAM_VAR_SCAL,            // type of variable
                          CS_PARAM_BC_HMG_NEUMANN);     // default BC

  gw->n_tracers += 1;
  if (gw->n_tracers > gw->n_max_tracers)
    bft_error(__FILE__, __LINE__, 0,
              _(" Maximum number of tracers is reached.\n"
                " Stop adding the tracer equation %s.\n"
                " Please modify your settings."), eqname);

  BFT_REALLOC(gw->tracer_eq_ids, gw->n_tracers, int);
  gw->tracer_eq_ids[tracer_id] = tracer_eq_id;

  /* Associate the advection field for the advection term */
  assert(gw->adv_field != NULL); /* Sanity check */
  cs_equation_link(eq, "advection", gw->adv_field);

  /* Set default option */
  cs_equation_set_param(eq, CS_EQKEY_SPACE_SCHEME, "cdo_vb");
  cs_equation_set_param(eq, CS_EQKEY_ITSOL, "bicg");
  cs_equation_set_param(eq, CS_EQKEY_BC_ENFORCEMENT, "weak");

  return eq;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Add a new equation related to the groundwater flow module
 *         This equation is a specific unsteady advection/diffusion/reaction eq.
 *         Tracer is advected thanks to the darcian velocity which is given
 *         by the resolution of the Richards equation.
 *         Diffusion/reaction parameters result from a physical modelling.
 *
 * \param[in, out] gw              pointer to a cs_groundwater_t structure
 * \param[in]      tracer_eq_id    id related to the tracer equation
 * \param[in]      ml_name         name of the related mesh location
 * \param[in]      wmd             value of the water molecular diffusivity
 * \param[in]      alpha_l         value of the longitudinal dispersivity
 * \param[in]      alpha_t         value of the transversal dispersivity
 * \param[in]      bulk_density    value of the bulk density
 * \param[in]      distrib_coef    value of the distribution coefficient
 * \param[in]      reaction_rate   value of the first order rate of reaction
 */
/*----------------------------------------------------------------------------*/

void
cs_groundwater_set_tracer_param(cs_groundwater_t    *gw,
                                int                  tracer_eq_id,
                                const char          *ml_name,
                                double               wmd,
                                double               alpha_l,
                                double               alpha_t,
                                double               bulk_density,
                                double               distrib_coef,
                                double               reaction_rate)
{
  /* Sanity check */
  if (gw == NULL) bft_error(__FILE__, __LINE__, 0, _(_err_empty_gw));

  int  tracer_id = _get_tracer_id(gw, tracer_eq_id);

  /* Look for the related soil */
  if (ml_name == NULL) { /* All soils have to be set for this tracer */

    for (int soil_id = 0; soil_id < gw->n_soils; soil_id++) {

      cs_gw_soil_t  *soil = gw->soil_param + soil_id;

      /* Set tracer parameters */
      _set_tracer_param(soil->tracer_param + tracer_id,
                        wmd,
                        alpha_l, alpha_t,
                        bulk_density, distrib_coef,
                        reaction_rate);

    } // Loop on soils

  }
  else { /* Set this tracer equation for a specific soil */

    int ml_id = cs_mesh_location_get_id_by_name(ml_name);
    if (ml_id == -1)
      bft_error(__FILE__, __LINE__, 0,
                _( " Stop setting a tracer equation."
                   " Invalid mesh location name %s.\n"
                   " This mesh location is not already defined.\n"), ml_name);

    int  soil_id = -1;
    for (int id = 0; id < gw->n_soils; id++) {
      if (gw->soil_param[id].ml_id == ml_id) {
        soil_id = id;
        break;
      }
    }

    if (soil_id == -1)
      bft_error(__FILE__, __LINE__, 0,
                _(" Stop setting a tracer equation."
                  " No soil related to mesh location %s has been found.\n"
                  " Please check your settings."), ml_name);

    cs_gw_soil_t  *soil = gw->soil_param + soil_id;

    /* Set tracer parameters */
    _set_tracer_param(soil->tracer_param + tracer_id,
                      wmd,
                      alpha_l, alpha_t,
                      bulk_density, distrib_coef,
                      reaction_rate);

  } /* Set a specific couple (tracer,soil) */

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Predefined settings for the Richards equation
 *
 * \param[in, out] gw        pointer to a cs_groundwater_t structure
 * \param[in, out] richards  pointer to the related cs_equation_t structure
 */
/*----------------------------------------------------------------------------*/

void
cs_groundwater_richards_setup(cs_groundwater_t    *gw,
                              cs_equation_t       *richards)
{
  /* Sanity checks */
  assert(richards != NULL);
  if (gw == NULL) bft_error(__FILE__, __LINE__, 0, _(_err_empty_gw));

  if (gw->n_soils == 0)
    bft_error(__FILE__, __LINE__, 0,
              _(" Groundwater module is activated but no soil is defined."));

  const cs_space_scheme_t  cdo_scheme = cs_equation_get_space_scheme(richards);
  if (cdo_scheme == CS_SPACE_SCHEME_CDOFB)
    bft_error(__FILE__, __LINE__, 0,
              _(" Richards eq. is only available for vertex-based schemes."));

  cs_property_t  *permeability = gw->permeability;
  bool has_previous = cs_equation_is_steady(richards) ? false:true;
  int  field_mask = CS_FIELD_INTENSIVE | CS_FIELD_VARIABLE;
  int  cell_loc_id = cs_mesh_location_get_id_by_name(N_("cells"));

  /* Create a moisture field attached to cells */
  gw->moisture_content = cs_field_create("moisture_content",
                                         field_mask,
                                         cell_loc_id,
                                         1,        // dimension
                                         has_previous);

  /* Allocate and initialize values */
  cs_field_allocate_values(gw->moisture_content);

  /* Create or shared a field attached to cell for the hydraulic head */
  if (cdo_scheme == CS_SPACE_SCHEME_CDOFB) // For a future usage
    gw->hydraulic_head = cs_equation_get_field(richards);

  else { // Create a new field

    /* Create a hydraulic head field attached to cells (field on vertices
       are already defined thanks to the Richards equation in this case) */
    gw->hydraulic_head = cs_field_create("hydraulic_head_cell",
                                         field_mask,
                                         cell_loc_id,
                                         1,        // dimension
                                         has_previous);

    /* Allocate and initialize values */
    cs_field_allocate_values(gw->hydraulic_head);

  }

  if (gw->with_gravitation) { /* Gravitation effect */

    gw->pressure_head = cs_field_create("pressure_head",
                                        field_mask,
                                        cell_loc_id,
                                        1,
                                        has_previous);

    /* Allocate and initialize values */
    cs_field_allocate_values(gw->pressure_head);

  }

  /* Set the values for the permeability and the moisture content
     and if needed set also the value of the soil capacity */

  gw->global_model = gw->soil_param[0].model;

  for (int soil_id = 0; soil_id < gw->n_soils; soil_id++) {

    const cs_gw_soil_t  *soil = gw->soil_param + soil_id;
    const double  theta_s = soil->saturated_moisture;

    /* Is there a unique model ? */
    if (soil->model != gw->global_model)
      gw->global_model = CS_GROUNDWATER_MODEL_COMPOSITE;

    const char  *ml_name = cs_mesh_location_get_name(soil->ml_id);
    const cs_lnum_t *n_elts = cs_mesh_location_get_n_elts(soil->ml_id);
    const cs_lnum_t  *elt_ids = cs_mesh_location_get_elt_list(soil->ml_id);

    /* Initialization of soil_id and moisture content */
    if (gw->n_soils > 1) {

      assert(elt_ids != NULL); /* sanity check */

# pragma omp parallel for if (n_elts[0] > CS_THR_MIN)
      for (cs_lnum_t i = 0; i < n_elts[0]; i++) {

        cs_lnum_t  c_id = elt_ids[i];

        gw->moisture_content->val[c_id] = theta_s;
        gw->soil_id[c_id] = soil_id;

      } // Loop on selected cells

    }
    else { /* n_soils == 1 => all cells are selected */

# pragma omp parallel for if (n_elts[0] > CS_THR_MIN)
      for (cs_lnum_t i = 0; i < n_elts[0]; i++)
        gw->moisture_content->val[i] = theta_s;

    }

    switch (soil->model) {

    case CS_GROUNDWATER_MODEL_GENUCHTEN:
      {
        cs_desc_t  desc = {.location = CS_FLAG_SCAL | cs_cdo_primal_cell,
                           .state = CS_FLAG_STATE_POTENTIAL};

        /* Set permeability tensor behavior */
        cs_property_def_by_law(permeability,
                               ml_name,
                               (const void *)soil,
                               _permeability_by_genuchten_law);

        if (gw->with_gravitation)
          cs_property_set_array(permeability, desc, gw->pressure_head->val);
        else
          cs_property_set_array(permeability, desc, gw->hydraulic_head->val);

        /* Soil capacity settings (related to unsteady term) */
        if (has_previous) {

          cs_property_t *capacity = cs_equation_get_time_property(richards);

          cs_property_def_by_law(cs_equation_get_time_property(richards),
                                 ml_name,
                                 (const void *)soil,
                                 _capacity_by_genuchten_law);

          if (gw->with_gravitation)
            cs_property_set_array(capacity, desc, gw->pressure_head->val);
          else
            cs_property_set_array(capacity, desc, gw->hydraulic_head->val);

        }

      }
      break;

    case CS_GROUNDWATER_MODEL_TRACY:
      {
        cs_desc_t  desc = {.location = CS_FLAG_SCAL | cs_cdo_primal_cell,
                           .state = CS_FLAG_STATE_POTENTIAL};

        /* Set permeability tensor behavior */
        cs_property_def_by_law(permeability,
                               ml_name,
                               (const void *)soil,
                               _permeability_by_tracy_law);

        if (gw->with_gravitation)
          cs_property_set_array(permeability, desc, gw->pressure_head->val);
        else
          cs_property_set_array(permeability, desc, gw->hydraulic_head->val);

        /* Soil capacity settings (related to unsteady term) */
        if (has_previous) {

          cs_property_t  *capacity = cs_equation_get_time_property(richards);

          const cs_gw_tracy_t  law = soil->tracy_param;
          const double  dh = law.h_s - law.h_r;
          const double  dtheta = soil->delta_moisture;

          cs_property_iso_def_by_value(capacity, ml_name, dtheta/dh);

        } /* Set the soil capacity */

      }
      break; // Tracy model

    case CS_GROUNDWATER_MODEL_SATURATED:

      switch (cs_property_get_type(permeability)) {

      case CS_PROPERTY_ISO:
        cs_property_iso_def_by_value(permeability,
                                     ml_name,
                                     soil->saturated_permeability.val);
        break;

      case CS_PROPERTY_ORTHO:
        cs_property_ortho_def_by_value(permeability,
                                       ml_name,
                                       soil->saturated_permeability.vect);
        break;

      case CS_PROPERTY_ANISO:
        cs_property_aniso_def_by_value(permeability,
                                       ml_name,
                  (const double (*)[3])soil->saturated_permeability.tens);
        break;

      default:
        bft_error(__FILE__, __LINE__, 0, _(" Invalid type of property."));
        break;

      } // End of switch on permeability type

      if (has_previous)
        bft_error(__FILE__, __LINE__, 0,
                  " Saturated model must yield a steady Richards equation.");

      break; // Saturated model

    default:
      bft_error(__FILE__, __LINE__, 0,
                _(" Invalid type of model for groundwater module.."));
      break; // Nothing to do

    } /* Switch depending on the type of model */

  } // Loop on the different type of soils

  { /* Define and then link the advection field to each tracer equations */
    cs_desc_t  desc = {.location = CS_FLAG_SCAL | cs_cdo_dual_face_byc,
                       .state = CS_FLAG_STATE_FLUX};

    cs_advection_field_def_by_array(gw->adv_field, desc, gw->darcian_flux);
  }
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Check if one needs to add a reaction term for a given tracer
 *
 * \param[in] gw         pointer to a cs_groundwater_t structure
 * \param[in] eq_id      id of the equation related to this tracer
 *
 * \returns true or false
 */
/*----------------------------------------------------------------------------*/

bool
cs_groundwater_tracer_needs_reaction(const cs_groundwater_t    *gw,
                                     int                        eq_id)
{
  int  tracer_id = _get_tracer_id(gw, eq_id);
  bool  is_needed = false;

  /* Loop on soils to check in a reaction term is needed */
  for (int soil_id = 0; soil_id < gw->n_soils && is_needed == false; soil_id++)
    {
      cs_gw_soil_t  *soil = gw->soil_param + soil_id;

      if (soil->tracer_param[tracer_id].reaction_rate > 0) is_needed = true;
    }

  return is_needed;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Check if one needs to add a diffusion term for a given tracer
 *
 * \param[in] gw         pointer to a cs_groundwater_t structure
 * \param[in] eq_id      id of the equation related to this tracer
 *
 * \returns true or false
 */
/*----------------------------------------------------------------------------*/

bool
cs_groundwater_tracer_needs_diffusion(const cs_groundwater_t    *gw,
                                      int                        eq_id)
{
  int  tracer_id = _get_tracer_id(gw, eq_id);
  bool  is_needed = false;

  /* Loop on soils to check in a reaction term is needed */
  for (int soil_id = 0; soil_id < gw->n_soils && is_needed == false; soil_id++)
    {
      cs_gw_soil_t  *soil = gw->soil_param + soil_id;

      if (soil->tracer_param[tracer_id].alpha_t > 0) is_needed = true;
      if (soil->tracer_param[tracer_id].alpha_l > 0) is_needed = true;
      if (soil->tracer_param[tracer_id].wmd > 0) is_needed = true;
    }

  return is_needed;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Predefined settings for a tracer equation
 *
 * \param[in]      tracer_eq_id  id of the equation related to this tracer
 * \param[in, out] eq            pointer to the related cs_equation_t structure
 * \param[in, out] gw            pointer to a cs_groundwater_t structure
 */
/*----------------------------------------------------------------------------*/

void
cs_groundwater_tracer_setup(int                  tracer_eq_id,
                            cs_equation_t       *eq,
                            cs_groundwater_t    *gw)
{
  const cs_flag_t  eq_flag = cs_equation_get_flag(eq);
  const cs_desc_t  desc1 = {.location = CS_FLAG_SCAL | cs_cdo_primal_cell,
                            .state = CS_FLAG_STATE_DENSITY};

  /* Sanity check */
  if (gw == NULL) bft_error(__FILE__, __LINE__, 0, _(_err_empty_gw));

  /* Set time property */
  const int  tracer_id = _get_tracer_id(gw, tracer_eq_id);
  cs_property_t  *time_pty = cs_equation_get_time_property(eq);

  for (int soil_id = 0; soil_id < gw->n_soils; soil_id++) {

    cs_gw_soil_t  *soil = gw->soil_param + soil_id;
    cs_gw_tracer_t  *tp = soil->tracer_param + tracer_id;

    cs_property_def_by_law(time_pty,
                           cs_mesh_location_get_name(soil->ml_id),
                           (const void *)tp,
                           _get_tracer_time_coeff);

  } // Loop on soils

  cs_property_set_array(time_pty, desc1, gw->moisture_content->val);

  /* Add a diffusion property */
  if (eq_flag & CS_EQUATION_DIFFUSION) {

    cs_property_t  *diff_pty = cs_equation_get_diffusion_property(eq);

    for (int soil_id = 0; soil_id < gw->n_soils; soil_id++) {

      cs_gw_soil_t  *soil = gw->soil_param + soil_id;
      cs_gw_tracer_t  *tp = soil->tracer_param + tracer_id;

      cs_property_def_by_scavec_law(diff_pty,
                                    cs_mesh_location_get_name(soil->ml_id),
                                    (const void *)tp,
                                    _get_tracer_diffusion_tensor);

    } // Loop on soils

    cs_property_set_array(diff_pty, desc1, gw->moisture_content->val);

    cs_desc_t  desc2 = {.location = CS_FLAG_SCAL | cs_cdo_dual_face_byc,
                        .state = CS_FLAG_STATE_FLUX};
    cs_property_set_second_array(diff_pty, desc2, gw->darcian_flux);

  } /* Diffusion term has to be set */

  /* Add a reaction property */
  if (eq_flag & CS_EQUATION_REACTION) {

    cs_property_t  *reac_pty = cs_equation_get_reaction_property(eq, "decay");

    for (int soil_id = 0; soil_id < gw->n_soils; soil_id++) {

      cs_gw_soil_t  *soil = gw->soil_param + soil_id;
      cs_gw_tracer_t  *tp = soil->tracer_param + tracer_id;

      cs_property_def_by_law(reac_pty,
                             cs_mesh_location_get_name(soil->ml_id),
                             (const void *)tp,
                             _get_tracer_reaction_coeff);

    } // Loop on soils

    cs_property_set_array(reac_pty, desc1, gw->moisture_content->val);

  } /* Reaction term has to be set */

  if (eq_flag & CS_EQUATION_DIFFUSION)
    cs_equation_set_param(eq, CS_EQKEY_ADV_SCHEME, "sg");

  /* TODO: add predefined source term */

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Compute the system related to groundwater flows module
 *
 * \param[in]      mesh       pointer to a cs_mesh_t structure
 * \param[in]      time_step  pointer to a cs_time_step_t structure
 * \param[in]      dt_cur     current value of the time step
 * \param[in]      connect    pointer to a cs_cdo_connect_t structure
 * \param[in]      cdoq       pointer to a cs_cdo_quantities_t structure
 * \param[in]      do_logcvg  output information on convergence or not
 * \param[in, out] eqs        array of pointers to cs_equation_t structures
 * \param[in, out] gw         pointer to a cs_groundwater_t structure
 */
/*----------------------------------------------------------------------------*/

void
cs_groundwater_compute(const cs_mesh_t              *mesh,
                       const cs_time_step_t         *time_step,
                       double                        dt_cur,
                       const cs_cdo_connect_t       *connect,
                       const cs_cdo_quantities_t    *cdoq,
                       bool                          do_logcvg,
                       cs_equation_t                *eqs[],
                       cs_groundwater_t             *gw)
{
  if (gw == NULL)
    return;

  const int  nt_cur = time_step->nt_cur;

  /* Solve the Richards equation */
  cs_equation_t  *richards = eqs[gw->richards_eq_id];

  /* Sanity check */
  assert(cs_equation_get_type(richards) == CS_EQUATION_TYPE_GROUNDWATER);

  if (nt_cur == 0) {

    /* Initialize system before resolution for all equations
       - create system builder
       - initialize field according to initial conditions
       - initialize source term */
    cs_equation_init_system(mesh, richards);

    /* Update hydraulic/pressure head */
    _update_head(connect, cdoq, richards, gw);

    /* Build and solve the linear system related to the Richards equations */
    if (cs_equation_is_steady(richards)) {

      /* Define the algebraic system */
      cs_equation_build_system(mesh, time_step, dt_cur, richards);

      /* Solve the algebraic system */
      cs_equation_solve(richards, do_logcvg);

      /* Update hydraulic/pressure head */
      _update_head(connect, cdoq, richards, gw);

      /* Compute the darcian flux */
      cs_equation_compute_diff_flux(richards, gw->darcian_flux);

      /* Update the moisture content */
      _update_moisture_content(cdoq, richards, gw);

    }

    for (int i = 0; i < gw->n_tracers; i++) {

      cs_equation_t  *eq = eqs[gw->tracer_eq_ids[i]];

      cs_equation_init_system(mesh, eq);

      if (cs_equation_is_steady(eq)) {

        /* Define the algebraic system */
        cs_equation_build_system(mesh, time_step, dt_cur, eq);

        /* Solve the algebraic system */
        cs_equation_solve(eq, do_logcvg);

      } /* Solve this equation which is steady */

    } /* Loop on tracer equations */

  }
  else { /* nt_cur > 0 */

    /* Build and solve the linear system related to the Richards equations */
    if (!cs_equation_is_steady(richards)) {

      /* Define the algebraic system */
      if (cs_equation_needs_build(richards)) // unsteady ?
        cs_equation_build_system(mesh, time_step, dt_cur, richards);

      /* Solve the algebraic system */
      cs_equation_solve(richards, do_logcvg);

      /* Update hydraulic/pressure head */
      _update_head(connect, cdoq, richards, gw);

      /* Compute the darcian flux */
      cs_equation_compute_diff_flux(richards, gw->darcian_flux);

      /* Update the moisture content */
      _update_moisture_content(cdoq, richards, gw);

    }

    for (int i = 0; i < gw->n_tracers; i++) {

      cs_equation_t  *eq = eqs[gw->tracer_eq_ids[i]];

      if (!cs_equation_is_steady(eq)) { // unsteady ?

        /* Define the algebraic system */
        if (cs_equation_needs_build(eq))
          cs_equation_build_system(mesh, time_step, dt_cur, eq);

        /* Solve the algebraic system */
        cs_equation_solve(eq, do_logcvg);

      } /* Solve this equation which is steady */

    } /* Loop on tracer equations */

  } /* nt_cur > 0 */

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Predefined post-processing output for the groundwater flow module
 *         prototype of this function is fixed since it is a function pointer
 *         defined in cs_post.h (cs_post_time_mesh_dep_output_t)
 *
 * \param[in, out] input        pointer to a optional structure (here a
 *                              cs_groundwater_t structure)
 * \param[in]      mesh_id      id of the output mesh for the current call
 * \param[in]      cat_id       category id of the output mesh for this call
 * \param[in]      ent_flag     indicate global presence of cells (ent_flag[0]),
 *                              interior faces (ent_flag[1]), boundary faces
 *                              (ent_flag[2]), particles (ent_flag[3]) or probes
 *                              (ent_flag[4])
 * \param[in]      n_cells      local number of cells of post_mesh
 * \param[in]      n_i_faces    local number of interior faces of post_mesh
 * \param[in]      n_b_faces    local number of boundary faces of post_mesh
 * \param[in]      cell_list    list of cells (1 to n)
 * \param[in]      i_face_list  list of interior faces (1 to n)
 * \param[in]      b_face_list  list of boundary faces (1 to n)
 * \param[in]      time_step    pointer to a cs_time_step_t struct.
 */
/*----------------------------------------------------------------------------*/

void
cs_groundwater_extra_post(void                      *input,
                          int                        mesh_id,
                          int                        cat_id,
                          int                        ent_flag[5],
                          cs_lnum_t                  n_cells,
                          cs_lnum_t                  n_i_faces,
                          cs_lnum_t                  n_b_faces,
                          const cs_lnum_t            cell_list[],
                          const cs_lnum_t            i_face_list[],
                          const cs_lnum_t            b_face_list[],
                          const cs_time_step_t      *time_step)
{
  CS_UNUSED(cat_id);
  CS_UNUSED(ent_flag);
  CS_UNUSED(n_cells);
  CS_UNUSED(n_i_faces);
  CS_UNUSED(n_b_faces);
  CS_UNUSED(cell_list);
  CS_UNUSED(i_face_list);
  CS_UNUSED(b_face_list);

  if (input == NULL)
    return;

  if (mesh_id != -1) /* Post-processing only on the generic volume mesh */
    return;

  const cs_groundwater_t  *gw = (const cs_groundwater_t *)input;

  if (gw->flag & CS_GROUNDWATER_POST_MOISTURE) {
    cs_field_t  *f = gw->moisture_content;
    cs_post_write_var(-1,              // id du maillage de post
                      f->name,
                      1,               // dim
                      true,            // interlace
                      true,            // true = original mesh
                      CS_POST_TYPE_cs_real_t,
                      f->val,          // values on cells
                      NULL,            // values at internal faces
                      NULL,            // values at border faces
                      time_step);      // time step structure
  }

  if (gw->with_gravitation) { /* Post-process pressure head */
    cs_field_t  *f = gw->pressure_head;
    cs_post_write_var(-1,              // id du maillage de post
                      f->name,
                      1,               // dim
                      true,            // interlace
                      true,            // true = original mesh
                      CS_POST_TYPE_cs_real_t,
                      f->val,          // values on cells
                      NULL,            // values at internal faces
                      NULL,            // values at border faces
                      time_step);      // time step structure
  }

}

/*----------------------------------------------------------------------------*/

END_C_DECLS