-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy paththermoTools.py
More file actions
2438 lines (1942 loc) · 82.6 KB
/
Copy paththermoTools.py
File metadata and controls
2438 lines (1942 loc) · 82.6 KB
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
"""
This module provides various functions for thermodynamic operations and fluid property calculations using the NeqSim library.
Functions:
fluid(name="srk", temperature=298.15, pressure=1.01325):
Create a fluid object with the specified thermodynamic model, temperature, and pressure.
readEclipseFluid(filename, wellName=""):
Read fluid data from an Eclipse file.
setEclipseComposition(fluid, filename, wellName=""):
Set the composition of a fluid object using data from an Eclipse file.
addFluids(fluids):
Combine multiple fluid objects into one.
fluid_df(reservoirFluiddf, lastIsPlusFraction=False, autoSetModel=False, modelName="", lumpComponents=True, numberOfLumpedComponents=12, add_all_components=True):
Create a fluid object from a DataFrame containing reservoir fluid data.
createfluid(fluid_type="dry gas"):
Create a fluid object using a predefined fluid type.
createfluid2(names, molefractions=None, unit="mol/sec"):
Create a fluid object using specified component names and mole fractions.
addOilFractions(fluid, charNames, molefractions, molarMass, density, lastIsPlusFraction=False, lumpComponents=True, numberOfPseudoComponents=12):
Add oil fractions to a fluid object.
newdatabase(system):
Create a new database for the specified system.
tunewaxmodel(fluid, experimentaldata, maxiterations=5):
Tune the wax model for a fluid object using experimental data.
data(system):
Get the result table from a system object.
table(system):
Create a table from a system object.
dataFrame(system):
Convert the result table of a system object to a pandas DataFrame.
calcproperties(gascondensateFluid, inputDict):
Calculate properties of a gas condensate fluid using specified input conditions.
fluidflashproperties(spec1, spec2, mode=1, system=None, components=None, fractions=None):
Perform a flash calculation and return fluid properties for a series of process conditions.
separatortest(fluid, pressure, temperature, GOR=None, Bo=None, display=False):
Perform a separator test on a fluid object and optionally display the results.
CVD(fluid, pressure, temperature, relativeVolume=None, liquidrelativevolume=None, Zgas=None, Zmix=None, cummulativemolepercdepleted=None, display=False):
Perform a Constant Volume Depletion (CVD) test on a fluid object and optionally display the results.
viscositysim(fluid, pressure, temperature, gasviscosity=None, oilviscosity=None, aqueousviscosity=None, display=False):
Simulate the viscosity of a fluid object under specified conditions and optionally display the results.
CME(fluid, pressure, temperature, saturationPressure, relativeVolume=None, liquidrelativevolume=None, Zgas=None, Yfactor=None, isothermalcompressibility=None, density=None, Bg=None, viscosity=None, display=False):
Perform a Constant Mass Expansion (CME) test on a fluid object and optionally display the results.
difflib(fluid, pressure, temperature, relativeVolume=None, Bo=None, Bg=None, relativegravity=None, Zgas=None, gasstandardvolume=None, Rs=None, oildensity=None, gasgravity=None, display=False):
Perform a Differential Liberation (DL) test on a fluid object and optionally display the results.
GOR(fluid, pressure, temperature, GORdata=None, Bo=None, display=False):
Calculate the Gas-Oil Ratio (GOR) of a fluid object under specified conditions and optionally display the results.
saturationpressure(fluid, temperature=-1.0):
Calculate the saturation pressure of a fluid object at a specified temperature.
swellingtest(fluid, fluid2, temperature, cummulativeMolePercentGasInjected, pressure=None, relativeoilvolume=None, display=False):
Perform a swelling test on a fluid object and optionally display the results.
printFrame(system):
Print the result table of a system object as a markdown table.
printFluid(system):
Print the result table of a system object.
volumecorrection(system, use=1):
Apply volume correction to a system object.
write(system, filename, newfile=0):
Write the data of a system object to a file.
appenddatabase(system):
Append data to the database of a system object.
show(system):
Display the system object.
showPDF(system):
Generate and display a PDF of the system object.
addComponent(thermoSystem, name, moles, unit="no", phase=-10):
Add a component to a thermodynamic system object.
temperature(thermoSystem, temp, phase=-1):
Set the temperature of a thermodynamic system object.
pressure(thermoSystem, pres, phase=-1):
Set the pressure of a thermodynamic system object.
reactionCheck(thermoSystem):
Initialize chemical reactions in a thermodynamic system object.
mixingRule(thermoSystem, mixRule="classic", GEmodel=""):
Set the mixing rule for a thermodynamic system object.
multiphase(testSystem, multiphase=1):
Enable or disable multiphase check for a test system object.
solidcheck(testSystem, solid=1):
Enable or disable solid phase check for a test system object.
solid(testSystem, solid=1):
Enable or disable solid phase check for a test system object.
GCV(testSystem, unit):
Calculate the Gross Calorific Value (GCV) of a test system object.
watersaturate(testSystem):
Saturate a test system object with water.
TPflash(testSystem, temperature=None, tUnit=None, pressure=None, pUnit=None):
Perform a temperature-pressure flash calculation on a test system object.
TPgradientFlash(testSystem, height, temperature):
Perform a temperature-pressure gradient flash calculation on a test system object.
TVflash(testSystem, volume, unit="m3"):
Perform a temperature-volume flash calculation on a test system object.
TSflash(testSystem, entropy, unit="J/K"):
Perform a temperature-entropy flash calculation on a test system object.
VSflash(testSystem, volume, entropy, unitVol="m3", unit="J/K"):
Perform a volume-entropy flash calculation on a test system object.
VHflash(testSystem, volume, enthalpy, unitVol="m3", unit="J"):
Perform a volume-enthalpy flash calculation on a test system object.
VUflash(testSystem, volume, energy, unitVol="m3", unit="J"):
Perform a volume-internal energy flash calculation on a test system object.
PUflash(testSystem, pressure, energy, unitPressure="bara", unitEnergy="J"):
Perform a pressure-internal energy flash calculation on a test system object.
PVTpropTable(fluid1, fileName, lowTemperature, highTemperature, Tsteps, lowPressure, highPressure, Psteps):
Generate a PVT property table for a fluid object and save it to a file.
TPsolidflash(testSystem):
Perform a temperature-pressure solid flash calculation on a test system object.
PHflash(testSystem, enthalpy, unit="J"):
Perform a pressure-enthalpy flash calculation on a test system object.
PHsolidflash(testSystem, enthalpy):
Perform a pressure-enthalpy solid flash calculation on a test system object.
PSflash(testSystem, entropy, unit="J/K"):
Perform a pressure-entropy flash calculation on a test system object.
freeze(testSystem):
Perform a freezing point temperature flash calculation on a test system object.
scaleCheck(testSystem):
Check the scale potential of a test system object.
ionComposition(testSystem):
Calculate the ion composition of a test system object.
hydp(testSystem):
Calculate the hydrate formation pressure of a test system object.
addfluids(fluid1, fluid2):
Add two fluid objects together.
hydt(testSystem, type=1):
Calculate the hydrate formation temperature of a test system object.
calcIonComposition(fluid1):
Calculate the ion composition of a fluid object.
checkScalePotential(fluid1):
Check the scale potential of a fluid object.
bubp(testSystem):
Calculate the bubble point pressure of a test system object.
bubt(testSystem):
Calculate the bubble point temperature of a test system object.
dewp(testSystem):
Calculate the dew point pressure of a test system object.
dewt(testSystem):
Calculate the dew point temperature of a test system object.
waterdewt(testSystem):
Calculate the water dew point temperature of a test system object.
phaseenvelope(testSystem, display=False):
Calculate the phase envelope of a test system object and optionally display the results.
fluidComposition(testSystem, composition):
Set the molar composition of a test system object.
fluidCompositionPlus(testSystem, composition):
Set the molar composition of a test system object with plus fractions.
getExtThermProp(function, thermoSystem, t=0, p=0):
Get extensive thermodynamic properties of a thermodynamic system object.
getIntThermProp(function, thermoSystem, t=0, p=0):
Get intensive thermodynamic properties of a thermodynamic system object.
getPhysProp(function, thermoSystem, t=0, p=0):
Get physical properties of a thermodynamic system object.
enthalpy(thermoSystem, t=0, p=0):
Get the enthalpy of a thermodynamic system object.
entropy(thermoSystem, t=0, p=0):
Get the entropy of a thermodynamic system object.
densityGERG2008(phase):
Get the density of a phase using the GERG-2008 model.
molvol(thermoSystem, t=0, p=0):
Get the molar volume of a thermodynamic system object.
energy(thermoSystem, t=0, p=0):
Get the internal energy of a thermodynamic system object.
gibbsenergy(thermoSystem, t=0, p=0):
Get the Gibbs energy of a thermodynamic system object.
helmholtzenergy(thermoSystem, t=0, p=0):
Get the Helmholtz energy of a thermodynamic system object.
molefrac(thermoSystem, comp, t=0, p=0):
Get the mole fraction of a component in a thermodynamic system object.
moles(thermoSystem, phase=0):
Get the number of moles in a thermodynamic system object.
beta(thermoSystem, t=0, p=0):
Get the phase fraction (beta) of a thermodynamic system object.
molarmass(thermoSystem, t=0, p=0):
Get the molar mass of a thermodynamic system object.
Z(thermoSystem, t=0, p=0):
Get the compressibility factor (Z) of a thermodynamic system object.
density(thermoSystem, volcor=1, t=0, p=0):
Get the density of a thermodynamic system object.
viscosity(thermoSystem, t=0, p=0):
Get the viscosity of a thermodynamic system object.
WAT(testSystem):
Calculate the Wax Appearance Temperature (WAT) of a test system object.
"""
import logging
from typing import List, Optional, Union
import jpype
import pandas
from jpype.types import *
from neqsim import has_matplotlib, has_tabulate
from neqsim import jneqsim
from neqsim.standards import ISO6976
import math
logger = logging.getLogger(__name__)
def _as_float_list(values) -> list[float]:
if values is None:
return []
if hasattr(values, "tolist"):
values = values.tolist()
return [float(v) for v in list(values)]
def _as_float_matrix(values) -> list[list[float]]:
if values is None:
return []
if hasattr(values, "tolist"):
values = values.tolist()
return [[float(v) for v in row] for row in list(values)]
if has_matplotlib():
import matplotlib.pyplot as plt
thermodynamicoperations = jneqsim.thermodynamicoperations.ThermodynamicOperations
fluidcreator = jneqsim.thermo.Fluid()
fluid_type = {
# SRK-based equations of state
"srk": jneqsim.thermo.system.SystemSrkEos,
"SRK-EoS": jneqsim.thermo.system.SystemSrkEos,
"srk-mc": jneqsim.thermo.system.SystemSrkMathiasCopeman,
"SRK-MC": jneqsim.thermo.system.SystemSrkMathiasCopeman,
"srk-peneloux": jneqsim.thermo.system.SystemSrkPenelouxEos,
"SRK-Peneloux": jneqsim.thermo.system.SystemSrkPenelouxEos,
"srk-twucoon": jneqsim.thermo.system.SystemSrkTwuCoonEos,
"SRK-TwuCoon": jneqsim.thermo.system.SystemSrkTwuCoonEos,
"srk-twoCoon": jneqsim.thermo.system.SystemSrkTwuCoonParamEos,
"SRK-TwuCoon-EOS": jneqsim.thermo.system.SystemSrkTwuCoonStatoilEos,
"srk-twucoon-statoil": jneqsim.thermo.system.SystemSrkTwuCoonStatoilEos,
"srk-s": jneqsim.thermo.system.SystemSrkSchwartzentruberEos,
"scrk": jneqsim.thermo.system.SystemSrkSchwartzentruberEos,
"ScRK-EoS": jneqsim.thermo.system.SystemSrkSchwartzentruberEos,
"srk-volcor": jneqsim.thermo.system.SystemSrkEosvolcor,
"SRK-volcor": jneqsim.thermo.system.SystemSrkEosvolcor,
# PR-based equations of state
"pr": jneqsim.thermo.system.SystemPrEos,
"PR-EoS": jneqsim.thermo.system.SystemPrEos,
"pr-mc": jneqsim.thermo.system.SystemPrMathiasCopeman,
"PR-MC": jneqsim.thermo.system.SystemPrMathiasCopeman,
"pr-danesh": jneqsim.thermo.system.SystemPrDanesh,
"PR-Danesh": jneqsim.thermo.system.SystemPrDanesh,
"pr-volcor": jneqsim.thermo.system.SystemPrEosvolcor,
"PR-volcor": jneqsim.thermo.system.SystemPrEosvolcor,
"pr-umr": jneqsim.thermo.system.SystemUMRPRUMCEos,
"UMR-PRU": jneqsim.thermo.system.SystemUMRPRUMCEos,
# PSRK
"psrk": jneqsim.thermo.system.SystemPsrkEos,
"Psrk-EoS": jneqsim.thermo.system.SystemPsrkEos,
"PSRK-EoS": jneqsim.thermo.system.SystemPsrkEos,
# CSP-SRK
"csp-srk": jneqsim.thermo.system.SystemCSPsrkEos,
"CSP-SRK": jneqsim.thermo.system.SystemCSPsrkEos,
# RK
"rk": jneqsim.thermo.system.SystemRKEos,
"RK-EoS": jneqsim.thermo.system.SystemRKEos,
# CPA equations of state
"cpa": jneqsim.thermo.system.SystemSrkCPAstatoil,
"cpa-srk": jneqsim.thermo.system.SystemSrkCPA,
"CPA-SRK-EoS": jneqsim.thermo.system.SystemSrkCPA,
"cpa-srk-s": jneqsim.thermo.system.SystemSrkCPAs,
"cpa-s": jneqsim.thermo.system.SystemSrkCPAs,
"sCPA": jneqsim.thermo.system.SystemSrkCPAs,
"cpa-statoil": jneqsim.thermo.system.SystemSrkCPAstatoil,
"cpa-pr": jneqsim.thermo.system.SystemPrCPA,
"CPA-PR-EoS": jneqsim.thermo.system.SystemPrCPA,
# Electrolyte models
"electrolyte": jneqsim.thermo.system.SystemFurstElectrolyteEos,
"Electrolyte-ScRK-EoS": jneqsim.thermo.system.SystemFurstElectrolyteEos,
"Electrolyte-CPA-EoS": jneqsim.thermo.system.SystemElectrolyteCPAstatoil,
"cpa-el": jneqsim.thermo.system.SystemElectrolyteCPA,
"electrolyte-cpa": jneqsim.thermo.system.SystemElectrolyteCPA,
# Activity coefficient models
"nrtl": jneqsim.thermo.system.SystemNRTL,
"NRTL": jneqsim.thermo.system.SystemNRTL,
"unifac": jneqsim.thermo.system.SystemUNIFAC,
"UNIFAC": jneqsim.thermo.system.SystemUNIFAC,
# Reference equations of state
"gerg-water": jneqsim.thermo.system.SystemGERGwaterEos,
"GERG-water": jneqsim.thermo.system.SystemGERGwaterEos,
"gerg-2008": jneqsim.thermo.system.SystemGERG2008Eos,
"GERG-2008": jneqsim.thermo.system.SystemGERG2008Eos,
"span-wagner": jneqsim.thermo.system.SystemSpanWagnerEos,
"Span-Wagner": jneqsim.thermo.system.SystemSpanWagnerEos,
"bwrs": jneqsim.thermo.system.SystemBWRSEos,
"BWRS": jneqsim.thermo.system.SystemBWRSEos,
# Leachman hydrogen reference EoS
"leachman": jneqsim.thermo.system.SystemLeachmanEos,
"Leachman": jneqsim.thermo.system.SystemLeachmanEos,
"leachman-h2": jneqsim.thermo.system.SystemLeachmanEos,
# Other
"ideal-gas": jneqsim.thermo.system.SystemIdealGas,
"ideal": jneqsim.thermo.system.SystemIdealGas,
}
# Special fluid types that require additional configuration
_special_fluid_types = {"gerg-2008-h2", "gerg-h2"}
# Create case-insensitive lookup for fluid types
_fluid_type_lower = {k.lower(): v for k, v in fluid_type.items()}
def fluid(name="srk", temperature=298.15, pressure=1.01325):
"""
Create a thermodynamic fluid system.
Parameters:
name (str): The name of the equation of state to use (case-insensitive). Default is "srk".
temperature (float): The temperature of the fluid in Kelvin. Default is 298.15 K.
pressure (float): The pressure of the fluid in bar. Default is 1.01325 bar.
Returns:
object: An instance of the specified thermodynamic fluid system.
Available models:
**SRK-based equations of state:**
Volume correction is ON by default. Use ``fluid.useVolumeCorrection(False)`` to disable.
- ``srk``: Standard Soave-Redlich-Kwong equation of state
- ``srk-mc``: SRK with Mathias-Copeman alpha function
- ``srk-peneloux``: SRK with Peneloux volume correction
- ``srk-twucoon``: SRK with Twu-Coon alpha function
- ``srk-twucoon-statoil``: SRK with Twu-Coon (Statoil parameters)
- ``srk-s`` / ``scrk``: SRK-Schwartzentruber equation of state
**PR-based equations of state:**
Volume correction is ON by default. Use ``fluid.useVolumeCorrection(False)`` to disable.
- ``pr``: Standard Peng-Robinson equation of state
- ``pr-mc``: PR with Mathias-Copeman alpha function
- ``pr-danesh``: PR with Danesh modifications for heavy oil
- ``pr-umr``: UMR-PRU (Universal Mixing Rule PR)
**Predictive and other cubic EoS:**
- ``psrk``: Predictive SRK equation of state
- ``csp-srk``: Corresponding States Principle SRK
- ``rk``: Redlich-Kwong equation of state
**CPA equations of state (for associating fluids):**
- ``cpa``: CPA-SRK (Statoil version) - recommended for water/glycol
- ``cpa-srk``: CPA-SRK equation of state
- ``cpa-srk-s`` / ``sCPA``: Simplified CPA-SRK
- ``cpa-pr``: CPA with Peng-Robinson
**Electrolyte models:**
- ``electrolyte``: Furst electrolyte equation of state
- ``electrolyte-cpa``: Electrolyte CPA equation of state
**Activity coefficient models:**
- ``nrtl``: NRTL activity coefficient model
- ``unifac``: UNIFAC activity coefficient model
**Reference equations of state:**
- ``gerg-2008``: GERG-2008 multiparameter equation of state for natural gas
- ``gerg-2008-h2`` / ``gerg-h2``: GERG-2008 with hydrogen extension (Beckmüller et al. 2022).
Improved hydrogen parameters for H2-containing gas mixtures.
- ``gerg-water``: GERG equation with water
- ``span-wagner``: Span-Wagner equation of state for CO2
- ``leachman`` / ``leachman-h2``: Leachman equation of state for pure hydrogen.
High-accuracy reference equation supporting normal, para, and ortho hydrogen.
- ``bwrs``: Benedict-Webb-Rubin-Starling equation of state
**Other:**
- ``ideal-gas`` / ``ideal``: Ideal gas equation of state
Example:
>>> from neqsim.thermo import fluid
>>> # Create a fluid using SRK equation of state
>>> my_fluid = fluid("srk", temperature=300, pressure=10)
>>> # Create a fluid for associating components using CPA
>>> cpa_fluid = fluid("cpa", temperature=298.15, pressure=1.01325)
"""
name_lower = name.lower()
# Handle special fluid types that need extra configuration
if name_lower in _special_fluid_types:
if name_lower in ("gerg-2008-h2", "gerg-h2"):
system = jneqsim.thermo.system.SystemGERG2008Eos(temperature, pressure)
system.useHydrogenEnhancedModel()
return system
if name_lower not in _fluid_type_lower:
raise ValueError(
f"Fluid model {name} not found. Available models are {list(fluid_type.keys())}"
)
fluid_function = _fluid_type_lower[name_lower]
return fluid_function(temperature, pressure)
def readEclipseFluid(filename, wellName=""):
"""
Reads an Eclipse fluid file and returns the fluid object.
Parameters:
filename (str): The path to the Eclipse fluid file.
wellName (str, optional): The name of the well. Defaults to an empty string.
Returns:
Fluid: The fluid object read from the file.
"""
jneqsim.thermo.util.readwrite.EclipseFluidReadWrite.pseudoName = wellName
fluid1 = jneqsim.thermo.util.readwrite.EclipseFluidReadWrite.read(filename)
return fluid1
def setEclipseComposition(fluid, filename, wellName=""):
jneqsim.thermo.util.readwrite.EclipseFluidReadWrite.pseudoName = wellName
jneqsim.thermo.util.readwrite.EclipseFluidReadWrite.setComposition(fluid, filename)
def addFluids(fluids):
"""
Combine multiple fluid objects into a single fluid object.
This function takes a list of fluid objects, clones the first fluid object,
and then adds each subsequent fluid object to the cloned fluid object.
Parameters:
fluids (list): A list of fluid objects to be combined. The first fluid object
in the list will be cloned, and the rest will be added to this clone.
Returns:
Fluid: A single fluid object that is the result of combining all the fluid objects
in the input list.
"""
fluid = fluids[0].clone()
numberOfFluids = len(fluids)
for i in range(numberOfFluids - 1):
fluid.addFluid(fluids[i + 1])
return fluid
def fluid_df(
reservoirFluiddf,
lastIsPlusFraction=False,
autoSetModel=False,
modelName="",
lumpComponents=True,
numberOfLumpedComponents=12,
add_all_components=True,
):
"""
Create a fluid object from a DataFrame containing reservoir fluid composition data.
Parameters:
reservoirFluiddf (pd.DataFrame): DataFrame containing the reservoir fluid composition.
lastIsPlusFraction (bool, optional): Indicates if the last component is a plus fraction. Defaults to False.
autoSetModel (bool, optional): If True, automatically selects the thermodynamic model. Defaults to False.
modelName (str, optional): Name of the thermodynamic model to use. Defaults to an empty string.
lumpComponents (bool, optional): If True, lumps components together. Defaults to True.
numberOfLumpedComponents (int, optional): Number of lumped components to create. Defaults to 12.
add_all_components (bool, optional): If True, adds all components regardless of their molar composition. Defaults to True.
Returns:
fluid: A fluid object created based on the provided composition data.
"""
if autoSetModel:
fluidcreator.setAutoSelectModel(True)
else:
fluidcreator.setAutoSelectModel(False)
if modelName:
fluidcreator.setThermoModel(modelName)
else:
fluidcreator.setAutoSelectModel(False)
TBPComponentsFrame = reservoirFluiddf.dropna()
if not add_all_components:
reservoirFluiddf = reservoirFluiddf[
reservoirFluiddf["MolarComposition[-]"] != 0.0
]
TBPComponentsFrame = TBPComponentsFrame[
TBPComponentsFrame["MolarComposition[-]"] > 0
]
else:
TBPComponentsFrame = reservoirFluiddf.dropna()
if "MolarMass[kg/mol]" in reservoirFluiddf:
definedComponentsFrame = reservoirFluiddf[
reservoirFluiddf["MolarMass[kg/mol]"].isnull()
]
else:
definedComponentsFrame = reservoirFluiddf
if not add_all_components:
definedComponentsFrame = definedComponentsFrame[
definedComponentsFrame["MolarComposition[-]"] > 0.0
]
if definedComponentsFrame.size > 0:
fluid7 = createfluid2(
definedComponentsFrame["ComponentName"].tolist(),
definedComponentsFrame["MolarComposition[-]"].tolist(),
)
else:
# When only pseudo components exist, create an empty base fluid
fluid7 = fluid("pr")
# Check if we have TBP/pseudo components to add (components with MolarMass)
hasTBPComponents = (
"MolarMass[kg/mol]" in reservoirFluiddf and TBPComponentsFrame.size > 0
)
if hasTBPComponents:
addOilFractions(
fluid7,
TBPComponentsFrame["ComponentName"].tolist(),
TBPComponentsFrame["MolarComposition[-]"].tolist(),
TBPComponentsFrame["MolarMass[kg/mol]"].tolist(),
TBPComponentsFrame["RelativeDensity[-]"].tolist(),
lastIsPlusFraction,
lumpComponents,
numberOfLumpedComponents,
)
return fluid7
def createfluid(fluid_type="dry gas"):
"""
Create a fluid object based on the specified fluid type.
Parameters:
fluid_type (str): The type of fluid to create. Default is "dry gas".
Returns:
Fluid: A fluid object created based on the specified fluid type.
"""
return fluidcreator.create(fluid_type)
def createfluid2(names, molefractions=None, unit="mol/sec"):
"""
Create a fluid with specified component names and mole fractions.
Parameters:
names (list of str): List of component names.
molefractions (list of float, optional): List of mole fractions corresponding to the component names. Defaults to None.
unit (str, optional): Unit of the mole fractions. Defaults to "mol/sec".
Returns:
Fluid: The created fluid object.
"""
if molefractions is None:
return fluidcreator.create2(JString[:](names))
return fluidcreator.create2(JString[:](names), _as_float_list(molefractions), unit)
def addOilFractions(
fluid,
charNames,
molefractions,
molarMass,
density,
lastIsPlusFraction=False,
lumpComponents=True,
numberOfPseudoComponents=12,
):
fluid.addOilFractions(
JString[:](charNames),
_as_float_list(molefractions),
_as_float_list(molarMass),
_as_float_list(density),
lastIsPlusFraction,
lumpComponents,
numberOfPseudoComponents,
)
def newdatabase(system):
system.createDatabase(1)
def tunewaxmodel(fluid, experimentaldata, maxiterations=5):
tempList = [x + 273.15 for x in experimentaldata["temperature"]]
presList = experimentaldata["pressure"]
expList = [[x * 100.0 for x in experimentaldata["experiment"]]]
waxsim = jneqsim.pvtsimulation.simulation.WaxFractionSim(fluid)
waxsim.setTemperaturesAndPressures(
_as_float_list(tempList), _as_float_list(presList)
)
waxsim.setExperimentalData(_as_float_matrix(expList))
waxsim.getOptimizer().setNumberOfTuningParameters(3)
waxsim.getOptimizer().setMaxNumberOfIterations(maxiterations)
waxsim.runTuning()
waxsim.runCalc()
results = {
"temperature": tempList,
"pressure": presList,
"experiment": expList,
"results": list(waxsim.getWaxFraction()),
"parameters": list(
waxsim.getOptimizer()
.getSampleSet()
.getSample(0)
.getFunction()
.getFittingParams()
),
}
return results
def data(system):
a = system.getResultTable()
return a
def table(system):
# todo: convert to class method
return system.createTable("")
def dataFrame(system):
# todo: convert to class method
return pandas.DataFrame(table(system)).astype(str)
def calcproperties(gascondensateFluid, inputDict):
"""
Calculate properties of a gas condensate fluid using the jneqsim PropertyGenerator.
Parameters:
gascondensateFluid (object): The gas condensate fluid object to be analyzed.
inputDict (dict): A dictionary containing the input parameters:
- "temperature" (list of float): List of temperatures at which to calculate properties.
- "pressure" (list of float): List of pressures at which to calculate properties.
Returns:
pandas.DataFrame: A DataFrame containing the calculated properties with keys as column names.
"""
properties = jneqsim.util.generator.PropertyGenerator(
gascondensateFluid,
_as_float_list(inputDict["temperature"]),
_as_float_list(inputDict["pressure"]),
)
props = properties.calculate()
calculatedProperties = {k: list(v) for k, v in props.items()}
df = pandas.DataFrame(calculatedProperties)
return df
def fluidflashproperties(
spec1: pandas.Series,
spec2: pandas.Series,
mode: Union[int, str] = 1,
system=None,
components: Optional[List[str]] = None,
fractions: Optional[list] = None,
):
"""Perform flash and return fluid properties for a series of process properties.
Args:
spec1 (pandas.Series): Process condition to perform flash at. Type depends on mode argument, see below for units.
spec2 (pandas.Series): Process condition to perform flash at. Type depends on mode argument, see below for units.
mode (int, str): Supported flash modes: PT or TP (1), PH (2) and PS (3). Defaults to 1.
system (_type_, optional): A default system is created if not passed and components and fractions can specify it.
components (list, optional): List of component names. Defaults to None, which requires a system input.
fractions (list, optional): List of fractions if same for all flashes or list of list of fractions per flash. Defaults to None, which requires a system input..
Raises:
ValueError: Invalid Mode input
ValueError: Invalid combination of system, components and fractions.
TypeError: Fraction must be list if provided.
NotImplementedError: _description_
NotImplementedError: _description_
Returns:
_type_: _description_
Input units:
- Flash pressure in bar absolute.
- Temperature in Kelvin
- Entalphy in J/mol
- Entropy in J/molK.
Pressure shall be specified as bara,
Fractions can be a single list of component fractions to use for all flashes or a list of lists where the first dimension the different components and the second dimension is the fraction per flash.
Same component list is used for all flashes.
"""
if isinstance(mode, int):
if mode == 1:
# Convert to PT
temp = spec1
spec1 = spec2
spec2 = temp
elif isinstance(mode, str):
if mode == "PT":
mode = 1
elif mode == "TP":
mode = 1
# Convert to PT
temp = spec1
spec1 = spec2
spec2 = temp
elif mode == "PH":
mode = 2
elif mode == "PS":
mode = 3
if not isinstance(mode, int) or mode < 1 or mode > 3:
raise ValueError("Mode must be in 'TP' or 1, 'PH' or 2 or 'PS' or 3")
if system is None:
if components is None or fractions is None:
raise ValueError(
"if system is not specified, components and fractions must be specified."
)
system = jneqsim.thermo.system.SystemSrkEos(273.15, 1.01325)
if not isinstance(components, list):
components = [components]
system.addComponents(components)
# Single component
if not isinstance(fractions, list):
fractions = [fractions]
if not all([isinstance(x, list) for x in fractions]):
system.setTotalNumberOfMoles(1)
system.setMolarComposition(fractions)
thermoOps = jneqsim.thermodynamicoperations.ThermodynamicOperations(system)
if isinstance(spec1, pandas.Series):
spec1 = spec1.to_list()
elif not isinstance(spec1, list):
spec1 = [spec1]
jSpec1 = jpype.java.util.ArrayList()
[jSpec1.add(float(x)) for x in spec1]
if isinstance(spec2, pandas.Series):
spec2 = spec2.to_list()
elif not isinstance(spec2, list):
spec2 = [spec2]
jSpec2 = jpype.java.util.ArrayList()
[jSpec2.add(float(x)) for x in spec2]
if fractions is not None:
if not isinstance(fractions, list):
raise TypeError("Fractions must be a list if provided")
if components is not None:
if not isinstance(components, list):
components = [components]
if all([isinstance(x, list) for x in components]):
raise NotImplementedError("Component list must be fixed if provided")
elif any([isinstance(x, list) for x in components]):
raise NotImplementedError("Component list must be fixed if provided")
else:
components = None
if all([isinstance(x, list) for x in fractions]):
# pivot fractions
num_components = len(fractions)
jFractions = jpype.java.util.ArrayList()
for k_comp in range(0, num_components):
jComp = jpype.java.util.ArrayList()
[jComp.add(x) for x in fractions[k_comp]]
jFractions.add(jComp)
fractions = jFractions
elif any([isinstance(x, list) for x in fractions]):
pass
# raise NotImplementedError
else:
fractions = None
return thermoOps.propertyFlash(jSpec1, jSpec2, mode, components, fractions)
def separatortest(fluid, pressure, temperature, GOR=None, Bo=None, display=False):
if GOR is None:
GOR = []
if Bo is None:
Bo = []
length = len(pressure)
sepSim = jneqsim.pvtsimulation.simulation.SeparatorTest(fluid)
sepSim.setSeparatorConditions(_as_float_list(temperature), _as_float_list(pressure))
sepSim.runCalc()
for i in range(0, length):
GOR.append(sepSim.getGOR()[i])
Bo.append(sepSim.getBofactor()[i])
i = i + 1
if display:
if has_matplotlib():
plt.figure()
plt.plot(pressure, Bo, "o")
plt.xlabel("Pressure [bara]")
plt.ylabel("Bo [m3/Sm3]")
plt.figure()
plt.plot(pressure, GOR, "o")
plt.xlabel("Pressure [bara]")
plt.ylabel("GOR [Sm3/Sm3]")
plt.figure()
else:
raise Exception("Package matplotlib is not installed")
def CVD(
fluid,
pressure,
temperature,
relativeVolume=None,
liquidrelativevolume=None,
Zgas=None,
Zmix=None,
cummulativemolepercdepleted=None,
display=False,
):
if relativeVolume is None:
relativeVolume = []
if liquidrelativevolume is None:
liquidrelativevolume = []
if Zgas is None:
Zgas = []
if Zmix is None:
Zmix = []
if cummulativemolepercdepleted is None:
cummulativemolepercdepleted = []
length = len(pressure)
cvdSim = jneqsim.pvtsimulation.simulation.ConstantVolumeDepletion(fluid)
cvdSim.setPressures(_as_float_list(pressure))
cvdSim.setTemperature(temperature)
cvdSim.runCalc()
for i in range(0, length):
Zgas.append(cvdSim.getZgas()[i])
Zmix.append(cvdSim.getZmix()[i])
liquidrelativevolume.append(cvdSim.getLiquidRelativeVolume()[i])
relativeVolume.append(cvdSim.getRelativeVolume()[i])
cummulativemolepercdepleted.append(cvdSim.getCummulativeMolePercDepleted()[i])
i = i + 1
if display:
if has_matplotlib():
plt.figure()
plt.plot(pressure, Zgas, "o")
plt.xlabel("Pressure [bara]")
plt.ylabel("Zgas [-]")
plt.figure()
plt.plot(pressure, relativeVolume, "o")
plt.xlabel("Pressure [bara]")
plt.ylabel("relativeVolume [-]")
plt.figure()
else:
raise Exception("Package matplotlib is not installed")
def viscositysim(
fluid,
pressure,
temperature,
gasviscosity=None,
oilviscosity=None,
aqueousviscosity=None,
display=False,
):
if gasviscosity is None:
gasviscosity = []
if oilviscosity is None:
oilviscosity = []
if aqueousviscosity is None:
aqueousviscosity = []
length = len(pressure)
cmeSim = jneqsim.pvtsimulation.simulation.ViscositySim(fluid)
cmeSim.setTemperaturesAndPressures(
_as_float_list(temperature), _as_float_list(pressure)
)
cmeSim.runCalc()
for i in range(0, length):
gasviscosity.append(cmeSim.getGasViscosity()[i])
oilviscosity.append(cmeSim.getOilViscosity()[i])
aqueousviscosity.append(cmeSim.getAqueousViscosity()[i])
if display:
if has_matplotlib():
plt.figure()
plt.plot(pressure, gasviscosity, "o")
plt.xlabel("Pressure [bara]")
plt.ylabel("gasviscosity [kg/msec]")
plt.figure()
plt.plot(pressure, oilviscosity, "o")
plt.xlabel("Pressure [bara]")
plt.ylabel("oilviscosity [kg/msec]")
plt.figure()
else:
raise Exception("Package matplotlib is not installed")
def CME(
fluid,
pressure,
temperature,
saturationPressure,
relativeVolume=None,
liquidrelativevolume=None,
Zgas=None,
Yfactor=None,
isothermalcompressibility=None,
density=None,
Bg=None,
viscosity=None,