mibiremo API reference
irmresult
PhreeqcRM result code mapping and error handling utilities.
This module provides utilities for interpreting and handling result codes returned by PhreeqcRM operations. PhreeqcRM functions return integer status codes that indicate success, failure, or specific error conditions. This module maps these numeric codes to human-readable error messages for improved debugging and logging.
The result codes follow the PhreeqcRM C++ library conventions and correspond to the IrmResult enumeration defined in IrmResult.h of the original PhreeqcRM source code.
Classes:
| Name | Description |
|---|---|
IRMStatus |
Named tuple containing status code, name, and message with convenience methods. |
Functions:
| Name | Description |
|---|---|
irm_result |
Maps integer error codes to IRMStatus objects with enhanced functionality. |
References:
IRMStatus
Bases: NamedTuple
PhreeqcRM status result with enhanced functionality.
This named tuple extends the basic error code mapping with convenience methods for better error handling and user experience.
Attributes:
| Name | Type | Description |
|---|---|---|
code |
int
|
The raw integer error code from PhreeqcRM. |
name |
str
|
Symbolic name of the error code (e.g., “IRM_OK”, “IRM_FAIL”). |
message |
str
|
Human-readable description of the error. |
Source code in mibiremo/irmresult.py
__bool__()
__int__()
Return the raw integer code for backwards compatibility.
Examples:
__str__()
Return a formatted string representation of the status.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Formatted string in the form “ERROR_NAME: Error description” |
raise_for_status(context='')
Raise an exception if the operation failed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
str
|
Additional context for the error message. |
''
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the status code indicates failure (non-zero). |
Examples:
>>> result = rm.rm_load_database("invalid.dat")
>>> result.raise_for_status("Loading database")
RuntimeError: Loading database: IRM_FAIL: Failure, Unspecified
Source code in mibiremo/irmresult.py
irm_result(code)
Map PhreeqcRM integer error codes to enhanced status objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
int
|
Integer error code returned by PhreeqcRM functions. Return codes are listed below: - 0: Success (IRM_OK) - -1: Out of memory error - -2: Invalid variable type - -3: Invalid argument - -4: Invalid row index - -5: Invalid column index - -6: Invalid PhreeqcRM instance ID - -7: Unspecified failure |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
A named tuple containing: - code (int): The raw integer error code - name (str): Symbolic error code name (e.g., “IRM_OK”, “IRM_FAIL”) - message (str): Human-readable error description |
Examples:
>>> result = irm_result(0)
>>> print(result) # "IRM_OK: Success"
>>> if result: # True for success
>>> print("Operation successful")
>>>
>>> error = irm_result(-1)
>>> print(int(error)) # -1 (backwards compatibility)
>>> error.raise_for_status("Memory allocation") # Raises RuntimeError
Source code in mibiremo/irmresult.py
phreeqc
Python interface to PhreeqcRM for geochemical reactive transport modeling.
PhreeqcRM is a reaction module developed by the U.S. Geological Survey (USGS) for coupling geochemical calculations with transport models. It provides a high-performance interface to PHREEQC geochemical modeling capabilities for reactive transport simulations in environmental and hydrological applications.
PhreeqcRM enables:
- Multi-threaded geochemical calculations for large-scale transport models
- Equilibrium and kinetic geochemical reactions in porous media
- Parallel processing for computationally intensive reactive transport
This interface provides a Python wrapper around the PhreeqcRM C library, simplifying the process of integrating geochemical calculations with transport models.
All rm_* methods in this class correspond directly to PhreeqcRM C functions, converted to lowercase Python naming convention with underscores (e.g., RM_LoadDatabase -> rm_load_database).
PhreeqcRM documentation and source code can be found at:
Last revision: 17/02/2026
PhreeqcRM
Python interface to PhreeqcRM for geochemical reactive transport modeling.
This class facilitates coupling between transport codes and geochemical reaction calculations by managing multiple reaction cells, each representing a grid cell in the transport model. The PhreeqcRM approach allows efficient parallel processing of geochemical calculations across large spatial domains.
The class handles
- Creation and initialization of PhreeqcRM instances
- Loading thermodynamic databases (PHREEQC format)
- Setting up initial chemical conditions from input files
- Running equilibrium and kinetic geochemical reactions
- Transferring concentrations between transport and reaction modules
- Managing porosity, saturation, temperature, and pressure fields
- Retrieving calculated properties and concentrations
Typical workflow
- Create instance and call create() method to initialize with grid size
- Load thermodynamic database with initialize_phreeqc()
- Set initial conditions with run_initial_from_file()
- In transport time loop:
- Transfer concentrations to reaction module with rm_set_concentrations()
- Advance time with rm_set_time() and rm_set_time_step()
- Run reactions with rm_run_cells()
- Retrieve updated concentrations with rm_get_concentrations()
Attributes:
| Name | Type | Description |
|---|---|---|
dllpath |
str
|
Path to the PhreeqcRM dynamic library file. |
nxyz |
int
|
Number of grid cells in the reactive transport model. |
n_threads |
int
|
Number of threads for parallel geochemical processing. |
libc |
CDLL
|
Handle to the loaded PhreeqcRM dynamic library. |
id |
int
|
Unique instance identifier returned by RM_Create. |
components |
ndarray
|
Array of component names for transport. |
species |
ndarray
|
Array of aqueous species names in the system. |
Note
This interface requires the PhreeqcRM dynamic library to be available in the lib/ subdirectory. The library handles the underlying PHREEQC calculations and memory management.
Examples:
See page Examples for usage examples.
Source code in mibiremo/phreeqc.py
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 | |
__init__()
Initialize PhreeqcRM instance.
Creates a new PhreeqcRM object with default values. The instance must be created using the create() method before it can be used for calculations.
Source code in mibiremo/phreeqc.py
create(dllpath=None, nxyz=1, n_threads=1)
Creates a PhreeqcRM reaction module instance.
Initializes the PhreeqcRM library, loads the dynamic library, and creates a reaction module with the specified number of grid cells and threads. This method must be called before any other PhreeqcRM operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dllpath
|
str
|
Path to the PhreeqcRM library. If None, uses the default library path based on the operating system. Defaults to None. |
None
|
nxyz
|
int
|
Number of grid cells in the model. Must be positive. Defaults to 1. |
1
|
n_threads
|
int
|
Number of threads for parallel processing. Use -1 for automatic detection of CPU count. Defaults to 1. |
1
|
Raises:
| Type | Description |
|---|---|
Exception
|
If the operating system is not supported (Windows/Linux only). |
RuntimeError
|
If PhreeqcRM instance creation fails. |
Examples:
Source code in mibiremo/phreeqc.py
get_selected_output_df()
Retrieve selected output data as a pandas DataFrame.
Extracts the current selected output data from PhreeqcRM and formats it as a pandas DataFrame with appropriate column headers. Selected output typically includes calculated properties like pH, pe, ionic strength, activities, saturation indices, and user-defined calculations.
Returns:
| Type | Description |
|---|---|
DataFrame
|
pandas.DataFrame: DataFrame containing selected output data with rows representing grid cells and columns representing the selected output variables defined in the PHREEQC input. |
Examples:
>>> df = rm.get_selected_output_df()
>>> print(df.columns) # Show available output variables
>>> print(df['pH']) # Access pH values for all cells
Source code in mibiremo/phreeqc.py
initialize_phreeqc(database_path, units_solution=2, units=1, porosity=1.0, saturation=1.0, multicomponent=True)
Initialize PhreeqcRM with database and default parameters.
Loads a thermodynamic database and sets up the PhreeqcRM instance with standard parameters for geochemical calculations. This is a convenience method that handles common initialization tasks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
database_path
|
str
|
Path to the PHREEQC database file (.dat format). Common databases include phreeqc.dat, Amm.dat, pitzer.dat. |
required |
units_solution
|
int
|
Units for solution concentrations. 1 = mol/L, 2 = mmol/L, 3 = μmol/L. Defaults to 2. |
2
|
units
|
int
|
Units for other phases (Exchange, Surface, Gas, Solid solutions, Kinetics). Defaults to 1. |
1
|
porosity
|
float
|
Porosity value assigned to all cells. Must be between 0 and 1. Defaults to 1.0. |
1.0
|
saturation
|
float
|
Saturation value assigned to all cells. Must be between 0 and 1. Defaults to 1.0. |
1.0
|
multicomponent
|
bool
|
Enable multicomponent diffusion by saving species concentrations. Defaults to True. |
True
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the PhreeqcRM instance is not initialized or if the database fails to load. |
Examples:
>>> rm = PhreeqcRM()
>>> rm.create(nxyz=100)
>>> rm.initialize_phreeqc("phreeqc.dat", units_solution=1)
Source code in mibiremo/phreeqc.py
rm_abort(result, err_str)
Abort the PhreeqcRM run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
int
|
Error code indicating reason for abort. |
required |
err_str
|
str
|
Error message string. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Source code in mibiremo/phreeqc.py
rm_close_files()
Close output files opened by RM_OpenFiles.
Closes all output files that were opened by RM_OpenFiles, including error logs and debug files. This method should be called before destroying the PhreeqcRM instance to ensure proper file cleanup.
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Examples:
>>> rm.rm_open_files() # Open files for logging
>>> # ... perform calculations ...
>>> result = rm.rm_close_files() # Close files when done
>>> if not result:
>>> print(f"Warning: {result}")
Source code in mibiremo/phreeqc.py
rm_concentrations2utility(c, n, tc, p_atm)
Transfer concentrations from a cell to the utility IPhreeqc instance.
Transfers solution concentrations from a reaction cell to the utility IPhreeqc instance for further calculations or analysis. This method allows access to the full PHREEQC functionality for individual cells.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
c
|
ndarray
|
Array of component concentrations to transfer. |
required |
n
|
int
|
Cell number from which to transfer concentrations. |
required |
tc
|
float
|
Temperature in Celsius for the utility calculation. |
required |
p_atm
|
float
|
Pressure in atmospheres for the utility calculation. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Source code in mibiremo/phreeqc.py
rm_create_mapping(grid2chem)
Create a mapping from grid cells to reaction cells.
Establishes the relationship between transport grid cells and reaction cells, allowing for optimization when multiple grid cells share the same chemical composition. This can significantly reduce computational requirements for large models with repeating chemical conditions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grid2chem
|
ndarray
|
Array mapping grid cells to reaction cells. Length should equal the number of grid cells in the transport model. Values are indices of reaction cells (0-based). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
After calling this method, the number of reaction cells may be different from the number of grid cells, potentially reducing computational overhead.
Source code in mibiremo/phreeqc.py
rm_decode_error(e)
Decode error code to human-readable message.
Converts a numeric error code returned by PhreeqcRM functions into a descriptive error message string for debugging and logging purposes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
e
|
int
|
Error code to decode. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Human-readable error message corresponding to the error code. |
Examples:
>>> result = rm.rm_run_cells()
>>> if not result:
>>> error_msg = rm.rm_decode_error(result.code)
>>> print(f"Error: {error_msg}")
Source code in mibiremo/phreeqc.py
rm_destroy()
Destroy a PhreeqcRM instance and free all associated memory.
Deallocates all memory associated with the PhreeqcRM instance, including reaction cells, species data, and internal data structures. This method should be called when the PhreeqcRM instance is no longer needed to prevent memory leaks.
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Warning
After calling this method, the PhreeqcRM instance should not be used for any further operations. All method calls will fail.
Examples:
>>> rm = PhreeqcRM()
>>> rm.create(nxyz=100)
>>> # ... use PhreeqcRM instance ...
>>> rm.rm_destroy() # Clean up when finished
Source code in mibiremo/phreeqc.py
rm_dump_module(dump_on, append)
Enable or disable dumping of reaction module data to file. Controls the output of detailed reaction module data to a dump file for debugging and analysis purposes. The dump file contains complete information about the state of all reaction cells.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dump_on
|
int
|
Enable (1) or disable (0) dump file creation. |
required |
append
|
int
|
Append to existing file (1) or overwrite (0). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
The dump file name is set by RM_SetDumpFileName(). If no name is set, a default name will be used.
Source code in mibiremo/phreeqc.py
rm_error_message(errstr)
Print an error message to the error output file.
Writes an error message to the PhreeqcRM error log file. The message is formatted with timestamp and process information for debugging.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
errstr
|
str
|
Error message string to write to the log. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
Error logging must be enabled with RM_OpenFiles() for messages to be written to file.
Source code in mibiremo/phreeqc.py
rm_find_components()
Find and count components for transport calculations.
Analyzes all chemical definitions in the reaction module to determine the minimum set of components (elements plus charge) required for transport calculations. This method must be called after initial conditions are set but before starting transport calculations.
The components identified include
- Chemical elements present in the system
- Electric charge balance
- Isotopes if defined in the database
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Number of components required for transport calculations. This defines the number of concentrations that must be transported for each grid cell. |
Note
This method should be called after RM_InitialPhreeqc2Module() and before beginning transport time stepping. The returned count determines array sizes for concentration transfers.
Examples:
>>> rm.run_initial_from_file("initial.pqi", ic_array)
>>> ncomp = rm.rm_find_components()
>>> print(f"Transport requires {ncomp} components")
Source code in mibiremo/phreeqc.py
rm_get_backward_mapping(n, list, size)
Get backward mapping from reaction cells to grid cells.
Retrieves the list of grid cell numbers that map to a specific reaction cell. This is the inverse of the forward mapping and is useful for distributing reaction cell results back to grid cells.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Reaction cell number for which to get the mapping. |
required |
list
|
ndarray
|
Array to receive grid cell numbers that map to the specified reaction cell. |
required |
size
|
int
|
Size of the list array. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. The number of grid cells mapping to reaction cell n. |
Source code in mibiremo/phreeqc.py
rm_get_chemistry_cell_count()
Get the number of reaction cells in the module.
Returns the number of reaction cells currently defined in the PhreeqcRM instance. This may be different from the number of grid cells if a mapping has been created to reduce computational requirements by grouping cells with identical chemistry.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Number of reaction cells in the module. |
Note
Without cell mapping, this equals the number of grid cells. With mapping, this may be significantly smaller, improving computational efficiency.
Source code in mibiremo/phreeqc.py
rm_get_component(num, chem_name, length)
Get the name of a component by index.
Retrieves the name of a transport component identified by its index. Components are the chemical entities that must be transported in reactive transport simulations, typically elements plus charge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num
|
int
|
Index of the component (0-based). |
required |
chem_name
|
ndarray
|
String array to store component names. The name will be stored at index num. |
required |
length
|
int
|
Maximum length of the component name string. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
This method is typically used in a loop to retrieve all component names after calling RM_FindComponents().
Source code in mibiremo/phreeqc.py
rm_get_component_count()
Get the number of transport components in the system.
Returns the number of chemical components (elements plus charge balance) that must be transported in reactive transport simulations. This count is determined after calling RM_FindComponents() and defines the size of concentration arrays.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Number of transport components, which includes: - Chemical elements present in the system (e.g., Ca, Cl, C) - Electric charge balance component - Isotopes if defined in the database - Excludes H2O unless RM_SetComponentH2O(1) was called |
Note
This method should be called after RM_FindComponents() to get the correct component count. The returned value determines array sizes for RM_SetConcentrations() and RM_GetConcentrations().
Examples:
>>> rm.run_initial_from_file("initial.pqi", ic_array)
>>> ncomp = rm.rm_get_component_count()
>>> conc_array = np.zeros(nxyz * ncomp)
>>> rm.rm_get_concentrations(conc_array)
Source code in mibiremo/phreeqc.py
rm_get_concentrations(c)
Retrieve component concentrations from reaction cells.
Extracts current component concentrations from all reaction cells after geochemical calculations. These concentrations represent the dissolved components that must be transported in reactive transport simulations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
c
|
ndarray
|
Array to receive concentrations with shape (nxyz * ncomps). Will be filled with current concentrations in the units specified by RM_SetUnitsSolution(). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
The array is organized with all components for cell 0, followed by all components for cell 1, etc. Use this method after RM_RunCells() to get updated concentrations for transport.
Examples:
>>> ncomp = rm.rm_get_component_count()
>>> conc = np.zeros(nxyz * ncomp)
>>> result = rm.rm_get_concentrations(conc)
>>> if result:
>>> # Reshape to (nxyz, ncomp) for easier handling
>>> conc_2d = conc.reshape(nxyz, ncomp)
Source code in mibiremo/phreeqc.py
rm_get_density(density)
Get solution density for all reaction cells.
Retrieves the calculated solution density for each reaction cell based on the current chemical composition, temperature, and pressure. Densities are calculated using the thermodynamic database properties.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
density
|
ndarray
|
Array to receive density values with length equal to the number of reaction cells. Units are kg/L. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
Density calculations depend on the thermodynamic database and the specific solution composition. This method should be called after RM_RunCells() to get current density values.
Source code in mibiremo/phreeqc.py
rm_get_end_cell(ec)
Get the ending cell number for the current MPI process.
In parallel (MPI) calculations, each process handles a subset of reaction cells. This method returns the index of the last cell handled by the current MPI process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ec
|
ctypes pointer
|
Pointer to receive the ending cell index. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
For single-process calculations, this typically returns nxyz-1. For MPI calculations, the range [start_cell, end_cell] defines the cells handled by the current process.
Source code in mibiremo/phreeqc.py
rm_get_equilibrium_phase_count()
Get the number of equilibrium phases defined in the system.
Returns the count of mineral phases that can potentially precipitate or dissolve based on the thermodynamic database and initial conditions defined in the PhreeqcRM instance.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Number of equilibrium phases defined in the system. |
Note
This count includes all phases that have been referenced in EQUILIBRIUM_PHASES blocks in the initial conditions, regardless of whether they are currently present in any cells.
Source code in mibiremo/phreeqc.py
rm_get_equilibrium_phase_name(num, name, l1)
Get the name of an equilibrium phase by index.
Retrieves the name of a mineral phase that can precipitate or dissolve in the geochemical system, identified by its index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num
|
int
|
Index of the equilibrium phase (0-based). |
required |
name
|
ctypes pointer
|
Buffer to receive the phase name. |
required |
l1
|
int
|
Maximum length of the name buffer. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Source code in mibiremo/phreeqc.py
rm_get_error_string(errstr, length)
Get the current error string from PhreeqcRM.
Retrieves the most recent error message generated by PhreeqcRM operations. This provides detailed information about the last error that occurred during calculations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
errstr
|
ctypes pointer
|
Buffer to receive the error string. |
required |
length
|
int
|
Maximum length of the error string buffer. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Source code in mibiremo/phreeqc.py
rm_get_error_string_length()
Get the length of the current error string.
Returns the length of the error message string that can be retrieved with RM_GetErrorString(). Use this to allocate appropriate buffer size before calling RM_GetErrorString().
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Length of the current error string in characters. |
Source code in mibiremo/phreeqc.py
rm_get_gfw(gfw)
Get gram formula weights for transport components.
Retrieves the gram formula weights (molecular weights) for all transport components. These weights are used to convert between molar and mass-based concentrations in transport calculations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gfw
|
ndarray
|
Array to receive gram formula weights. Length should equal the number of components. Units are g/mol. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
The gram formula weights correspond to the components identified by RM_FindComponents() and can be retrieved by RM_GetComponent().
Source code in mibiremo/phreeqc.py
rm_get_grid_cell_count()
Get the number of grid cells in the model.
Returns the total number of grid cells defined for the transport model, as specified when the PhreeqcRM instance was created.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Number of grid cells in the transport model. |
Note
This is the nxyz parameter that was passed to RM_Create(). It represents the total number of cells in the transport grid, which may be different from the number of reaction cells if cell mapping is used.
Source code in mibiremo/phreeqc.py
rm_get_saturation(sat_calc)
Get saturation values for all reaction cells.
Retrieves the current saturation values for all reaction cells. Saturation represents the fraction of pore space occupied by water and affects the volume calculations in reactive transport.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sat_calc
|
ndarray
|
Array to receive saturation values. Length should equal the number of reaction cells. Values range from 0 to 1. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Source code in mibiremo/phreeqc.py
rm_get_selected_output(so)
Retrieve selected output data from all reaction cells.
Extracts the current selected output data, which includes calculated properties such as pH, pe, ionic strength, mineral saturation indices, species activities, and user-defined calculations specified in the PHREEQC input files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
so
|
ndarray
|
Array to receive selected output data with shape (nxyz, ncol) where ncol is the number of selected output columns defined in the PHREEQC input. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
Use RM_GetSelectedOutputColumnCount() to determine the number of columns and RM_GetSelectedOutputHeading() to get column names. The get_selected_output_df() method provides a more convenient pandas DataFrame interface to this data.
Source code in mibiremo/phreeqc.py
rm_get_selected_output_column_count()
Get number of columns in selected output.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Number of selected output columns. |
rm_get_selected_output_row_count()
Get number of rows in selected output.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Number of selected output rows. |
rm_get_species_concentrations(species_conc)
Retrieve aqueous species concentrations from reaction cells.
Extracts the concentrations of individual aqueous species from all reaction cells. This provides more detailed chemical information than component concentrations, including the speciation of dissolved elements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
species_conc
|
ndarray
|
Array to receive species concentrations with shape (nxyz * nspecies). Species concentrations are in the same units as solution concentrations (mol/L, mmol/L, or μmol/L). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
Species saving must be enabled with RM_SetSpeciesSaveOn(1) before this method can be used. Use RM_GetSpeciesCount() to determine the number of species and RM_GetSpeciesName() to get species names.
Examples:
>>> rm.rm_set_species_save_on(1) # Enable species saving
>>> rm.rm_run_cells() # Run reactions
>>> nspecies = rm.rm_get_species_count()
>>> species_c = np.zeros(nxyz * nspecies)
>>> rm.rm_get_species_concentrations(species_c)
Source code in mibiremo/phreeqc.py
rm_get_species_count()
Get the number of aqueous species in the geochemical system.
Returns the total number of dissolved aqueous species that can exist in the current geochemical system based on the loaded thermodynamic database and the chemical components present in the system.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Number of aqueous species defined in the system. This includes primary species (elements and basis species) and secondary species (complexes) formed from the primary species. |
Note
The species count is determined after loading the database and running initial equilibrium calculations. Species names can be retrieved using RM_GetSpeciesName() with indices from 0 to count-1.
Examples:
>>> nspecies = rm.rm_get_species_count()
>>> print(f"System contains {nspecies} aqueous species")
>>> # Get all species names
>>> species_names = np.zeros(nspecies, dtype='U20')
>>> for i in range(nspecies):
>>> rm.rm_get_species_name(i, species_names, 20)
Source code in mibiremo/phreeqc.py
rm_get_species_d25(diffc)
Get diffusion coefficients at 25°C for all aqueous species.
Retrieves the reference diffusion coefficients (at 25°C in water) for all aqueous species in the system. These values are used in multicomponent diffusion calculations in reactive transport models.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
diffc
|
ndarray
|
Array to receive diffusion coefficients with length equal to the number of species. Units are m²/s. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
Diffusion coefficients are taken from the thermodynamic database. For transport at different temperatures, these values should be corrected using appropriate temperature relationships.
Source code in mibiremo/phreeqc.py
rm_get_species_log10_gammas(species_log10gammas)
Get log10 activity coefficients for all aqueous species.
Retrieves the base-10 logarithm of activity coefficients for all aqueous species in each reaction cell. Activity coefficients account for non-ideal solution behavior and are used to calculate activities from concentrations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
species_log10gammas
|
ndarray
|
Array to receive log10 activity coefficients with shape (nxyz * nspecies). Values are dimensionless. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
Activity coefficients depend on ionic strength, temperature, and the activity model used in the thermodynamic database (e.g., Debye-Hückel, Pitzer, SIT). Species saving must be enabled.
Source code in mibiremo/phreeqc.py
rm_get_species_name(num, chem_name, length)
Get the name of an aqueous species by index.
Retrieves the name of an aqueous species identified by its index. Species names follow PHREEQC conventions and include charge states for ionic species.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num
|
int
|
Index of the species (0-based). |
required |
chem_name
|
ndarray
|
String array to store species names. The name will be stored at index num. |
required |
length
|
int
|
Maximum length of the species name string. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Examples:
>>> nspecies = rm.rm_get_species_count()
>>> species_names = np.zeros(nspecies, dtype='U20')
>>> for i in range(nspecies):
>>> rm.rm_get_species_name(i, species_names, 20)
>>> print(species_names) # ['H2O', 'H+', 'OH-', 'Ca+2', ...]
Source code in mibiremo/phreeqc.py
rm_get_species_save_on()
Check if species concentration saving is enabled.
Returns the current setting for species concentration saving. When enabled, PhreeqcRM calculates and stores individual species concentrations that can be retrieved with RM_GetSpeciesConcentrations().
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
1 if species saving is enabled, 0 if disabled. |
Note
Species saving increases memory usage and computation time but provides detailed speciation information useful for analysis and multicomponent diffusion calculations.
Source code in mibiremo/phreeqc.py
rm_get_species_z(z)
Get charge values for all aqueous species.
Retrieves the electric charge (valence) for each aqueous species in the system. Charge values are essential for electrostatic calculations and charge balance constraints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
z
|
ndarray
|
Array to receive charge values with length equal to the number of species. Values are dimensionless (e.g., +2 for Ca+2, -1 for Cl-, 0 for neutral species). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
Charge values are defined in the thermodynamic database and are used in activity coefficient calculations and electroneutrality constraints.
Source code in mibiremo/phreeqc.py
rm_get_time()
Get the current simulation time.
Returns the current time in the reactive transport simulation. This time is used for kinetic rate calculations and time-dependent boundary conditions.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
Current simulation time in user-defined units (typically seconds, days, or years depending on the model setup). |
Note
The simulation time is set by RM_SetTime() and is used internally by PhreeqcRM for kinetic calculations. The time units should be consistent with kinetic rate constants in the database.
Examples:
Source code in mibiremo/phreeqc.py
rm_get_time_step()
Get the current time step duration.
Returns the duration of the current time step used for kinetic calculations and time-dependent processes in the geochemical system.
Returns:
| Name | Type | Description |
|---|---|---|
float |
float
|
Current time step duration in user-defined units (typically seconds, days, or years consistent with the simulation time units). |
Note
The time step is set by RM_SetTimeStep() and affects the integration of kinetic rate equations. Smaller time steps provide more accurate solutions but require more computational time.
Examples:
Source code in mibiremo/phreeqc.py
rm_initial_phreeqc2_module(ic1, ic2, f1)
Transfer initial conditions from InitialPhreeqc to reaction module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ic1
|
ndarray
|
Initial condition indices for primary entities. |
required |
ic2
|
ndarray
|
Initial condition indices for secondary entities. |
required |
f1
|
ndarray
|
Mixing fractions for primary entities. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Source code in mibiremo/phreeqc.py
rm_load_database(db_name)
Load a thermodynamic database for geochemical calculations.
Loads a PHREEQC-format thermodynamic database containing thermodynamic data for aqueous species, minerals, gases, and other phases. The database defines the chemical system and enables geochemical calculations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
db_name
|
str
|
Path to the database file. Common databases include: - “phreeqc.dat”: Standard PHREEQC database (25°C) - “Amm.dat”: Extended database with ammonia species - “pitzer.dat”: Pitzer interaction parameter database - “sit.dat”: Specific ion interaction theory database |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the database file cannot be found or loaded. |
Note
This method must be called before setting up initial conditions or running calculations. The database determines which species, minerals, and reactions are available for calculations.
Examples:
>>> rm = PhreeqcRM()
>>> rm.create(nxyz=100)
>>> result = rm.rm_load_database("phreeqc.dat")
>>> if not result:
>>> raise RuntimeError(f"Failed to load database: {result}")
Source code in mibiremo/phreeqc.py
rm_open_files()
Open output files for logging, debugging, and error reporting.
Creates and opens output files for PhreeqcRM logging, error messages, and debugging information. File names are based on the prefix set by RM_SetFilePrefix().
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Files created
- {prefix}.log: General log messages and information
- {prefix}.err: Error messages and warnings
- {prefix}.out: PHREEQC output from calculations
Note
Call RM_SetFilePrefix() before this method to set the file name prefix. Use RM_CloseFiles() to properly close files when finished.
Examples:
>>> rm.rm_set_file_prefix("simulation")
>>> rm.rm_open_files() # Creates simulation.log, simulation.err, etc.
>>> # ... run calculations ...
>>> rm.rm_close_files() # Clean up
Source code in mibiremo/phreeqc.py
rm_run_cells()
Run geochemical reactions for all reaction cells.
Performs equilibrium speciation and kinetic reactions for the current time step in all reaction cells. This is the core computational method that updates chemical compositions based on thermodynamic equilibrium and reaction kinetics.
The method performs
- Aqueous speciation calculations
- Mineral precipitation/dissolution equilibrium
- Ion exchange equilibrium
- Surface complexation equilibrium
- Gas phase equilibrium
- Kinetic reaction integration over the time step
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
Before calling this method, ensure that: - Concentrations are set with RM_SetConcentrations() - Current time is set with RM_SetTime() - Time step is set with RM_SetTimeStep() - Temperature and pressure are set if needed
Examples:
>>> rm.rm_set_concentrations(concentrations)
>>> rm.rm_set_time(current_time)
>>> rm.rm_set_time_step(dt)
>>> result = rm.rm_run_cells()
>>> if result:
>>> rm.rm_get_concentrations(updated_concentrations)
>>> else:
>>> print(f"Reaction failed: {result}")
Source code in mibiremo/phreeqc.py
rm_run_file(workers, initial_phreeqc, utility, chem_name)
Run a PHREEQC input file in specified PhreeqcRM instances.
Executes a PHREEQC input file (.pqi format) in one or more PhreeqcRM instances. This is used to define initial conditions, equilibrium phases, exchange assemblages, surface complexation sites, gas phases, solid solutions, and kinetic reactions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
workers
|
int
|
Run in worker instances (1) or not (0). Worker instances handle the main geochemical calculations for reaction cells. |
required |
initial_phreeqc
|
int
|
Run in initial PhreeqcRM instance (1) or not (0). Used for defining initial chemical conditions and templates. |
required |
utility
|
int
|
Run in utility instance (1) or not (0). Utility instance provides access to full PHREEQC functionality for special calculations. |
required |
chem_name
|
str
|
Path to the PHREEQC input file containing chemical definitions and calculations. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
PHREEQC input files define the chemical system using standard PHREEQC syntax. Common blocks include SOLUTION, EQUILIBRIUM_PHASES, EXCHANGE, SURFACE, GAS_PHASE, SOLID_SOLUTIONS, KINETICS, and SELECTED_OUTPUT.
Examples:
>>> # Run initial conditions file in initial PhreeqcRM instance
>>> result = rm.rm_run_file(0, 1, 0, "initial_conditions.pqi")
>>> if not result:
>>> print(f"Error running initial conditions file: {result}")
Source code in mibiremo/phreeqc.py
rm_run_string(workers, initial_phreeqc, utility, input_string)
Run PHREEQC input from a string in specified instances.
Executes PHREEQC input commands provided as a string in one or more PhreeqcRM instances. This allows dynamic generation of PHREEQC input without creating temporary files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
workers
|
int
|
Run in worker instances (1) or not (0). |
required |
initial_phreeqc
|
int
|
Run in initial PhreeqcRM instance (1) or not (0). |
required |
utility
|
int
|
Run in utility instance (1) or not (0). |
required |
input_string
|
str
|
PHREEQC input commands as a string, using standard PHREEQC syntax with newline separators. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Examples:
>>> phreeqc_input = '''
>>> SOLUTION 1
>>> pH 7.0
>>> Ca 1.0
>>> Cl 2.0
>>> END
>>> '''
>>> rm.rm_run_string(0, 1, 0, phreeqc_input)
Source code in mibiremo/phreeqc.py
rm_set_component_h2o(tf)
Set whether to include H2O as a transport component.
Controls whether water (H2O) is included in the list of components that must be transported in reactive transport simulations. This setting affects the component count and transport requirements.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tf
|
int
|
Include H2O as a component: 1 = Include H2O as a transport component 0 = Exclude H2O from transport components (default) |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
Typically, H2O is not transported as a separate component because water content is determined by porosity, saturation, and density. Including H2O increases the number of transport equations but may be necessary for some specialized applications.
Examples:
>>> rm.rm_set_component_h2o(0) # Standard: don't transport H2O
>>> ncomp = rm.rm_find_components() # Get component count
Source code in mibiremo/phreeqc.py
rm_set_concentrations(c)
Set component concentrations for all reaction cells.
Transfers concentration data from the transport model to the reaction module. This method is typically called at each transport time step to provide updated concentrations for geochemical calculations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
c
|
ndarray
|
Concentration array with shape (nxyz * ncomps) containing concentrations for all cells and components. Concentrations must be in the units specified by RM_SetUnitsSolution(). Array is organized with all components for cell 0, followed by all components for cell 1, etc. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
This method sets the starting concentrations for the next call to RM_RunCells(). The concentrations are used as initial conditions for equilibrium and kinetic calculations.
Examples:
>>> # Transport model updates concentrations
>>> new_conc = transport_step(old_conc, velocity, dt)
>>> # Transfer to reaction module
>>> result = rm.rm_set_concentrations(new_conc.flatten())
>>> if result:
>>> rm.rm_run_cells() # Run geochemical reactions
Source code in mibiremo/phreeqc.py
rm_set_file_prefix(prefix)
Set prefix for output files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
Prefix string for output file names. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Source code in mibiremo/phreeqc.py
rm_set_porosity(por)
Set porosity values for all grid cells.
Defines the porosity (void fraction) for each grid cell, which represents the fraction of bulk volume occupied by pore space. Porosity affects volume calculations for concentration conversions and reaction extent calculations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
por
|
ndarray
|
Array of porosity values for each cell. Length should equal the number of grid cells (nxyz). Values must be between 0 and 1, where: - 0 = no pore space (solid rock) - 1 = completely porous (pure fluid) - Typical values: 0.1-0.4 for sedimentary rocks |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
Porosity is used with saturation to calculate the water volume in each cell: water_volume = porosity × saturation × bulk_volume. This affects concentration calculations and reaction stoichiometry.
Examples:
Source code in mibiremo/phreeqc.py
rm_set_rebalance_fraction(f)
Set load balancing algorithm fraction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
f
|
float
|
Fraction for load balancing (typically 0.5). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Source code in mibiremo/phreeqc.py
rm_set_saturation(sat)
Set water saturation values for all grid cells.
Defines the water saturation for each grid cell, representing the fraction of pore space occupied by water. Saturation affects volume calculations and is particularly important in unsaturated zone modeling where gas phase may occupy part of the pore space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sat
|
ndarray
|
Array of saturation values for each cell. Length should equal the number of grid cells (nxyz). Values must be between 0 and 1, where: - 0 = dry (no water in pores) - 1 = fully saturated (all pores filled with water) - Typical values: 0.1-1.0 depending on vadose zone conditions |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
Water saturation is used with porosity to calculate the actual water volume: water_volume = porosity × saturation × bulk_volume. This directly affects solution concentrations and reaction rates.
Examples:
>>> # Fully saturated conditions
>>> saturation = np.ones(nxyz)
>>> rm.rm_set_saturation(saturation)
>>>
>>> # Partially saturated (vadose zone)
>>> sat_profile = np.linspace(0.3, 1.0, nxyz) # Increasing with depth
>>> rm.rm_set_saturation(sat_profile)
Source code in mibiremo/phreeqc.py
rm_set_species_save_on(save_on)
Enable or disable saving of aqueous species concentrations.
Controls whether PhreeqcRM calculates and stores individual aqueous species concentrations that can be retrieved with RM_GetSpeciesConcentrations(). This provides detailed speciation information but increases memory usage and computation time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_on
|
int
|
Species saving option: 1 = Enable species concentration saving 0 = Disable species saving (default, saves memory and time) |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
When enabled, PhreeqcRM stores concentrations for all aqueous species after each call to RM_RunCells(). This is required for: - Multicomponent diffusion calculations - Detailed speciation analysis - Species-specific output and post-processing
Examples:
>>> rm.rm_set_species_save_on(1) # Enable species saving
>>> rm.rm_run_cells() # Calculate with species saving
>>> species_conc = np.zeros(nxyz * nspecies)
>>> rm.rm_get_species_concentrations(species_conc)
Source code in mibiremo/phreeqc.py
rm_set_time(time)
Set the current simulation time for geochemical calculations.
Updates the simulation time used by PhreeqcRM for kinetic rate calculations and time-dependent processes. The time should be consistent with the time stepping in the transport model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
time
|
float
|
Current simulation time in user-defined units. Units should be consistent with kinetic rate constants in the thermodynamic database (typically seconds, days, or years). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
This method should be called before each call to RM_RunCells() to ensure kinetic calculations use the correct time. The time is used to integrate kinetic rate equations over the time step.
Examples:
>>> for step in range(num_steps):
>>> current_time = step * dt
>>> rm.rm_set_time(current_time)
>>> rm.rm_set_time_step(dt)
>>> rm.rm_run_cells()
Source code in mibiremo/phreeqc.py
rm_set_time_step(time_step)
Set the time step duration for kinetic calculations.
Specifies the time interval over which kinetic reactions will be integrated during the next call to RM_RunCells(). The time step affects the accuracy of kinetic calculations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
time_step
|
float
|
Time step duration in user-defined units. Must be positive and consistent with simulation time units. Smaller time steps provide better accuracy for fast kinetic reactions but increase computational cost. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
The time step is used for integrating kinetic rate equations. For stiff kinetic systems, smaller time steps may be required for numerical stability and accuracy.
Examples:
>>> dt = 0.1 # 0.1 day time step
>>> rm.rm_set_time_step(dt)
>>> rm.rm_run_cells() # Integrate kinetics over dt
Source code in mibiremo/phreeqc.py
rm_set_units_exchange(option)
Set units for exchange reactions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
option
|
int
|
Units option for exchange calculations. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Source code in mibiremo/phreeqc.py
rm_set_units_solution(option)
Set concentration units for aqueous solutions.
Specifies the units for solution concentrations used in all concentration transfers between the transport model and PhreeqcRM. This affects how concentration data is interpreted and returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
option
|
int
|
Units option for solution concentrations: 1 = mol/L (molar) 2 = mmol/L (millimolar) - commonly used 3 = μmol/L (micromolar) - for trace species |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Note
This setting affects: - RM_SetConcentrations() input interpretation - RM_GetConcentrations() output units - RM_GetSpeciesConcentrations() output units - Initial condition concentration scaling
Examples:
>>> rm.rm_set_units_solution(2) # Use mmol/L
>>> # Now all concentrations are in millimolar units
>>> conc_mmol = np.array([1.0, 0.5, 2.0]) # 1, 0.5, 2 mmol/L
>>> rm.rm_set_concentrations(conc_mmol)
Source code in mibiremo/phreeqc.py
rm_set_units_surface(option)
Set units for surface complexation reactions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
option
|
int
|
Units option for surface calculations. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
IRMStatus |
IRMStatus
|
Status object with code, name, and message. Use bool(result) to check success. |
Source code in mibiremo/phreeqc.py
run_initial_from_file(pqi_file, ic)
Set up initial conditions from PHREEQC input file and initial conditions array.
Loads initial geochemical conditions by running a PHREEQC input file and mapping the defined solutions, phases, and other components to the grid cells. This method also retrieves component and species information for later use.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pqi_file
|
str
|
Path to the PHREEQC input file (.pqi format) containing definitions for solutions, equilibrium phases, exchange, surface, gas phases, solid solutions, and kinetic reactions. |
required |
ic
|
ndarray
|
Initial conditions array with shape (nxyz, 7) where each row corresponds to a grid cell and columns represent: - Column 0: Solution ID - Column 1: Equilibrium phase ID - Column 2: Exchange ID - Column 3: Surface ID - Column 4: Gas phase ID - Column 5: Solid solution ID - Column 6: Kinetic reaction ID Use -1 for unused components. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the PHREEQC input file fails to run. |
ValueError
|
If initial conditions array has incorrect shape or cannot be converted to integer array. |
Examples:
>>> import numpy as np
>>> ic = np.array([[1, -1, -1, -1, -1, -1, -1]]) # Only solution 1
>>> rm.run_initial_from_file("initial.pqi", ic)
Source code in mibiremo/phreeqc.py
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 | |
semilagsolver
Semi-Lagrangian solver for 1D advection-diffusion equation on a uniform grid.
Author: Matteo Masi Last revision: 17/02/2026
SemiLagSolver
Semi-Lagrangian solver for 1D advection-diffusion transport equations.
This class implements a semi-Lagrangian numerical scheme for solving the one-dimensional advection-diffusion equation on uniform grids. The solver uses operator splitting to handle advection and diffusion separately, providing accurate and stable solutions for transport problems.
The numerical approach consists of two sequential steps
- Advection: Solved using the Method of Characteristics (MOC) with cubic spline interpolation (PCHIP - Piecewise Cubic Hermite Interpolating Polynomial) to maintain monotonicity and prevent oscillations.
- Diffusion: Solved using the Saul’yev alternating direction method, which provides unconditional stability for the diffusion equation.
Boundary Conditions
- Inlet (left boundary, x=0): Dirichlet-type condition with prescribed concentration value.
- Outlet (right boundary): Neumann-type condition (zero gradient) allowing natural outflow of transported species.
Mathematical Formulation
The solver addresses the 1D advection-diffusion equation:
∂C/∂t + v∂C/∂x = D∂²C/∂x²
where: - C(x,t): Concentration field - v: Advection velocity (constant) - D: Diffusion/dispersion coefficient (constant)
Numerical Stability
- The cubic spline advection step is stable for any Courant number
- The Saul’yev diffusion solver is unconditionally stable
- Combined scheme maintains stability and accuracy for typical transport problems
Applications
- Reactive transport modeling in porous media
- Contaminant transport in groundwater systems
- Chemical species transport in environmental flows
- Coupling with geochemical reaction modules (e.g., PhreeqcRM)
Attributes:
| Name | Type | Description |
|---|---|---|
x |
ndarray
|
Spatial coordinate array (uniform spacing required). |
C |
ndarray
|
Current concentration field at grid points. |
v |
float
|
Advection velocity in consistent units with spatial coordinates. |
d |
float
|
Diffusion coefficient in consistent units (L²/T). |
dt |
float
|
Time step for numerical integration in consistent time units. |
dx |
float
|
Spatial grid spacing (automatically calculated from x). |
Note
The spatial grid must be uniformly spaced for the numerical scheme to work correctly. Non-uniform grids are not supported in this implementation.
Source code in mibiremo/semilagsolver.py
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 | |
__init__(x, c_init, v, d, dt)
Initialize the Semi-Lagrangian solver with transport parameters.
Sets up the numerical solver with spatial discretization, initial conditions, and transport parameters. Validates input consistency and calculates derived parameters needed for the numerical scheme.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ndarray
|
Spatial coordinate array defining the 1D computational domain. Must be uniformly spaced with at least 2 points. Units should be consistent with velocity and diffusion coefficient. |
required |
c_init
|
ndarray
|
Initial concentration field at each grid point. Length must match the spatial coordinate array. Units are user-defined but should be consistent throughout the simulation. |
required |
v
|
float
|
Advection velocity (positive for left-to-right flow). Units must be consistent with spatial coordinates and time step (e.g., if x is in meters and dt in days, v should be in m/day). |
required |
d
|
float
|
Diffusion/dispersion coefficient (must be non-negative). Units must be L²/T where L and T are consistent with spatial coordinates and time step (e.g., m²/day). |
required |
dt
|
float
|
Time step for numerical integration (must be positive). Units should be consistent with velocity and diffusion coefficient. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If spatial coordinates are not uniformly spaced or if concentration array length doesn’t match spatial coordinates. |
ValueError
|
If transport parameters are not physically reasonable (negative diffusion, zero or negative time step). |
Examples:
>>> x = np.linspace(0, 5, 51) # 5 m domain, 0.1 m spacing
>>> C0 = np.exp(-x**2) # Gaussian initial condition
>>> solver = SemiLagSolver(x, C0, v=0.5, d=0.05, dt=0.01)
Source code in mibiremo/semilagsolver.py
cubic_spline_advection(c_bound)
Solve the advection step using cubic spline interpolation.
Implements the Method of Characteristics (MOC) for the advection equation ∂C/∂t + v∂C/∂x = 0 using backward tracking of characteristic lines. Uses PCHIP (Piecewise Cubic Hermite Interpolating Polynomial) to maintain monotonicity and prevent numerical oscillations.
The method works by
- Computing departure points: xi = x - v*dt (backward tracking)
- Interpolating concentrations at departure points using cubic splines
- Applying inlet boundary condition for points that tracked outside domain
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
c_bound
|
float
|
Inlet concentration value applied at the left boundary (x=0) for any characteristic lines that originated from outside the computational domain. Units should match the concentration field. |
required |
Note
This method modifies self.C in-place. The cubic spline interpolation preserves monotonicity, making it suitable for concentration fields where spurious oscillations must be avoided.
Numerical Properties
- Unconditionally stable (no CFL restriction)
- Maintains monotonicity (no new extrema created)
- Handles arbitrary Courant numbers (v*dt/dx)
- Exact for linear concentration profiles
Source code in mibiremo/semilagsolver.py
saulyev_solver_alt(c_bound)
Solve the diffusion step using the Saul’yev alternating direction method.
Implements the Saul’yev scheme for the diffusion equation ∂C/∂t = D∂²C/∂x² using alternating direction sweeps to achieve unconditional stability. The method performs two passes: 1. Left-to-right sweep using forward differences 2. Right-to-left sweep using backward differences 3. Final solution is the average of both sweeps
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
c_bound
|
float
|
Inlet concentration value applied at the left boundary during the diffusion solve. This maintains consistency with the advection boundary condition. |
required |
Algorithm Details
- Left-to-Right Pass: For each cell i, uses implicit treatment of left neighbor and explicit treatment of right neighbor
- Right-to-Left Pass: For each cell i, uses implicit treatment of right neighbor and explicit treatment of left neighbor
- Averaging: Combines both solutions to achieve second-order accuracy
Boundary Conditions
- Left boundary (x=0): Dirichlet condition with prescribed c_bound
- Right boundary: Zero gradient (Neumann) condition implemented by using the same concentration as the last interior point
Numerical Properties
- Unconditionally stable for any time step size
- Second-order accurate in space and time
- Preserves maximum principle (no spurious extrema)
- Handles arbitrary diffusion numbers (D*dt/dx²)
Note
This method modifies self.C in-place. The alternating direction approach eliminates the restrictive stability constraint of explicit methods while maintaining computational efficiency.
Source code in mibiremo/semilagsolver.py
transport(c_bound)
Perform one complete transport time step with coupled advection-diffusion.
Executes the full semi-Lagrangian algorithm by sequentially applying the advection and diffusion operators using operator splitting. This approach decouples the hyperbolic (advection) and parabolic (diffusion) aspects of the transport equation for enhanced numerical stability.
The operator splitting sequence
- Advection Step using cubic spline MOC
- Diffusion Step using Saul’yev method
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
c_bound
|
float
|
Inlet boundary concentration applied at x=0 for both advection and diffusion steps. This represents the concentration of material entering the domain (e.g., injection well concentration, upstream boundary condition, etc.). |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
numpy.ndarray: Updated concentration field after the complete transport step. The array has the same shape as the initial concentration and represents C(x, t+dt). |
Note
This method updates the internal concentration field (self.C) and returns the updated values. For reactive transport coupling, call this method to advance transport, then apply geochemical reactions to the returned concentration field.