-
Notifications
You must be signed in to change notification settings - Fork 0
/
calibrate.py
2402 lines (1845 loc) · 84.4 KB
/
calibrate.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 phases subpackage implements a Python interface with the Phase
Objective-C classes as well as the infrastructure for pure phase thermodynamic calibration.
"""
from thermoengine import core
from thermoengine import model
from thermoengine import chem
import numpy as np
import scipy as sp
import pandas as pd
from os import path
import re
import copy
from pandas import DataFrame
from collections import OrderedDict
# specialized numerical imports
from scipy import stats, random, interpolate as interp, optimize as optim
import numdifftools as nd
RGAS = 8.3144598
# __all__ = ['Database','Data','ParamModel','RxnModel']
__all__ = ['Database']
#===================================================
class Database:
"""
Calibration database model object.
Parameters
----------
rxn_data: pandas df
experimental data input
modelDB: str
choose thermodynamic model database (e.g., 'Berman' is a valid input)
reaction_library:
TOLsvd: int
Ndraw: int
ortho_scale: int
ratio that dictates level of rxn complexity (orthogonality/simplicity)
TOL: int
complexity of rxns
ignore_kinetics: boolean, default False
contaminant_phases: str list
rxn_trans_typ: ['logisitic']
Tscl_energy: 1.0
Returns
-------
rxn_svd: array of ints
matrix of valid, lineraly independent reactions
TODO
----
- get trusted data?
- priors?
"""
RXN_FACTORS = ['flux', 'seed', 'contaminant']
RXN_SCL_VALUES = [1, 1, 1]
RXN_DEFAULT_VALUES = [1, 1, 0]
PHASE_PARAM_LOOKUP = {'V0': 'V', 'S0': 'S', 'dH0': 'delta H'}
T0 = 300.0
P0 = 1.0
def __init__(self, rxn_data, modelDB=None,reaction_library=None,
ignore_kinetics=False, contaminant_phases=None,
rxn_trans_typ='logistic', TOLsvd=1e-4, Ndraw=10,
ortho_scale=15, TOL=1e-10, phase_priors=None, rxn_priors=None,
ref_energy_phases=None):
if modelDB is None:
modelDB = model.Database()
self._init_rxns(rxn_data, modelDB, reaction_library, Ndraw, TOLsvd, ortho_scale, TOL)
self._init_params(phase_priors, rxn_priors, ref_energy_phases)
self.modelDB = modelDB
self.ignore_kinetics = ignore_kinetics
self.contaminant_phases = contaminant_phases
self.rxn_trans_typ = rxn_trans_typ
def _init_rxns(self, rxn_data, modelDB, reaction_library, Ndraw, TOLsvd, ortho_scale, TOL):
rxn_coefs = None
rxn_eqns = None #Need to revisit this
phases = None
if reaction_library is None:
#endmember_ids = [0,0]
#rxns = [modelDB.get_rxn(irxn_prop['phases'], endmember_ids,
#irxn_prop['coefs'])
#for irxn_prop in rxn_data.rxn_props]
#rxn_eqns = [irxn_prop['eqn'] for irxn_prop in rxn_data.rxn_props]
#phases = []
#for irxn in rxns:
#phases.extend(irxn.phases)
#phases = np.unique(phases)
phase_symbols=chem.get_phase_symbols(rxn_data)
rxn_svd_props = chem.calc_reaction_svd(phase_symbols, TOLsvd=TOLsvd)
rxn_svd = rxn_svd_props['rxn_svd']
Nbasis=len(rxn_svd)
wtcoefs, costs, rxn_coefs_raw, wtcoefs_ortho = chem.get_rxns(rxn_svd, Ndraw=Ndraw, ortho_scale=ortho_scale, Nbasis=Nbasis, TOL=TOL)
rxn_coefs = rxn_coefs_raw.copy()
(np.place(rxn_coefs, abs(rxn_coefs)< 1e-2, 0))
#rxns =
#endmember_ids = np.arange(0,len(rxn_coefs[0]))
phases = phase_symbols
else:
assert False, 'reaction_library is not None, need to implement user defined set of reactions'
self.reaction_library = reaction_library
self.rxn_data = rxn_data
self.rxn_coefs = rxn_coefs
self.rxn_eqns = rxn_eqns
self.rxns = rxns
self.phases = phases
#self.endmember_ids = endmember_ids
#TK
def _init_params(self, phase_priors, rxn_priors,
ref_energy_phases):
self._param_values = []
self._param_names = []
self._param_scales = []
self._set_ref_energy_phases(ref_energy_phases)
self._init_rxn_params()
self._init_phase_params()
N = len(self._param_names)
self._param_values = np.array(self._param_values)
self._param_names = np.array(self._param_names)
self._param_scales = np.array(self._param_scales)
self._free_params = np.tile(False, (N,))
self._set_phase_priors(phase_priors, ref_energy_phases)
self._set_rxn_priors(rxn_priors)
def _set_ref_energy_phases(self, ref_energy_phases):
phases = self.phases
#TK
if phases is None:
print('phases is None')
else:
phase_symbols = np.array(
[iphs.abbrev for iphs in phases])
print('phases is good to go')
#phase_symbols = np.array(
#[iphs.abbrev for iphs in phases])
if ref_energy_phases is None:
ref_energy_phases = [phase_symbols[0]]
else:
assert np.all([ref_phs in phase_symbols
for ref_phs in ref_energy_phases]),(
'The ref_energy_phases provided '
'are not valid.'
)
H0_ref_phases = []
for phase_name in ref_energy_phases:
iref_phase, = phases[phase_symbols==phase_name]
H0_ref_phases.append(iref_phase)
self._ref_energy_phases = H0_ref_phases
def _get_ref_energy(self, phase):
ref_energy_phases = self._ref_energy_phases
assert len(ref_energy_phases)==1, (
'Currently, only a single ref_energy_phase is implimented. Must work to implement composition-dependent enthalpy ref.'
)
ref_phase = ref_energy_phases[0]
H0, = ref_phase.get_param_values(param_names=['delta H'])
return H0
def _set_phase_priors(self, phase_priors, ref_energy_phases):
phases = self.phases
phase_symbols = np.array(
[iphs.abbrev for iphs in phases])
# from IPython import embed; embed(); import ipdb; ipdb.set_trace()
prior_name = []
prior_avg = []
prior_error = []
for ind, iphs in enumerate(phases):
isym = iphs.abbrev
imask = phase_priors['phase']==isym
if np.any(imask):
ipriors = phase_priors[imask]
for iname, iavg, ierror in zip(
ipriors['param_name'],
ipriors['param_value'],
ipriors['param_error']):
if iname=='H0':
iparam_name = 'dH0_P'+str(int(ind))
# Adjust dH0 value here
iavg = iavg
else:
iparam_name = iname+'_P'+str(int(ind))
prior_name.append(iparam_name)
prior_avg.append(iavg)
prior_error.append(ierror)
self._prior_name = np.array(prior_name)
self._prior_avg = np.array(prior_avg)
self._prior_error = np.array(prior_error)
def _set_rxn_priors(self, rxn_priors):
pass
def _append_param(self, param_name, param_value, scale=1):
self._param_names.append(param_name)
self._param_values.append(param_value/scale)
self._param_scales.append(scale)
def _init_rxn_params(self):
rxns = self.rxns
for factor, scl_val in zip(self.RXN_FACTORS,
self.RXN_SCL_VALUES):
param_basename = 'alpha_'+factor+'_R'
self._append_param(param_basename+'*', 0.0)
for ind, irxn in enumerate(rxns):
self._append_param(param_basename+str(ind), 0.0)
def _init_phase_params(self):
T0 = self.T0
P0 = self.P0
def get_set_phase_param(param_name):
if param_name.startswith('dH0_P'):
H0, iphs = self._get_phase_param(param_name, return_phase=True)
H0_ref = self._get_ref_energy(iphs)
# val0 = (H0 - H0_ref)/1e3
val0 = (H0 - H0_ref)
scale = np.abs(val0)
else:
val0 = self._get_phase_param(param_name)
scale = np.abs(val0)
self._append_param(param_name, val0, scale=scale)
for ind, iphs in enumerate(self.phases):
get_set_phase_param('V0_P'+str(ind))
get_set_phase_param('S0_P'+str(ind))
if iphs not in self._ref_energy_phases:
get_set_phase_param('dH0_P'+str(ind))
def _split_param_name(self, param_name):
ind_sep = param_name.rfind('_')
param_typ, phs_key = param_name[0:ind_sep], param_name[ind_sep+1:]
return param_typ, phs_key
def _get_phase_param(self, param_name, return_phase=False):
param_typ, phs_key = self._split_param_name(param_name)
assert phs_key[0]=='P', (
'This parameter must be a phase parameter.'
)
phs_ind = int(phs_key[1:])
iphs = self.phases[phs_ind]
value = iphs.get_param_values(
param_names=self.PHASE_PARAM_LOOKUP[param_typ])[0]
if return_phase:
return value, iphs
else:
return value
def _update_phase_params(self):
phase_param_names = ['delta H', 'V', 'S']
calib_param_basenames = ['dH0_P', 'V0_P', 'S0_P']
def _add_set_params(basename, phase, calib_names, calib_values,
phase_param_names, phase_param_values):
phase_param_lookup = {'V0':'V', 'S0':'S', 'dH0':'delta H'}
mask = [iname.startswith(basename) for iname in calib_names]
if np.any(mask):
val = calib_values[mask]
else:
val = None
if val is not None and basename=='dH0':
H0_ref = self._get_ref_energy(phase)
# H0 = 1e3*(val + H0_ref)
H0 = val + H0_ref
val = H0
if val is not None:
phase_param_values.append(val)
phase_param_names.append(phase_param_lookup[basename])
pass
for ind, iphase in enumerate(self.phases):
icalib_param_names = self.get_param_group(kind='phase', id=ind)
# icalib_param_values = self.param_values(
# param_group=icalib_param_names, scale_params=False)
icalib_param_values = self.param_values(
param_group=icalib_param_names, scale_params=True)
iphase_param_names = []
iphase_param_values = []
_add_set_params('V0', iphase,
icalib_param_names, icalib_param_values,
iphase_param_names, iphase_param_values)
_add_set_params('S0', iphase,
icalib_param_names, icalib_param_values,
iphase_param_names, iphase_param_values)
_add_set_params('dH0', iphase,
icalib_param_names, icalib_param_values,
iphase_param_names, iphase_param_values)
iphase.set_param_values(param_names=iphase_param_names,
param_values=iphase_param_values)
pass
#===========================
def _get_param_group_index(self, param_group):
if param_group is None:
param_group = self.get_param_group(free=True)
else:
param_group = np.array(param_group)
loc = np.zeros(len(param_group), dtype=int)
for ind, name in enumerate(param_group):
iloc, = np.where(self._param_names==name)
loc[ind] = iloc
return loc
def get_param_group(self, kind='all', id=None,
base=None, free=None):
"""
kind: ['all', 'phase', 'rxn']
id: [None, '*', int]
base: [None, str]
free: [None, True, False]
"""
param_names = self._param_names
def _get_param_mask(symbol, id):
base = '.*_'+symbol
if id is None:
mask = np.array(
[re.match(base+'[\*0-9]*', iname) is not None
for iname in param_names])
elif id == '*':
mask = np.array(
[re.match(base+'\*', iname) is not None
for iname in param_names])
else:
mask = np.array(
[re.match(base+str(int(id)), iname) is not None
for iname in param_names])
return mask
if kind == 'all':
mask = np.tile(True, param_names.size)
elif kind == 'phase':
mask = _get_param_mask('P', id)
elif kind == 'rxn':
mask = _get_param_mask('R', id)
else:
assert False, (
'That is not a valid param_group kind.'
)
if free is None:
pass
elif free:
mask = mask & self._free_params
else:
mask = mask & ~self._free_params
if base is not None:
mask = mask & np.array([name.startswith(base)
for name in param_names])
param_group = param_names[mask]
return param_group
def scale_params(self, param_values, param_group=None):
param_scales = self.param_scales(param_group=param_group)
scaled_param_values = param_values*param_scales
return scaled_param_values
def unscale_params(self, scaled_param_values, param_group=None):
param_scales = self.param_scales(param_group=param_group)
param_values = param_values/param_scales
return param_values
def param_names(self, param_group=None):
ind = self._get_param_group_index(param_group)
return self._param_names[ind]
def param_scales(self, param_group=None):
ind = self._get_param_group_index(param_group)
return self._param_scales[ind]
def param_values(self, param_group=None, scale_params=False):
ind = self._get_param_group_index(param_group)
param_values = self._param_values[ind]
if scale_params:
return self.scale_params(param_values, param_group=param_group)
else:
return param_values
def param_errors(self, param_group=None):
ind = self._get_param_group_index(param_group)
return self._param_errors[ind]
def set_param_values(self, param_values, param_group=None):
ind = self._get_param_group_index(param_group)
self._param_values[ind] = param_values
self._update_phase_params()
pass
def add_free_params(self, param_group):
ind = self._get_param_group_index(param_group)
self._free_params[ind] = True
def del_free_params(self, param_group):
ind = self._get_param_group_index(param_group)
self._free_params[ind] = False
pass
#===========================
def rxn_affinity(self):
rxns = self.rxns
rxn_data = self.rxn_data
P = rxn_data.conditions['P']
T = rxn_data.conditions['T']
rxn_id = rxn_data.rxn['rxn_id']
rxn_affinity = np.zeros(len(P))
for ind, (irxn_id, iT, iP) in enumerate(zip(rxn_id, T, P)):
irxn = rxns[irxn_id]
rxn_affinity[ind] = irxn.affinity(iT, iP)
return rxn_affinity
def rxn_affinity_error(self):
rxns = self.rxns
rxn_data = self.rxn_data
P = rxn_data.conditions['P']
T = rxn_data.conditions['T']
P_err = rxn_data.conditions['P_err']
T_err = rxn_data.conditions['T_err']
rxn_id = rxn_data.rxn['rxn_id']
affinity_err = np.zeros(len(P))
# from IPython import embed; embed(); import ipdb; ipdb.set_trace()
for ind, (irxn_id, iT, iP, iTerr, iPerr) in enumerate(zip(rxn_id, T, P, T_err, P_err)):
irxn = rxns[irxn_id]
irxn_vol = irxn.volume(iT, iP)
irxn_entropy = irxn.entropy(iT, iP)
affinity_err[ind] = np.sqrt(
(irxn_vol*iPerr)**2 + (irxn_entropy*iTerr)**2
)
return affinity_err
def rxn_affinity_thresh(self):
rxns = self.rxns
rxn_data = self.rxn_data
P = rxn_data.conditions['P']
T = rxn_data.conditions['T']
P_err = rxn_data.conditions['P_err']
T_err = rxn_data.conditions['T_err']
rxn_id = rxn_data.rxn['rxn_id']
affinity_thresh = np.zeros(len(P))
if self.ignore_kinetics:
return affinity_thresh
# # get universal reaction parameters
# alpha_t_all = param_d['alpha_t_rxn_all']
# alpha_T_all = param_d['alpha_T_rxn_all']
# alpha_H2O_all = param_d['alpha_H2O_rxn_all']
# for ind,(rxn_eqn, rxn_obj) in enumerate(zip(rxn_eqn_l,rxn_l)):
# msk_rxn = dat_d['rxn']==rxn_eqn
# idGrxn_a = rxn_obj.get_rxn_gibbs_energy(dat_d['T'][msk_rxn],
# dat_d['P'][msk_rxn],
# peratom=True )
# # idVrxn_a = rxn_obj.get_rxn_volume(dat_d['T'][msk_rxn],
# # dat_d['P'][msk_rxn],
# # peratom=True )
# # idSrxn_a = rxn_obj.get_rxn_entropy(dat_d['T'][msk_rxn],
# # dat_d['P'][msk_rxn],
# # peratom=True )
# # get reaction-specific parameters
# alpha_0_rxn = param_d['alpha_0_rxn'+str(ind)]
# dalpha_t_rxn = param_d['dalpha_t_rxn'+str(ind)]
# dalpha_T_rxn = param_d['dalpha_T_rxn'+str(ind)]
# dalpha_H2O_rxn = param_d['dalpha_H2O_rxn'+str(ind)]
# logGth_a[msk_rxn] = alpha_0_rxn \
# + (alpha_t_all+dalpha_t_rxn)*dat_d['time'][msk_rxn] \
# + (alpha_T_all+dalpha_T_rxn)*dat_d['T'][msk_rxn] \
# + (alpha_H2O_all+dalpha_H2O_rxn)*dat_d['water'][msk_rxn]
# dGrxn_a[msk_rxn] = idGrxn_a
# # dVrxn_a[msk_rxn] = idVrxn_a
# # dSrxn_a[msk_rxn] = idSrxn_a
# Gth_a = Gthresh_scl*np.exp(logGth_a)
# # sigG_a = np.sqrt((dat_d['Perr']*dVrxn_a)**2+(dat_d['Terr']*dSrxn_a)**2)
# loglk_a = np.zeros(Gth_a.size)
# loglk_a[msk_rxndir] = iloglk_a
# # from IPython import embed; embed(); import ipdb; ipdb.set_trace()
# for ind, (irxn_id, iT, iP, iTerr, iPerr) in enumerate(zip(rxn_id, T, P, T_err, P_err)):
# irxn = rxns[irxn_id]
# irxn_vol = irxn.volume(iT, iP)
# irxn_entropy = irxn.entropy(iT, iP)
# affinity_err[ind] = np.sqrt(
# (irxn_vol*iPerr)**2 + (irxn_entropy*iTerr)**2
# )
return affinity_thresh
def eval_model_costfun(self, param_values, param_group=None,
full_output=False, kind='logistic'):
N = len(param_values)
# log_prior = -0.5*((param_values-np.array([29,-125, -3.5]))/10)**2
# log_prior = -0.5*((param_values-np.array([5.147, 4.412, 4.983]))/0.1)**2
# log_prior = -0.5*((param_values-np.array([1,1,1]))/0.02)**2
prior = np.sign(param_values)*np.ones(param_values.shape)
log_prior = -0.5*((param_values-prior)/0.02)**2
# param_values = 5*np.exp(param_values*1e-3)
self.set_param_values(param_values, param_group=param_group)
# What about trust values?
affinity = self.rxn_affinity()
affinity_err = self.rxn_affinity_error()
affinity_thresh = self.rxn_affinity_thresh()
rxn_dir = self.rxn_data.rxn['rxn_dir']
log_like = Stats.logprob_rxn_dir(rxn_dir, affinity, affinity_err,
affinity_thresh, kind=kind)
# log_prior = -0.5*((param_values-np.array([29,-125, -3.5]))/1)**2
log_like_tot = np.sum(log_like)
log_prior_tot = np.sum(log_prior)
# log_prior = self.eval_log_prior()
cost_val = np.hstack((-log_like, -log_prior))
cost_tot = - log_like_tot - log_prior_tot
if full_output:
output = OrderedDict()
output['cost_tot'] = cost_tot
output['cost_val'] = cost_val
output['log_like'] = log_like
output['log_prior'] = log_prior
output['log_prior_tot'] = log_prior_tot
output['log_like_tot'] = log_like_tot
output['affinity'] = affinity
output['affinity_err'] = affinity_err
output['affinity_thresh'] = affinity_thresh
return output
else:
return cost_tot
def fit_model(self, param_group=None, full_output=False,
kind='logistic', method='Nelder-Mead'):
# Extract only trustworthy data
# self._dat_trust_d = self.extract_trust_data()
params0 = self.param_values(param_group=param_group)
# params0 = np.log(params0/5)/1e-3
model_cost0 = self.eval_model_costfun(
params0, param_group=param_group,
kind=kind, full_output=True)
# print(params0)
# print(model_cost0)
# param0_unscale_a = self.get_param_values(free_params)
# param0_a = self.unscale_params(param0_unscale_a, free_params)
# param0_tbl = self.get_param_table(param_nm_a=free_params)
# Precalculate approx Gibbs energy uncertainties
# sigG_trust_a = self.propagate_data_errors(param0_unscale_a,
# free_params=free_params)
# self._sigG_trust_a = sigG_trust_a
# costfun = lambda params: self.eval_model_costfun_scl(
# params0, free_params=free_params)
# lnprob_f = lambda param_a: -costfun(param_a)
costfun = lambda params: self.eval_model_costfun(
params, param_group=param_group, kind=kind, full_output=False)
method = 'Nelder-Mead'
# method = 'BFGS'
result = optim.minimize(costfun, params0, method=method,
options={'disp':True, 'maxiter':1e4})
# set best-fit value
self.set_param_values(result.x, param_group=param_group)
return result
# def shift_one_param(shift,ind,mu_a=result.x,costfun=costfun):
# param_a = np.copy(mu_a)
# param_a[ind] += shift
# return costfun(param_a)
# # Create re-scaled-shifted function for hessian
# mu_a = result.x
# cost0 = costfun(mu_a)
# delx_param_scl = np.zeros(mu_a.shape)
# dcost_target=1
# for ind,param in enumerate(mu_a):
# del0 = 1e-2
# idelcostfun = lambda dx, ind=ind,target=dcost_target: \
# shift_one_param(dx,ind)-cost0-dcost_target
# delx = optim.fsolve(idelcostfun,del0)
# delx_param_scl[ind] = np.abs(delx)
# norm_costfun = lambda dx_a, shift_scl=delx_param_scl,\
# mu_a=mu_a,costfun=costfun: costfun(dx_a*shift_scl+mu_a)
# curv_scl_a = delx_param_scl*self.get_param_scl_values(free_params)
# scl_mat_a = core.make_scale_matrix(curv_scl_a)
# Hnorm_fun = nd.Hessian(norm_costfun,step = 1e-2)
# Hnorm_a = Hnorm_fun(np.zeros(mu_a.shape))
# covnorm_a = np.linalg.pinv(Hnorm_a)
# cov_a = covnorm_a*scl_mat_a
# try:
# err_a = np.sqrt(np.diag(cov_a))
# # print(cov_a)
# err_scl_a = core.make_scale_matrix(err_a)
# corr_a = cov_a/err_scl_a
# except:
# err_a = None
# corr_a = None
# # MCMC
# # ndim = len(free_params)
# # nwalkers = 10*ndim
# # walker_pos0_a = [result['x'] + 1e-4*np.random.randn(ndim)
# # for i in range(nwalkers)]
# # sampler = emcee.EnsembleSampler(nwalkers, ndim,lnprob_f)
# # sampler.run_mcmc(walker_pos0_a,10)
# # from IPython import embed; embed(); import ipdb; ipdb.set_trace()
# paramf_unscale_a = self.scale_params(result.x, free_params)
# self.set_param_values(paramf_unscale_a,free_params)
# self._fit_result_d = result
# if full_output:
# output_d = {}
# output_d['err_a'] = err_a
# output_d['corr_a'] = corr_a
# self._mu_a = paramf_unscale_a
# self._err_a = err_a
# self._corr_a = corr_a
# for key in self._param_error_d:
# self._param_error_d[key] = np.nan
# for key,err_val in zip(free_params,err_a):
# self._param_error_d[key] = err_val
# model_cost_d = self.eval_model_costfun(paramf_unscale_a,
# free_params=free_params,
# full_output=True)
# param_tbl = self.get_param_table(param_nm_a=free_params)
# param_all_tbl = self.get_param_table(typ='all')
# output_d['free_params'] = free_params
# output_d['costval0'] = model_cost0_d['cost_val']
# output_d['costdata0_df'] = model_cost0_d['cost_data_df']
# output_d['param0_tbl'] = param0_tbl
# output_d['costval'] = model_cost_d['cost_val']
# output_d['costdata_df'] = model_cost_d['cost_data_df']
# output_d['prior_df'] = model_cost_d['prior_df']
# output_d['param_tbl'] = param_tbl
# output_d['param_all_tbl'] = param_all_tbl
# output_d['result'] = result
# # output_d['param_d'] = copy.copy(self._param_d)
# # output_d['param0_a'] = param0_a
# # output_d['paramf_a'] = result.x
# # output_d['param0_unscl_a'] = param0_unscale_a
# # output_d['paramf_unscl_a'] = paramf_unscale_a
# return output_d
pass
#===================================================
class Stats:
@classmethod
def logprior_fun(cls, x, kind='studentt', dof=5):
if kind == 'studentt':
# Variance of student's t distribution is slightly larger than a
# normal (depending on dof). Thus the relative residual x must be
# scaled down to match the desired standard deviation.
const = np.sqrt(1.0*dof/(dof-2))
log_prob = stats.t.logpdf(x/const,dof)
elif (kind == 'normal') | (kind == 'erf'):
log_prob = stats.norm.log_pdf(x)
return log_prob
@classmethod
def rxn_trans_fun(self, x, kind='logistic'):
if kind == 'logistic':
const = 1.8138 # pi/sqrt(3)
# F_a = 1.0/(1+np.exp(-const*x))
# Special optimized version of logistic function
prob = sp.special.expit(const*x)
elif (kind == 'normal') | (kind == 'erf'):
const = 0.70711 # 1/sqrt(2)
prob = 0.5*(1+sp.special.erf(const*x))
return prob
@classmethod
def rxn_logtrans_fun(cls, x, kind='logistic'):
if kind == 'logistic':
const = 1.8138 # pi/sqrt(3)
# Special optimized version of logistic function
log_prob = -np.logaddexp(0,-const*x)
elif (kind == 'normal') | (kind == 'erf'):
const = 0.70711 # 1/sqrt(2)
# Special optimized version of log-cdf for normal distribution
log_prob = sp.special.log_ndtr(x)
return log_prob
@classmethod
def logprob_rxn_dir(cls, rxn_dir, affinity, affinity_err, affinity_thresh,
kind='logistic'):
"""
rxndir = ['FWD', 'REV', 'NC', 'FWD?', 'REV?', 'NC?']
"""
shp = affinity.shape
x_fwd = (affinity-affinity_thresh)/affinity_err
x_rev = -(affinity+affinity_thresh)/affinity_err
ones = np.ones(shp)
zeros = np.zeros(shp)
log_prob = np.zeros(shp)
log_prob[rxn_dir=='FWD'] = cls.rxn_logtrans_fun(
x_fwd[rxn_dir=='FWD'], kind=kind)
log_prob[rxn_dir=='REV'] = cls.rxn_logtrans_fun(
x_rev[rxn_dir=='REV'], kind=kind)
log_prob[rxn_dir=='BIASED'] = 0.0
log_prob[rxn_dir=='FWD?'] = sp.special.logsumexp(
np.vstack((
cls.rxn_logtrans_fun(x_rev[rxn_dir=='FWD?'], kind=kind),
zeros[rxn_dir=='FWD?'])), axis=0,
b=np.vstack((-ones[rxn_dir=='FWD?'], +ones[rxn_dir=='FWD?'])))
log_prob[rxn_dir=='REV?'] = sp.special.logsumexp(
np.vstack((
cls.rxn_logtrans_fun(x_fwd[rxn_dir=='REV?'], kind=kind),
zeros[rxn_dir=='REV?'])), axis=0,
b=np.vstack((-ones[rxn_dir=='REV?'], +ones[rxn_dir=='REV?'])))
log_prob[rxn_dir=='NC'] = sp.special.logsumexp(
np.vstack((
cls.rxn_logtrans_fun(x_fwd[rxn_dir=='REV?'], kind=kind),
cls.rxn_logtrans_fun(x_rev[rxn_dir=='REV?'], kind=kind),
zeros[rxn_dir=='REV?'])), axis=0,
b=np.vstack((-ones[rxn_dir=='REV?'], -ones[rxn_dir=='REV?'], +ones[rxn_dir=='REV?'])))
log_prob[np.isnan(log_prob)] = -np.inf
# from IPython import embed; embed(); import ipdb; ipdb.set_trace()
return log_prob
#===================================================
class Database_OLD:
def __init__(self, rxn_data, thermoDB=None, ignore_kinetics=False,
contaminant_phases=None, rxn_trans_typ='logistic',
Tscl_energy=1.0):
if thermoDB is None:
thermoDB = model.Database()
self.rxn_data = rxn_data
self.thermoDB = thermoDB
self.ignore_kinetics = ignore_kinetics
self.contaminant_phases = contaminant_phases
self.rxn_trans_typ = rxn_trans_typ
# self.datadir = DATADIR
self.Escl = 3.0/2*RGAS*Tscl_energy
# self.Gthresh_scl = 3.0/2*Rgas*Tthresh_scl
# self.Gthresh_scl = self.Escl
# dat_df, rxn_d_l, phasesym_l = self.filter_phase_rev_data(
# raw_df, mask_phs_l=mask_phs_l)
# self._dat_trust_d = self.extract_trust_data()
# self.load_exp_prior_data()
self._param_d = {}
self.init_model_phases(phasesym_l)
self.init_model_rxns(rxn_d_l)
self.init_exp_priors()
self.init_param_scl()
param_error_d = self._param_d.copy()
for key in param_error_d:
param_error_d[key] = np.nan
self._param_error_d = param_error_d
param_name_a = np.array(list(self._param_d.keys()))
self._free_param_a = param_name_a
self.load_exp_prior_data()
# sigG_trust_a = self.propagate_data_errors(param0_unscale_a)
# self._sigG_trust_a = sigG_trust_a
self._sigG_trust_a = None
def load_exp_prior_data( self ):
datadir = self.datadir
filenm = 'ExpPriorData.xlsx'
parentpath = path.dirname(__file__)
pathnm = path.join(parentpath,datadir,filenm)
exp_prior_data_df = pd.read_excel(pathnm,sheetname=None)
# Cycle through sheets, each representing a different parameter
all_prior_df = pd.DataFrame()
for paramnm in exp_prior_data_df:
if (paramnm[0]=='<') & (paramnm[-1]=='>'):
# This sheet provides metadata (such as references) rather than
# actual priors
continue
data_df = exp_prior_data_df[paramnm]
param_s = pd.Series(np.tile(paramnm,data_df.shape[0]))
data_df['Param'] = param_s
prior_data_df = data_df[['Phase','Abbrev','Param','Trust',
'Data','Error','Ref']]
all_prior_df = all_prior_df.append(prior_data_df)
# phssym_a = data_df['Abbrev']
# val_a = data_df['Data']
# err_a = data_df['Error']
# trust_a = data_df['Trust']
# refID_a = data_df['RefID']
# for sym in phssym_a:
# prior_d = {'refID':refID_a,'phase_sym':phssym_a,'value':val_a,
# 'error':err_a,'trust':trust_a}
self.all_prior_df = all_prior_df
pass
def init_exp_priors(self):
all_prior_df = self.all_prior_df
exp_prior_df = pd.DataFrame()
for ind,phs in enumerate(self.phs_key):
prior_dat_phs_df = all_prior_df[all_prior_df['Abbrev'] == phs].copy()
param_name_s = pd.Series(prior_dat_phs_df['Param']+str(ind))
prior_dat_phs_df['Param'] = param_name_s
exp_prior_df = exp_prior_df.append(prior_dat_phs_df,ignore_index=True)
# print(prior_dat_phs_df)
self.exp_prior_df = exp_prior_df
pass
def init_param_scl(self):
param_name_a = np.array(list(self._param_d.keys()))
# Define the scale for each type of parameter
S0_param_keys_a = np.sort(param_name_a[np.char.startswith(param_name_a,'S0_phs')])
V0_param_keys_a = np.sort(param_name_a[np.char.startswith(param_name_a,'V0_phs')])
dH0_param_keys_a = np.sort(param_name_a[np.char.startswith(param_name_a,'dH0_phs')])
S0_scl_atom = np.mean(self.get_param_values(S0_param_keys_a)/self.Natom_a)
V0_scl_atom = np.mean(self.get_param_values(V0_param_keys_a)/self.Natom_a)
# dH0_a = self.get_param_values(dH0_param_keys_a)/self.Natom_a
# dH0_scl_atom = 3./2*Rgas*1e1
dH0_scl_atom = self.Escl
# alpha_T_scl = 1.0/1000 # 1/K
alpha_T_scl = 1.0/1.0 # 1/K
alpha_t_scl = 1.0
alpha_H2O_scl = 1.0
alpha_0_scl = 1.0
param_scl_d = {}
for ind,phs in enumerate(self.phase_l):
Natom=phs.props_d['Natom']
param_scl_d['S0_phs'+str(ind)] = S0_scl_atom*Natom
param_scl_d['V0_phs'+str(ind)] = V0_scl_atom*Natom
param_scl_d['dH0_phs'+str(ind)] = dH0_scl_atom*Natom
param_scl_d['alpha_t_rxn_all'] =alpha_t_scl
param_scl_d['alpha_T_rxn_all'] =alpha_T_scl
param_scl_d['alpha_H2O_rxn_all'] =alpha_H2O_scl
# logGth_rxn = log(3/2*Rgas*1) + alpha_i*X_i
rxn_l = self.rxn_l
for ind,rxn in enumerate(rxn_l):
# self._param_d['logGth0_rxn'+str(ind)] = -
param_scl_d['alpha_0_rxn'+str(ind)] = alpha_0_scl
param_scl_d['dalpha_t_rxn'+str(ind)] = alpha_t_scl
param_scl_d['dalpha_T_rxn'+str(ind)] = alpha_T_scl
param_scl_d['dalpha_H2O_rxn'+str(ind)] = alpha_H2O_scl