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
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
import os
import time
import math
import random
import decimal
from datetime import datetime
import warnings
from typing import List, Any, Dict

# Third-party library imports
import pandas as pd
import numpy as np
import requests
import json
import http.client
import smtplib
import pyodbc
from sqlalchemy import create_engine, text
from snowflake.sqlalchemy import URL

class WhitsonConnection:
    def __init__(self, client_name = None, client_id = None, client_secret = None):
        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 response.status_code == 500:
                    print("Internal Server Error (500) encountered.")
                    break

                if not res or 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_id_name_external_id_uwi_api(self, well_ids: list[int]):
        """
        Get a list of projects in field.
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/data_fields"
        response = requests.post(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            json={"well_ids" : well_ids, "data_fields": ["id", "name", "uwi_api", "external_id"]}
        )
        return response.json()

    def get_external_id_dict_from_project(self, project_ids: list[int], page_size: int = 3000, remove_substring: str = None) -> dict[str, int]:
        """
        Retrieves a dictionary mapping well external IDs to their whitson+ IDs 
        for wells in the specified projects.

        Args:
            project_ids (list[int]): A list of whitson+ project IDs to retrieve wells from.
            page_size (int, optional): The number of wells to fetch per request. Defaults to 3000.
            remove_substring (str, optional): A substring to remove from each 
                                          `external_id` if present. Defaults to None.

        Returns:
            dict[str, int]: A dictionary where the keys are the well external IDs 
                            (non-None) and the values are the corresponding 
                            internal IDs (non-None).

        Raises:
            ValueError: If the `project_ids` list is empty.
        """
        if not project_ids:
            raise ValueError("The 'project_ids' list cannot be empty.")

        wells = self.get_wells_from_projects(project_ids, page_size)

        return {
            (item['external_id'].replace(remove_substring, '') if remove_substring else item['external_id']): item['id'] 
            for item in wells 
            if item['external_id'] is not None and item['id'] is not None
        }

    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] = None, convert_to_float : bool = False)  -> 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
        if columns_to_drop != None:
            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.")


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

        if convert_to_float:
            columns_to_convert = [
                'qo_sc', 'qw_sc', 'qg_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'
            ]

            # Retain only the columns that exist in the dataframe
            columns_to_convert = [col for col in columns_to_convert if col in df.columns]

            # Convert the specified columns to float
            df[columns_to_convert] = df[columns_to_convert].astype(float)

            # Set pressure columns to 14.7 if they are less than or equal to 14.7
            pressure_columns = ['p_sep', 'p_wf_measured', 'p_tubing', 'p_casing', 'line_pressure']
            pressure_columns = [col for col in pressure_columns if col in df.columns]
            df[pressure_columns] = df[pressure_columns].apply(lambda col: col.map(lambda x: max(x, 14.7)))

            # Set other specified columns to 0 if they are less than 0
            non_negative_columns = [
                'qo_sc', 'qw_sc', 'qg_sc', 'qo_sep', 'qg_sep', 'qw_sep', 't_sep', 
                'qg_gas_lift', 'liquid_level', 'choke_size'
            ]
            non_negative_columns = [col for col in non_negative_columns if col in df.columns]
            df[non_negative_columns] = df[non_negative_columns].apply(lambda col: col.map(lambda x: max(x, 0)))

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

        # # Remove rows where all columns except 'date' are NaN
        # df = df.dropna(subset=df.columns.difference(['date']), how='all')

        # df.to_excel(f'example-{counter}.xlsx')

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

        # Remove duplicate dates
        df_unique = df.drop_duplicates(subset=['well_id', 'date'])

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

        # 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 duplicate dates were found.")

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

    def get_production(
        self,
        well_id: int,
    ) -> requests.Response:
        """
        Get production data.
        """
        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 production data")
        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 delete_prod_data_between_dates(self, well_id: int, start_date: str, end_date: str):
        """
        Deletes production data for a specified well within a given date range.

        This function sends a DELETE request to the specified API endpoint to remove
        production data associated with a well for the given start and end dates. 
        If the deletion is successful, a success message is printed; otherwise, 
        the response's error message is printed.

        Args:
            well_id (int): The unique identifier for the well.
            start_date (str): The start date for the range of data to delete, formatted as 'YYYY-MM-DD'.
            end_date (str): The end date for the range of data to delete, formatted as 'YYYY-MM-DD'.

        Returns:
            requests.Response: The response object returned by the DELETE request.
                This can be used for further inspection of the request's result.

        Raises:
            ValueError: If the response status code indicates failure, an error message
            will be printed detailing the issue.

        Example:
            delete_prod_data_between_dates(well_id=123, start_date="2023-01-01", end_date="2023-01-31")
        """
        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}",
            },
            params={"start_date": start_date, "end_date": end_date},
        )
        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()    

    def get_pvt_mass_fluid_data_from_projects(self, project_id_list: List[int]) -> List[dict]:
        """
        Get the fluid properties after PVT initialization for all wells across multiple projects.

        Parameters:
        project_id_list (List[int]): A list of project IDs for which to retrieve fluid data.

        Returns:
        List[dict]: A list of responses containing fluid data for all projects.

        Example usage:
        response = whitson_connection.get_pvt_mass_fluid_data_from_projects([project_id1, project_id2])
        """
        all_fluid_data = []  # Store fluid data from all projects

        for project_id in project_id_list:
            response = self.get_pvt_mass_fluid_data(project_id)  # Call the existing function
            if response:  # Assuming response is a dictionary or list
                all_fluid_data.extend(response)  # Add the fluid data from this project to the list

        return all_fluid_data

    ### 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 not in [None, 0] and qg is not None 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 edit_rate_type_for_well(self, well_id: int, rate_type: str):
        """
        Updates the rate type for a specified well in the Whitson+ platform.

        Parameters:
            well_id (int): The unique identifier for the well in the Whitson+ system.
            rate_type (str): The rate type to set for the well. Valid options are:
                            - "measured" for stock tank rate
                            - "common" for separator rate

        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/set_production_rate_type/{rate_type}"
        response = requests.put(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },
            params={"well_id": well_id, "rate_type": rate_type},
        )
        if response.status_code >= 200 and response.status_code < 300:
            print(f"Changed the rate type on well with id {well_id}")
        else:
            print(response.text)
        return response


    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 run_separator_oil_shrinkage_calc_in_projects(self, project_id_list: List[int]) -> None:
        """
        Executes the separator oil shrinkage calculation for all wells in the specified projects.

        This function retrieves wells from the provided `project_id_list` using a page size of 3000 
        and runs the separator oil shrinkage calculation for each well.

        Args:
            project_id_list (List[int]): A list of project IDs from which to retrieve wells.

        Returns:
            None: This function does not return any value.

        Notes:
            - API documentation for the well monitoring process: 
            https://internal.whitson.com/api-external/swagger/#/Well%20Monitoring/get_api_external_v1_wells__well_id__run_well_monitoring
        """

        # Retrieve wells from the specified project IDs using the page size
        wells = self.get_wells_from_projects(project_id_list, page_size=3000)

        # Execute separator oil shrinkage calculation for each well
        for well in wells:
            self.run_separator_oil_shrinkage_calc(well['id'])

    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, last_updated: str = None, return_all : bool = True) -> 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.
        If last_updated is specified as "YYYY-MM-DD" the BHP calcs updated after this date is 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:
                try:
                    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
                            "updated": last_updated,
                            "return_all" : return_all,
                        },
                    )
                    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
                except:
                    print('Something went wrong')
                page += 1  # Move to the next page
                print(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_wellbore_data_from_well_id_list(self, well_id_list: list[int], updated: str = None) -> dict:
        """
        Fetch BHP input data for a list of wells using their well IDs.

        Args:
            well_id_list (list[int]): A list of well IDs to retrieve BHP input data for.
            updated (str, optional): Date to filter the BHP input on and onwards in the format 'YYYY-MM-DD'. 
                                    If not specified, all data is retrieved.

        Returns:
            dict: A dictionary containing the BHP input data for the specified wells in JSON format.

        Raises:
            requests.exceptions.RequestException: If there is an issue with the HTTP request.

        Example:
            >>> client.get_wellbore_data_from_well_id_list([101, 102], "2024-11-29")
            {
                "well_data": [...]
            }
        """
        url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/bhp_inputs"

        params = {"well_ids": well_id_list}
        if updated:
            params["updated"] = updated

        try:
            response = requests.patch(
                url,
                headers={
                    "content-type": "application/json",
                    "Authorization": f"Bearer {self.access_token}",
                },
                json=params,
            )
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            raise Exception(f"Failed to fetch wellbore data: {e}")

    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 perforated interval 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]

        if first_well_data.get('well_data_tubing', [{}]) == []:
            return False

        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()

# ---------------------------------------------------------------------------------------------------------
# Data Status (on whitson) Related Functions
# ---------------------------------------------------------------------------------------------------------

    def get_new_data_status_by_project_id(self, project_id: int) -> requests.Response:
        """
        Get (existing) data status for well {well_id}.
        Bool flag set to True if there are changes in any of the fields returned since last BHP calc, 
        False if there is no change in input to BHP calc since the previous run.

        Example params:
        this_project_id = integer

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

        if response.status_code == 200:
            print(f"New Data Status successfully retrieved for project {project_id}")
        else:
            print("Something went wrong - ", response)

        return response.json()

    def get_well_data_status(self, well_id: int) -> requests.Response:
        """
        Get data status (data exists/not) for well {well_id}.

        Example params:
        this_well_id = integer

        Example function call:
        response = whitson_connection.get_data_status(this_well_id)
        """
        response = requests.get(
            f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/status",
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            }
        )
        if response.status_code == 200:
            print(f"Data Status 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()

    def get_dca_saved_cases(self, well_id: int) -> requests.Response:
        """
        Fetch saved Decline Curve Analysis (DCA) cases for a given well ID.

        Args:
            well_id (int): The unique identifier of the well.

        Returns:
            requests.Response: The API response containing the DCA data if successful.

        Example:
            >>> response = whitson_connection.get_dca_saved_cases(12345)
            >>> if response.status_code == 200:
            >>>     print(response.json())
        """
        response = requests.get(
            f"http://{self.client_name}.whitson.com/api-external/v1/wells/{well_id}/well_dca/saved_cases",
            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()


    def get_dca_fits_by_well_id_list(self, well_id_list: dict) -> requests.Response:
        """
        Retrieve DCA fits for one or more wells using their IDs.

        This function sends a PATCH request to update or retrieve Decline Curve Analysis (DCA) fits
        for wells specified in the payload. The well IDs are provided in a dictionary format.

        Parameters:
        ----------
        well_id_list : dict
            A dictionary containing the IDs of the wells. The payload structure is:
            {
                "well_ids": [
                    <well_id_1>, <well_id_2>, ...
                ]
            }

        Returns:
        -------
        requests.Response
            The response object from the API call, containing the status and any data returned by the server.

        Example:
        --------
        Example payload:
        well_id_list = {
            "well_ids": [
                123, 456, 789
            ]
        }

        Example function call:
        response = whitson_connection.get_dca_fits_by_well_id_list(well_id_list)

        More information:
        -----------------
        For details about the endpoint, visit:
        https://internal.whitson.com/api-external/swagger/#/DCA/patch_api_external_v1_wells_dca
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/dca"
        response = requests.patch(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },  
            json=well_id_list,
            # params={
            #             "updated": last_updated,
            #         },
        )
        if response.status_code >= 200 and response.status_code < 300:
            print(f"successfully retrieved DCA well(s).")
        else:
            print(response.text)
        return response.json()

    def get_dca_daily_rates_by_well_id_list(self, well_id_list: dict) -> requests.Response:
        """
        Retrieve Decline Curve Analysis (DCA) daily rates for specified wells.

        This method sends a PATCH request to fetch or update DCA daily rates for wells
        identified by their IDs. The well IDs should be provided in the payload in a dictionary format.

        Parameters:
        ----------
        well_id_list : dict
            A dictionary containing the well IDs in the following structure:
            {
                "well_ids": [
                    <well_id_1>, <well_id_2>, ...
                ]
            }

        Returns:
        -------
        requests.Response
            The response object from the API call, which includes the HTTP status, any error messages,
            and the returned data from the server.

        Example:
        --------
        Payload structure:
        well_id_list = {
            "well_ids": [
                123, 456, 789
            ]
        }

        Function call:
        response = whitson_connection.get_dca_daily_rates_by_well_id_list(well_id_list)

        Endpoint Documentation:
        ------------------------
        Refer to the API documentation for more details:
        https://internal.whitson.com/api-external/swagger/#/DCA/patch_api_external_v1_wells_dca

        Notes:
        ------
        - Ensure the `self.access_token` is valid for authentication.
        - The method prints a success message for responses with status codes in the 200-299 range.
        - Non-successful responses log the server's response text for troubleshooting.
        """
        base_url = f"http://{self.client_name}.whitson.com/api-external/v1/wells/dca/daily_rates"
        response = requests.get(
            base_url,
            headers={
                "content-type": "application/json",
                "Authorization": f"Bearer {self.access_token}",
            },  
            params={
                "well_ids": well_id_list,
            },
        )
        if response.status_code >= 200 and response.status_code < 300:
            print(f"successfully retrieved DCA forecasted daily rates.")
        else:
            print(response.text)
        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.
        """
        # snowflake_connection.execute("USE WAREHOUSE XS")
        # Explicitly activate the warehouse
        snowflake_query = text(snowflake_query)
        result = snowflake_connection.execute(snowflake_query)
        rows = result.fetchall()
        columns = result.keys()
        return pd.DataFrame(rows, columns=columns)

# ---------------------------------------------------------------------------------------------------------
#  DATABRICKS Related Functions (https://www.databricks.com/)
# ---------------------------------------------------------------------------------------------------------
    def databricks_connection(self, dsn : str, host : str, port : str, token : str, http_path : str):
        """Create a connection string to connect to a Databricks cluster."""
        connection_string = (
            f'DSN={dsn};'
            f'HOST={host};'
            f'PORT={port};'
            f'OAuthMechanism=3;'  # OAuth mechanism for token-based authentication
            f'Auth_AccessToken={token};'  # Use Auth_AccessToken instead of Token
            f'HTTPPath={http_path};'
            f'SSL=1;'
        )

        return pyodbc.connect(connection_string, autocommit=True) 

# ---------------------------------------------------------------------------------------------------------
# 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)

    def run_function(self, func):
        try:
            # Print the name of the function being run
            print(f"Starting {func.__name__} process.")

            # Capture the start time
            start_time = time.time()

            # Run the function
            func()

            # Capture the end time
            end_time = time.time()

            # Calculate the duration in seconds
            elapsed_time = end_time - start_time

            # Convert the time to minutes and seconds
            minutes = int(elapsed_time // 60)
            seconds = int(elapsed_time % 60)

            # Print completion message with time
            time_string = f"{func.__name__} completed successfully in {minutes} minutes and {seconds} seconds.\n"
            print(time_string)

            return time_string

        except Exception as e:
            # Print an error message if the function fails
            error_string = f"Something went wrong while running {func.__name__}: {e}\n"
            print(error_string)

            return error_string

    def _convert_dataframe_to_timestamp_json(self, dataframe, primary_key = 'well_id', timestamp_column_name = 'insert_date') -> json:
        """"""
        dataframe = dataframe[[primary_key, timestamp_column_name]].copy()
        dataframe[timestamp_column_name] = pd.to_datetime(dataframe[timestamp_column_name])
        dataframe = dataframe.loc[dataframe.groupby(primary_key)[timestamp_column_name].idxmax()]
        return dataframe.to_json(orient='records', date_format='iso', indent=4)

    def _save_dataframe_timestamp_to_json(self, dataframe, filepath, primary_key = 'well_id', timestamp_column_name = 'insert_date'):
        """"""
        dataframe = dataframe[[primary_key, timestamp_column_name]].copy()
        dataframe[timestamp_column_name] = pd.to_datetime(dataframe[timestamp_column_name])
        dataframe = dataframe.loc[dataframe.groupby(primary_key)[timestamp_column_name].idxmax()]
        dataframe.to_json(filepath, orient='records', date_format='iso', indent=4)

    def _find_new_or_updated_well_ids(self, old_list, new_list, primary_key, timestamp_key):
        """
        Find primary keys where the timestamp differs or where new primary keys are present.

        Parameters:
        old_list (list): The old list of dictionaries containing primary keys and timestamps.
        new_list (list): The new list of dictionaries containing primary keys and timestamps.
        primary_key (str): The key representing the primary key in each dictionary.
        timestamp_key (str): The key representing the timestamp in each dictionary.

        Returns:
        list: A list of primary keys where either:
            - The primary key is present in the new list but not in the old (new record).
            - The primary key exists in both lists, but the timestamps differ (updated record).
        """
        if old_list is None:
            return [item[primary_key] for item in new_list]

        differences = []

        # Convert the lists to dictionaries for easier comparison
        old_dict = {item[primary_key]: item[timestamp_key] for item in old_list}
        new_dict = {item[primary_key]: item[timestamp_key] for item in new_list}

        # Find primary keys that are either new or have a different timestamp
        for key in new_dict:
            if key not in old_dict or old_dict[key] != new_dict[key]:
                differences.append(key)

        return differences

    def is_data_sync_needed(self, dataframe: pd.DataFrame, json_filename: str, client_name: str = None) -> bool:
        """
        Determines if the provided DataFrame needs to be synced with the JSON file.
        If the file does not exist or if the JSON content differs, it updates the file 
        and returns True (indicating syncing is necessary). Otherwise, returns False.

        Parameters:
        ----------
        dataframe : pd.DataFrame
            The DataFrame to be compared or saved.
        json_filename : str
            The name of the JSON file to compare against or save to.
        client_name : str
            The name of the client, used to create the file path dynamically.

        Returns:
        -------
        bool
            True if syncing is necessary (file does not exist or JSON is different), 
            False if the data matches the existing file.

        Notes:
        -----
        - If the JSON file exists, the function reads its contents and compares it with the 
        JSON representation of the provided DataFrame.
        - If the JSON file does not exist, the function creates it by dumping the 
        provided DataFrame into the JSON file.
        - The JSON file is stored in the path: `scheduler/company/{client_name}/associated_files/{json_filename}.json`
        """

        client_name_to_use = self.client_name.lower() if client_name == None else client_name

        filepath = os.path.dirname(os.path.abspath(__file__)).replace('aries_python_code', "") + f'scheduler\\company\\{client_name_to_use}\\associated_files\\{json_filename}.json'

        if os.path.exists(filepath):

            # Load JSON from a file
            with open(filepath, 'r') as file:
                df_from_json = json.load(file)  

            # Convert the dataframe to JSON and parse it as a dictionary
            df_from_dataframe = json.loads(dataframe.to_json(orient='records'))

            # Check if they are equal
            is_equal = df_from_json == df_from_dataframe

            if is_equal:
                return False  # No need to sync if data is the same
            else:
                dataframe.to_json(filepath, orient='records', indent=4)
                return True   # Sync is needed if data is different
        else:
            dataframe.to_json(filepath, orient='records', indent=4)
            print(f"File created and data frame saved to {filepath}")
            return True       # Sync is needed if the file does not exist

    def get_dataframe_to_update(self, dataframe: pd.DataFrame, timestamp_filename: str, primary_key: str, timestamp_column_name: str, client_name: str = None) -> List[str]:
        """
        Identify well IDs from the provided DataFrame that are new or have updated timestamps
        by comparing them with records in an existing JSON timestamp file. If discrepancies
        are found (i.e., new or modified well IDs), the function returns these IDs and updates
        the JSON timestamp file.

        Parameters:
        dataframe (pd.DataFrame): The current DataFrame containing well IDs and their corresponding timestamps.
        timestamp_filename (str): The name of the JSON file (excluding path) to store historical well ID timestamps.
        primary_key (str): The column name in the DataFrame that uniquely identifies each well (e.g., 'well_id').
        timestamp_column_name (str): The column name in the DataFrame representing the timestamp for each well ID.
        client_name (str, optional): The name of the client used to construct the JSON file path. Defaults to None,
                                    in which case the object's `client_name` attribute is used.

        Returns:
        List[str]: A list of well IDs that are either new or have an updated timestamp in the DataFrame compared 
                to the records in the JSON file.
        """
        client_name_to_use = self.client_name.lower() if client_name == None else client_name

        filepath = os.path.dirname(os.path.abspath(__file__)).replace('aries_python_code', "") + f'scheduler\\company\\{client_name_to_use}\\associated_files\\{timestamp_filename}.json'
        new_timestamp = json.loads(self._convert_dataframe_to_timestamp_json(dataframe, primary_key, timestamp_column_name))
        old_timestamp = json.load(open(filepath)) if os.path.exists(filepath) else None
        well_ids_to_update = self._find_new_or_updated_well_ids(old_timestamp, new_timestamp, primary_key, timestamp_column_name)
        self._save_dataframe_timestamp_to_json(dataframe, filepath, primary_key, timestamp_column_name)
        return dataframe[dataframe[primary_key].isin(well_ids_to_update)]

    def send_email(self, from_email: str, password: str, to_email: str, subject: str, body: str, smtp_server: str = "smtp.office365.com", smtp_port: int = 587) -> None:
        """
        Sends an email using the specified SMTP server.

        Parameters:
            from_email (str): The sender's email address.
            password (str): The sender's email account password.
            to_email (str): The recipient's email address.
            subject (str): The subject of the email.
            body (str): The body of the email, which will be formatted as HTML.
            smtp_server (str, optional): The SMTP server address. Default is "smtp.office365.com".
            smtp_port (int, optional): The SMTP server port. Default is 587.

        Returns:
            None
        """

        message = f"Subject: {subject}\n\n{body}"

        formatted_body = body.replace('\n', '<br>')
        html_body = f"""
        <html>
        <body>
            <p style="font-size:10px; font-family:Arial;">{formatted_body}</p>
        </body>
        </html>
        """

        message = f"Subject: {subject}\n"
        message += "MIME-Version: 1.0\n"
        message += "Content-Type: text/html\n\n"
        message += html_body

        with smtplib.SMTP(smtp_server, smtp_port) as server:
            server.starttls()
            server.login(from_email, password)
            server.sendmail(from_email, to_email, message)

    def clean_deviation_survey_payload(self, data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """
        Cleans a list of dictionaries by removing duplicates based on the 'md' value, ensuring the list is sorted in increasing order,
        and removing any entry where 'md' or 'tvd' includes a NaN value.

        Parameters:
        data (List[Dict[str, Any]]): A list of dictionaries, where each dictionary contains 'md' and 'tvd' keys.

        Returns:
        List[Dict[str, Any]]: A cleaned and sorted list of dictionaries based on 'md'.
        """
        # Remove entries with NaN values for 'md' or 'tvd'
        data = [entry for entry in data if not (pd.isna(entry['md']) or pd.isna(entry['tvd']))]

        # Convert 'md' and 'tvd' to floats
        data = [{'md': float(entry['md']), 'tvd': float(entry['tvd'])} for entry in data]

        unique_data = {}
        for entry in data:
            if entry['md'] not in unique_data:
                unique_data[entry['md']] = entry

        cleaned_data = sorted(unique_data.values(), key=lambda x: x['md'])
        return cleaned_data

    def get_new_well_ids_2(self, unique_well_ids_df: pd.DataFrame,  json_filename: str, client_name: str = None) -> List[dict]:
        """
        Returns a list of new well IDs not already present in the saved JSON file for the specified client.
        Overwrites the JSON file with the new set of well IDs.

        Parameters:
        - unique_well_ids_df (pd.DataFrame): DataFrame containing the queried well IDs.
        - client_name (str): The name of the client for directory construction.
        - json_filename (str): The base name of the JSON file where well IDs are stored.

        Returns:
        - list: A list of new well IDs. Returns an empty list if no new well IDs are detected.
        """
        client_name_to_use = self.client_name.lower() if client_name == None else client_name

        # Determine the full JSON filepath
        filepath = os.path.join(
            os.path.dirname(os.path.abspath(__file__)).replace('aries_python_code', ""),
            f'scheduler/company/{client_name_to_use}/associated_files/{json_filename}.json'
        )

        # Load existing well IDs from JSON if the file exists, else initialize an empty list
        if os.path.exists(filepath):
            with open(filepath, 'r') as file:
                existing_well_ids = json.load(file)
        else:
            existing_well_ids = []

        # Convert the new well IDs to a dictionary format for comparison
        new_well_ids = json.loads(unique_well_ids_df.to_json(orient='records'))

        # Identify only new well IDs
        new_wells_only = [well for well in new_well_ids if well not in existing_well_ids]

        # Overwrite the JSON with the new well IDs (latest dataset)
        unique_well_ids_df.to_json(filepath, orient='records', indent=4)

        return new_wells_only  # Returns list of new well IDs or empty list if none

    def get_new_well_ids(self, unique_well_ids_df: pd.DataFrame, json_filename: str, client_name: str = None) -> List[str]:
        """
        Returns a list of new well IDs not already present in the saved JSON file for the specified client.
        Updates the JSON file with the new set of unique well IDs, storing one well ID per line.

        Parameters:
        - unique_well_ids_df (pd.DataFrame): DataFrame containing the queried well IDs (must include a 'well_id' column).
        - json_filename (str): The base name of the JSON file where well IDs are stored.
        - client_name (str, optional): The name of the client for directory construction. Defaults to `self.client_name`.

        Returns:
        - List[str]: A list of new well IDs. Returns an empty list if no new well IDs are detected.
        """
        if "well_id" not in unique_well_ids_df.columns:
            raise ValueError("The DataFrame must contain a 'well_id' column.")

        client_name_to_use = self.client_name.lower() if client_name is None else client_name

        # Determine the full JSON filepath
        filepath = os.path.join(
            os.path.dirname(os.path.abspath(__file__)).replace('aries_python_code', ""),
            f'scheduler/company/{client_name_to_use}/associated_files/{json_filename}.json'
        )

        # Load existing well IDs from JSON if the file exists
        if os.path.exists(filepath):
            with open(filepath, 'r') as file:
                existing_well_ids = set(json.load(file))
        else:
            existing_well_ids = set()

        # Extract unique well IDs from the DataFrame
        new_well_ids = set(unique_well_ids_df['well_id'].astype(str))  # Ensure all well_ids are strings

        # Identify only new well IDs
        new_wells_only = list(new_well_ids - existing_well_ids)

        # Update the JSON file with the latest unique well IDs
        updated_well_ids = list(existing_well_ids.union(new_well_ids))
        with open(filepath, 'w') as file:
            json.dump(updated_well_ids, file, indent=4)

        return new_wells_only

    def _find_decimals(self, data):
        if isinstance(data, dict):
            for key, value in data.items():
                if isinstance(value, decimal.Decimal):
                    print(f"Decimal found at key '{key}' with value {value}")
                elif isinstance(value, dict):
                    self._find_decimals(value)
                elif isinstance(value, list):
                    for item in value:
                        self._find_decimals(item)
        elif isinstance(data, list):
            for item in data:
                self._find_decimals(item)


## Done!


## Done!
## Last updated - 4 Oct 2024

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)