-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmcmc.py
More file actions
1760 lines (1631 loc) · 74 KB
/
mcmc.py
File metadata and controls
1760 lines (1631 loc) · 74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import json
import numpy as np
import scipy
import pandas as pd
import matplotlib.pyplot as plt
from copy import copy
from copy import deepcopy
from sympy import *
from random import seed, random, choice
from itertools import product, permutations
from scipy.optimize import curve_fit
# from scipy.misc import comb
from sym_thermo_constraint import sym_thermo_constraint
from simplify_expr import simplify_expr
run_thermo_constraint = False
penalizing_parameters = False
change_complexity = True
run_new_canonical = False
axiom1_weight, axiom2_weight = 10., 5.
complexity_penalty = 1.
parameter_penalty = 1.
# import multiprocessing
# from multiprocessing import Pool
# import time
# import warnings
# warnings.filterwarnings('error')
# seed(1111)
# -----------------------------------------------------------------------------
# The accepted operations (key: operation; value: #offspring)
# -----------------------------------------------------------------------------
# OPS = {
# 'sin': 1,
# 'cos': 1,
# 'tan': 1,
# 'exp': 1,
# 'log': 1,
# 'sinh' : 1,
# 'cosh' : 1,
# 'tanh' : 1,
# 'pow2' : 1,
# 'pow3' : 1,
# 'abs' : 1,
# 'sqrt' : 1,
# 'fac' : 1,
# '-' : 1,
# '+' : 2,
# '*' : 2,
# '/' : 2,
# '**' : 2,
# }
OPS = {
#'pow2' : 1,
#'pow3' : 1,
#'sqrt' : 1,
'-' : 2,
'+' : 2,
'*' : 2,
'/' : 2,
}
# -----------------------------------------------------------------------------
# The Node class
# -----------------------------------------------------------------------------
class Node():
""" The Node class."""
def __init__(self, value, parent=None, offspring=[]):
self.parent = parent
self.offspring = offspring
self.value = value
self.order = len(self.offspring)
return
def pr(self, show_pow=False):
if self.offspring == []:
return '%s' % self.value
elif len(self.offspring) == 2:
return '(%s %s %s)' % (self.offspring[0].pr(show_pow=show_pow),
self.value,
self.offspring[1].pr(show_pow=show_pow))
else:
if show_pow:
return '%s(%s)' % (self.value,
','.join([o.pr(show_pow=show_pow)
for o in self.offspring]))
else:
if self.value == 'pow2':
return '(%s ** 2)' % (
self.offspring[0].pr(show_pow=show_pow)
)
elif self.value == 'pow3':
return '(%s ** 3)' % (
self.offspring[0].pr(show_pow=show_pow)
)
else:
return '%s(%s)' % (
self.value,
','.join([o.pr(show_pow=show_pow)
for o in self.offspring])
)
# -----------------------------------------------------------------------------
# The Tree class
# -----------------------------------------------------------------------------
class Tree():
""" The Tree class."""
# -------------------------------------------------------------------------
def __init__(self, ops=OPS, variables=['x'], parameters=['a'],
prior_par={}, x=None, y=None, BT=1., PT=1.,
max_size=50,
root_value=None, from_string=None):
# The variables and parameters
self.variables = variables
self.parameters = [p if p.startswith('_') and p.endswith('_')
else '_%s_' % p
for p in parameters]
# The root
if root_value == None:
self.root = Node(choice(self.variables+self.parameters),
offspring=[],
parent=None)
else:
self.root = Node(root_value,
offspring=[],
parent=None)
# The possible operations
self.ops = ops
# The possible orders of the operations, move types, and move
# type probabilities
self.op_orders = list(set([0] + [n for n in list(ops.values())]))
self.move_types = [p for p in permutations(self.op_orders, 2)]
# Elementary trees (including leaves), indexed by order
self.ets = dict([(o, []) for o in self.op_orders])
self.ets[0] = [self.root]
# Distinct parameters used
self.dist_par = list(set([n.value for n in self.ets[0]
if n.value in self.parameters]))
self.n_dist_par = len(self.dist_par)
# Nodes of the tree (operations + leaves)
self.nodes = [self.root]
# Tree size and other properties of the model
self.size = 1
self.max_size = max_size
# Space of all possible leaves and elementary trees
# (dict. indexed by order)
self.et_space = self.build_et_space()
# Space of all possible root replacement trees
self.rr_space = self.build_rr_space()
self.num_rr = len(self.rr_space)
# Number of operations of each type
self.nops = dict([[o, 0] for o in ops])
# The parameters of the prior propability (default: 5 everywhere)
if prior_par == {}:
self.prior_par = dict([('Nopi_%s' % t, 10.) for t in self.ops])
#-------- Modification ----------
if change_complexity:
self.prior_par = dict([('Nopi_%s' % t, complexity_penalty) for t in self.ops])
#--------------------------------
else:
self.prior_par = prior_par
# The datasets
if x is None:
self.x = {'d0' : pd.DataFrame()}
self.y = {'d0' : pd.Series(dtype=float)}
elif isinstance(x, pd.DataFrame):
self.x = {'d0' : x}
self.y = {'d0' : y}
elif isinstance(x, dict):
self.x = x
if y is None:
self.y = dict([(ds, pd.Series(dtype=float)) for ds in self.x])
else:
self.y = y
else:
raise TypeError('x must be either a dict or a pandas.DataFrame')
# The values of the model parameters (one set of values for each dataset)
self.par_values = dict([
(ds, deepcopy(dict([(p, 1.) for p in self.parameters])))
for ds in self.x
])
# BIC and prior temperature
self.BT = float(BT)
self.PT = float(PT)
# Build from string
if from_string != None:
self.build_from_string(from_string)
# For fast fitting, we save past successful fits to this formula
self.fit_par = {}
#------------------ Modification ---------------------------------
self.bool_thermo, self.axiom = [], ''
self.tree_error = []
#-----------------------------------------------------------------
# Goodness of fit measures
self.sse = self.get_sse()
self.bic = self.get_bic()
self.E, self.EB, self.EP = self.get_energy()
# To control formula degeneracy (i.e. different trees that
# correspond to the same canonical formula), we store the
# representative tree for each canonical formula
self.representative = {}
self.representative[self.canonical()] = (
str(self), self.E, deepcopy(self.par_values)
)
# Done
return
# -------------------------------------------------------------------------
def __repr__(self):
return self.root.pr()
# -------------------------------------------------------------------------
def pr(self, show_pow=True):
return self.root.pr(show_pow=show_pow)
# -------------------------------------------------------------------------
# NEED TO DOUBLE CHECK THIS METHOD!!!!
def set_par_values(self, par_values):
if set(par_values.keys()) == set(self.x.keys()):
# Parameter sets match the data: simply overwrite
self.par_values = deepcopy(par_values)
elif (set(self.parameters) <= set(par_values.keys()) and
len(list(self.x.keys())) == 1):
# The par_values provided are enough to specify all model
# parameters (self.parameters is a subset of
# par_lavues.keys()) and there is only one dataset: use
# the data to specify the dataset label.
self.par_values = {list(self.x.keys())[0] : deepcopy(par_values)}
else:
raise ValueError('Parameter datasets do not match x/y datasets.')
return
# -------------------------------------------------------------------------
def canonical(self, verbose=False):
"""Return the canonical form of a tree.
"""
if not run_new_canonical:
try:
cansp = sympify(str(self).replace(' ', ''))
can = str(cansp)
ps = list([str(s) for s in cansp.free_symbols])
positions = []
for p in ps:
if p.startswith('_') and p.endswith('_'):
positions.append((can.find(p), p))
positions.sort()
pcount = 1
for pos, p in positions:
can = can.replace(p, 'c%d' % pcount)
pcount += 1
except:
if verbose:
print('WARNING: Could not get canonical form for', \
str(self), '(using full form!)', file=sys.stderr)
can = str(self)
return can.replace(' ', '')
################# Modification ###############################
else:
try:
ex = sympify(str(self))
atomd = dict([(a.name, a) for a in ex.atoms() if a.is_Symbol])
variables = [atomd[v] for v in self.variables if v in list(atomd.keys())]
parameters = [atomd[p] for p in self.parameters if p in list(atomd.keys())]
can = simplify_expr(ex, variables, parameters) # simplify the expression
except:
print('Didn\'t use Canonical form')
print(self)
can = str(self)
return str(can).replace(' ', '')
# -------------------------------------------------------------------------
def latex(self):
return latex(sympify(self.canonical()))
# -------------------------------------------------------------------------
def __parse_recursive(self, string, variables=None, parameters=None,
vpreturn=False):
""" Parse a string obtained from Tree.__repr__() so that it can be used by build_from_string.
"""
if variables == None:
variables = []
if parameters == None:
parameters = []
# Leaf
if '(' not in string:
if string.startswith('_'):
if string not in parameters:
parameters.append(string)
else:
if string not in variables:
variables.append(string)
rval = [string, []]
# Not a leaf: parse the expression
else:
ready = False
while not ready:
nterm, terms, nopenpar, op, opactive = 0, [''], 0, '', True
for c in string:
if opactive and c == '(':
opactive = False
if opactive and c != ' ':
op += c
elif opactive and c == ' ':
opactive = False
nterm += 1
terms.append('')
elif nopenpar == 1 and c == ' ':
opactive = True
elif c == '(':
if nopenpar > 0:
terms[nterm] += c
nopenpar += 1
elif c == ')':
nopenpar -= 1
if nopenpar > 0:
terms[nterm] += c
else:
terms[nterm] += c
if op != '':
ready = True
rval = [op, [self.__parse_recursive(t,
variables=variables,
parameters=parameters)
for t in terms]]
else:
if string[0] == '(' and string[-1] == ')':
string = string[1:-1]
else:
raise
# Done parsing
if vpreturn:
return rval, parameters, variables
else:
return rval
# -------------------------------------------------------------------------
def __grow_tree(self, target, value, offspring):
"""Auxiliary function used to recursively grow a tree from an expression parsed with __parse_recursive().
"""
try:
tmpoff = [self.variables[0] for i in range(len(offspring))]
except IndexError:
tmpoff = [self.parameters[0] for i in range(len(offspring))]
self.et_replace(target, [value, tmpoff], verbose=False)
for i in range(len(offspring)):
self.__grow_tree(target.offspring[i],
offspring[i][0], offspring[i][1])
return
# -------------------------------------------------------------------------
def build_from_string(self, string, verbose=False):
"""Build the tree from an expression formatted according to Tree.__repr__().
"""
tlist, parameters, variables = self.__parse_recursive(string,
vpreturn=True)
self.__init__(ops=self.ops, prior_par=self.prior_par,
x=self.x, y=self.y, BT=self.BT, PT=self.PT,
parameters=parameters, variables=variables)
self.__grow_tree(self.root, tlist[0], tlist[1])
self.get_sse(verbose=verbose)
self.get_bic(verbose=verbose)
self.fit_par = {} # Forget all values fitted so far
return
# -------------------------------------------------------------------------
def build_et_space(self):
"""Build the space of possible elementary trees, which is a dictionary indexed by the order of the elementary tree.
"""
et_space = dict([(o, []) for o in self.op_orders])
et_space[0] = [[x, []] for x in self.variables + self.parameters]
for op, noff in list(self.ops.items()):
for vs in product(et_space[0], repeat=noff):
et_space[noff].append([op, [v[0] for v in vs]])
return et_space
# -------------------------------------------------------------------------
def build_rr_space(self):
"""Build the space of possible trees for the root replacement move.
"""
rr_space = []
for op, noff in list(self.ops.items()):
if noff == 1:
rr_space.append([op, []])
else:
for vs in product(self.et_space[0], repeat=(noff-1)):
rr_space.append([op, [v[0] for v in vs]])
return rr_space
# -------------------------------------------------------------------------
def replace_root(self, rr=None, update_gof=True, verbose=False):
"""Replace the root with a "root replacement" rr (if provided; otherwise choose one at random from self.rr_space). Returns the new root if the move was possible, and None if not (because the replacement would lead to a tree larger than self.max_size."
"""
# If no RR is provided, randomly choose one
if rr == None:
rr = choice(self.rr_space)
# Return None if the replacement is too big
if (self.size + self.ops[rr[0]]) > self.max_size:
return None
# Create the new root and replace exisiting root
newRoot = Node(rr[0], offspring=[], parent=None)
newRoot.order = 1 + len(rr[1])
if newRoot.order != self.ops[rr[0]]:
raise
newRoot.offspring.append(self.root)
self.root.parent = newRoot
self.root = newRoot
self.nops[self.root.value] += 1
self.nodes.append(self.root)
self.size += 1
oldRoot = self.root.offspring[0]
for leaf in rr[1]:
self.root.offspring.append(Node(leaf, offspring=[],
parent=self.root))
self.nodes.append(self.root.offspring[-1])
self.ets[0].append(self.root.offspring[-1])
self.size += 1
# Add new root to elementary trees if necessary (that is, iff
# the old root was a leaf)
if oldRoot.offspring == []:
self.ets[self.root.order].append(self.root)
# Update list of distinct parameters
self.dist_par = list(set([n.value for n in self.ets[0]
if n.value in self.parameters]))
self.n_dist_par = len(self.dist_par)
# Update goodness of fit measures, if necessary
if update_gof == True:
self.sse = self.get_sse(verbose=verbose)
self.bic = self.get_bic(verbose=verbose)
self.E = self.get_energy(verbose=verbose)
return self.root
# -------------------------------------------------------------------------
def is_root_prunable(self):
""" Check if the root is "prunable".
"""
if self.size == 1:
isPrunable = False
elif self.size == 2:
isPrunable = True
else:
isPrunable = True
for o in self.root.offspring[1:]:
if o.offspring != []:
isPrunable = False
break
return isPrunable
# -------------------------------------------------------------------------
def prune_root(self, update_gof=True, verbose=False):
"""Cut the root and its rightmost leaves (provided they are, indeed, leaves), leaving the leftmost branch as the new tree. Returns the pruned root with the same format as the replacement roots in self.rr_space (or None if pruning was impossible).
"""
# Check if the root is "prunable" (and return None if not)
if not self.is_root_prunable():
return None
# Let's do it!
rr = [self.root.value, []]
self.nodes.remove(self.root)
try:
self.ets[len(self.root.offspring)].remove(self.root)
except ValueError:
pass
self.nops[self.root.value] -= 1
self.size -= 1
for o in self.root.offspring[1:]:
rr[1].append(o.value)
self.nodes.remove(o)
self.size -= 1
self.ets[0].remove(o)
self.root = self.root.offspring[0]
self.root.parent = None
# Update list of distinct parameters
self.dist_par = list(set([n.value for n in self.ets[0]
if n.value in self.parameters]))
self.n_dist_par = len(self.dist_par)
# Update goodness of fit measures, if necessary
if update_gof == True:
self.sse = self.get_sse(verbose=verbose)
self.bic = self.get_bic(verbose=verbose)
self.E = self.get_energy(verbose=verbose)
# Done
return rr
# -------------------------------------------------------------------------
def _add_et(self, node, et_order=None, et=None, update_gof=True,
verbose=False):
"""Add an elementary tree replacing the node, which must be a leaf.
"""
if node.offspring != []:
raise
# If no ET is provided, randomly choose one (of the specified
# order if given, or totally at random otherwise)
if et == None:
if et_order != None:
et = choice(self.et_space[et_order])
else:
all_ets = []
for o in [o for o in self.op_orders if o > 0]:
all_ets += self.et_space[o]
et = choice(all_ets)
et_order = len(et[1])
else:
et_order = len(et[1])
# Update the node and its offspring
node.value = et[0]
try:
self.nops[node.value] += 1
except KeyError:
pass
node.offspring = [Node(v, parent=node, offspring=[]) for v in et[1]]
self.ets[et_order].append(node)
try:
self.ets[len(node.parent.offspring)].remove(node.parent)
except ValueError:
pass
except AttributeError:
pass
# Add the offspring to the list of nodes
for n in node.offspring:
self.nodes.append(n)
# Remove the node from the list of leaves and add its offspring
self.ets[0].remove(node)
for o in node.offspring:
self.ets[0].append(o)
self.size += 1
# Update list of distinct parameters
self.dist_par = list(set([n.value for n in self.ets[0]
if n.value in self.parameters]))
self.n_dist_par = len(self.dist_par)
# Update goodness of fit measures, if necessary
if update_gof == True:
self.sse = self.get_sse(verbose=verbose)
self.bic = self.get_bic(verbose=verbose)
self.E = self.get_energy(verbose=verbose)
return node
# -------------------------------------------------------------------------
def _del_et(self, node, leaf=None, update_gof=True, verbose=False):
"""Remove an elementary tree, replacing it by a leaf.
"""
if self.size == 1:
return None
if leaf == None:
leaf = choice(self.et_space[0])[0]
self.nops[node.value] -= 1
node.value = leaf
self.ets[len(node.offspring)].remove(node)
self.ets[0].append(node)
for o in node.offspring:
self.ets[0].remove(o)
self.nodes.remove(o)
self.size -= 1
node.offspring = []
if (node.parent != None):
is_parent_et = True
for o in node.parent.offspring:
if o not in self.ets[0]:
is_parent_et = False
break
if is_parent_et == True:
self.ets[len(node.parent.offspring)].append(node.parent)
# Update list of distinct parameters
self.dist_par = list(set([n.value for n in self.ets[0]
if n.value in self.parameters]))
self.n_dist_par = len(self.dist_par)
# Update goodness of fit measures, if necessary
if update_gof == True:
self.sse = self.get_sse(verbose=verbose)
self.bic = self.get_bic(verbose=verbose)
self.E = self.get_energy(verbose=verbose)
return node
# -------------------------------------------------------------------------
def et_replace(self, target, new, update_gof=True, verbose=False):
"""Replace one ET by another one, both of arbitrary order. target is a
Node and new is a tuple [node_value, [list, of, offspring, values]]
"""
oini, ofin = len(target.offspring), len(new[1])
if oini == 0:
added = self._add_et(target, et=new, update_gof=False,
verbose=verbose)
else:
if ofin == 0:
added = self._del_et(target, leaf=new[0], update_gof=False,
verbose=verbose)
else:
self._del_et(target, update_gof=False, verbose=verbose)
added = self._add_et(target, et=new, update_gof=False,
verbose=verbose)
# Update goodness of fit measures, if necessary
if update_gof == True:
self.sse = self.get_sse(verbose=verbose)
self.bic = self.get_bic(verbose=verbose)
# Done
return added
# -------------------------------------------------------------------------
def get_sse(self, fit=True, verbose=False):
"""Get the sum of squared errors, fitting the expression represented by the Tree to the existing data, if specified (by default, yes).
"""
# Return 0 if there is no data
if list(self.x.values())[0].empty or list(self.y.values())[0].empty:
self.sse = 0
return 0
# Convert the Tree into a SymPy expression
ex = sympify(str(self))
# Convert the expression to a function that can be used by
# curve_fit, i.e. that takes as arguments (x, a0, a1, ..., an)
atomd = dict([(a.name, a) for a in ex.atoms() if a.is_Symbol])
variables = [atomd[v] for v in self.variables if v in list(atomd.keys())]
parameters = [atomd[p] for p in self.parameters if p in list(atomd.keys())]
try:
flam = lambdify(
variables + parameters, ex, [
"numpy",
{'fac' : scipy.special.factorial}
])
except:
self.sse = dict([(ds, np.inf) for ds in self.x])
return self.sse
if fit:
if len(parameters) == 0: # Nothing to fit
for ds in self.x:
for p in self.parameters:
self.par_values[ds][p] = 1.
elif str(self) in self.fit_par: # Recover previously fit parameters
self.par_values = self.fit_par[str(self)]
else: # Do the fit for all datasets
self.fit_par[str(self)] = {}
for ds in self.x:
this_x, this_y = self.x[ds], self.y[ds]
xmat = [this_x[v.name] for v in variables]
def feval(x, *params):
args = [xi for xi in x] + [p for p in params]
return flam(*args)
try:
# Fit the parameters
res = curve_fit(
feval, xmat, this_y,
p0=[self.par_values[ds][p.name]
for p in parameters],
maxfev=10000,
)
# Reassign the values of the parameters
self.par_values[ds] = dict(
[(parameters[i].name, res[0][i])
for i in range(len(res[0]))]
)
for p in self.parameters:
if p not in self.par_values[ds]:
self.par_values[ds][p] = 1.
# Save this fit
self.fit_par[str(self)][ds] = deepcopy(
self.par_values[ds]
)
except:
# Save this (unsuccessful) fit and print warning
self.fit_par[str(self)][ds] = deepcopy(
self.par_values[ds]
)
if verbose:
print('#Cannot_fit:%s # # # # #' % str(self).replace(' ', ''), file=sys.stderr)
# Sum of squared errors
self.sse = {}
for ds in self.x:
this_x, this_y = self.x[ds], self.y[ds]
xmat = [this_x[v.name] for v in variables]
ar = [np.array(xi) for xi in xmat] + \
[self.par_values[ds][p.name] for p in parameters]
try:
se = np.square(this_y - flam(*ar))
if sum(np.isnan(se)) > 0:
raise ValueError
else:
self.sse[ds] = np.sum(se)
except:
if verbose:
print('> Cannot calculate SSE for %s: inf' % self, file=sys.stderr)
self.sse[ds] = np.inf
# Done
return self.sse
# -------------------------------------------------------------------------
def get_bic(self, reset=True, fit=False, verbose=False):
"""Calculate the Bayesian information criterion (BIC) of the current expression, given the data. If reset==False, the value of self.bic will not be updated (by default, it will).
"""
if list(self.x.values())[0].empty or list(self.y.values())[0].empty:
if reset:
self.bic = 0
return 0
# Get the sum of squared errors (fitting, if required)
sse = self.get_sse(fit=fit, verbose=verbose)
# Calculate the BIC
parameters = set([p.value for p in self.ets[0]
if p.value in self.parameters])
k = 1 + len(parameters)
BIC = 0.
for ds in self.y:
n = len(self.y[ds])
BIC += (k - n) * np.log(n) + n * (np.log(2. * np.pi) + log(sse[ds]) + 1)
if reset == True:
self.bic = BIC
return BIC
# -------------------------------------------------------------------------
def get_energy(self, bic=False, reset=False, verbose=False):
"""Calculate the "energy" of a given formula, that is, approximate minus log-posterior of the formula given the data (the approximation coming from the use of the BIC instead of the exactly integrated likelihood).
"""
# Contribtution of the data (recalculating BIC if necessary)
if bic == True:
EB = self.get_bic(reset=reset, verbose=verbose) / 2.
else:
EB = self.bic / 2.
# Contribution from the prior
EP = 0.0
#--------- Modification ---------------------
if run_thermo_constraint:
# Convert the Tree into a SymPy expression
ex = sympify(str(self))
atomd = dict([(a.name, a) for a in ex.atoms() if a.is_Symbol])
variables = [atomd[v] for v in self.variables if v in list(atomd.keys())]
parameters = [atomd[p] for p in self.parameters if p in list(atomd.keys())]
# Checking with thermo constraint (only applicable for 1 variable)
if len(variables) == 1:
try:
self.bool_thermo, self.axiom, tree_error = sym_thermo_constraint(ex, variables[0], parameters)
if tree_error != '':
self.tree_error.append(tree_error)
if self.bool_thermo is False and self.axiom == 'Axiom 1':
EP += axiom1_weight
elif self.bool_thermo is False and self.axiom == 'Axiom 2':
EP += axiom2_weight
else:
EP += 0
except:
EP += 0
else:
self.bool_thermo = False
self.axiom = 'Axiom 1'
EP += axiom1_weight
# ----------------------------------------------------------
for op, nop in list(self.nops.items()):
try:
EP += self.prior_par['Nopi_%s' % op] * nop
except KeyError:
pass
try:
EP += self.prior_par['Nopi2_%s' % op] * nop**2
except KeyError:
pass
# Reset the value, if necessary
if reset:
self.EB = EB
self.EP = EP
self.E = EB + EP
# Done
return EB + EP, EB, EP
# -------------------------------------------------------------------------
def update_representative(self, verbose=False):
"""Check if we've seen this formula before, either in its current form
or in another form.
*If we haven't seen it, save it and return 1.
*If we have seen it and this IS the representative, just return 0.
*If we have seen it and the representative has smaller energy, just return -1.
*If we have seen it and the representative has higher energy, update
the representatitve and return -2.
"""
# Check for canonical representative
canonical = self.canonical(verbose=verbose)
try: # We've seen this canonical before!
rep, rep_energy, rep_par_values = self.representative[canonical]
except KeyError: # Never seen this canonical formula before:
# save it and return 1
self.get_bic(reset=True, fit=True, verbose=verbose)
new_energy = self.get_energy(bic=False, verbose=verbose)
self.representative[canonical] = (str(self), new_energy,
deepcopy(self.par_values))
return 1
# If we've seen this canonical before, check if the
# representative needs to be updated
if rep == str(self): # This IS the representative: return 0
return 0
else:
# CAUTION: CHANGED TO NEVER UPDATE REPRESENTATIVE!!!!!!!!
return -1
# END OF CAUTION ZONE
"""
self.get_bic(reset=True, fit=True, verbose=verbose)
new_energy = self.get_energy(bic=False, verbose=verbose)
if (new_energy - rep_energy) < -1.e-6: # Update
# representative &
# return -2
print >> sys.stdout, 'Updating rep: ||', canonical, '||', rep, '||', str(self), '||', rep_energy, '||', new_energy
print >> sys.stderr, 'Updating rep: ||', canonical, '||', rep, '||', str(self), '||', rep_energy, '||', new_energy
self.representative[canonical] = (str(self),
new_energy,
deepcopy(self.par_values))
return -2
else: # Not the representative: return -1
return -1
"""
# -------------------------------------------------------------------------
def dE_et(self, target, new, verbose=False):
"""Calculate the energy change associated to the replacement of one ET
by another, both of arbitrary order. "target" is a Node() and "new" is
a tuple [node_value, [list, of, offspring, values]].
"""
dEB, dEP = 0.0, 0.0
# Some terms of the acceptance (number of possible move types
# from initial and final configurations), as well as checking
# if the tree is canonically acceptable.
# number of possible move types from initial
nif = sum([int(len(self.ets[oi]) > 0 and
(self.size + of - oi) <= self.max_size)
for oi, of in self.move_types])
# replace
old = [target.value, [o.value for o in target.offspring]]
old_bic, old_sse, old_energy = self.bic, deepcopy(self.sse), self.E
old_par_values = deepcopy(self.par_values)
added = self.et_replace(target, new, update_gof=False, verbose=verbose)
# number of possible move types from final
nfi = sum([int(len(self.ets[oi]) > 0 and
(self.size + of - oi) <= self.max_size)
for oi, of in self.move_types])
# check/update canonical representative
rep_res = self.update_representative(verbose=verbose)
if rep_res == -1:
# this formula is forbidden
self.et_replace(added, old, update_gof=False, verbose=verbose)
self.bic, self.sse, self.E = old_bic, deepcopy(old_sse), old_energy
self.par_values = old_par_values
return np.inf, np.inf, np.inf, deepcopy(self.par_values), nif, nfi
# leave the whole thing as it was before the back & fore
self.et_replace(added, old, update_gof=False, verbose=verbose)
self.bic, self.sse, self.E = old_bic, deepcopy(old_sse), old_energy
self.par_values = old_par_values
# Prior: change due to the numbers of each operation
try:
dEP -= self.prior_par['Nopi_%s' % target.value]
except KeyError:
pass
try:
dEP += self.prior_par['Nopi_%s' % new[0]]
except KeyError:
pass
try:
dEP += (self.prior_par['Nopi2_%s' % target.value] *
((self.nops[target.value] - 1)**2 -
(self.nops[target.value])**2))
except KeyError:
pass
try:
dEP += (self.prior_par['Nopi2_%s' % new[0]] *
((self.nops[new[0]] + 1)**2 -
(self.nops[new[0]])**2))
except KeyError:
pass
# Data
if not list(self.x.values())[0].empty:
bicOld = self.bic
sseOld = deepcopy(self.sse)
par_valuesOld = deepcopy(self.par_values)
old = [target.value, [o.value for o in target.offspring]]
# replace
added = self.et_replace(target, new, update_gof=True,
verbose=verbose)
bicNew = self.bic
par_valuesNew = deepcopy(self.par_values)
# leave the whole thing as it was before the back & fore
self.et_replace(added, old, update_gof=False, verbose=verbose)
self.bic = bicOld
self.sse = deepcopy(sseOld)
self.par_values = par_valuesOld
dEB += (bicNew - bicOld) / 2.
else:
par_valuesNew = deepcopy(self.par_values)
# Done
try:
dEB = float(dEB)
dEP = float(dEP)
dE = dEB + dEP
except:
dEB, dEP, dE = np.inf, np.inf, np.inf
return dE, dEB, dEP, par_valuesNew, nif, nfi
# -------------------------------------------------------------------------
def dE_lr(self, target, new, verbose=False):
"""Calculate the energy change associated to a long-range move (the replacement of the value of a node. "target" is a Node() and "new" is a node_value.
"""
dEB, dEP = 0.0, 0.0
par_valuesNew = deepcopy(self.par_values)
if target.value != new:
# Check if the new tree is canonically acceptable.
old = target.value
old_bic, old_sse, old_energy = self.bic, deepcopy(self.sse), self.E
old_par_values = deepcopy(self.par_values)
target.value = new
try:
self.nops[old] -= 1
self.nops[new] += 1
except KeyError:
pass
# check/update canonical representative
rep_res = self.update_representative(verbose=verbose)
if rep_res == -1:
# this formula is forbidden
target.value = old
try:
self.nops[old] += 1
self.nops[new] -= 1
except KeyError:
pass
self.bic, self.sse, self.E = old_bic, deepcopy(old_sse), old_energy
self.par_values = old_par_values
return np.inf, np.inf, np.inf, None
# leave the whole thing as it was before the back & fore
target.value = old
try:
self.nops[old] += 1
self.nops[new] -= 1
except KeyError:
pass
self.bic, self.sse, self.E = old_bic, deepcopy(old_sse), old_energy
self.par_values = old_par_values
# Prior: change due to the numbers of each operation
try:
dEP -= self.prior_par['Nopi_%s' % target.value]
except KeyError:
pass
try:
dEP += self.prior_par['Nopi_%s' % new]
except KeyError:
pass
try:
dEP += (self.prior_par['Nopi2_%s' % target.value] *
((self.nops[target.value] - 1)**2 -
(self.nops[target.value])**2))
except KeyError:
pass
try:
dEP += (self.prior_par['Nopi2_%s' % new] *
((self.nops[new] + 1)**2 -
(self.nops[new])**2))
except KeyError:
pass
# Data
if not list(self.x.values())[0].empty: