-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathplot.py
executable file
·1354 lines (1112 loc) · 51.5 KB
/
plot.py
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
#!/usr/bin/env python
# (TODO)
#%% Plot pure Functions
class PsatPlots:
def __init__(self, comp, model):
from tinydb import TinyDB, Query
# init database
self.db = TinyDB('.db/pure_db.json')
pplots = Query()
self.DBr = self.db.search((pplots.name == comp)
& (pplots.name == model)
& (pplots.dtype == 'psat_r'))
return
def save_psat_range(self, P_sat_store, T_sat_store, p):
from tinydb import TinyDB
import numpy
db = TinyDB('.db/pure_db.json')
db_store = {'dtype' : 'psat_r',
'name' : p['name'][0],
'P_sat_r' : P_sat_store,
'T_sat_r' : T_sat_store,
'P_data' : p['P'],
'T_data' : p['T'],
'model': p['Model'][0],
'm' : numpy.ndarray.tolist(p['m'])
}
db.insert(db_store)
return
def psat_range(self, s, p):
import numpy
import logging
from models import van_der_waals as VdW
#VdW = van_der_waals.VdW()
# inits
s['b'] = p['b_c'] # b = b_c
T_sat_store = numpy.linspace(min(p['T']), max(p['T']))
P_sat_store = []
P_est = numpy.interp(T_sat_store, p['T'], p['P'])
i = 0
# Loop through model points
for T, P in zip(T_sat_store[:len(T_sat_store) - 1],
P_est[:len(T_sat_store) - 1]): # Trim crit.
s['T'] = T # Solve P_sat at this Temperature
s['P'] = P # P est
try:
s = VdW.Psat_V_roots(s, p, tol=1e-1)
P_sat_store.append(s['P_sat'])
except IOError:
logging.warning("Could not converge Maxwell integral at "
"point T = {}, P = {}".format(T, P))
P_sat_store.append(P) # Append estimate
P_sat_store.append(p['P_c']) # Append Critical point
T_sat_store = numpy.ndarray.tolist(T_sat_store)
# Save results in databasis
self.save_psat_range(P_sat_store, T_sat_store, p)
return P_sat_store, T_sat_store
def plot_Psat(self, comp, options=None, figno=None):
"""
Parameters
----------
s : class
Contains the dictionaries with the state of each component.
p : class
Contains the dictionary describing the mixture parameters.
options : dict
Options to pass to matplotlib.pyplot.plot
"""
import matplotlib.pyplot as plot
from tinydb import TinyDB, Query
db = TinyDB('.db/pure_db.json')
pplots = Query()
DBr = db.search((pplots.name == comp)
& (pplots.dtype == 'psat_r'))
DBr[0]['P_sat_r']
P_sat_store = DBr[0]['P_sat_r']
T_sat_store = DBr[0]['T_sat_r']
P_data = DBr[0]['P_data']
T_data = DBr[0]['T_data']
model = DBr[0]['model']
m = DBr[0]['m']
plot.figure(figno)
#plot.rcParams['text.latex.preamble']=[r"\usepackage{lmodern}"]
#plot.rcParams.update(options)
plot.plot(T_data, P_data, 'xr', label='Data points')
plot.plot(T_sat_store, P_sat_store, '--r',
label='Van der Waals EoS %s m = %s'% (model[0], m[0]))
plot.xlabel("Temperature / K")
plot.ylabel("Pressure$^{sat}$ / Pa")
plot.title("Van der Waals EoS correlation for $%s$" \
% comp)
#plot.legend(loc=options['legend.loc'])
plot.legend()
plot.show()
return
# %% nComp Plots
class GibbsSurface: #TODO add g_mix plotes here and refactor local variables
def __init__(self):
pass
def plot_g_mix(s, p, g_x_func, Tie=None, plane_func=None, plan_args=None,
x_r=1000, FigNo = None):
"""
Plots the surface of the Gibbs energy of mixing function. Binary and
Trenary plots only.
Parameters
----------
s : class
Contains the dictionaries with the system state information.
NOTE: Must be updated to system state at P, T, {x}, {y}...
p : class
Contains the dictionary describing the parameters.
g_x_func : function
Returns the gibbs energy at a the current composition
point. Should accept s, p as first two arguments.
Returns a class containing scalar value .m['g_mix']['m']
Tie : list of vectors, optional
Equilibrium tie lines (of n - 1 independent components) to be added
to the plots.
For a binary system specify 2 tie lines as
[[x_1_a, x_1_b], [x_1_c, x_1_d]]
For a trenary system specify the parameters in the plane construction
as
[[G_p, x_1, lambda_1, x_2, lambda_2]]
where G_p is the solution to the global problem at [x_1, x_2] and
lamda_i is the solution duality multipliers.
x_r : int, optional
Number of composition points to plot.
FigNo : int or None, optional
Figure number to plot in matplotlib. Specify None when plotting
several figures in a loop.
Dependencies
------------
numpy
matplotlib
"""
import numpy as np
#% Binary
if p.m['n'] == 2:
from matplotlib import pyplot as plot
#% Initialize
g_mix_r = {'t': []} # Contains range of solutions for all phases
for ph in p.m['Valid phases']:
g_mix_r[ph] = []
X_r = np.linspace(0, 1, x_r)
for X in X_r: # Calculate range of G_mix
#X = [X_r[i]]
s = s.update_state(s, p, X = X, Force_Update=True)
s = g_x_func(s, p)
g_mix_r['t'].append(np.float64(s.m['g_mix']['t']))
for ph in p.m['Valid phases']:
g_mix_r[ph].append(np.float64(s.m['g_mix'][ph]))
if FigNo is None:
plot.figure()
else:
plot.figure(FigNo)
for ph in p.m['Valid phases']:
plot.plot(X_r, g_mix_r[ph], label=ph)
plot.plot(X_r, g_mix_r['t'])
if Tie is not None: # Add tie lines
for point in Tie:
X = [point[0]]
s = s.update_state(s, p, X = X, Force_Update=True)
s = g_x_func(s, p)
G1 = np.float64(s.m['g_mix']['t'])
X = [point[1]]
s = s.update_state(s, p, X = X, Force_Update=True)
s = g_x_func(s, p)
G2 = np.float64(s.m['g_mix']['t'])
plot.plot(point,[G1, G2])
Slope = (G1 - G2)/ (point[0] - point[1])
plot.annotate('slope = {}'.format(Slope),
xy=(point[1], G2 + G2*0.5) )
if plane_func is not None: # Add solution dual planes
pfunc = []
for X in X_r: # Calculate range of plane func
#s = s.update_state(s, p, X=X, Force_Update=True)
pfunc.append(plane_func(X, *plan_args))
plot.plot(X_r, pfunc, label=r'Dual plane $\lambda^*$ = {}' "\n"
r'$X^*$ = {}'.format(plan_args[1],
plan_args[3]),
linewidth=1.0)
plot.xlabel(r"$z_1$", fontsize=14)
plot.ylabel(r"$\Delta$g", fontsize=14)
plot.title("{}-{} Gibbs energy of mixing at T = {}, P = {}".format(
p.c[1]['name'][0],
p.c[2]['name'][0],
s.m['T'],
s.m['P']))
plot.legend()
#plot.show()
return
#% Trenary
if p.m['n'] == 3:
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plot
from matplotlib import cm
# Define Tie planes
def tie(X, T):
G_p, x_1, lambda_1, x_2, lambda_2 = T
return G_p + lambda_1 * (X[0] - x_1) + lambda_2 * (X[1] - x_2)
x_range = np.linspace(1e-15, 1.0, x_r)
y_range = np.linspace(1e-15, 1.0, x_r)
xg, yg = np.meshgrid(x_range, y_range)
g_mix_r = {'t': np.zeros((x_r, x_r))}
for ph in p.m['Valid phases']:
g_mix_r[ph] = np.zeros((x_r, x_r))
Tie_planes = []
for z in range(len(Tie)):
Tie_planes.append(np.zeros((x_r, x_r)))
for i in range(xg.shape[0]):
for j in range(yg.shape[0]):
X = [xg[i, j], yg[i, j]] # [x_1, x_2]
if sum(X) > 1.0:#1.0:
for z in range(len(Tie)):
Tie_planes[z][i, j] = None
g_mix_r['t'][i, j] = None
for ph in p.m['Valid phases']:
g_mix_r[ph][i, j] = None
else:
# Tie lines
for z in range(len(Tie)):
Tie_planes[z][i, j] = tie(X, Tie[z])
# g_func
s = s.update_state(s, p, X = X, Force_Update=True)
s = g_x_func(s, p)
g_mix_r['t'][i, j] = np.float64(s.m['g_mix']['t'])
for ph in p.m['Valid phases']:
g_mix_r[ph][i, j] = np.float64(s.m['g_mix'][ph])
if FigNo is None:
fig = plot.figure()# plot.figure()
else:
fig = plot.figure(FigNo)
# Plots
ax = fig.gca(projection='3d')
X, Y = xg, yg
# Gibbs phase surfaces
rst = 1
cst = 1
for ph in p.m['Valid phases']:
Z = g_mix_r[ph]
ax.plot_surface(X, Y, Z, rstride=rst, cstride=cst, alpha=0.1)
#cset = ax.contour(X, Y, Z, zdir='x', offset=-0.1, cmap=cm.coolwarm)
#cset = ax.contour(X, Y, Z, zdir='y', offset=-0.1, cmap=cm.coolwarm)
# Gibbs minimum surface
Z = g_mix_r['t']
ax.plot_surface(X, Y, Z, rstride=rst, cstride=cst, alpha=0.1,color='r')
if False:
cset = ax.contour(X, Y, Z, zdir='x', offset=-0.1, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='y', offset=-0.1, cmap=cm.coolwarm)
# Planes
rst = 4
cst = 4
for z in range(len(Tie)):
ax.plot_surface(X, Y, Tie_planes[z], rstride=rst, cstride=cst,
alpha=0.1)
ax.set_xlabel('$x_1$')
ax.set_xlim(0, 1)
ax.set_ylabel('$x_2$')
ax.set_ylim(0, 1)
ax.set_zlabel('$\Delta g$', rotation = 90)
#plot.show()
return s
else:
import logging
logging.warn('Too many independent components to plot hypersurface '
+'in R^3.')
class IsoDetection:
"""
Iso plots using phase equilibrium detection.
"""
def __init__(self, T=None, P=None, components=None):
self.T = T
self.P = P
self.comps = components
def plot_iso(self, s, p, g_x_func, T=None, P=None, res=30, n=1000,
tol=1e-9, gtol=1e-2, n_dual=300, phase_tol=1e-3,
LLE_only=False, VLE_only=False, Plot_Results=False,
data_only=False):
"""
Main function to call when for plotting isotherms/isobars for either
binary or ternary systems.
Parameters
----------
s : class
Contains the dictionaries with the system state information.
NOTE: Must be updated to system state at P, T, {x}, {y}...
p : class
Contains the dictionary describing the parameters.
g_x_func : function
Returns the gibbs energy at a the current composition
point. Should accept s, p as first two arguments.
Returns a class containing scalar value .m['g_mix']['t']
T : list
Isotherms to simulate
P: list
Isobars to simulate
res : integer
Specifies the number of data points to be simulated within the
specified range.
tol : scalar, optional
Tolerance used in ``dual_equal``, if epsilon >= UBD - LBD that will
terminate the routine.
gtol : scalar, optional
Minimum tolerance between hyperplane solution
Note: The Dual solution is not perfect so a low tolerance is
required, but a too low tol could potentially include points that do
not truly lie on the equilibrium plane within the considered
instability region.
n_dual : scalar, optional
Number of sampling points used in the tgo routine in solving LBD
of the dual problem.
Note: It is recommended to use at least ``100 + p.m['n'] * 100``
phase_tol : scalar, optional
The minimum seperation between equilibrium planes required to
be considered a phase. Defaults to 0.001
LLE_only : boolean, optional
If True then only phase seperation of same volume root
instability will be calculated.
VLE_only : boolean, optional
If True then phase seperation of same volume root instability
will be ignored.
Plot_Results : boolean, optional
If True the g_mix curve with tie lines will be plotted for
binary and ternary systems.
data_only : boolean, optional
If True only data will be plotted with no model simulations
"""
import numpy
if T is not None:
Pre = None
for t in T:
# look for data in database
nodbdata = True
from tinydb import TinyDB, Query
self.db = TinyDB('.db/iso_db.json')
pplots = Query()
self.DBr = self.db.search((pplots.dtype == 'iso_r')
& (pplots.comps == self.comps)
& (pplots.T == t)
& (pplots.P == Pre)
& (pplots.r == p.m['r'])
& (pplots.s == p.m['s'])
& (pplots.kij == p.m['k'])
& (pplots.res == res)
& (pplots.LLE_only == LLE_only)
& (pplots.VLE_only == VLE_only)
)
if len(self.DBr) > 0:
nodbdata = False
import logging
plot_kwargs = self.DBr[0]['plot_kwargs']
logging.warn('Found data in database for specified params')
# Find model results and data points
(P_range, T_range, r_ph_eq, r_mph_eq, r_mph_ph, data_x_mph,
data_x_ph, data_t, data_p) = self.iso_range(s, p,
g_x_func, T=t, P=None, res=res,
n=n, tol=tol, gtol=gtol, n_dual=n_dual,
phase_tol=phase_tol, LLE_only=LLE_only,
VLE_only=VLE_only, Plot_Results=True,
data_only=data_only, nodbdata=nodbdata)
# Process VLE points
model_x_mph, model_p_mph, model_t_mph = None, None, None
if nodbdata:
plot_kwargs = {}
if not LLE_only:
if not data_only:
model_x_mph, model_p_mph, model_t_mph = \
self.process_VLE_range(p, P_range, T_range,
r_mph_eq, r_mph_ph)
plot_kwargs['model_p_mph'] = model_p_mph
plot_kwargs['model_x_mph'] = model_x_mph
# Process LLE points
model_x_ph, model_p_ph, model_t_ph = None, None, None
if nodbdata:
if not VLE_only:
if not data_only:
model_x_ph, model_p_ph, model_t_ph = \
self.process_LLE_range(p, P_range, T_range,
r_ph_eq)
plot_kwargs['model_p_ph'] = model_p_ph
plot_kwargs['model_x_ph'] = model_x_ph
# Save data
if nodbdata:
kij = p.m['k']
p_r = p.m['r']
p_s = p.m['s']
self.save_iso_range(self.comps, Pre, t, kij, p_r, p_s, res,
LLE_only, VLE_only, plot_kwargs)
# Plot each isotherm
if p.m['n'] == 2:
self.plot_iso_t_bin(t, p,
data_p=data_p,
data_x_mph=data_x_mph,
data_x_ph = data_x_ph,
# model_p_mph=model_p_mph,
#model_t_mph=model_t_ph,
# model_x_mph=model_x_mph,
# model_p_ph=model_p_ph,
#model_t_ph=model_t_ph,
# model_x_ph=model_x_ph,
LLE_only=LLE_only,
VLE_only=VLE_only,
**plot_kwargs)
elif p.m['n'] == 3:
pass
else:
import logging
logging.warning('Dimensionality too high, ignoring plot'
'request')
if P is not None:
T = None
for Pre in P:
# look for data in database
nodbdata = True
from tinydb import TinyDB, Query
self.db = TinyDB('.db/iso_db.json')
pplots = Query()
self.DBr = self.db.search((pplots.dtype == 'iso_r')
& (pplots.comps == self.comps)
& (pplots.T == t)
& (pplots.P == Pre)
& (pplots.r == p.m['r'])
& (pplots.s == p.m['s'])
& (pplots.kij == p.m['k'])
& (pplots.res == res)
& (pplots.LLE_only == LLE_only)
& (pplots.VLE_only == VLE_only)
)
if len(self.DBr) > 0:
nodbdata = False
import logging
plot_kwargs = self.DBr[0]['plot_kwargs']
logging.warn('Found data in database for specified params')
# Find model results and data points
(P_range, T_range, r_ph_eq, r_mph_eq, r_mph_ph,
data_x_mph,
data_x_ph, data_t, data_p) = self.iso_range(s, p,
g_x_func,
T=None,
P=Pre,
res=res,
n=n,
tol=tol,
gtol=gtol,
n_dual=n_dual,
phase_tol=phase_tol,
LLE_only=LLE_only,
VLE_only=VLE_only,
Plot_Results=True,
data_only=data_only,
nodbdata=nodbdata)
# Process VLE points
model_x_mph, model_p_mph, model_t_mph = None, None, None
if nodbdata:
plot_kwargs = {}
if not LLE_only:
if not data_only:
model_x_mph, model_p_mph, model_t_mph = \
self.process_VLE_range(p, P_range, T_range,
r_mph_eq, r_mph_ph)
plot_kwargs['model_t_mph'] = model_t_mph
plot_kwargs['model_x_mph'] = model_x_mph
# Process LLE points
model_x_ph, model_p_ph, model_t_ph = None, None, None
if nodbdata:
if not VLE_only:
if not data_only:
# Process results
model_x_ph, model_p_ph, model_t_ph = \
self.process_LLE_range(p, P_range, T_range,
r_ph_eq)
plot_kwargs['model_t_ph'] = model_t_ph
plot_kwargs['model_x_ph'] = model_x_ph
# Save data
if nodbdata:
kij = p.m['k']
p_r = p.m['r']
p_s = p.m['s']
self.save_iso_range(self.comps, P, T, kij, p_r, p_s, res,
LLE_only, VLE_only, plot_kwargs)
# Plot each isotherm
if p.m['n'] == 2:
self.plot_iso_p_bin(Pre, p,
#data_p=data_p,
data_x_mph=data_x_mph,
data_x_ph=data_x_ph,
# model_p_mph=model_p_mph,
# model_t_mph=model_t_ph,
# model_x_mph=model_x_mph,
# model_p_ph=model_p_ph,
# model_t_ph=model_t_ph,
# model_x_ph=model_x_ph,
LLE_only=LLE_only,
VLE_only=VLE_only,
**plot_kwargs)
elif p.m['n'] == 3:
pass
else:
import logging
logging.warning(
'Dimensionality too high, ignoring plot'
'request')
return
def iso_range(self, s, p, g_x_func, T=None, P=None, res=30, n=1000,
tol=1e-9, gtol=1e-2, n_dual=300, phase_tol=1e-3,
LLE_only=False, VLE_only=False, Plot_Results=False,
data_only=False, nodbdata=True):
"""
Function used to find model ranges over isotherms/bars and organize
the results into data containers that can be used plot functions.
Parameters
----------
s : class
Contains the dictionaries with the system state information.
NOTE: Must be updated to system state at P, T, {x}, {y}...
p : class
Contains the dictionary describing the parameters.
g_x_func : function
Returns the gibbs energy at a the current composition
point. Should accept s, p as first two arguments.
Returns a class containing scalar value .m['g_mix']['t']
T : float
Isotherm to simulate
P: float
Isobar to simulate
res : integer
Specifies the number of data points to be simulated within the
specified range.
tol : scalar, optional
Tolerance used in ``dual_equal``, if epsilon >= UBD - LBD that will
terminate the routine.
gtol : scalar, optional
Minimum tolerance between hyperplane solution
Note: The Dual solution is not perfect so a low tolerance is
required, but a too low tol could potentially include points that do
not truly lie on the equilibrium plane within the considered
instability region.
n_dual : scalar, optional
Number of sampling points used in the tgo routine in solving LBD
of the dual problem.
Note: It is recommended to use at least ``100 + p.m['n'] * 100``
phase_tol : scalar, optional
The minimum seperation between equilibrium planes required to
be considered a phase. Defaults to 0.001
LLE_only : boolean, optional
If True then only phase seperation of same volume root
instability will be calculated.
VLE_only : boolean, optional
If True then phase seperation of same volume root instability
will be ignored.
Plot_Results : boolean, optional
If True the g_mix curve with tie lines will be plotted for
binary and ternary systems.
Returns
-------
data_x_mph : dict containing vector containing of all the equilibrium
points in the isotherm/bar (VLE type only)
data_x_ph : dict containing vector containing of all the equilibrium
points in the isotherm/bar (VLE type and LLE type
(TODO separate))
data_t : vector containing all the temperature points in the iso-
therm/bar
data_p : vector containing all the pressure points in the isotherm/bar
P_range : vector of size ``res``
Range of pressure points over the min/max of the isotherm/bar
T_range : vector of size ``res``
Range of temperature points over the min/max of the
isotherm/bar
r_ph_eq : list of size ``res`` containing ph_eq returns:
ph_eq : dict containing keys for each phase in p.m['Valid phases'],
ex:
ph_eq[ph] : list containing composition vectors
Contains a list of equilibrium points of phase (ph)
seperations in the same volume root of the EOS
(ex. LLE type)
r_mph_eq : list of size ``res`` containing mph_eq returns:
mph_eq : list containing composition vectors
contains a list of equilibrium points of phase
seperations in different volume roots of the EOS (mph)
(ex. VLE type)
r_mph_ph : list of size ``res`` containing mph_ph returns:
mph_ph : list containing strings
containts the phase string of the corresponding ``mph_eq``
equilibrium point
"""
import numpy
from ncomp import equilibrium_range as er
if T is not None:
iso_ind = numpy.where(numpy.array(p.m['T']) == T)
data_p = numpy.array(p.m['P'])[iso_ind]
PT_Range = [(min(data_p), max(data_p)),
(T, T)]
data_t = None
if P is not None:
iso_ind = numpy.where(numpy.array(p.m['P']) == P)
data_t = numpy.array(p.m['T'])[iso_ind]
PT_Range = [(min(data_t), max(data_t)),
(P, P)]
data_p = None
# Organize data
# VLE phases
data_x_mph = {}
for ph in p.m['Valid phases']:
data_x_mph[ph] = []
data_x_mph[ph].append([]) # Empty tuple for 0 index
for comp_n in range(1, p.m['n']):
data_x_mph[ph].append(numpy.array(p.m[ph][comp_n])[iso_ind])
# LLE phases
data_x_ph = {}
for ph in p.m['Data phases']:
data_x_ph[ph] = []
data_x_ph[ph].append([]) # Empty tuple for 0 index
for comp_n in range(1, p.m['n']):
data_x_ph[ph].append(numpy.array(p.m[ph][comp_n])[iso_ind])
# Find model outputs
if (not data_only) and nodbdata:
P_range, T_range, r_ph_eq, r_mph_eq, r_mph_ph = \
er(g_x_func, s, p, PT_Range=PT_Range, n=n, res=res, tol=tol,
gtol=gtol, n_dual=n_dual, phase_tol=phase_tol,
LLE_only=LLE_only, VLE_only=VLE_only,
Plot_Results=Plot_Results)
else:
import scipy
P_range = scipy.linspace(PT_Range[0][0], PT_Range[0][1], res)
T_range = scipy.linspace(PT_Range[1][0], PT_Range[1][1], res)
r_ph_eq, r_mph_eq, r_mph_ph = None, None, None
return (P_range, T_range, r_ph_eq, r_mph_eq, r_mph_ph, data_x_mph,
data_x_ph, data_t, data_p)
def save_iso_range(self, comps, P, T, kij, p_r, p_s, res,
LLE_only, VLE_only, plot_kwargs):
from tinydb import TinyDB
import numpy
db = TinyDB('.db/iso_db.json')
db_store = {'dtype' : 'iso_r',
'comps' : comps,
'P' : P,
'T' : T,
'kij' : kij,
'r' : p_r,
's' : p_s,
'res' : res,
'LLE_only' : LLE_only,
'VLE_only' : VLE_only,
'plot_kwargs' : plot_kwargs
}
db.insert(db_store)
return
def process_LLE_range(self, p, P_range, T_range, r_ph_eq): # UNTESTED
"""
Process the equilibrium points found in ncomp.equilibrium_range into
plotable results for LLE type equilibrium points.
Parameters
----------
p : class
Contains the dictionary describing the parameters.
P_range: list
contains the pressure points at each model simulation
T_range: list
contains the temperature points at each model simulation
r_ph_eq : list containing ph_eq returns:
ph_eq : dict containing keys for each phase in p.m['Valid phases'], ex:
ph_eq[ph] : list containing composition vectors
Contains a list of equilibrium points of phase (ph)
seperations in the same volume root of the EOS
(ex. LLE type)
Returns
-------
model_x_ph: dict containing equilibrium tie line vectors for each phase
model_p_ph: dict containing pressure vectors at each tie line
model_t_ph: dict containing temperature vectors at each tie line
"""
model_x_ph = {} # LLE type equilibrium tie lines
model_p_ph = {}
model_t_ph = {}
for ph in p.m['Data phases']:
model_x_ph[ph] = []
model_p_ph[ph] = []
model_t_ph[ph] = []
for i in range(len(P_range)):
for ph in p.m['Valid phases']:
if len(r_ph_eq[i][ph]) > 0: # Equilibrium point found
for j in range(len(r_ph_eq[i][ph])):
if len(r_ph_eq[i][ph][j]) > 1: # discard single points
model_x_ph[ph].append(r_ph_eq[i][ph][j][0])
model_p_ph[ph].append(P_range[i])
model_t_ph[ph].append(T_range[i])
l = 0
for ph2 in p.m['Data phases']:
l += 1
if ph2 is not ph:
try:
model_x_ph[ph].append(
r_ph_eq[i][ph][j][l])
model_p_ph[ph].append(P_range[i])
model_t_ph[ph].append(T_range[i])
except IndexError:
model_x_ph[ph].append(None)
model_p_ph[ph].append(None)
model_t_ph[ph].append(None)
#for l in range(1, len(r_ph_eq[i][ph][j])):
# for
# Attach a pressure and temperature
# point for each of these to keep dims
return model_x_ph, model_p_ph, model_t_ph
def process_VLE_range(self, p, P_range, T_range, r_mph_eq, r_mph_ph):
"""
Process the equilibrium points found in ncomp.equilibrium_range into
plotable results for VLE type equilibrium points.
Parameters
----------
p : class
Contains the dictionary describing the parameters.
P_range: list
contains the pressure points at each model simulation
T_range: list
contains the temperature points at each model simulation
r_mph_eq : list containing mph_eq returns:
mph_eq : list containing composition vectors
contains a list of equilibrium points of phase
seperations in different volume roots of the EOS (mph)
(ex. VLE type)
r_mph_ph : list containing mph_ph returns:
mph_ph : list containing strings
containts the phase string of the corresponding ``mph_eq``
equilibrium point
Returns
-------
model_x_mph: dict containing equilibrium tie line vectors for each
phase
model_p_mph: dict containing pressure vectors at each tie line
model_t_mph: dict containing temperature vectors at each tie line
"""
# Set empty containers for all equilibrium points
model_x_mph = {} # VLE type equilibrium container
model_p_mph = {}
model_t_mph = {}
for ph in p.m['Valid phases']:
model_x_mph[ph] = []
model_p_mph[ph] = []
model_t_mph[ph] = []
for i in range(len(P_range)):
# print('r_mph_eq[i] = {}'.format(r_mph_eq[i]))
# print('r_mph_ph[i] = {}'.format(r_mph_ph[i]))
# print('model_p_mph = {}'.format(model_p_mph))
if len(r_mph_eq[i]) > 0: # Equilibrium point found
for j in range(len(r_mph_eq[i])):
if len(r_mph_eq[i][j]) > 1: # discard single points
print('r_mph_eq[i][j] = {}'.format(r_mph_eq[i][j]))
print('r_mph_ph[i][j] = {}'.format(r_mph_ph[i][j]))
for l in range(len(r_mph_eq[i][j])):
print('r_mph_eq[i][j][l] = {}'.format(r_mph_eq[i][j][l]))
print('r_mph_ph[i][j][l] = {}'.format(r_mph_ph[i][j][l]))
if p.m['n'] == 2:
model_x_mph[r_mph_ph[i][j][l]].append(
r_mph_eq[i][j][l][0])
else:
model_x_mph[r_mph_ph[i][j][l]].append(
r_mph_eq[i][j][l])
model_p_mph[r_mph_ph[i][j][l]].append(P_range[i])
model_t_mph[r_mph_ph[i][j][l]].append(T_range[i])
# Attach a pressure and temperature
# point for each of these to keep dims
# Sort:
import numpy
if (model_p_mph is not None) and (len(model_p_mph) > 0):
for ph in p.m['Valid phases']:
#model_x_mph[ph] = numpy.sort(model_x_mph[ph] )
print('model_x_mph[{}] = {}'.format(ph, model_x_mph[ph]))
sind = numpy.argsort(model_x_mph[ph])
print('sind = {}'.format(sind))
model_x_mph[ph] = numpy.array(model_x_mph[ph])[sind]
model_p_mph[ph] = numpy.array(model_p_mph[ph])[sind]
model_t_mph[ph] = numpy.array(model_t_mph[ph])[sind]
model_x_mph[ph] = numpy.ndarray.tolist(model_x_mph[ph])
model_p_mph[ph] = numpy.ndarray.tolist(model_p_mph[ph])
model_t_mph[ph] = numpy.ndarray.tolist(model_t_mph[ph])
return model_x_mph, model_p_mph, model_t_mph
def plot_iso_t_bin(self, T, p, data_p=None, data_x_mph=None,
data_x_ph=None, model_p_mph=None, model_x_mph=None,
model_p_ph=None, model_x_ph=None,
k=['All'], FigNo=None, plot_options=None,
plot_tie_lines=True, LLE_only=False, VLE_only=False):
"""
Plot binary isotherms for the specified data and model ranges
Parameters
----------
T : float
Temperature of isotherm to plot.
p : class
Contains the dictionary describing the parameters.
data_p : vector
Pressure data values at each point
data_x_mph : dict containing vector containing of all the equilibrium
points in the isotherm/bar (VLE type only)
Contains the composition data points at each data_p for
every valid phase
ex. data_x = {'x': [p.m['x'][1][25:36], # x_1
p.m['x'][2][25:36]], # x_2
'y': [p.m['y'][1][25:36], # y_1
p.m['y'][2][25:36]] # y_2
}
data_x_ph : dict containing vector containing of all the equilibrium
points in the isotherm/bar (VLE type and LLE type
(TODO separate))
model_x_mph: dict containing equilibrium tie line vectors for each
phase
model_p_mph: dict containing pressure vectors at each tie line
model_x_ph: dict containing equilibrium tie line vectors for each phase
model_p_ph: dict containing pressure vectors at each tie line
k : list, optional
List contain valid phases for the current equilibrium calculation.
ex. k = ['x', 'y']
If default value None is the value in p.m['Valid phases'] is retained.
FigNo : int or None, optional
Figure number to plot in matplotlib. Specify None when plotting
several figures in a loop.
options : dict
Options to pass to matplotlib.pyplot.plot
"""
if k == ['All']:
k = p.m['Valid phases']
from matplotlib import pyplot as plot
if FigNo is None: