-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
1882 lines (1570 loc) · 66.3 KB
/
model.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
"""The Model module of ThermoEngine implements a Python interface with the Phase
objective-C classes as well as the infrastructure for pure phase thermodynamic
calibration. The module contains methods that allow for loading and selection of built-in
thermodynamic databases.
"""
from thermoengine import core
from thermoengine import chem
from thermoengine import phases
import thermoengine as thm
from typing import Type, List, Dict
import numpy as np
import pandas as pd
import re
from os import path
from collections import OrderedDict
import warnings
import deprecation
import sys
DATADIR = 'data/databases'
#warnings.filterwarnings('error', category=DeprecationWarning)
warnings.filterwarnings('module', category=DeprecationWarning)
__all__ = ['Database']
def _read_database_file(filename, index_col=None):
# database = self.phase_details['database']
# phase_details = self.phase_details
parentpath = path.dirname(__file__)
pathname = path.join(parentpath, DATADIR, filename)
tableDB = pd.read_csv(pathname, index_col=index_col)
return tableDB, pathname
#===================================================
class Database:
"""
Thermodynamic database model object
Simple access to many competing thermodynamic database models. A wide
variety of published models are available. Models are defined using
low-level code together with list of implemented Pure and Solution phases.
Parameters
----------
database: {'Berman', 'Stixrude', 'HollandAndPowell', 'CoderModule'}
Chosen thermodynamic database (str ID)
liq_mod: {'v1.0', 'v1.1', 'v1.2', 'pMELTS'}
Chosen version of liquid model (str ID)
calib: {True, False}
Access calibration code or code optimized for speed (bool)
phase_tuple: {None}
A tuple that is set if database is 'CoderModule'. The first element is a
string corresponding to the name of the module. The second element is a
dictionary of abbreviations (keys) and a list of [ClassName, PhaseType]
(values) containing phases coded by the module. The abbreviations must
be consistent with the standard list in PurePhasdeList.csv or
SolutionPhaseList.csv. The ClassNames are implementation-specific.
PhaseType is either 'pure' or 'solution'.
Methods
-------
disable_gibbs_energy_reference_state
enable_gibbs_energy_reference_state
get_assemblage
get_phase
get_rxn
redox_buffer
redox_state
Attributes
----------
calib
coder_module
database
liq_mod
phase_info
phase_tuple
phases
Examples
--------
Retrieve a copy of the Berman/MELTS database.
>>> model.Database()
Retrieve a copy of the Stixrude database.
>>> model.Database(database='Stixrude')
Retrieve a copy of the *Berman* database generated by the Coder module in
ThermoEngine that contains the pure (stoichiometric) phase class
*Potassium_Feldspar* with code generation that includes parameter
calibration methods.
>>> modelDB = model.Database(database="CoderModule", calib=True,
phase_tuple=('berman', {'Or':['Potassium_Feldspar','pure']}))
Retrieve a copy of the *Simple_Solution* database generated by the coder
module in ThermoEngine that contains the solution phase class *Feldspar*
with code generation that includes parameter calibration methods.
>>> modelDB = model.Database(database="CoderModule", calib=True,
phase_tuple=('Simple_Solution', {'Fsp':['Feldspar','solution']}))
Notes
-----
The database maintains a single copy of each phase object, which is shared
among all processes. Thus, any changes to phase models (through
calibration, for example) automatically propagate across all uses of the
database.
Deprecated methods
- phase_attributes
- phase_details
- phase_obj
- phase_props
NEEDS UPDATING
- disable_gibbs_energy_reference_state
- enable_gibbs_energy_reference_state
"""
_phases: Dict[str, Type[thm.phases.Phase]]
def __init__(self, database='Berman', liq_mod='v1.0', calib=True,
phase_tuple=None):
# Store database name at top-level for convenience
# load active phase list
# self._init_phase_details()
# self._init_active_phases(liq_mod=liq_mod)
# self._init_phase_attributes()
# Read in allowable phases
fixH2O = True
global_phase_info, global_info_files = phases.get_phase_info()
if phase_tuple and database == 'CoderModule':
coder_module = phase_tuple[0]
phase_dict = phase_tuple[1]
# self.valid_phase_symbols.extend(phase_dict.keys())
else:
coder_module = None
phase_dict = None
self._database = database
self._coder_module = coder_module
self._calib = calib
self._liq_mod = liq_mod
self._phase_tuple = phase_tuple
self._init_active_phase_info(global_info_files, global_phase_info, phase_dict)
self._init_special_phases(fixH2O)
# self._init_database()
self._phase_info = pd.DataFrame(columns=['abbrev', 'phase_name', 'formula',
'phase_type', 'endmember_num'])
for iabbrev, iphs in self._phases.items():
self._add_phase_info(iphs)
pass
def _add_phase_info(self, phase):
phs_info = {
'abbrev': phase.abbrev,
'phase_name': phase.phase_name,
'formula': phase.formula,
'phase_type': phase.phase_type,
'endmember_num': phase.endmember_num
}
self._phase_info = self._phase_info.append(phs_info, ignore_index=True)
def _init_special_phases(self, fixH2O):
self._phases = OrderedDict()
if self._database != 'CoderModule':
self._load_special_phases('solution', fixH2O, self._liq_mod)
self._load_special_phases('pure', fixH2O, self._liq_mod)
def _init_active_phase_info(self, global_info_files, global_phase_info, phase_dict):
database=self._database
active_pure_filename, active_pure_phases = (
self._load_validate_info('PurePhases.csv', database, 'pure',
global_phase_info, global_info_files,
phase_dict=phase_dict)
)
active_soln_filename, active_soln_phases = (
self._load_validate_info('SolutionPhases.csv', database, 'solution',
global_phase_info, global_info_files,
phase_dict=phase_dict)
)
self.valid_phase_symbols = []
self.valid_phase_symbols.extend(active_pure_phases.Abbrev)
self.valid_phase_symbols.extend(active_soln_phases.Abbrev)
self._phase_model_class_info = {}
for indx, phase_info in active_pure_phases.iterrows():
self._phase_model_class_info[phase_info['Abbrev']] = {
'type': 'pure',
'classname': phase_info['ClassName']}
for indx, phase_info in active_soln_phases.iterrows():
self._phase_model_class_info[phase_info['Abbrev']] = {
'type': 'solution',
'classname': phase_info['ClassName']}
def _load_validate_info(self, basename, database, phase_type,
global_phase_info, global_info_files,
phase_dict=None):
# load
phase_info = global_phase_info[phase_type]
if database != 'CoderModule':
filename = database+basename
active_phases, active_filename = _read_database_file(
filename)
elif phase_dict:
data = []
for key,value in phase_dict.items():
if value[1] == phase_type:
data.append([key, value[0], None])
active_phases = pd.DataFrame(data,
columns=['Abbrev', 'ClassName', 'FormulaOveride'])
active_filename = 'CoderModule'
return active_filename, active_phases
else:
print ('If database is set to "CoderModule" then the second ' +
'argument of "phase_tuple" must contain a dictionary of ' +
'phase Abbreviations:ClassNames that are available in the ' +
'module.')
# validate
abbrev_valid = active_phases['Abbrev'].isin(phase_info['Abbrev'])
err_msg = (
'The {phase_type} phase library defined in '
'{filename} contains some invalid phase '
'abbreviations, shown below: \n\n'
'{invalid_phases}\n\n'
'Check that the abbreviations conform to the '
'list given in: "{phase_info_file}"')
invalid_phases = str(active_phases[~abbrev_valid])
phase_info_file = global_info_files[phase_type]
assert abbrev_valid.all(), (
err_msg.format(phase_type=phase_type,
filename=active_filename,
invalid_phases=invalid_phases,
phase_info_file=phase_info_file)
)
return active_filename, active_phases
def _init_database(self):
# Create and store class for each phase
# propsDB = OrderedDict()
for abbrev in self._phase_model_class_info:
info = self._phase_model_class_info[abbrev]
self._phases[abbrev] = self._init_phase_model(abbrev, info['classname'], info['type'])
def _init_phase_model(self, abbrev, classnm, phase_type):
try:
if self._database == 'CoderModule':
phase_ptr = self._init_phase_coder(self._coder_module, classnm,
abbrev, phase_type, calib=(self._calib))
else:
phase_ptr = self._init_phase_obj(classnm + self._database, abbrev,
phase_type, calib=(self._calib))
except:
print('{classnm} is not a valid ClassName for '
'the {database} database.'. \
format(classnm=classnm, database=(self._database)))
return phase_ptr
def _load_special_phases(self, phase_type, fixH2O, liq_mod):
def add_special_phase(abbrev, phase_obj):
self._phases[abbrev] = phase_obj
self.valid_phase_symbols.append(abbrev)
if fixH2O and (phase_type=='pure'):
H2O_classnm = 'GenericH2O'
H2O_phase_obj = self._init_phase_obj(
H2O_classnm, 'H2O', phase_type, calib=False)
add_special_phase('H2O', H2O_phase_obj)
if (liq_mod is not None) and (phase_type=='solution'):
if liq_mod=='v1.0':
liq_classnm = 'LiquidMelts'
elif liq_mod=='v1.1':
liq_classnm = 'LiquidMeltsPlusOldH2OandNewCO2'
elif liq_mod=='v1.2':
liq_classnm = 'LiquidMeltsPlusCO2'
elif liq_mod=='pMELTS':
liq_classnm = 'LiquidpMelts'
else:
assert False, (
'Chosen liq_mod is not valid'
)
liq_phase_obj = self._init_phase_obj(
liq_classnm, 'Liq', phase_type, calib=True)
add_special_phase('Liq', liq_phase_obj)
if (phase_type=='solution'):
alloy_solid_classnm = 'AlloySolid'
alloy_liquid_classnm = 'AlloyLiquid'
MtlS_phase_obj = self._init_phase_obj(
alloy_solid_classnm, 'MtlS', phase_type, calib=False)
MtlL_phase_obj = self._init_phase_obj(
alloy_liquid_classnm, 'MtlL', phase_type, calib=False)
add_special_phase('MtlS', MtlS_phase_obj)
add_special_phase('MtlL', MtlL_phase_obj)
#########################################################
def _init_phase_obj(self, classname, abbrev, phase_type, calib=None):
if phase_type=='pure':
if calib is None:
phase_obj = phases.PurePhase(classname, abbrev)
else:
phase_obj = phases.PurePhase(classname, abbrev, calib=calib)
elif phase_type=='solution':
if calib is None:
phase_obj = phases.SolutionPhase(classname, abbrev)
else:
phase_obj = phases.SolutionPhase(classname, abbrev, calib=calib)
return phase_obj
def _init_phase_coder(self, coder_module, classnm, abbrev, phase_type,
calib=False):
ptr_name = 'cy_' + classnm + '_' + coder_module.split('.')[-1] + '_' + (
'calib_' if calib else '')
if phase_type=='pure':
if calib is None:
phase_ptr = phases.PurePhase(ptr_name, abbrev, source='coder',
coder_module=coder_module)
else:
phase_ptr = phases.PurePhase(ptr_name, abbrev, calib=calib,
source='coder', coder_module=coder_module)
elif phase_type=='solution':
if calib is None:
phase_ptr = phases.SolutionPhase(ptr_name, abbrev,
source='coder', coder_module=coder_module)
else:
phase_ptr = phases.SolutionPhase(ptr_name, abbrev, calib=calib,
source='coder', coder_module=coder_module)
return phase_ptr
@property
def liq_mod(self):
"""
Name of current liquid model
Refers to version of MELTS.
"""
return self._liq_mod
@property
def database(self):
"""
Name of current database
"""
return self._database
@property
def phases(self) -> Dict[str, Type[thm.phases.Phase]]:
"""
Dictionary of phase objects
Phase objects stored under official abbreviation. See phase_info for
information on each phase.
"""
return self._phases
@property
def phase_info(self):
"""
Phase info table for all members of current database
Basic phase information stored in pandas dataframe with columns:
'abbrev' - Official phase abbreviation
'phase_name' - Full phase name
'formula' - Chemical formula (or generic formula for solution phases)
'phase_type' - Solution or pure
'endmember_num' - Number of endmembers (1 for pure phases)
"""
return self._phase_info
@property
def calib(self):
"""
The code base for this phase implements model calibration functions.
Returns
-------
bool
"""
return self._calib
@property
def coder_module(self):
"""
Module name of Coder-generated database
Returns
-------
str
Name of Coder module
"""
return self._coder_module
@property
def phase_tuple(self):
"""
Dictionary of phases in a Coder-generated database
Returns
-------
tuple of strs
(1) str of coder_module
(2) dict of phases coded in the coder_module. *key* is abbreviation.
*value* is a two-component list of phase_name and phase_type;
*phase_type* is either 'pure' or 'solution'.
"""
return self._phase_tuple
@property
@deprecation.deprecated(
deprecated_in="1.0", removed_in="2.0",
details="Use phase_info instead.")
def phase_details(self):
# deprecated_in="1.0", removed_in="2.0",
# current_version=__version__,
# warnings.warn(
# "phase_details is deprecated, use phase_info instead.",
# DeprecationWarning)
pass
@property
@deprecation.deprecated(
deprecated_in="1.0", removed_in="2.0",
details=(
"For basic phase properties, use phase_info instead.\n"
"For detailed phase properties, retrieve them directly "
"from the desired phase object stored in phases." ))
def phase_attributes(self):
# warnings.warn((
# "'phase_attributes' is deprecated.\n"
# "For basic phase properties, use 'phase_info' instead.\n"
# "For detailed phase properties, retrieve them directly "
# "from the desired phase object stored in 'phases'."),
# DeprecationWarning)
pass
@property
@deprecation.deprecated(
deprecated_in="1.0", removed_in="2.0",
details=(
"Direct access to the non-Python phase calculation object is "
"not recommended. Instead, use the Python interface provided by "
"the desired phase stored in phases."))
def phase_obj(self):
# warnings.warn((
# "'phase_obj' is deprecated.\n"
# "Direct access to the non-python phase calculation object is "
# "not recommended. Instead, use the python interface provided by "
# "the desired phase stored in 'phases'."),
# DeprecationWarning)
pass
@property
@deprecation.deprecated(
deprecated_in="1.0", removed_in="2.0",
details=(
"Instead retrieve properties directly "
"from the desired phase object stored in phases."))
def phase_props(self):
# warnings.warn((
# "'phase_props' is deprecated.\n"
# "Instead retrieve properties directly "
# "from the desired phase object stored in 'phases'."),
# DeprecationWarning)
pass
##################
def enable_gibbs_energy_reference_state(self):
"""
Enable Helgeson convention of Gibbs energy.
Use Helgeson (SUPCRT) convention of Gibbs free energy
of formation rather than enthalpy of formation at Tr, Pr.
"""
# call method on any phase class (automatically applied to all)
# next(iter(self.phases.values()))
for phase in self.phases.values():
phase.enable_gibbs_energy_reference_state()
def disable_gibbs_energy_reference_state(self):
"""
Disable Helgeson convention of Gibbs energy.
Use standard enthalpy of formation at Tr, Pr as reference, rather
than Helgeson (SUPCRT) convention of Gibbs free energy of formation.
"""
# call method on any phase class (automatically applied to all)
# next(iter(self.phases.values()))
for phase in self.phases.values():
phase.disable_gibbs_energy_reference_state()
def get_phase_obj(self, phasesym_l):
"""
Get a phase that is coded in Objective-C by symbol.
Parameters
----------
phasesym_l : []
A list of abbreviations of desired phases.
Returns
-------
phase_obj_l
List of phase objects corresponding to desired phases.
"""
phase_details = self.phase_details
phase_obj_l = []
for phasesym in phasesym_l:
try:
# phase_obj_l.append(phase_details['purephase_obj_d'][phasesym])
phase_obj_l.append(phase_details['pure_props'][phasesym]['obj'])
except:
assert False, '"'+phasesym+'" is not a valid phase abbreviation. Try again.'
return phase_obj_l
def get_all_phases(self) -> List[Type[thm.phases.Phase]]:
all_phases = self.valid_phase_symbols
if self._database is not 'Berman':
filtered_phases = [phs for phs in all_phases
if phs not in ['Liq', 'MtlS', 'MtlL','H2O']]
all_phases = filtered_phases
return self.get_phases(all_phases)
def get_phase(self, phase_symbol:str) -> Type[thm.phases.Phase]:
"""
Get phase from current database by symbol.
Parameters
----------
phase_symbol : str
Abbreviation of desired phase. Must use correct ThermoEngine format.
Returns
-------
phase : obj
Phase object corresponding to desired phase.
Notes
-----
The phase object retrieved by this method remains tied to the Database
(i.e., it points to a single copy stored in the Database).
Any changes made to this phase (e.g., through calibration) thus
propagate to the entire Database.
Examples
--------
phase = modelDB.get_phase('Aeg')
sym_list = ['Aeg', 'Ky', 'Sil', 'Qtz']
phase_list = [modelDB.get_phase(sym) for sym in sym_list]
"""
# warn_val = warnings.warn(
# "phase_details is deprecated, use phase_info instead.",
# DeprecationWarning)
self._validate_phase_symbol(phase_symbol)
if phase_symbol not in self.phases:
info = self._phase_model_class_info[phase_symbol]
phs = self._init_phase_model(phase_symbol, info['classname'], info['type'])
self._phases[phase_symbol] = phs
self._add_phase_info(phs)
return self.phases[phase_symbol]
def get_phases(self, phase_symbols:List[str]) -> List[Type[thm.phases.Phase]]:
return [self.get_phase(sym) for sym in phase_symbols]
def _validate_phase_symbol(self, phase_symbol):
if phase_symbol not in self.valid_phase_symbols:
err_msg = (
'"{phase_symbol}" is not a valid '
'phase symbol for this database. '
'Select from the following available '
'phase symbol keys: {allowedsyms}'
)
phase_list = self.valid_phase_symbols
if self.phase_tuple is not None:
phase_list.append((self.phase_tuple[1]).keys())
raise self.InvalidPhaseSymbol(
err_msg.format(
phase_symbol=phase_symbol,
allowedsyms=phase_list)
)
class InvalidPhaseSymbol(Exception):
pass
def warn_test(self):
"""
This method is called when some function is deprecated.
"""
warnings.filterwarnings('error', category=DeprecationWarning)
print('hello')
warnings.warn("Big old warning test", DeprecationWarning)
print(sys.stderr)
print('world')
def get_assemblage(self, phase_symbols):
"""
Get phase assemblage from current database by symbol.
An assemblage represents a set of coexisting phases.
Parameters
----------
phase_symbols : list of strings
List of abbreviations of coexisting phases.
Must use correct ThermoEngine format.
Returns
-------
assemblage : obj
Assemblage object corresponding to coexisting phases.
Examples
--------
sym_list = ['Ky', 'Sil', 'Qtz']
assemblage = modelDB.get_assemblage(sym_list)
"""
phase_objs = []
for phase_symbol in phase_symbols:
phase_obj = self.get_phase(phase_symbol)
phase_objs.append(phase_obj)
assemblage = phases.Assemblage(phase_objs, obj_is_classnm=False)
return assemblage
def get_rxn(self, phase_symbols, endmember_ids, rxn_coefs,
coefs_per_atom=False):
"""
Get an endmember reaction from current database.
A reaction is represented as a stoichiometrically balanced
exchange of atoms between a set of endmember (or pure) phases.
Parameters
----------
phase_symbols : list of strings
List of abbreviations of reacting phases
endmember_ids : list of ints
List of integers representing endmember ID number for each phase
rxn_coefs : array
Array of reaction coefficients. Positive values are products;
negative values are reactants. Coefficients should be
stoichiometrically balanced.
coefs_per_atom : bool, default False
If False, rxn coefficients are defined per formula unit of each
endmember.
If True, coefficients are given on per atom basis. Thus they are
independent of the formula unit definition.
This is useful to avoid mistakes for phases with multiple standard
formula definitions (e.g., En is often given as MgSiO3 OR Mg2Si2O6).
Returns
-------
rxn : obj
rxn object for reacting endmember phases
Examples
--------
phase_symbols = ['Per', 'Qz', 'Cpx']
endmember_ids = [0, 0, 1]
rxn_coefs = [2, 2, 1]
rxn = modelDB.get_rxn(phase_symbols, endmember_ids, rxn_coefs)
# rxn_coefs defined per atom basis
rxn_coefs = [2, 3, 5]
rxn = modelDB.get_rxn(phase_symbols, endmember_ids, rxn_coefs,
coefs_per_atom=True)
"""
assert (
(len(endmember_ids) == len(phase_symbols)) and (len(phase_symbols) == len(rxn_coefs))), 'phase_symbols, endmember_ids, and rxn_coefs must all be equal'
phase_objs = []
for phase_symbol in phase_symbols:
phase_objs.append(self.get_phase(phase_symbol))
# from IPython import embed;embed();import ipdb;ipdb.set_trace()
rxn = phases.Rxn(phase_objs, endmember_ids, rxn_coefs,
coefs_per_atom=coefs_per_atom)
return rxn
def _redox_state_Kress91(self, T, P, oxide_comp, logfO2=None):
"""
Fe redox model of Kress and Carmichael 1991
Calculate ln(Fe2O3/FeO) ratio given lnfO2, T, P, bulk composition.
Alternatively, can predict lnfO2 values given measured ferric & ferrous comp.
Parameters
----------
T : double (array)
temperature in Kelvin
P : double (array)
pressure in bars
oxide_comp : double array (matrix)
molar oxide composition in standard order. Either measured FeO and Fe2O3 are
provided, or total iron reported as FeO (e.g. FeO*)
logfO2 : double (array), default None
If provided, the measured logfO2 value is used to predict the ln(Fe2O3/FeO).
Otherwise, reported FeO and Fe2O3 values are used to predict logfO2.
Returns
-------
output : double (array)
Output depends on whether logfO2 values are provided.
ln_Fe_oxide_ratio : If logfO2 values are given, return log ferric/ferrous ratio of melt.
logfO2 : If not, return predicted logfO2, given measured ferric and ferrous content of melt.
"""
predict_fO2 = False
if logfO2 is None:
predict_fO2 = True
OXIDES = chem.OXIDE_ORDER
# ['SiO2', 'TiO2', 'Al2O3', 'Fe2O3', 'Cr2O3', 'FeO', 'MnO', 'MgO',
# 'NiO', 'CoO', 'CaO', 'Na2O', 'K2O', 'P2O5', 'H2O', 'CO2']
T0 = 1673.15 # K
a = 0.196
b = 1.1492e4 # K
c = -6.675
e = -3.364
f = -7.01e-7 * 1.0e5 # K/bar
g = -1.54e-10 * 1.0e5 # 1/bar
h = 3.85e-17 * 1.0e5 * 1.0e5 # K/bar^2
# dAl2O3 = -2.243
# dFeO = -1.828
# dCaO = 3.201
# dNa2O = 5.854
# dK2O = 6.215
mol_oxides = np.array(oxide_comp.copy())
# from IPython import embed; embed()
XFeO_equiv = mol_oxides[:, OXIDES=='FeO'] + 2*mol_oxides[:, OXIDES=='Fe2O3']
# print(mol_oxides.shape)
# print(XFeO_equiv.shape)
if predict_fO2:
ln_Fe_oxide_ratio = np.squeeze(np.log(mol_oxides[:, OXIDES=='Fe2O3']/mol_oxides[:, OXIDES=='FeO']))
# display(ln_Fe_oxide_ratio)
mol_oxides[:, OXIDES=='FeO'] = XFeO_equiv
mol_oxides[:, OXIDES=='Fe2O3'] = 0.0
if mol_oxides.ndim==2:
mol_oxide_tot = np.sum(mol_oxides, axis=1)
mol_oxides /= mol_oxide_tot[:,np.newaxis]
elif mol_oxides.ndim==1:
mol_oxide_tot = np.sum(mol_oxides)
mol_oxides /= mol_oxide_tot
else:
assert False, 'mol_oxides must be either an array of compositions, or a matrix for many experiments'
d = np.zeros(len(OXIDES))
d[OXIDES=='Al2O3'] = -2.243
d[OXIDES=='FeO'] = -1.828
d[OXIDES=='CaO'] = +3.201
d[OXIDES=='Na2O'] = +5.854
d[OXIDES=='K2O'] = +6.215
atm_terms = b/T + c + e*(1.0-T0/T - np.log(T/T0))
press_terms = f*P/T + g*(T-T0)*P/T+ h*P*P/T
comp_terms = np.dot(mol_oxides, d)
if not predict_fO2:
lnfO2 = logfO2/np.log10(np.exp(1))
ln_Fe_oxide_ratio = a*lnfO2 + atm_terms + press_terms + comp_terms
return ln_Fe_oxide_ratio
else:
# print(ln_Fe_oxide_ratio )
# print((atm_terms + press_terms + comp_terms))
lnfO2 = (ln_Fe_oxide_ratio -
(atm_terms + press_terms + comp_terms))/a
logfO2 = lnfO2*np.log10(np.exp(1))
return logfO2
def redox_state(self, T, P, oxide_comp=None, logfO2=None,
phase_of_interest=None, method=None):
"""
Parameters
----------
T : array-like
Temperature in Kelvin.
P : array-like
Pressure in bars.
oxide_comp : dict of arrays, optional
Molar oxide composition of each phase.
logfO2 : double (array), optional
Base 10 logfO2 values with fO2 in bars
phase_of_interest : {'Liq', 'Spl'}
Abbreviation of redox-sensitive phase used to determine
redox state.
method : {'consistent', 'coexist', 'stoich', 'Kress91'}
'consistent' :
'coexist' :
'stoich' :
'Kress91' :
"""
def not_implemented_error(method, phase_of_interest):
raise NotImplementedError(
'The method "'+method+'" is not implemented ' +
'for phase_of_interest "'+phase_of_interest+'".')
output = None
if phase_of_interest=='Liq':
if method=='Kress91':
if oxide_comp['Liq'].ndim==1:
oxide_comp['Liq'] = oxide_comp['Liq'][np.newaxis, :]
liq_oxide_comp = oxide_comp['Liq']
# print(liq_oxide_comp.shape)
output = self._redox_state_Kress91(
T, P, liq_oxide_comp, logfO2=logfO2)
if logfO2 is None:
logfO2 = output
else:
ln_Fe_oxide_ratio = output
Fe_oxide_ratio = np.exp(ln_Fe_oxide_ratio)
ind_FeO = np.where(chem.OXIDE_ORDER=='FeO')[0][0]
ind_Fe2O3 = np.where(chem.OXIDE_ORDER=='Fe2O3')[0][0]
XFeO = liq_oxide_comp[:, ind_FeO]
XFe2O3 = liq_oxide_comp[:, ind_Fe2O3]
XFeOs = XFeO + 2*XFe2O3
XFeO = XFeOs/(1+2*Fe_oxide_ratio)
XFe2O3 = 0.5*(XFeOs - XFeO)
oxide_comp['Liq'][:, ind_FeO] = XFeO
oxide_comp['Liq'][:, ind_Fe2O3] = XFe2O3
else:
not_implemented_error(method, phase_of_interest)
elif phase_of_interest=='Spl':
not_implemented_error(method, phase_of_interest)
else:
not_implemented_error(method, phase_of_interest)
return output
def redox_buffer(self, T, P, buffer=None, method=None,
ignore_lims=True):
"""
Calculate logfO2 values for common oxygen buffers.
Parameters
----------
T : double (array)
Temperature in Kelvin
P : double (array)
Pressure in bars
buffer : {'IW', 'IM', 'NNO', 'Co+CoO', 'Cu+Cu2O', ('HM'/'MH'),
('MW'/'WM'), 'MMO', 'CCO', ('QFM'/'FMQ'), 'QIF'}
Models of common oxygen fugacity buffer systems with sources.
'IW' : Iron-Wustite [1?,2,3]
'IM' : Iron-Magnetite [1?,3]
'NNO' : Nickel-Nickel Oxide [2,3]
'Co+CoO' : Cobalt-Cobalt Oxide [3]
'Cu+Cu2O' : Copper-Copper Oxide [2]
'HM' or 'MH' : Magnetite-Hematite [1,2,3]
'MW' or 'WM' : Magnetite-Wustite [1?,2,3]
'MMO' : MnO-Mn3O4 [2]
'CCO' : Graphite-CO-CO2 [2]
'QFM' or 'FMQ' : Quartz-Fayalite-Magnetite [1,2,3]
'QIF' : Quartz-Iron-Fayalite [1?,3]
method : {'consistent', 'LEPR', 'Frost1991'}
Method used to calculate redox buffer value. Default depends on
buffer availability (see above), in preference order
{'consistent', 'LEPR', 'Frost1991'}.
[1] 'consistent' : Directly evaluate chemical potentials for each
phase using current thermodynamic database
[2] 'LEPR' : Empirical expressions constructed for LEPR database
(Hirschmann et al. 2008) based on previously published studies
[3] 'Frost91' : Empirical expressions from review article
Frost 1991
Returns
-------
logfO2 : double (array)
Base 10 logfO2 values with fO2 in bars
Publication Sources
-------------------
[1] consistent method based on MELTS thermodynamic database,
incorporating Berman 1988 and ???
[2] M. Hirschmann et al. (2008) Library of Experimental Phase Relations
(LEPR): A database and Web portal for experimental magmatic
phase equilibria data
[3] B. R. Frost (1991) Introduction to oxygen fugacity and
its petrologic importance
"""
BUFFER_OPTS = ['IW', 'IM', 'NNO', 'Co+CoO', 'Cu+Cu2O', 'HM', 'MH',
'MW', 'WM', 'MMO', 'CCO', 'QFM', 'FMQ', 'QIF']
assert buffer in BUFFER_OPTS, (
'Selected buffer ' + buffer + ' is not available. Please select from ' + str(BUFFER_OPTS)
)
def not_implemented_error(method, buffer):
raise NotImplementedError(
'The method "'+method+'" is not implimented ' +
'for the redox buffer "'+buffer+'".')
if buffer=='IW':
method = 'LEPR' if method is None else method
if method=='consistent':
not_implemented_error(method, buffer)
elif method=='LEPR':
logfO2 = self._empirical_redox_buffer(
T, P, A=-28776.8, B=14.057, C=.055, D=-.8853)
elif method=='Frost91':
logfO2 = self._empirical_redox_buffer(
T, P, A=-27489, B=6.702, C=.055, ignore_lims=ignore_lims,
Tlims=np.array([565, 1200])+273.15)
else:
not_implemented_error(method, buffer)
elif buffer=='IM':
method = 'Frost91' if method is None else method
if method=='consistent':
not_implemented_error(method, buffer)
elif method=='LEPR':