-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathncomp.py
2206 lines (1771 loc) · 76.6 KB
/
ncomp.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 python2
# -*- coding: utf-8 -*-
"""
Script to simulate phase equilibria of multicomponent systems.
"""
# %% Imports
from __future__ import division
from models import van_der_waals as VdW
import data_handling
import plot
import numpy
# %% Define state variable class
class state:
"""Class defining state variables """
def __init__(self):
self.s = {} # System state vars
self.c = [] # creates a new empty list for components
self.c.append('nan') # Define an empty set in index 0
# Define the dynamically
self.update_dp = None
def mixed(self):
# Mixture states
self.m = {'a_mix': {}, # Mixture activity coefficient states
'b_mix': {}, # Mixture co-volume coefficient states
}
def pure(self, p, i):
self.c.append({}) # Pure component states
self.c[i]['b'] = p.c[i]['b_c'] # Invariant co volume parameter.
# % Calculate state at P, T, {composition} for all phases
def update_state(self, s, p, P=None, T=None, phase=['All'], X=None,
Force_Update=False):
"""
This function calculates the new state variables of the system at the
specified pressure, temperature and composition vector.
Parameters
----------
s : class
Contains the dictionaries with the state of each component.
p : class
Contains the dictionary describing the mixture parameters.
P : scalar, optional
Pressure (Pa), if None the current state pressure will be used.
T : scalar, optional
Temperature (K), if None the current state temperature will be
used.
phase : string inside a list, optional
Phase to be updated, if the default value 'All' is used then
all viable phases will be updated.
X : vectors embedded inside a list, optional
Entries of list conaint the compositon vector with n - 1 components
List must be in correct phase order specified in
p.m['Valid phases'] and components in correct component number as
specified in the data. If None the current state composition will
be used.
Example specification with 4 independent components:
# x_1 x_2 x_3 y_1 y_2 y_3
X = [[0.1, 0.3, 0.6], [0.3, 0.4, 0.3]]
If only less than 'All' phases are being updated, specify only the
needed composition vector.
Example for phase='x' with 4 independent components:
# x_1 x_2 x_3
X = [[0.1, 0.3, 0.6]]
Force_Update : booleean, optional
If True this will force an update of a single vector
input for X for all phases regardless of the number
of phases specified with "phase". X must be a single
vector/list to avoid failure. Use conservatively.
Dependencies
------------
numpy
logging
Returns
-------
s : class output.
Contains the new updated state. Values changed:
s.c[i]['a'] for all components p.m['n']
s.m['a']
s.b['a']
if P:
s.c[n]['P'] for all components p.m['n']
if T:
s.c[n]['T'] for all components p.m['n']
if X:
s.c[i][ph] for all components p.m['n'] for all phases.
Examples
--------
s = s.update_state(s, p,
P=I['P'],
T=I['T'],
phase=['x','y'],
X=[[0.5,0.2],[0.2,0.2]])
"""
import logging
from numpy import array, size
# Independent updates
if P is not None: # Update pressure
s.m['P'] = P
for i in range(1, p.m['n'] + 1):
s.c[i]['P'] = P
if T is not None: # Update temperature
s.m['T'] = T
for i in range(1, p.m['n'] + 1):
s.c[i]['T'] = T
if X is not None: # Update new compositions
if Force_Update:
for ph in p.m['Valid phases']:
Sigma_x_dep = 0.0 # Sum of dependent components
for i in range(1, p.m['n']):
if size(X) == 1: # Ugly fix because of the zip
X = array([X]) # c
# onversion to float or list
s.c[i][ph] = X[i-1]
Sigma_x_dep += X[i-1]
# Dependent component
s.c[p.m['n']][ph] = 1.0 - Sigma_x_dep
elif phase[0] is 'All':
if len(X) != len(p.m['Valid phases']): # Check for dimensions
raise IOError('The array of X specified does not match'
+' the number of phases expected. len(X) = '
'{} .'.format(len(X))
+'len(p.m[\'Valid phases\']) = {}'
.format(len(p.m['Valid phases'])))
for xp, ph in zip(X, p.m['Valid phases']):
Sigma_x_dep = 0.0 # Sum of dependent components
for i in range(1, p.m['n']): # Independent components
if size(xp) == 1: # Ugly fix because of the zip
xp = array([xp]) # conversion to float or list
s.c[i][ph] = xp[i-1]
Sigma_x_dep += xp[i-1]
# Dependent component
s.c[p.m['n']][ph] = 1.0 - Sigma_x_dep
elif phase is not None:
if len(X) != len(phase): # Check for dimensions
raise IOError('The array of X specified does not match'
+' the number of phases expected. len(X) = '
'{} .'.format(len(X))
+'len(phase) = {}'
.format(len(phase)))
for xp, ph in zip(X, phase):
Sigma_x_dep = 0.0 # Sum of dependent components
for i in range(1, p.m['n']): # Independent components
if size(xp) == 1: # Ugly fix because of the zip
xp = array([xp]) # conversion to float
s.c[i][ph] = xp[i-1]
Sigma_x_dep += xp[i-1]
# Dependent component
s.c[p.m['n']][ph] = 1.0 - Sigma_x_dep
# Dependent updates
for i in range(1, p.m['n']+1): # Update pure activity coefficents
s.c[i]['a'] = VdW.a_T(s.c[i],p.c[i])['a'] # a(T)
try: # Note: Highly non-linear models
if phase[0] is 'All':
for ph in p.m['Valid phases']:
s.m['a_mix'][ph] = a_mix(s, p, phase=ph)
s.m['b_mix'][ph] = b_mix(s, p, phase=ph)
elif phase is not None:
for ph in phase:
s.m['a_mix'][ph] = a_mix(s, p, phase=ph)
s.m['b_mix'][ph] = b_mix(s, p, phase=ph)
except(ValueError, ZeroDivisionError): # DO NOT RAISE, SET PENALTY
s.s['Math Error'] = True
logging.warn('Math Domain error in s.update_state'
+'at {} Pa {} K'.format(s.s['P'], s.s['T'])
)
try: # Default optimization state z
s.m['a'] = a_mix(s, p, phase='x')
s.m['b'] = b_mix(s, p, phase='x')
except KeyError:
raise IOError('Specify at least one viable phase as \'x\' for'
'optimization routines')
# Find Volume Roots ('V_v' and 'V_l') at P, T, a, b for all components
# and phases
for i in range(1, p.m['n']+1):
s.c[i] = VdW.V_root(s.c[i], p.c[i])
s.m = VdW.V_root(s.m, p.m) # 'V_v' and 'V_l' mixture volumes at x1, x2
return s
# Define multi component initialisation
def n_comp_init(data):
"""
Initiate state and parameter class objects based on specified data
input.
"""
# Define parameter class
p = data_handling.MixParameters()
p.mixture_parameters(data.VLE, data)
p.m['n'] = len(data.comps) # Define system size
for i in range(p.m['n']): # Set params for all compounds
p.parameters(data.c[i]) # Defines p.c[i]
#p.parameter_build(data.c[i])
p.m['R'] = p.c[1]['R'] # Use a component Universal gas constant
# %% Initialize state variables
s = state()
s.mixed() # Define mix state variable, call using s.m['key']
# Define three component state variables (use index 1 and 2 for clarity)
for i in range(1, p.m['n']+1):
s.pure(p, i) # Call using ex. s.c[1]['key']
p.m['R'] = p.c[1]['R'] # Use a component Universal gas constant
# %% Initialize state variables
s = state()
s.mixed() # Define mix state variable, call using s.m['key']
# Define three component state variables (use index 1 and 2 for clarity)
for i in range(1, p.m['n']+1):
s.pure(p, i) # Call using ex. s.c[1]['key']
return s, p
# %% Define mixture models
def a_ij(s, p, i=1, j=1): # (Validated)
"""
Returns the temperature dependent a_ij parameter at specified indices.
Parameters
----------
s : class
Contains the dictionaries with the state of each component.
Note: s.c[i]['a'] and s.c[j]['a'] MUST be updated to the current state
temperature value (s.s['T']) before calling.
p : class
Contains the dictionary describing the mixture parameters.
Holds p.m['k'][i][j]
i, j : int, optional
The first component indices.
phase : string, optional
Phase to be calculated, ex. liquid phase 'x'.
Dependencies
------------
math.sqrt
Returns
-------
a_ij : scalar output.
"""
from math import sqrt
if i == j:
return s.c[i]['a'] # Return pure paramater
else: # find mixture aij i =/= j
return (1 - p.m['k'][i][j]) * sqrt(s.c[i]['a'] * s.c[j]['a'])
def a_mix(s, p, phase='x'): # (Validated)
"""
Returns the calculated DWPM mixture parameter at current system state for
the specified phase.
Parameters
----------
s : class
Contains the dictionaries with the state of each component.
p : class
Contains the dictionary describing the mixture parameters.
Holds p.m['n'], p.m['r'] and p.m['s']
phase : string, optional
Phase to be calculated, ex. liquid phase 'x'.
Dependencies
------------
nComp.a_ij
Returns
-------
a_mix : scalar output.
"""
# SUM^n_i x_i * [Sigma^n_j=1 (x_k a_ij^s)^(r/s)]
Sigma2 = 0
for i in range(1, p.m['n']+1):
# SUM^n_j=1 (x_k a_ij^s)
Sigma1 = 0
for j in range(1, p.m['n']+1):
Sigma1 += s.c[j][phase] * a_ij(s, p, i, j)**p.m['s']
# SUM^n_j=1 (x_k a_ij^s)^(r/s)
Sigma1rs = Sigma1**(p.m['r']/p.m['s'])
Sigma2 += s.c[i][phase] * Sigma1rs
# a_mix = (SUM^n_i x_i * [Sigma^n_j=1 (x_k a_ij^s)^(r/s)])^(1/r)
return Sigma2**(1/p.m['r'])
def a_mix_partial_k(s, p, k=1, phase='x'): # (Validated)
"""
Returns a_mix_partial of component k in the specified phase.
Parameters
----------
s : class
Contains the dictionaries with the state of each component.
p : class
Contains the dictionary describing the mixture parameters.
Holds p.m['n'], p.m['r'] and p.m['s']
phase : string, optional
Phase to be calculated, ex. liquid phase 'x'.
Dependencies
------------
nComp.a_ij
Returns
-------
a_mix_partial_k : scalar output.
"""
amix = a_mix(s, p, phase)
Term1 = (1 - 1/p.m['r'] - 1/p.m['s']) * amix
Term2 = 1/p.m['r'] * amix**(1 - 1/p.m['r'])
# CT1 = SUM^n_i=1 x_i * a_ik^s * [SUM^n_j=1 (x_j * a_ij^s)^(r/s - 1)]
Sigma2 = 0
for i in range(1, p.m['n']+1):
# SUM^n_j=1 x_j * a_ij ^ s
Sigma1 = 0
for j in range(1, p.m['n']+1):
Sigma1 += s.c[j][phase] * a_ij(s, p, i, j)**p.m['s']
# SUM^n_j=1 (x_j * a_ij^s)^(r/s - 1)
Sigma1rs = Sigma1**(p.m['r']/p.m['s'] - 1)
# x_i * a_ik^s * [SUM^n_j=1 (x_j * a_ij^s)^(r/s - 1)]
Sigma2 += s.c[i][phase] * (a_ij(s, p, i, k)**p.m['s']) * Sigma1rs
CT1 = (p.m['r']/p.m['s']) * Sigma2
# CT2 = (SUM^n_j=1 (x_j * a_ij^s)^(r/s)
Sigma3 = 0
for j in range(1, p.m['n']+1):
Sigma3 += s.c[j][phase] * a_ij(s, p, k, j)**p.m['s']
CT2 = Sigma3**(p.m['r']/p.m['s'])
return Term1 + Term2 * (CT1 + CT2)
def b_mix(s, p, phase='x'): # (Validated)
"""
Returns the calculated volume mixture parameter at current system state for
the specified phase.
Parameters
----------
s : class
Contains the dictionaries with the state of each component.
p : class
Contains the dictionary describing the parameters.
phase : string, optional
Phase to be calculated, ex. liquid phase 'x'.
Returns
-------
b_mix : scalar output.
"""
b_mix = 0.0
for i in range(1, p.m['n']+1):
b_mix += s.c[i][phase]*s.c[i]['b']
return b_mix
def d_b_mix_d_x(s, p, d=1, z=1, m=1, phase='x'): # (Validated)
"""
Returns the calculated differential of the volume mixture parameter at
current system state for the specified component phase.
Parameters
----------
s : class
Contains the dictionaries with the state of each component.
p : class
Contains the dictionary describing the parameters.
d : int, optional
The differential order. Should be 1 for Jacobian entires and 2 for
Hessian entires.
z : int, optional
The n - 1 independent component number of the first differential.
m : int, optional
The n - 1 independent component number of the second differential.
phase : string, optional
Phase to be calculated, ex. liquid phase 'x'.
Returns
-------
d_b_mix_dx : scalar output.
"""
if d == 1:
return s.c[z]['b'] - s.c[p.m['n']]['b']
# Note s.c[p.m['n']]['b'] refers to the volume parameter of the
# independent component
if d == 2:
return 0.0 # For all x_z
# %% Define Gibbs energy functions for VdW EoS (cubic with 2 volume roots)
def g_R_k_i(s, p, k='x', i=1): # (Validated)
"""
Residual Gibbs energy g_R_k_i((T,P) of a single component where k is the
specified phase and i is the component in phase k.
Parameters
----------
s : class
Contains the dictionaries with the state of the specified component.
p : class
Contains the dictionary describing the component parameters.
k : string, optional
Phase to be calculated, ex. liquid phase 'x'.
i : integer, optional
The component number in phase k to calculate. ex. 1
Dependencies
------------
math
Returns
-------
g_R_k_i : scalar output.
"""
from numpy import log
if k == 'y': # 'y' = Vapour phase standard
V = s.c[i]['V_v']
else: # Assume all phases other than vapour are liquid, ex. 'x'
V = s.c[i]['V_l']
return (s.c[i]['P'] * V / (p.c[i]['R'] * s.c[i]['T']) - 1.0
- log(s.c[i]['P'] / (p.c[i]['R'] * s.c[i]['T']))
- log(V - s.c[i]['b'])
- s.c[i]['a'] / (p.c[i]['R'] * s.c[i]['T'] * V))
def g_R_mix_i(s, p, k='x'): # (Validated)
"""
Residual Gibbs energy g_R_mix_i((T,P) of a mixture where k is the specified
phase.
Parameters
----------
s : class
Contains the dictionaries with the state of the specified component.
p : class
Contains the dictionary describing the component parameters.
k : string, optional
Phase to be calculated, ex. liquid phase 'x'.
Dependencies
------------
math
Returns
-------
g_R_k_i : scalar output.
"""
from numpy import log
if k == 'y': # 'y' = Vapour phase standard
V = s.m['V_v']
else: # Assume all phases other than vapour are liquid, ex. 'x'
V = s.m['V_l']
if V < s.m['b']:
import logging
# V = (1.0 + 100000*(s.m['b'] - V)) * s.m['b']
if V > 0:
V = s.m['b'] + 1e-15/(s.m['b'] - V) #* (1.0 + 1e-30)
if V < 0:
V = s.m['b'] + 1e-15/abs(V)
#logging.warning("V < b_mix in g_R_mix_i, setting to V = {}".format(V))
#logging.warn("V < b_mix in g_R_mix_i, setting to V = {}".format(V))
return (s.m['P'] * V / (p.m['R'] * s.m['T']) - 1.0
- log(s.m['P'] / (p.m['R'] * s.m['T']))
- log(V - s.m['b'])
- s.m['a'] / (p.m['R'] * s.m['T'] * V))
def g_IG_k(s, p, k='x'): # (Validated)
"""
Change in gibbs energy for mixing of ideal gasses.
Parameters
----------
s : class
Contains the dictionaries with the system state information.
k : string, optional
Phase to be calculated, ex. liquid phase 'x'.
Dependencies
------------
math
Returns
-------
g_IG_k : scalar output.
"""
from numpy import log
Sigma_g_IG_k = 0.0 # Sum of ideal gas terms
for i in range(1, p.m['n']+1):
if s.c[i][k] == 0.0: # Prevent math errors from zero log call.
pass # should be = 0 as s2['y']*log(s2['y']) = 1*log(1) = 0
else:
if s.c[i][k] < 0.0:
#TODO: This should never step outside bounds, found out why
# s.c[2][k] is ofter < 0
print('s.c[{}][{}] = {}'.format(i, k, s.c[i][k]))
#s.c[i][k] = abs(s.c[i][k])
Sigma_g_IG_k += s.c[i][k] * log(s.c[i][k])
return Sigma_g_IG_k
def g_mix(s, p, k=None, ref='x', update_system=False): # (Validated)
"""
Returns the gibbs energy at specified composition relative to a reference
phase pure component gibbs energy.
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.
k : string, optional # TODO UNFINISHED
Force phase to be calculated, ex. liquid phase 'x'.
ref : string, optional
Selected reference phase. Note that is common practice to choose a
liquid phase 'x' as the reference phase.
update_system : boolean, optional # TODO UNFINISHED
This updates the system state to the current P, T and
composition conditions. Only use if the system dictionary
has not been updated to the current independent variables.
Dependencies
------------
math
Returns
-------
s : class output.
Contains the following values (or more if more phases are chosen):
s.m['g_mix']['t'] : scalar, Total Gibbs energy of mixing.
s.m['g_mix']['x'] : scalar, Gibbs energy of mixing for liquid phase.
s.m['g_mix']['y'] : scalar, Gibbs energy of mixing for vapour phase.
s.m['g_mix']['ph min'] : string, contains the phase/volume root of
with lowest Gibbs energy.
s.s['Math Error'] : boolean, if True a math error occured during
calculations. All other values set to 0.
"""
import logging
if update_system: # TODO TEST
Xvec = [[]] # Construct update vector
for i in range(1, p.m['n']): # for n-1 independent components
Xvec[0].append(s.c[i][k])
s.update_state(s, p, P = s .m['P'], T = s.m['T'], phase = k,
X = Xvec)
s.update_state(s, p) # Update Volumes and activity coeff.
# try:
Sigma_g_ref = 0.0
for i in range(1, p.m['n'] + 1):
Sigma_g_ref -= s.c[i][ref] * g_R_k_i(s, p, k = ref, i=i)
s.m['g_mix^R'] = {}
for ph in p.m['Valid phases']:
s.m['g_mix^R'][ph] = g_R_mix_i(s, p, k = ph) + Sigma_g_ref
s.m['g_mix'] = {}
g_min = []
g_abs_min = numpy.inf#long # "inf" large int
for ph in p.m['Valid phases']:
s.m['g_mix'][ph] = s.m['g_mix^R'][ph] + g_IG_k(s, p, k=ph)
g_min.append(s.m['g_mix'][ph])
if s.m['g_mix'][ph] < g_abs_min: # Find lowest phase string
s.m['g_mix']['ph min'] = ph
g_abs_min = s.m['g_mix'][ph]
s.m['g_mix']['t'] = min(g_min)
s.s['Math Error'] = False
# except(ValueError, ZeroDivisionError):
# import numpy
# s.m['g_mix'] = {}
# s.s['Math Error'] = True
# logging.error('Math Domain error in g_mix(s,p)')
# for ph in p.m['Valid phases']:
# s.m['g_mix'][ph] = numpy.nan#0.0
#
# s.m['g_mix']['t'] = numpy.nan#0.0
return s
# %% Duality formulation
def ubd(X_D, Z_0, g_x_func, s, p, k=None):
"""
Returns the arguments to be used in the optimisation of the upper bounding
problem with scipy.optimize.linprog.
used
Parameters
----------
X_D : vector (1xn array)
Contains the current composition point in the overall dual
optimisation. Constant for the upper bounding problem.
Z_0 : vector (1xn array)
Feed composition. Constant.
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']
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.
k : list, optional (TODO)
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.
Returns
-------
c : array_like
Coefficients of the linear objective function to be minimized.
A : A_eq : array_like, optional
2-D array which, when matrix-multiplied by x, gives the values of the
upper-bound inequality constraints at x.
b : array_like, optional
1-D array of values representing the upper-bound of each inequality
constraint (row) in.
"""
import numpy
# Coefficients of UBD linear objective function
c = numpy.zeros([p.m['n']]) # linrpog maximize/minimize? D
# Documentation is contradictory across version; check
c[p.m['n'] - 1] = -1.0 # -1.0 change max --> min problem
# Coefficients of Lambda inequality constraints
A = numpy.zeros([len(X_D) + 1, # rows = for all X_D + Global ineq
p.m['n']] # cols = n comps + eta
)
b = numpy.zeros(len(X_D) + 1)
# Global problem bound (Fill last row of A and last element in b
# G_p (Primal problem Z_0_i - x_i = 0 for all i)
# TODO: Move outside function and outside loop in dual
s = s.update_state(s, p, X = Z_0, Force_Update=True)
G_P = g_x_func(s, p).m['g_mix']['t']
A[len(X_D), p.m['n'] - 1] = 1 # set eta to 1
b[len(X_D)] = G_P
# Bounds for all X_d in X_D
A[:, p.m['n'] - 1] = 1 # set all eta coefficients = 1
for X, k in zip(X_D, range(len(X_D))):
# Find G(X_d)
s = s.update_state(s, p, X = X, Force_Update=True)
#TODO: This only needs to be evaluated once for every x \in X^D
G_d = g_x_func(s, p).m['g_mix']['t']
b[k] = G_d
for i in range(p.m['n'] - 1):
A[k, i] = -(Z_0[i] - X_D[k][i])
if False:
print('c shape = {}'.format(numpy.shape(c)))
print('A shape = {}'.format(numpy.shape(A)))
print('b shape = {}'.format(numpy.shape(b)))
print('c = {}'.format(c))
print('A = {}'.format(A))
print('b = {}'.format(b))
return c, A, b
def lbd(X, g_x_func, Lambda_d, Z_0, s, p, k=['All']):
"""
Returns the lower bounding problem of the dual extremum.
Parameters
----------
X : vector (1xn array)
Contains the current composition point in the overall dual
optimisation to be optimised to the minimum value of the lbd.
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']
Lambda_d : vector (1xn array)
Contains the diality multipliers Lambda \in R^m.
Constant for the lower bounding problem.
Z_0 : vector (1xn array)
Feed composition. Constant.
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.
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.
Dependencies
------------
numpy.array
math.e
Returns
-------
lbd : scalar
Value of the lower bounding problem at X.
"""
# Update system to new composition.
s.update_state(s, p, X = X, phase=k, Force_Update=True)
return g_x_func(s, p).m['g_mix']['t'] + sum(Lambda_d * (Z_0 - X))
def dual_equal(s, p, g_x_func, Z_0, k=None, P=None, T=None, tol=1e-9, n=100):
"""
Dev notes and TODO list
-----------------------
TODO: -The material bounds is too high since (Mitsos') \hat{X} is the true
upper limit for a given feedpoint
-Look into using X_bounds scheme of Pereira instead for low mole Z_0
-Add valid phases option.
-Add constraints to x_i =/= 0 or 1 for all i to prevent vertical
hyperplanes.
-Construct bounds which is a list of tuples in [0,1] \in R^n
NOTES: -Strictly the composition in all phases in should be specified in
X_d, refer to older versions of this script when different comp.
spaces need to be used.
-----------------------
Find the phase equilibrium solution using the daul optimization algorithm.
Ref. Mitsos and Barton (2007)
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']
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.
P : scalar, optional
Pressure (Pa), if unspecified the current state pressure will be used.
T : scalar, optional
Temperature (K), if unspecified the current state temperature will be
used.
Z_0 : vector
Contains the feed composition point (must be and unstable point to
find multiphase equilibria).
tol : scalar, optional
Tolerance, if epsilon >= UBD - LBD that will terminate the routine.
n : 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``
Dependencies
------------
numpy
Returns
-------
X_sol : vector
Contains the first optimised equilibrium point of the dual problem
Lambda_sol : vector
Contains the optimised lagrange multipliers (partial chemical
potential) sol. of the dual solution hyperplane
d_res : optimisation object return
Contains the final solution to the dual problem with the
following values:
d_res.fun : lbd plane solution at equil point
d_res.xl : Other local composition solutions from final tgo
d_res.funl : lbd plane at local composition solutions
"""
import numpy
from scipy.optimize import linprog
from tgo import tgo
def x_lim(X): # limiting function used in TGO defining material constraints
import numpy
#return -numpy.sum(X, axis=-1) + 1.0
return -numpy.sum(X, axis=0) + 1.0
if k is None:
k = p.m['Valid phases']
# Initialize
Z_0 = numpy.array(Z_0)
LBD = - 1e300 # -inf
s.update_state(s, p, X = Z_0, phase = k, Force_Update=True)
# G_p (Primal problem Z_0_i - x_i = 0 for all i):
UBD = g_x_func(s, p).m['g_mix']['t']
# X bounds used in UBD optimization
X_bounds = [[], # Upper bound (bar x)
[] # Lower bound (hat x)
]
for i in range(p.m['n']-1):
# Append an independent coordinate point for each bound
X_bounds[0].append(numpy.zeros(shape=(p.m['n']-1)))
X_bounds[1].append(numpy.zeros(shape=(p.m['n']-1)))
# Set upper bound coordinate point i
Sigma_ind = 0.0 # Sum of independent components excluding i
# (lever rule)
for k_ind in range(p.m['n']-1): # Note: k var name is used as phase
# Set k != i (k==i changed at end of loop)
X_bounds[0][i][k_ind] = Z_0[k_ind]
if k_ind != i:
Sigma_ind += Z_0[k_ind] # Test, use numpy.sum if working
# Set Lower bound coordinate point i
X_bounds[1][i][k_ind] = Z_0[k_ind]
# (Remaining bound coordinate points kept at zero)
X_bounds[0][i][i] = 1.0 - Sigma_ind # change from Z_0[k]
# Construct physical bounds x \in [0, 1] for all independent components
Bounds = []
L_bounds = [] # Lambda inf bounds used in linprog.
for i in range(p.m['n'] - 1):
Bounds.append((1e-10, 0.99999999))
L_bounds.append((-numpy.inf, numpy.inf))
L_bounds.append((-numpy.inf, numpy.inf)) # Append extra bound set for eta
# Update state to random X to initialise state class.
X_sol = numpy.array(X_bounds[1][0]) # set X_sol to lower bounds
s.update_state(s, p, X = X_sol , phase = k, Force_Update=True)
X_D = [] # set empty list
# Add every X_bounds to X_D list to use in linprog
for i in range(p.m['n']-1):
X_D.append(X_bounds[0][i])
X_D.append(X_bounds[1][i])
if True: # Lambda estimates using differentials at Z_0
# NOTE on CO2-ethane test this cut the iterations down to 6 from 9
Lambda_d = numpy.zeros_like(Z_0)
s.update_state(s, p, X=Z_0, phase=k, Force_Update=True)
for z in range(1, p.m['n']):
Lambda_d[z - 1] = FD(g_mix, s, p, d=1, z=z, gmix=True)
#print('Lambda_d from init FD est. = {}'.format(Lambda_d))
# Solve LBD for first cutting plane
d_res = tgo(lbd, Bounds, args=(g_x_func, Lambda_d, Z_0, s, p, k),
g_cons=x_lim,
n=n,
#k_t=2,
# n = 100 + 100*(p.m['n'] - 1),
) # skip=2)
X_sol = d_res.x
X_D.append(X_sol)
#print('X_sol from init FD est. = {}'.format(X_sol))
if len(d_res.xl) > 0:
for i in range(len(d_res.xl)):
#print('d_res.xl{}'
# ' from init FD est. = {}'.format(i, d_res.xl[i]))
X_D.append(d_res.xl[i])
# print('X_D at init = {}'.format(X_D))
#%% Normal calculation of daul problem if Z_0 is unstable.
iteration = 0
#X_D.append(numpy.array([ 0.19390632]))
while abs(UBD - LBD) >= tol:
iteration +=1
# Solve UBD
# Find new bounds for linprog
c, A, b = ubd(X_D, Z_0, g_x_func, s, p)
# Find mulitpliers with max problem.
lp_sol = linprog(c, A_ub=A, b_ub=b, bounds=L_bounds)
Lambda_sol = numpy.delete(lp_sol.x, numpy.shape(lp_sol.x)[0] - 1)
# If float convert back to 1x1 array
Lambda_sol = numpy.array(Lambda_sol)
UBD = -lp_sol.fun # Final func value is neg. of minimised max. problem
# dual stepping plots
if 0:
print('Iteration number: {}'.format(iteration))
#print('Lambda_sol: {}'.format(Lambda_sol))
print('X_sol: {}'.format(X_sol))
print('X_D: {}'.format(X_D))
x_r = 1000
# Lagrange function surface
plane_args = (Lambda_sol, Z_0, g_x_func, s, p, ['All'])
plot.plot_ep(dual_lagrange, x_r, s, p, args=plane_args)
# Dual plane
if p.m['n'] == 2: