Skip to content

Helper Functions

whitson_connect is a collection of API helper functions, packaged within a WhitsonConnection class.

Most of the examples in this manual use the whitson_connect library.

You can download the python file below and simply import it into your own script to execute some of the example workflows in subsequent sections. Using a WhitsonConnection object to run HTTP requests and access some of the endpoints available to you.

This simplifies the process of making external API requests in whitson+ to fetch data, create wells, add production data, adjust settings in bulk, run calculations in the software and finally also extract results and information from whitson+.

Helper Class: WhitsonConnection

What does this script, whitson_connect.py do?

This script defines a helper class WhitsonConnection, used for example to import production data from ARIES here.

Click here to download whitson_connect.py

Save the script in this section as a python file in your working directory and import whitson_connect in your script to call these functions using a WhitsonConnection object - you can pass arguments and data as parameters and payloads, respectively.

The class shows a few examples of the available endpoints. A complete list can be found here.

   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
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
import http.client
import json
import requests
import os 
import time
import math
import random
import pandas as pd
import warnings
import numpy as np
from datetime import datetime
from sqlalchemy import create_engine
from snowflake.sqlalchemy import URL


class WhitsonConnection:
    def __init__(self, client_name, client_id, client_secret):
        self.client_name = client_name
        self.client_id = client_id
        self.client_secret = client_secret
        self.access_token = None

    def get_access_token(self):
        """
        Get a access token for a given work session.
        """
        conn = http.client.HTTPSConnection("whitson.eu.auth0.com")
        payload = {
            "client_id": self.client_id,
            "client_secret": self.client_secret,
            "audience": f"https://{self.client_name}.whitson.com/",
            "grant_type": "client_credentials",
        }

        headers = {"content-type": "application/json"}
        conn.request("POST", "/oauth/token", json.dumps(payload), headers)
        res = conn.getresponse()
        data = res.read()
        return json.loads(data.decode("utf-8")).get("access_token")

    def _read_token_from_file(self, file_path):
        if os.path.exists(file_path):
            with open(file_path, 'r') as file:
                try:
                    data = json.load(file)
                    return data.get('client_id'), data.get('access_token'), data.get('timestamp')
                except json.JSONDecodeError:
                    return None, None, None
        else:
            return None, None, None

    def _write_token_to_file(self, file_path, token, timestamp):
        data = {'client_id': self.client_id, 'access_token': token, 'timestamp': timestamp}
        with open(file_path, 'w') as file:
            json.dump(data, file)

    def get_access_token_smart(self):
        """
        Get an access token for a given work session. 
        Does not request a new one if the previous token has been requested within the last 24 hrs. 
        """
        token_file_path = "access_token.txt"
        stored_client_id, stored_token, stored_timestamp = self._read_token_from_file(token_file_path)

        current_time = time.time()

        # Check if a token was previously requested within the last 24 hours
        if stored_client_id == self.client_id and stored_token and (current_time - stored_timestamp) < (24 * 60 * 60):
            return stored_token
        else:
            conn = http.client.HTTPSConnection("whitson.eu.auth0.com")
            payload = {
                "client_id": self.client_id,
                "client_secret": self.client_secret,
                "audience": f"https://{self.client_name}.whitson.com/",
                "grant_type": "client_credentials",
            }

            headers = {"content-type": "application/json"}
            conn.request("POST", "/oauth/token", json.dumps(payload), headers)
            res = conn.getresponse()
            data = res.read()
            new_token = json.loads(data.decode("utf-8")).get("access_token")

            # Update the stored token and timestamp
            self._write_token_to_file(token_file_path, new_token, current_time)

            return new_token


    def get_valid_or_default(self, value: float, default: float = None) -> float:
        """
        Returns the given value if it is not NaN; otherwise, returns the specified default value.

        Args:
            value (float): The value to be checked for NaN.
            default (float, optional): The value to return if the input is NaN. Defaults to None.

        Returns:
            float: The original value if it is not NaN, otherwise the default value.
        """
        return value if not pd.isna(value) else default

    def get_well_id_by_uwi_api(self, wells : list[dict], uwi_api: str):
        """
        Get the well_id of a given uwi_api.

        lookup_key is the database value in whitson+ where the uwi_api is stored, typically uwi_api or external_id.

        """
        return next(
            (well["id"] for well in wells if well.get('uwi_api') == uwi_api),
            None  # Default value if no match is found
        )


    def get_well_id_by_propnum(self, wells : list[dict], propnum: str, lookup_key : str = "uwi_api"):
        """
        Get the well_id of a given propnum.

        lookup_key is the database value in whitson+ where the propnum is stored, typically uwi_api or external_id.

        """
        return next(
            (well["id"] for well in wells if well.get(lookup_key) == propnum),
            None  # Default value if no match is found
        )

    def get_well_id_by_wellname(self, wells : list[dict], wellname: str):
        """
        Get the well_id of a given wellname.
        """
        return next(
            (well["id"] for well in wells if well.get('name') == wellname),
            None  # Default value if no match is found
        )

    def get_fields(self):
        """
        Get all fields on domain.
        """
        base_url = f"https://{self.client_name}.whitson.com/api-external/v1/"
        response = requests.get(
            base_url + "fields",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
        )
        res = response.json()
        if not res:
            raise Exception("no existing fields")
        return res

    def get_wells(self, project_id : int):
        """
        Get a list of wells in a project.
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells"
        response = requests.get(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            params={
                "project_id": project_id,
            },
        )
        res = response.json()
        if not res:
            return []
        return res

    def get_well_from_well_id(self, well_id : int):
        """
        Get the well info, given a well ID.
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells"
        response = requests.get(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            params={
                "well_id": well_id,
            },
        )
        res = response.json()
        if not res:
            return []
        return res

    def get_wells_from_projects(self, project_ids: list[int], page_size : int = 1000):
        """
        Get a list of wells from projects with project_id given in list.

        Example: whitson_wells = whitson_connection.get_wells_from_project([1, 2, 3])

        Lower the page size if 502 Error
        """
        all_wells = []
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells_paginated"

        for project_id in project_ids:
            page = 1  # Start with the first page

            while True:
                response = requests.get(
                    base_url,
                    headers={
                        "content-type": "application/json",
                        "Authorization": f"Bearer {self.access_token}",
                    },
                    params={
                        "project_id": project_id,
                        "page": page,
                        "page_size": page_size, # Lower this if Error 502
                    },
                )
                res = response.json()

                if not res:  # If the response is empty, there are no more wells for this project
                    break

                all_wells.extend(res)  # Append the wells from this page to the list of all wells
                page += 1  # Move to the next page

        return all_wells

    def get_wells_and_scenarios_from_projects(self, project_ids: list[int], page_size : int = 1000):
        """
        Get 2 lists - one for all wells, one for all scenarios (except those created by @whitson.com users) 
        - from multiple projects with each project_id given in list.

        Example payload:
        project_ids = [1,2,3]

        Example function call:
        whitson_wells = whitson_connection.get_wells_and_scenarios_from_projects(project_ids)

        Lower the page size if 502 Error
        """
        all_wells = []

        all_scenarios = []
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells_paginated"

        #print("Collecting Wells for Projects - ", project_ids)
        for project_id in project_ids:
            page = 1  # Start with the first page

            while True:
                response = requests.get(
                    base_url,
                    headers={
                        "content-type": "application/json",
                        "Authorization": f"Bearer {self.access_token}",
                    },
                    params={
                        "project_id": project_id,
                        "page": page,
                        "page_size": page_size, # Lower this if Error 502
                    },
                )
                res = response.json()

                if not res:  # If the response is empty, there are no more wells for this project
                    break
                #print("Writing page", page, " for project id -", project_id)
                all_wells.extend(res)  # Append the wells from this page to the list of all wells
                page += 1  # Move to the next page

            #print("Found - ", len(all_wells), "wells in total for all projects", project_ids)

            #Collecting Scenarios for Project
            #print("Collecting Scenarios for Project - ", project_id)
            base_url_scenario = f"http://{self.client_name}.whitson.com/api-external/v1/scenario"
            response = requests.get(
                        base_url_scenario,
                        headers={
                            "content-type": "application/json",
                            "Authorization": f"Bearer {self.access_token}",
                        },
                        params={
                            "project_id": project_id,
                            },
                    )

            res = response.json()

            #keeping only external scenarios
            external_scenarios = []
            #print("Found ", len(res), " scnenarios in project id - ", project_id)
            for i, scenario in enumerate(res.copy()):
                if "@whitson.com" not in scenario["owner"]:
                    scenario["project_id"] = project_id 
                    scenario["name"] = next((well["name"] for well in all_wells if well.get("id") == scenario["main_well_id"]), None) 
                    scenario["id"] = scenario["scenario_id"] #Consistent with get wells
                    external_scenarios.append(scenario)
            #print("Found ", len(external_scenarios)," external scenarios in project", project_id)
            all_scenarios.extend(external_scenarios) #keeping only external scenarios

        return all_wells, all_scenarios

    def get_projects(self, field_id: int):
        """
        Get a list of projects in field.
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/fields/{field_id}/projects"
        response = requests.get(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
        )
        res = response.json()
        if not res:
            raise Exception("no existing wells")
        return res

    def create_well(self, payload: dict) -> requests.Response:
        """
        Create a new well on a domain.
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells"
        response = requests.post(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            json=payload,
        )
        if response.status_code >= 200 and response.status_code < 300:
            print(f"successfully created well {payload['name']}")
        else:
            print(response.text)
        return response

    def edit_well_info(self, payload: dict) -> requests.Response:
        """
        Edit well info for one or more wells at the same time. 

        Example payload:
        well_info = [{'id': 10, 'l_w': 5000}, {'id': 11, 'l_w': 10000}]

        Example function call:
        whitson_connection.edit_well_info(well_info)

        More info about endpoint here: https://internal.whitson.com/api-external/swagger/#/Base%20Data/patch_api_external_v1_wells
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells"
        response = requests.patch(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },  
            json=payload,
        )
        if response.status_code >= 200 and response.status_code < 300:
            print(f"successfully edited well(s).")
        else:
            print(response.text)
        return response

    def create_project(self, field_id: int, payload: dict) -> requests.Response:
        """
        Create a new project on a domain.
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/fields/{field_id}/projects"
        response = requests.post(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            json=payload,
        )
        if response.status_code >= 200 and response.status_code < 300:
            print(f"successfully created project {payload['name']}")
        else:
            print(response.text)
        return response

    def upload_production_to_well(
        self,
        well_id: int,
        payload: list[dict],
        append_only: bool = False,
    ) -> requests.Response:
        """
        Upload production data to well.

        Parameters:
        well_id (int): The ID of the well to update.
        payload (list[dict]): A list of dictionaries containing the production data.
        append_only (bool): Determines the behavior for handling existing data.
            - False: Replaces existing data for matching dates with payload data. For a given matching date, the entire dataset will be replaced with the payload data (not merged). Appends new data if the date does not exist. Does not affect old data not in the payload.
            - True: Appends new data if the date does not exist. Rejects payload data if the date exists. Does not affect old data not in the payload.

        Returns:
        requests.Response: The response from the API after attempting to upload the production data.
        """
        response = requests.post(
            f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/production_data",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            json=payload,
            params={"append_only": append_only},
        )
        if response.status_code >= 200 and response.status_code < 300:
            print(f"successfully updated production data on well {well_id}")
        else:
            print(response.text)
        return response

    def bulk_upload_production_to_well(self, payload: list[dict]) -> requests.Response:
        """
        Uploads production data to a specified well in bulk.

        This function sends a POST request to the Whitson API to upload a list of production data records associated with a well. 
        Each production data entry must include the `well_id` and the `date` of the production.

        Parameters:
        - payload (list[dict]): A list of dictionaries containing production data entries. 
        Each dictionary should have the following keys:
            - well_id (int): The ID of the well that holds the production record. (required)
            - date (str): The date of the production in ISO 8601 format (e.g., "2024-09-14T21:07:08.556Z"). (required)
            - Additional optional fields may include:
            - qo_sc, qw_sc, qg_sc, qo_se, qw_se, qg_se, qo_sep, qw_sep, qg_sep, p_sep, t_sep, p_wf_measured, 
                p_tubing, p_casing, p_gas_lift, liquid_level, choke_size, line_pressure, etc., as defined by the API.

        Returns:
        - requests.Response: The response object from the POST request.
        - If the request is successful (status code 200-299), "success" is printed.
        - If the request fails, the error response text is printed.

        Example:
        >>> payload = [
                {
                    "well_id": 123,
                    "date": "2024-09-14T21:07:08.556Z",
                    "qo_sc": 100.0,
                    "qw_sc": 200.0,
                    # Additional production data fields...
                }
            ]
        >>> response = bulk_upload_production_to_well(payload)
        >>> if response.status_code == 200:
                print("Production data uploaded successfully.")
            else:
                print("Failed to upload production data.")
        """
        response = requests.post(
            f"http://{self.client_name}.whitson.com/api-external/v1/wells/production_data",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            json=payload,
        )
        if response.status_code >= 200 and response.status_code < 300:
            print("success")
        else:
            print(response.text)
        return response

    def convert_dataframe_to_prod_payload(self, df, columns_to_drop: list[str]) -> list[dict]:
        """
        Converts a DataFrame into a production data payload suitable for the Whitson+ API.

        This function processes a DataFrame by dropping specified columns, removing rows where the well ID is not found,
        and converting any NaN values to None to ensure JSON compatibility. The 'date' column is formatted to ISO 8601 format.

        **Assumptions:**
        - The DataFrame is expected to contain the columns as shown in the provided schema, including:
        'well_id', 'date', 'qo_sc', 'qg_sc', 'qw_sc', 'qo_sep', 'qg_sep', 'qw_sep', 'p_sep', 't_sep',
        'p_wf_measured', 'p_tubing', 'p_casing', 'qg_gas_lift', 'liquid_level', 'choke_size', 'line_pressure'.
        - The 'date' column must be present and contain date values that can be converted to ISO 8601 format.
        - The DataFrame is assumed to be in the format shown in the provided image, where certain values may be NaN.

        Parameters:
        - df (pd.DataFrame): The input DataFrame containing production data.
        - columns_to_drop (list[str]): A list of column names to be dropped from the DataFrame.

        Returns:
        - list[dict]: A list of dictionaries where each dictionary represents a row of the production data payload 
        formatted for the Whitson+ API.

        Example:
        >>> payload = convert_dataframe_to_prod_payload(df, ['insert_date'])
        >>> print(payload)
        [
            {
                "well_id": 0,
                "date": "2024-09-14T21:07:08.556Z",
                "qo_sc": None,
                "qg_sc": None,
                "qw_sc": None,
                "qo_sep": None,
                "qg_sep": None,
                "qw_sep": None,
                "p_sep": None,
                "t_sep": None,
                "p_wf_measured": None,
                "p_tubing": None,
                "p_casing": None,
                "qg_gas_lift": None,
                "liquid_level": None,
                "choke_size": None,
                "line_pressure": None
            }
        ]
        """
        # Drop the specified columns from the DataFrame
        df = df.drop(columns=columns_to_drop)

        # Record the original number of rows
        original_row_count = len(df)

        # Drop rows where 'well_id' is NaN after mapping
        df = df.dropna(subset=['well_id'])

        # Record the new number of rows
        new_row_count = len(df)

        # Print a message if rows were removed
        if original_row_count > new_row_count:
            print(f"Removed {original_row_count - new_row_count} rows where UWI was not found in the dictionary.")

        # Replace NaN values with None for JSON compatibility
        df = df.replace({np.nan: None})

        # Convert the 'date' column to ISO 8601 format
        df['date'] = pd.to_datetime(df['date']).dt.strftime('%Y-%m-%dT%H:%M:%S.%fZ')

        # Convert the DataFrame to a list of dictionaries for API upload
        return df.to_dict('records')

    def get_production(
        self,
        well_id: int,
    ) -> requests.Response:
        """
        Get a list of wells.
        """
        response = requests.get(
            f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/production_data",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
        )
        res = response.json()
        if not res:
            raise Exception("no existing wells")
        return res

    def delete_prod_data(self, well_id: int | None = None):
        """
        Delete production to well.
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/production_data"
        response = requests.delete(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
        )
        if response.status_code >= 200 and response.status_code < 300:
            print(f"successfully deleted production data for well {well_id}")
        else:
            print(response.text)
        return response

    def get_well_deviation_data(self, well_id: int) -> requests.Response:
        """
        Get well deviation data of a well in the database.
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/bhp_input/well_deviation_survey"
        response = requests.get(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
        )
        res = response.json()
        if not res:
            raise Exception("Something went weong")
        return res


    def get_max_md_well_deviation_data(self, well_id: int) -> requests.Response:
        """
        Get the max md of a well deviation survey.
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/bhp_input/well_deviation_survey"
        response = requests.get(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
        )
        res = response.json()

        if not res:
            raise Exception("Something went weong")
        else:
            if not res or not all('md' in item for item in res):
                return None
            else: 
                return max(item['md'] for item in res)

# ---------------------------------------------------------------------------------------------------------
# PVT Related Functions
# ---------------------------------------------------------------------------------------------------------

    def edit_input_quick(self, well_id: int, payload: dict) -> requests.Response:
        """
        Edit the input quick (PVT) property of a well.
        """
        response = requests.put(
            f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/input_quick",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            json=payload,
        )
        if response.status_code >= 200 and response.status_code < 300:
            print(f"successfully edited input quick for well {well_id}")
        else:
            print(response.text)
        return response

### Getting mass fluid data

    def get_pvt_fluid_data(self, well_id:int) -> requests.Response:
        """
        Get the fluid properties after PVT initialization for {well_id}.

        Example payload:
        well_id = this_well_id (a number of type int)
        --> see swagger doc for additional params you can use such as well name or well id directly.

        Example usage:
        response = whitson_connection.get_pvt_fluid_data(well_id)

        """
        response = requests.get(
                f"http://{self.client_name}.whitson.com/api-external/v1/mass_fluid_data",
                headers={
                    "content-type": "application/json",
                    "Authorization": f"Bearer {self.access_token}",
                }, 
            params = {"well_id" : well_id}
            )

        if response.status_code == 200:
           print(f"Fluid data successfully retrieved for well_id {well_id} ")
        else:
            print("Something went wrong - ", response)

        return response.json()    


    def get_pvt_mass_fluid_data(self, project_id:int) -> requests.Response:
        """
        Get the fluid properties after PVT initialization for all the wells in {project_id}.

        Example payload:
        project_id = this_project_id (a number of type int)
        --> see swagger doc for additional params you can use such as well name or well id directly.

        Example usage:
        response = whitson_connection.get_pvt_mass_fluid_data(project_id)

        """
        response = requests.get(
                f"http://{self.client_name}.whitson.com/api-external/v1/mass_fluid_data",
                headers={
                    "content-type": "application/json",
                    "Authorization": f"Bearer {self.access_token}",
                }, 
            params = {"project_id" : project_id}
            )

        if response.status_code == 200:
           print(f"Fluid data successfully retrieved for all wells in project {project_id} ")
        else:
            print("Something went wrong - ", response)

        return response.json()    

    ### Getting bot table

    def get_pvt_bot_table(self, well_id) -> requests.Response:
        """
        Get the black oil table generated for the {well_id} - each row of the BOT is returned as one element in the response.

        Example payload:
        well_id = this_well_id

        Example usage:
        response = whitson_connection.get_pvt_bot_table(well_id)

        """
        response = requests.get(
                f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/bot/bot_table",
                headers={
                    "content-type": "application/json",
                    "Authorization": f"Bearer {self.access_token}",
                }, 
            params = {"well_id" : well_id }
            )

        if response.status_code == 200:
            print(f"BOT successfully retrieved for well {well_id}")
        else:
            print("Something went wrong - ", response)

        return response.json()

    def run_composition_calc(self, well_id: int) -> requests.Response:
        """
        Run PVT (composition) calculation on well.
        """
        response = requests.get(
            f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/run_composition_calc",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
        )
        if response.status_code >= 200 and response.status_code < 300:
            print(f"success on running composition calc on well {well_id}")
        else:
            print(response.text)
        return response


    def calc_median_gor(self, well_id: int, production_data: list[dict] = None, is_sep_rates: bool = False, num_of_timesteps: int = 30, default: float = 1000) -> float: 
        """
        Calculate the median Gas-Oil Ratio (GOR) for a given well over a specified number of timesteps.

        This function retrieves production data for the specified well and calculates the GOR
        as the ratio of gas production (qg_sep) to oil production (qo_sep) for each timestep.
        If separator rates are used, the corresponding GOR is calculated using separator data.

        The function filters out None values and identifies the first valid non-zero GOR value. 
        It then calculates the median GOR from the subsequent data points, up to the specified 
        `number_of_timesteps`. If no valid GOR values are found, the function returns a default value.

        Parameters:
            well_id (int): The unique identifier for the well.
            production_data (dict, optional): use production data available instead of getting it from whitson+.
            is_sep_rates (bool, optional): Flag to determine if separator rates should be used. Defaults to False.
            num_of_timesteps (int, optional): The number of data points to consider for the median calculation. Defaults to 30.
            default (float, optional): The value to return if no valid GOR values are found. Defaults to 1000.

        Returns:
            float: The median GOR value for the specified well over the selected time steps, 
                or the default value if no valid data is available.
        """
        production_data = self.get_production(well_id) if production_data == None else production_data

        prefix = '_sep' if is_sep_rates else ''
        qo_sep_series = [entry['qo' + prefix] for entry in production_data]
        qg_sep_series = [entry['qg' + prefix] for entry in production_data]
        gor = [qg / qo * 1000 if qo != 0 else None for qo, qg in zip(qo_sep_series, qg_sep_series)]

        filtered_gor = [value for value in gor if value is not None]
        first_non_zero_index = next((i for i, value in enumerate(filtered_gor) if value != 0), None)

        if first_non_zero_index is not None:
            selected_gor = filtered_gor[first_non_zero_index:first_non_zero_index + num_of_timesteps]

            return np.median(selected_gor) if selected_gor else None
        else:
            return default 

# ---------------------------------------------------------------------------------------------------------
# BHP Input Related Functions
# ---------------------------------------------------------------------------------------------------------


    def upload_well_data_to_well(
        self, well_id: int, payload: list[dict]
    ) -> requests.Response:
        """
        Upload a well data to a well.
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/bhp_input/well_data"
        response = requests.post(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            json=payload,
        )
        if response.status_code >= 200 and response.status_code < 300:
            print(f"successfully updated well_data to well {well_id}")
        else:
            print(response.text)
        return response

    def edit_well_data_for_well_data_id(
            self, well_data_id: int, payload: list[dict]
        ) -> requests.Response:
            """
            Edit a well data to for well_data_id WELL_DATA_ID.
            """
            base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/bhp_input/well_data/{well_data_id}"
            response = requests.put(
                base_url,
                headers={
                    "content-type": "application/json",
                    "Authorization": f"Bearer {self.access_token}",
                },
                json=payload,
            )
            if response.status_code >= 200 and response.status_code < 300:
                print(f"successfully updated well_data to well {well_data_id}")
            else:
                print(response.text)
            return response


    def edit_well_deviation_data(
        self, well_id: int, payload: list[dict]
    ) -> requests.Response:
        """
        Edit well deviation data of a well in the database.
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/bhp_input/well_deviation_survey"
        response = requests.put(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            json=payload,
        )
        if response.status_code >= 200 and response.status_code < 300:
            print(f"changed well deivation survey on well_id {well_id}")
        else:
            print(response.text)
        return response

    def run_bhp_calc(self, well_id: int) -> requests.Response:
        """
        Run bhp calculation on the well specified by the provided well_id.

        More info here: https://internal.whitson.com/api-external/swagger/#/BHP%20Data/get_api_external_v1_wells_run_bhp_calculation
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/run_bhp_calculation"
        response = requests.get(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
        )
        if response.status_code == 202:
            print(f"successfully ran bhp calc on Well: {well_id}")
        else:
            print(response.text)

    def run_bhp_calc_in_projects(self, project_ids: list) -> requests.Response:
        """
        Bulk Run bhp calculation on all the wells specified by the provided project_ids

        Example Payload:
        project_ids = [255, 94]
        Example function call:
        whitson_connection.run_bhp_calc_in_projects(project_ids)

        More info here: https://internal.whitson.com/api-external/swagger/#/BHP%20Data/get_api_external_v1_wells_run_bhp_calculation
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/run_bhp_calculation"

        for project_id in project_ids:
            response = requests.get(
                base_url,
                headers={
                    "content-type": "application/json",
                    "Authorization": f"Bearer {self.access_token}",
                },
                params = {"project_id" : project_id}
            )
            if response.status_code == 202:
                print(f"successfully ran bhp calc on Project: {project_id}")
            else:
                print(response.text)

    def run_separator_oil_shrinkage_calc(self, well_id: int) -> requests.Response:
        """
        Run common process conversion and separator oil shrinkage on the well specified by the provided well_id.

        More info here: https://internal.whitson.com/api-external/swagger/#/Well%20Monitoring/get_api_external_v1_wells__well_id__run_well_monitoring
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/run_well_monitoring"
        response = requests.get(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
        )
        if response.status_code == 202:
            print(f"successfully run separator oil shrinkage calc on {well_id}")
        else:
            print(response.text)
        return response

    def get_bhp_calc(self, well_id: int, from_date: str = None) -> requests.Response:
        """
        Get bhp calculation on the well specified by the provided well_id. 
        If from_date is specified as "YYYY-MM-DD" the BHP calcs after this date is returned. 
        If the from_date is not specified, all BHP records are returned.

        More info here: https://internal.whitson.com/api-external/swagger/#/BHP%20Data/get_api_external_v1_wells__well_id__bhp_calculation
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/bhp_calculation"
        response = requests.get(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            params = {
                "from_date": from_date
            },
        )
        if response.status_code == 200:
            print(f"successfully retrieved bhp calc on {well_id}")
        else:
            print(response.text)
        return response.json()

    def get_bhp_from_projects(self, project_ids: list[int], from_date: str = None, page_size : int = 1000) -> requests.Response:
        """
        Get a list of well BHPs from projects with project_id given in list.
        Example: whitson_wells_bhp = whitson_connection.get_bhp_from_projects([1, 2, 3])
        If from_date is specified as "YYYY-MM-DD" the BHP calcs after this date is returned. 
        If the from_date is not specified, all BHP records are returned.
        Lower the page size if 502 Error
        """
        all_wells = []
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/bhp_calculation"
        for project_id in project_ids:
            page = 1  # Start with the first page
            while True:
                response = requests.get(
                    base_url,
                    headers={
                        "content-type": "application/json",
                        "Authorization": f"Bearer {self.access_token}",
                    },
                    params={
                        "project_id": project_id,
                        "page": page,
                        "from_date": from_date,
                        "page_size": page_size, # Lower this if Error 502
                    },
                )
                res = response.json()
                if not res:  # If the response is empty, there are no more wells for this project
                    break
                all_wells.extend(res)  # Append the wells from this page to the list of all wells
                page += 1  # Move to the next page
        return all_wells

    def get_well_data(self, well_id: int = 0):
        """
        Get the wellbore info.
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/bhp_input/well_data"
        response = requests.get(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
        )
        return response.json()

    def get_well_deviation_and_perf_interval(self, well_id: int = 0):
        """
        Get the bottomhole pressure input.
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/bhp_input"
        response = requests.get(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
        )
        return response.json()


    def edit_perf_interval(self, well_id: int, payload: list[dict]):
        """
        Edit perf interval
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/bhp_input"
        response = requests.put(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            json=payload,
        )
        if response.status_code >= 200 and response.status_code < 300:
            print(f"changed well deivation survey on well_id {well_id}")
        else:
            print(response.text)
        return response

    def is_wellbore_configuration_already_uploaded(self, new_wellbore_configuration, existing_wellbore_data):
        """
        Checks if a wellbore configuration with the same 'use_from_date' as the new configuration
        already exists in the existing wellbore data.

        Args:
            new_wellbore_configuration (dict): The new wellbore configuration to check.
            existing_wellbore_data (list of dict): The list of existing wellbore configurations.

        Returns:
            bool: True if a configuration with the same 'use_from_date' already exists, False otherwise.
        """
        return any(wellbore['use_from_date'] == new_wellbore_configuration['use_from_date'] for wellbore in existing_wellbore_data)

    def is_default_well_configuration(self, wellbore_data) -> bool:
        """
        Checks if the provided wellbore data represents a default well configuration.

        Args:
            wellbore_data (list of dict): List containing dictionaries representing wellbore data.
                Each dictionary should have keys 'use_from_date', 'well_data_casing', and 'well_data_tubing'.

        Returns:
            bool: True if the well configuration matches default criteria:
                - 'bottom_md' of the first casing is 12000,
                - 'bottom_md' of the first tubing is 7000,
                - 'use_from_date' is None.
            False otherwise.
        """
        if not isinstance(wellbore_data, list) or len(wellbore_data) == 0:
            return False

        first_well_data = wellbore_data[0]

        return (
            first_well_data.get('use_from_date') is None
            and first_well_data.get('well_data_casing', [{}])[0].get('bottom_md') == 12000
            and first_well_data.get('well_data_tubing', [{}])[0].get('bottom_md') == 7000
        )

    def is_default_deviation_survey(self, well_id: int) -> bool:
        """
        Checks if the provided deviation survey is is whitson+ default.
        """

        default_survey = [{'md': 0.0, 'tvd': 0.0}, {'md': 7000.0, 'tvd': 7000.0}, {'md': 12000.0, 'tvd': 7000.0}]
        return (default_survey ==  self.get_well_deviation_data(well_id))


    def is_default_perforated_interval(self, well_id) -> bool:
        """
        Checks if the provided perforation interval is whitson+ default.
        """

        well_and_perf = self.get_well_deviation_and_perf_interval(well_id)

        return (
            well_and_perf.get('top_perforation_md') == 7100
            and well_and_perf.get('bottom_perforation_md') == 12000
        )

    def run_numerical_model(self, well_id: int):
        """
        Run numerical model
        """
        base_url = f"http://{self.client_name}.whitson.com//api-external/v1/wells/{well_id}/run_history_matching"
        response = requests.get(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            params={"well_id": str(well_id), "grid_refinement": "Low", "rate_control": "BHP", "include_forecast": "true"},
        )
        if response.status_code >= 200 and response.status_code < 300:
            print(f"Successfully ran numerical model for well with id {well_id}")
        else:
            print(response.text)
        return response

    def get_numerical_model_rates_and_pressures(self, well_id: int):
        """
        Edit perf interval
        """
        base_url = f"http://{self.client_name}.whitson.com//api-external/v1/wells/{well_id}/history_matching"
        response = requests.get(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
        )
        if response.status_code >= 200 and response.status_code < 300:
            print(f"successfully retrieved numerical model rates and pressures for well_id {well_id}")
        else:
            print(response.text)
        return response.json()

    def get_pwf_active(self, well_id: int, from_date: str = None) -> requests.Response:
        """s
        Get active pwf from the database for the given well_id, from the start date in from_date.

        Example params:
        this_well_id = integer
        this_from_date = "YYYY-MM-DD"

        Example function call:
        active_pwf_well = whitson_connection.get_pwf_active(this_well_id, this_from_date)
        """

        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/pwf_active"
        response = requests.get(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            params={"from_date": from_date},
        )
        if response.status_code == 200:
            print(f"successfully received active pwf on {well_id}")
        else:
            print(response.text)
        return response.json()

    def get_pwf_active_multiple(self, payload: dict) -> requests.Response:
        """
        Get active pwf from the database for all the well_ids from the start date in from_date

        Example payload:
        payload = {"from_date":"YYYY-MM-DD", "page": 0, "page_size": 10}

        Example function call:
        active_pwf_wells = whitson_connection.get_pwf_active_multiple(payload)

        """

        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/pwf_active"
        response = requests.get(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            params=payload,
        )
        if response.status_code == 200:
            print(f"successfully recieved active pwf")
        elif response.status_code == 404:
            print(f"No wells found matching the payload criteria") 
        else: print(response.text)
        return response.json()

    def get_available_custom_attributes(self, well_id: int) -> requests.Response:
        """
        Get available (existing) custom attributes for well {well_id}.

        Example params:
        this_well_id = integer

        Example function call:
        response = whitson_connection.get_available_custom_attributes(this_well_id)
        """
        response = requests.get(
            f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/available_custom_attributes",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            }
        )

        if response.status_code == 200:
            print(f"Custom attribute(s) successfully retrieved for well {well_id}")
        else:
            print("Something went wrong - ", response)

        return response.json()

    def get_custom_attribute_value(self, well_id: int) -> requests.Response:
        """
        Get values for (existing) custom attributes for well {well_id}.

        Example params:
        this_well_id = integer

        Example function call:
        response = whitson_connection.get_custom_attributes_value(this_well_id)
        """
        response = requests.get(
            f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/custom_attributes",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            }
        )

        if response.status_code == 200:
            print(f"Custom attribute(s) data successfully retrieved for well {well_id}")
        else:
            print("Something went wrong - ", response)

        return response.json()

    def delete_custom_attribute_value(self, well_id: int, attribute_name: str) -> requests.Response:
        """
        Delete values for (existing) custom attributes for well {well_id}. Note that this does not delete the custom attribute from the project.

        Example params:
        this_well_id = integer
        this_custom_attribute = 'MyAttribute'

        Example function call:
        response = whitson_connection.delete_custom_attributes_value(this_well_id, this_custom_attribute)
        """
        response = requests.delete(
            f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/custom_attributes/{attribute_name}",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            }
        )

        if response.status_code == 200:
            print(f"Custom attribute(s) successfully updated for well {well_id}")
        else:
            print("Something went wrong - ", response)

        return response.json()

    def edit_custom_attribute_value(self, well_id: int, payload: dict) -> requests.Response:
        """
        Set values for (existing) custom attributes for well {well_id}.

        Example payload:
        payload = {"attribute_name": "MyNumericAttribute",
           "number_attribute": {"attribute_value": 1250}}

        Example function call:
        response = whitson_connection.set_custom_attributes_value(this_well_id, payload)
        """
        response = requests.post(
            f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/custom_attributes",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            json = payload,
        )

        if response.status_code == 200:
            print(f"Custom attribute(s) successfully updated for well {well_id}")
        elif response.status_code == 403:
            print(f"Custom attribute does not exist")
        else:
            print("Something went wrong - ", response)

        return response

    def edit_well_deviation_survey(self, well_id: int, payload: dict) -> requests.Response:
        """

        Example payload: [{'md': 0, 'tvd': 0}, {'md': 95.1, 'tvd': 95.1}, {'md': 153.6, 'tvd': 153.6}]

        Endpoint: https://internal.whitson.com/api-external/swagger/#/BHP%20Data/put_api_external_v1_wells__well_id__bhp_input_well_deviation_survey

        """
        response = requests.put(
            f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/bhp_input/well_deviation_survey",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            json=payload,
        )
        if response.status_code >= 200 and response.status_code < 300:
            print(f"successfully edited well deviation survey for {well_id}.")
        else:
            print(response.text)
        return response

    def delete_wellbore_config_by_well_data_id(self, well_data_id: int): 
        """
        Delete wellbore with wellbore id well_data_id.
        """
        response = requests.delete(
            f"http://{self.client_name}.whitson.com/api-external/v1/wells/bhp_input/well_data/{well_data_id}",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            }
        )

        if response.status_code == 200:
            print(f"Wellbore config {well_data_id} successfully deleted")
        else:
            print("Something went wrong - ", response)

        return response.json()

# ---------------------------------------------------------------------------------------------------------
# Analytical RTA Related Functions
# ---------------------------------------------------------------------------------------------------------

    def get_classical_rta_interpretation(self, well_id: int) -> requests.Response:
        """
        Get (existing) classical RTA results for well {well_id}.

        Example params:
        this_well_id = integer

        Example function call:
        response = whitson_connection.get_classical_rta_interpretation(this_well_id)
        """
        response = requests.get(
            f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/arta_interpretations",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            }
        )

        if response.status_code == 200:
            print(f"Classical RTA data successfully retrieved for well {well_id}")
            return response.json()
        else:
            print("Something went wrong - ", response)

    def get_analytical_rta_timeseries(self, well_id: int) -> requests.Response:
        """
        Get (existing) analytical RTA timeseries for well {well_id}.

        Example params:
        this_well_id = integer

        Example function call:
        response = whitson_connection.get_analytical_rta_time_series(this_well_id)
        """
        response = requests.get(
            f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/arta_time_series",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            }
        )

        if response.status_code == 200:
            print(f"Analytical RTA timeseries data successfully retrieved for well {well_id}")
        else:
            print("Something went wrong - ", response)

        return response.json()


    def get_material_balance_timeseries(self, well_id: int) -> requests.Response:
        """
        Get (existing) material balance timeseries for well {well_id}.

        Example params:
        this_well_id = integer

        Example function call:
        response = whitson_connection.get_material_balance_timeseries(this_well_id)
        """
        response = requests.get(
            f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/material_balance_time",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            }
        )

        if response.status_code == 200:
            print(f"Material balance timeseries successfully retrieved for well {well_id}")
        else:
            print("Something went wrong - ", response)

        return response.json()

    def get_fractional_rta_interpretations(self, well_id: int) -> requests.Response:
        """
        Get (existing) fractional RTA interpretations for well {well_id}.

        Example params:
        this_well_id = integer

        Example function call:
        response = whitson_connection.get_fractional_rta_interpretations(this_well_id)
        """
        response = requests.get(
            f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/fractional_rta_interpretations",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            }
        )

        if response.status_code == 200:
            print(f"Fractional RTA data successfully retrieved for well {well_id}")
        else:
            print("Something went wrong - ", response)

        return response.json()


# ---------------------------------------------------------------------------------------------------------
# Numerical RTA Related Functions
# ---------------------------------------------------------------------------------------------------------

    def _get_nrta_report_dataframe(self):
        return pd.DataFrame(
            columns=[
                "Run",
                "swi",
                "fcd",
                "swc",
                "sorw",
                "sorg",
                "sgc",
                "nw",
                "now",
                "ng",
                "nog",
                "Error",
                "Probability_to_Accept",
                "Was_Accepted",
            ]
        )


    def _edit_nrta_weight_factors(self, payload: dict) -> requests.Response:
        """
        Edit numerical RTA weight factors.

        payload = [{
            "well_id": 1,
            "oil_cum": 0,
            "gas_cum": 0,
            "water_cum": 0,
            "gor_cum": 0,
            "oil": 0,
            "gas": 0,
            "water": 0,
            "gor": 0
        }]
        """
        response = requests.put(
        f"http://{self.client_name}.whitson.com/api-external/v1/wells/edit_nrta_weight_factors",
        headers={
            "content-type": "application/json",
            "Authorization": f"Bearer {self.access_token}",
        },
        json=payload,
        )
        return response

    def _edit_nrta_project_parameters(self, project_id: int, params):
        swi, fcd, swc, sorw, sorg, sgc, nw, now, ng, nog = params
        rel_perm_fcd = {
            "fcd": fcd,
            "swc": swc,
            "sorw": sorw,
            "sorg": sorg,
            "sgc": sgc,
            "nw": nw,
            "now": now,
            "ng": ng,
            "nog": nog,
            "krwro": 1,
            "krgro": 1,
            "krocw": 1,
            "fracture_swc": 0,
            "fracture_sorw": 0,
            "fracture_sorg": 0,
            "fracture_sgc": 0,
            "fracture_nw": 1,
            "fracture_now": 1,
            "fracture_ng": 1,
            "fracture_nog": 1,
            "fracture_krwro": 1,
            "fracture_krocw": 1,
            "fracture_krgro": 1,
        }

        swi_gamma_cr = {
            "Sw_i": swi,
            "gamma_m": 0.0000,
            "gamma_f": 0.0000,
            "cr": 0.000004,
        }

        wells = self.get_wells(project_id)

        rel_perm_fcd_payload = []
        swi_pressure_dep_payload = []

        for well in wells:
            well_id = well["id"]

            # For rel_perm_fcd_payload
            rel_perm_fcd_payload.append(
                {"well_id": well_id, **rel_perm_fcd}  # Unpack rel_perm_fcd dictionary
            )

            # For swi_pressure_dep_payload
            swi_pressure_dep_payload.append(
                {"id": well_id, **swi_gamma_cr}  # Unpack swi_gamma_cr dictionary
            )

        self.__edit_input_nrta_rel_perm_and_fcd_all_wells_project(rel_perm_fcd_payload)
        self.__edit_swi_pressure_dep_all_wells_in_project(swi_pressure_dep_payload)

    def __edit_swi_pressure_dep_all_wells_in_project(self, payload: dict) -> requests.Response:
        """
        Edit the NRTA input for all wells in project.
        """
        response = requests.patch(
            f"http://{self.client_name}.whitson.com/api-external/v1/wells",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            json=payload,
        )
        # if response.status_code >= 200 and response.status_code < 300:
        #     print(f"successfully edited info for well {well_id}")
        # else:
        # print(response.text)
        return response

    def __edit_input_nrta_rel_perm_and_fcd_all_wells_project(self, payload: dict) -> requests.Response:
        """
        Edit the NRTA input for all wells in project.
        """
        response = requests.put(
            f"http://{self.client_name}.whitson.com/api-external/v1/wells/rta_input",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            json=payload,
            # params={"project_id": self.project_id},
        )
        # if response.status_code >= 200 and response.status_code < 300:
        #     print(f"successfully edited input quick for well {well_id}")
        # else:
        #     print(response.text)
        return response

    def _run_nrta_on_all_wells_in_project(self, project_id : int, params : dict = {"grid_refinement": "Low", "num_type_curves": "5_normal"}, sleep_time : dict = 0):
        """
        Executes numerical rate transient analysis (NRTA) on all wells in the current project.

        This method iterates through all wells in the project and performs NRTA on each well
        using the specified parameters.

        Parameters:
        ----------
        params : dict, optional
        A dictionary containing parameters for the NRTA. Defaults to:
        {
            "grid_refinement": "Low",
            "num_type_curves": "5_normal"
        }
        - "grid_refinement" (str): Specifies the level of grid refinement for the NRTA. Possible values are "Low", "Medium", and "High".
        - "num_type_curves" (str): Specifies the number and type of curves to be used in the analysis. The default value is "5_normal".

        sleep_time : int, optional
        The amount of time to wait (in seconds) between processing each well. Defaults to 0.
        """

        wells = self.get_wells(project_id)
        for well in wells:
            time.sleep(sleep_time)
            well_id = well["id"]
            self.run_numerical_rta_for_well(well_id, params)


    def run_numerical_rta_for_well(self, well_id: int, params : dict = {"grid_refinement": "Low", "num_type_curves": "5_normal"}) -> requests.Response:
        """
        Runs numerical rate transient analysis (NRTA) for a specified well.

        This method sends a request to the Whitson API to initiate NRTA for the well identified by `well_id`
        using the given parameters.

        Parameters:
        ----------
        well_id : int
            The ID of the well for which to run the NRTA.
        params : dict, optional
            A dictionary containing parameters for the NRTA. Defaults to:
            {
                "grid_refinement": "Low",
                "num_type_curves": "5_normal"
            }
            - "grid_refinement" (str): Specifies the level of grid refinement for the NRTA. Possible values are "Low", "Medium", and "High".
            - "num_type_curves" (str): Specifies the number and type of curves to be used in the analysis. The default value is "5_normal".

        """

        response = requests.get(
            f"http://{self.client_name}.whitson.com//api-external/v1/wells/{well_id}/run_rta",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            params=params,
        )
        # if response.status_code == 202:
        #     print(f"Numerical RTA for well {well_id}")
        # else:
        #     print(response.text)
        return response

    def run_numerical_rta_autofit(self, well_id: int) -> requests.Response:
        """
        Runs the numerical rate transient analysis (NRTA) autofit for a specified well.

        This method sends a request to the Whitson API to perform an autofit NRTA on the well
        identified by `well_id`.

        Parameters:
        ----------
        well_id : int
            The ID of the well for which to run the NRTA autofit.
        """

        response = requests.get(
            f"http://{self.client_name}.whitson.com//api-external/v1/wells/{well_id}/autofit_rta",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
        )
        # time.sleep(0.05)
        # if response.status_code == 200:
        #     print(f"Numerical RTA Autofit successful for well {well_id}")
        # else:
        #     print(response.text)
        return response

    def _run_nrta_autofit_on_all_wells_in_project(self, project_id: int, sleep_time: int = 0):
        """
        Runs the numerical rate transient analysis (NRTA) autofit for all wells in a specified project.

        This method retrieves all wells associated with the given `project_id` and performs an NRTA autofit
        on each well.

        Parameters:
        ----------
        project_id : int
            The ID of the project for which to run the NRTA autofit on all wells.

        sleep_time : int, optional
        The amount of time to wait (in seconds) between processing each well. Defaults to 0.
        """

        wells = self.get_wells(project_id)
        for well in wells:
            time.sleep(sleep_time)
            well_id = well["id"]
            self.run_numerical_rta_autofit(well_id)

    def _update_nrta_input_parameters(self, min_values, max_values, params):
        """
        Update NRTA input parameters with small random variations.

        This method adjusts each parameter by adding a random value within a defined
        jump size range, ensuring the updated parameters remain within specified minimum
        and maximum values.

        Parameters
        ----------
        min_values : list or array-like
            The minimum values for each parameter.
        max_values : list or array-like
            The maximum values for each parameter.
        params : list or array-like
            The current parameters to be updated.

        Returns
        -------
        tuple
            A tuple of updated parameters, each adjusted by a small random amount
            and constrained within the provided minimum and maximum values.
        """
        # Define the jump size
        jump_size = [
            (max_val - min_val) / 5 for min_val, max_val in zip(min_values, max_values)
        ]

        # Update each parameter with a small random amount within its specified range
        updated_parameters = [
            param + random.uniform(-jump, jump)
            for param, jump in zip(params, jump_size)
        ]

        # Ensure the updated values stay within the specified range
        updated_parameters = [
            max(min_val, min(max_val, updated_param))
            for updated_param, min_val, max_val in zip(
                updated_parameters, min_values, max_values
            )
        ]

        return tuple(updated_parameters)


    def _get_total_project_error(self, project_id: int, weights: dict):
        """
        Calculate the total project error and individual well errors for a given project.

        This method computes the total error for a project by aggregating individual well 
        errors. It also returns the LFP (Last Flowing Pressure) and OOIP (Original Oil in Place) 
        values for each well.

        Parameters
        ----------
        project_id : int
            The unique identifier of the project for which the error is being calculated.
        weights : dict
            A dictionary containing weights for different error components used in the 
            error calculation.

        Returns
        -------
        tuple
            A tuple containing:
            - error (float): The average total error for the project.
            - individual_errors (list of float): The average individual errors for each well.
            - lfps (list of float): The Last Flowing Pressure values for each well.
            - ooips (list of float): The Original Oil in Place values for each well.
        """
        wells = self.get_wells(project_id)

        error = 0
        cumulative_individual_errors = []
        lfps = []
        ooips = []

        all_nrta_data = self._get_nrta_outputs_for_project(project_id)
        all_nrta_data = sorted(all_nrta_data, key=lambda x: x["well_id"])

        lfps = [entry["lfp"] for entry in all_nrta_data]
        ooips = [entry["ooip"] for entry in all_nrta_data]

        get_all_errors_in_project = self._get_all_errors_in_project(project_id)

        for well in get_all_errors_in_project:
            this_error, individual_errors = self._get_nrta_error(well, weights)
            error += this_error

            if not cumulative_individual_errors:
                cumulative_individual_errors = individual_errors
            else:
                cumulative_individual_errors = [
                    sum(x) for x in zip(cumulative_individual_errors, individual_errors)
                ]

        error = error / len(wells)
        individual_errors = [
            error / len(wells) for error in cumulative_individual_errors
        ]

        return error, individual_errors, lfps, ooips


    def _get_nrta_outputs_for_project(self, project_id: int):
        """
        Retrieve NRTA outputs for a specific project.

        This method fetches LFP (Last Flowing Pressure), OOIP (Original Oil in Place),
        OGIP (Original Gas in Place), and OGIP_a for the given project using the API.

        Parameters
        ----------
        project_id : int
            The unique identifier of the project.

        Returns
        -------
        list
            A list of dictionaries containing NRTA output data for each well in the project.

        Raises
        ------
        Exception
            If no wells are found for the given project.
        """
        base_url = (
            f"http://{self.client_name}.whitson.com/api-external/v1/wells/rta_calc"
        )
        response = requests.get(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            params={"project_id": project_id},
        )
        res = response.json()
        if not res:
            raise Exception("no existing wells")
        return res

    def _get_all_errors_in_project(self,  project_id : int):
        """
        Retrieve all errors for a specific project.

        This method fetches error data for all wells in the specified project using the API.

        Parameters
        ----------
        project_id : int
            The unique identifier of the project.

        Returns
        -------
        list
            A list of dictionaries containing error data for each well in the project.

        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells//rta_autofit_rms"
        response = requests.get(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            params={"project_id": project_id},
        )
        res = response.json()
        if not res:
            raise Exception("no existing wells")
        return res


    def _get_nrta_error(self, res, weights: dict):
        """
        Calculate NRTA error for a given well.

        This method computes the error for each run based on the provided results and weights.

        Parameters
        ----------
        res : dict
            A dictionary containing the results for a specific well.
        weights : dict
            A dictionary containing weights for different error components.

        Returns
        -------
        tuple
            A tuple containing:
            - tot_error (float): The total calculated error for the well.
            - individual_errors (list of float): The individual error values for each component.
        """

        individual_errors = [value for key, value in res.items()]

        res.pop("well_id", None)

        tot_error = math.log10(
            sum(((weights[key] * value) ) for key, value in res.items())
        )

        return tot_error, individual_errors

    def _append_to_nrta_report(
        self,
        result_df,
        run,
        test_parameters,
        this_error,
        probability_to_accept,
        was_accpeted,
        individual_errors,
        lfps,
        ooips,
    ):
        """
        Append NRTA run results to the report DataFrame.

        This method adds the results of an NRTA run, including test parameters, error metrics,
        and other relevant data, to the provided result DataFrame.

        Parameters
        ----------
        result_df : pd.DataFrame
            The DataFrame to which the results will be appended.
        run : int
            The run identifier.
        test_parameters : list
            The list of test parameters used in the run.
        this_error : float
            The total error for the run.
        probability_to_accept : float
            The probability of accepting the run.
        was_accpeted : bool
            Whether the run was accepted.
        individual_errors : list of float
            The list of individual errors for each error component.
        lfps : list of float
            The Last Flowing Pressure values for the wells.
        ooips : list of float
            The Original Oil in Place values for the wells.

        Returns
        -------
        pd.DataFrame
            The updated result DataFrame with the new run results appended.
        """    
        warnings.simplefilter(action="ignore", category=FutureWarning)
        row = {
            "Run": run,
            "swi": test_parameters[0],
            "fcd": test_parameters[1],
            "swc": test_parameters[2],
            "sorw": test_parameters[3],
            "sorg": test_parameters[4],
            "sgc": test_parameters[5],
            "nw": test_parameters[6],
            "now": test_parameters[7],
            "ng": test_parameters[8],
            "nog": test_parameters[9],
            "Error": this_error,
            "Probability_to_Accept": probability_to_accept,
            "Was_Accepted": was_accpeted,
            "cum_oil_error": individual_errors[4],
            "cum_gas_error": individual_errors[0],
            "cum_water_error": individual_errors[6],
            "cum_gor_error": individual_errors[2],
            "oil_error": individual_errors[5],
            "gas_error": individual_errors[1],
            "water_error": individual_errors[7],
            "gor_error": individual_errors[3],
        }

        row_string = (
            f"{run}, "
            f"{test_parameters[0]:.4f}, "
            f"{test_parameters[1]:.4f}, "
            f"{test_parameters[2]:.4f}, "
            f"{test_parameters[3]:.4f}, "
            f"{test_parameters[4]:.4f}, "
            f"{test_parameters[5]:.4f}, "
            f"{test_parameters[6]:.4f}, "
            f"{test_parameters[7]:.4f}, "
            f"{test_parameters[8]:.4f}, "
            f"{test_parameters[9]:.4f}, "
            f"{this_error:.4f}, "
            f"{probability_to_accept:.4f}, "
            f"{was_accpeted}, "
            f"{individual_errors[4]:.4f}, "
            f"{individual_errors[0]:.4f}, "
            f"{individual_errors[6]:.4f}, "
            f"{individual_errors[2]:.4f}, "
            f"{individual_errors[5]:.4f}, "
            f"{individual_errors[1]:.4f}, "
            f"{individual_errors[7]:.4f}, "
            f"{individual_errors[3]:.4f}"
        )

        print(row_string)

        # Concatenate all lfps and ooips into strings separated by commas
        lfps_str = ", ".join(map(str, lfps))
        ooips_str = ", ".join(map(str, ooips))

        # Add lfps and ooips to the row dictionary
        row["lfps"] = lfps_str
        row["ooips"] = ooips_str

        # Append the row to the result DataFrame
        row_df = pd.DataFrame([row])
        result_df = pd.concat([result_df, row_df], ignore_index=True)

        return result_df

# ---------------------------------------------------------------------------------------------------------
# DCA related Functions
# ---------------------------------------------------------------------------------------------------------

    def get_dca_fits(self, well_id: int) -> requests.Response:
        """
        Get (existing) DCA fits for well {well_id}.

        Example params:
        this_well_id = integer

        Example function call:
        response = whitson_connection.get_dca_fits(this_well_id)
        """
        response = requests.get(
            f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/well_dca/dca_export",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            }
        )

        if response.status_code == 200:
            print(f"DCA data successfully retrieved for well {well_id}")
        else:
            print("Something went wrong - ", response)

        return response.json()

# ---------------------------------------------------------------------------------------------------------
# SNOWFLAKE Related Functions (https://www.snowflake.com/en/)
# ---------------------------------------------------------------------------------------------------------

    def snowflake_connection(self, account : str, user : str, password, database: str, schema : str ='PUBLIC', warehouse : str ='XS', role : str ='ACCOUNTADMIN'):
        """
        Creates a connection to Snowflake using the provided credentials and parameters.

        Parameters:
        - account (str): The Snowflake account identifier, typically in the format '<account_identifier>.<region>.<cloud_provider>'.
        - user (str): The Snowflake user name.
        - password (str): The password for the Snowflake user.
        - database (str): The name of the Snowflake database to connect to.
        - schema (str): The schema within the database. Default is 'PUBLIC'.
        - warehouse (str): The name of the Snowflake warehouse to use. Default is 'XS'.
        - role (str): The role to use for the connection. Default is 'ACCOUNTADMIN'.

        Returns:
        - connection: A connection object to the Snowflake database.
        """
        engine = create_engine(URL(
            account=account,
            user=user,
            password=password,
            database=database,
            schema=schema,
            warehouse=warehouse,
            role=role
        ))

        return engine.connect()

    def snowflake_table_to_dataframe(self, snowflake_connection, snowflake_query: str) -> pd.DataFrame:
        """
        Executes a query on a Snowflake connection and returns the result as a pandas DataFrame.

        Parameters:
        - snowflake_connection: An active SQLAlchemy connection object to Snowflake.
        - snowflake_query (str): The SQL query to execute on the Snowflake database.

        Returns:
        - pd.DataFrame: A pandas DataFrame containing the results of the executed query.

        Example:
        >>> connection = create_snowflake_connection(account='your_account', user='your_user', password='your_password', database='your_database')
        >>> query = "SELECT * FROM your_database.your_schema.your_table"
        >>> df = snowflake_table_to_dataframe(connection, query)
        >>> print(df.head())

        Notes:
        - Ensure that the Snowflake connection is active and properly configured before calling this function.
        - The function fetches all rows from the result set, so be mindful of the query size to avoid memory issues.
        """
        result = snowflake_connection.execute(snowflake_query)
        rows = result.fetchall()
        columns = result.keys()
        return pd.DataFrame(rows, columns=columns)

# ---------------------------------------------------------------------------------------------------------
# PRODMAN related Functions (https://prodman.ca/)
# ---------------------------------------------------------------------------------------------------------

    def prodman_get_wells(self, domain: str, api_key: str) -> json:
        """
        Fetches well data from the Prodman API for a given domain.

        This function sends a GET request to the Prodman API, using the provided domain and API key, 
        to retrieve a list of wells in JSON format. The function returns the parsed JSON response if 
        the request is successful, otherwise, it prints an error message and returns an empty list.

        Args:
            domain (str): The domain name to be used in the API request URL (e.g., 'example' for 'https://example.prodman.ca').
            api_key (str): The API key required for authentication to access the Prodman API.

        Returns:
            json: A list of well data in JSON format if the request is successful. 
            If the request fails, an empty list is returned.

        More info about PRODMAN api can be found at https://YOURCOMPANYDOMAIN.prodman.ca/api/help.
        """
        params = {
            'api_key': api_key
        }

        url = f"https://{domain}.prodman.ca/api/wells/&return-type=json"
        response = requests.get(url, params=params)

        if response.status_code == 200:
            content = response.content.decode('utf-8')
            return json.loads(content)
        else: 
            print(f"Error: {response.status_code}")
            return []

    def prodman_get_production(self, domain: str, api_key: str) -> json:
        """
        Fetches production data from the Prodman API for all wells within a specified date range.

        This function sends a GET request to the Prodman API, using the provided domain and API key,
        to retrieve production data for all wells. The data includes fields such as `entity_id`, `date`,
        `oil`, `gas`, and `water`. The results are returned in JSON format. If the request fails, the 
        function prints an error message and returns an empty list.

        Args:
            domain (str): The domain name to be used in the API request URL (e.g., 'example' for 'https://example.prodman.ca').
            api_key (str): The API key required for authentication to access the Prodman API.

        Returns:
            json: A list of production data in JSON format if the request is successful.
            If the request fails, an empty list is returned.

        More info about PRODMAN api can be found at https://YOURCOMPANYDOMAIN.prodman.ca/api/help.
        """

        params = {
            'api_key': api_key, 
            'well_id': 'all',
            'start': '2000-01-01', 
            'end': datetime.today().strftime('%Y-%m-%d'),
            'fields': 'entity_id, date, oil, gas, water, casing, tubing',
            'units': 'us',
            'return-type': 'json'
        }

        url = f"https://{domain}.prodman.ca/api/production/"
        response = requests.get(url, params=params)

        if response.status_code == 200:
            content = response.content.decode('utf-8')
            return json.loads(content)
        else: 
            print(f"Error: {response.status_code}")
            return []

    def propman_canada_uwi_cleanup(self, uwi: str) -> str:
        """
        Cleans up a UWI string for Propman Canada.

        This function performs the following steps:
        1. Removes all occurrences of '-' and '/' from the input UWI string.
        2. Ensures the cleaned UWI string starts with '1'. If it does not, '1' is added at the beginning.
        3. Pads the UWI string with '0's at the end to make it exactly 16 characters long if it has fewer than 16 characters.
        4. Prints the processed UWI if modifications are made.
        5. Prints a warning if the cleaned UWI is already 16 characters or more without needing modifications.

        Parameters:
        uwi (str): The input UWI string to be cleaned and formatted.

        Returns:
        str: The cleaned and formatted UWI string.
        """
        # Replace '/' and '-' with an empty string using str.replace
        cleaned_uwi = uwi.replace('/', '').replace('-', '')

        # Ensure the UWI starts with '1'
        if not cleaned_uwi.startswith('1'):
            cleaned_uwi = '1' + cleaned_uwi

        # If the length is less than 16, pad with '0' at the end
        if len(cleaned_uwi) == 15:
            cleaned_uwi = cleaned_uwi.ljust(16, '0')
            print(f"Processed UWI: {cleaned_uwi}")
            return cleaned_uwi
        elif len(cleaned_uwi) == 16:
            return cleaned_uwi 
        else:
            # print("Warning: The processed UWI already meets the requirements or is longer than 16 characters.")
            return cleaned_uwi

# ---------------------------------------------------------------------------------------------------------
# General Functions
# ---------------------------------------------------------------------------------------------------------

    def round_to_significant_digits(self, number: float, digits: int = 4) -> float:
        """
        Rounds a number to the specified number of significant digits.

        Parameters:
        -----------
        number : float
            The number to be rounded.
        digits : int
            The number of significant digits to round to.

        Returns:
        --------
        float
            The number rounded to the specified number of significant digits.
            Returns 0 if the input number is 0 to avoid log10 errors.

        Examples:
        ---------
        >>> round_to_significant_digits(12345.6789, 3)
        12300

        >>> round_to_significant_digits(0.012345, 4)
        0.01235

        Notes:
        ------
        This function uses logarithmic calculations to determine the
        appropriate rounding level for the desired number of significant
        digits. It handles zero input separately to avoid mathematical
        issues with logarithms of zero.
        """
        if number == 0:
            return 0  # Return 0 if the input is 0 to avoid log10 issues

        significant_digits = digits - int(math.floor(math.log10(abs(number)))) - 1
        return round(number, significant_digits)

## Done

We'll routinely add to this class to improve the usability of the endpoints and simplify eAPI workflows further. Feel free to send your feedback/wishlist at support@whitson.com.

Getting Started

After downloading the helper class above, you can import it into your script as shown below. You can request us (at support@whitson.com) to provide the client id and client secret or the key contact in your company, who confidentially maintains the client id and client secret values used for your company. This will be used to generate an authorization token which can be used for 24 hours, so please be mindful about the number of times you use the get_access_token() function on line 46.

The script below is an example of how to create a WhitsonConnection class object and use one of the functions to retrieve all the well header information stored in the database for all the wells in the project.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import whitson_connect

# To fill
CLIENT = "your_domain_here" #This is the company suffix in your whitson urls ex. 'courses' in courses.whitson.com
CLIENT_ID = "your_client_id_here" # Available on request
CLIENT_SECRET = "your_client_secret" # Available on request
PROJECT_ID = "your_project_id_here" # This is the numeric value of the project, available from the URL like '638' in https://courses.whitson.com/fields/5/projects/638/

## Creating a WhitsonConnection class object
whitson_connection = whitson_connect.WhitsonConnection(
    CLIENT, CLIENT_ID, CLIENT_SECRET
)

## Issuing an authorization token here - automatically saves the access token in the working directory so only one token is issued every 24 hours.
whitson_connection.access_token = whitson_connection.get_access_token_smart()

## Get all the wells in the project
whitson_wells = whitson_connection.get_wells(PROJECT_ID)

print(whitson_wells)