lfit-python 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- lfit_python/__init__.py +27 -0
- lfit_python/chains.py +157 -0
- lfit_python/cli/__init__.py +1 -0
- lfit_python/cli/limbdark.py +64 -0
- lfit_python/cli/mcmcfit.py +168 -0
- lfit_python/cli/physparams.py +154 -0
- lfit_python/cli/reddening.py +50 -0
- lfit_python/cli/summary.py +78 -0
- lfit_python/cli/update_input.py +65 -0
- lfit_python/cli/watch.py +39 -0
- lfit_python/cli/wdparams.py +223 -0
- lfit_python/cv_model.py +864 -0
- lfit_python/data/Bergeron/README +7 -0
- lfit_python/data/Bergeron/Table_DA +257 -0
- lfit_python/data/Bergeron/Table_DA_sdss +307 -0
- lfit_python/data/Bergeron/Table_DB +312 -0
- lfit_python/data/Bergeron/color_correction_tables/color_corrections_HCAM-GTC-super_minus_ntt_ucam.csv +1067 -0
- lfit_python/data/Bergeron/color_correction_tables/color_corrections_HCAM-GTC-super_minus_tnt_uspec.csv +1067 -0
- lfit_python/data/Gianninas13/ld_coeffs_g.txt +654 -0
- lfit_python/data/Gianninas13/ld_coeffs_i.txt +654 -0
- lfit_python/data/Gianninas13/ld_coeffs_r.txt +654 -0
- lfit_python/data/Gianninas13/ld_coeffs_u.txt +654 -0
- lfit_python/data/Gianninas13/ld_coeffs_z.txt +654 -0
- lfit_python/data/Gianninas13/radial_bright_profiles.txt +6925 -0
- lfit_python/data/Hamada/mr_hamada.dat +1307 -0
- lfit_python/data/Panei/12C-MR-H-He/12C-MR-H-He.dat +387 -0
- lfit_python/data/Panei/12C-MR-H-He/12C-MR-H-He.saver +750 -0
- lfit_python/data/Panei/12C-MR-He/12C-MR-He.dat +431 -0
- lfit_python/data/Panei/HS/04He-H-S.dat +158 -0
- lfit_python/data/Panei/HS/12C-H-S.dat +158 -0
- lfit_python/data/Panei/HS/16O-H-S.dat +158 -0
- lfit_python/data/Panei/HS/28Si-H-S.dat +158 -0
- lfit_python/data/Panei/HS/56Fe-H-S.dat +158 -0
- lfit_python/data/Panei/othercores/04He-MR-H.dat +91 -0
- lfit_python/data/Panei/othercores/16O-MR-H-He.dat +602 -0
- lfit_python/data/Panei/othercores/28Si-MR-H-He.dat +386 -0
- lfit_python/data/Panei/othercores/56Fe-MR-H-He.dat +390 -0
- lfit_python/data/Panei/othercores/old/04He-MR-H.save +120 -0
- lfit_python/data/Panei/othercores/old/04He-MR.save +130 -0
- lfit_python/data/Panei/othercores/old/16O-MR-H-He.save +602 -0
- lfit_python/data/Panei/othercores/old/16O-MR-He.save +469 -0
- lfit_python/data/Panei/othercores/old/28Si-MR-H-He.save +386 -0
- lfit_python/data/Panei/othercores/old/28Si-MR-He.save +402 -0
- lfit_python/data/Panei/othercores/old/56Fe-MR-H-He.save +633 -0
- lfit_python/data/Panei/othercores/old/56Fe-MR-He.save +537 -0
- lfit_python/data/Wood95/co040.2.04dt1 +80 -0
- lfit_python/data/Wood95/co050.2.04dt1 +82 -0
- lfit_python/data/Wood95/co060.2.04dt1 +85 -0
- lfit_python/data/Wood95/co070.2.04dt1 +91 -0
- lfit_python/data/Wood95/co080.2.04dt1 +100 -0
- lfit_python/data/Wood95/co090.2.04dt1 +99 -0
- lfit_python/data/Wood95/co100.2.04dt1 +100 -0
- lfit_python/data/althaus/readme.tex +12 -0
- lfit_python/data/althaus/t106.one +1132 -0
- lfit_python/data/althaus/t108.one +679 -0
- lfit_python/data/althaus/t110.one +821 -0
- lfit_python/data/althaus/t112.one +239 -0
- lfit_python/data/althaus/t114.one +355 -0
- lfit_python/data/althaus/t116.one +353 -0
- lfit_python/data/althaus/t118.one +356 -0
- lfit_python/data/althaus/t120.one +882 -0
- lfit_python/data/althaus/t122.one +901 -0
- lfit_python/data/althaus/t124.one +913 -0
- lfit_python/data/althaus/t126.one +739 -0
- lfit_python/data/althaus/t128.one +665 -0
- lfit_python/data/althaus/t130.one +626 -0
- lfit_python/likelihood.py +26 -0
- lfit_python/limbdark.py +47 -0
- lfit_python/model.py +801 -0
- lfit_python/physical_params.py +279 -0
- lfit_python/plotting.py +364 -0
- lfit_python/priors.py +51 -0
- lfit_python/sampling.py +472 -0
- lfit_python/summary.py +327 -0
- lfit_python/watch_app.py +1001 -0
- lfit_python/wdparams.py +587 -0
- lfit_python-0.1.0.dist-info/METADATA +222 -0
- lfit_python-0.1.0.dist-info/RECORD +81 -0
- lfit_python-0.1.0.dist-info/WHEEL +5 -0
- lfit_python-0.1.0.dist-info/entry_points.txt +9 -0
- lfit_python-0.1.0.dist-info/top_level.txt +1 -0
lfit_python/model.py
ADDED
|
@@ -0,0 +1,801 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Base classes for the MCMC fitting routine. Allows the creation of a
|
|
3
|
+
hierarchical model structure, that can also track the prior knowledge of the
|
|
4
|
+
parameters of that model.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import inspect
|
|
8
|
+
import os
|
|
9
|
+
|
|
10
|
+
import networkx as nx
|
|
11
|
+
import numpy as np
|
|
12
|
+
import scipy.stats as stats
|
|
13
|
+
|
|
14
|
+
TINY = -np.inf
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def extract_par_and_key(key):
|
|
18
|
+
"""As stated. For example,
|
|
19
|
+
extract_par_and_key("wdFlux_long_complex_key_label)
|
|
20
|
+
>>> ("wdFlux", "long_complex_key_label")
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
if key.startswith("ln_"):
|
|
24
|
+
key = key.split("_")
|
|
25
|
+
|
|
26
|
+
par = "_".join(key[:3])
|
|
27
|
+
label = "_".join(key[3:])
|
|
28
|
+
elif key == "tau_gp_core":
|
|
29
|
+
par, label = "tau_gp", "core"
|
|
30
|
+
else:
|
|
31
|
+
par, label = key.split("_")[0], "_".join(key.split("_")[1:])
|
|
32
|
+
|
|
33
|
+
return par, label
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def scipy_dist(dist_string, val1, val2):
|
|
37
|
+
val1 = float(val1)
|
|
38
|
+
val2 = float(val2)
|
|
39
|
+
if dist_string == "uniform":
|
|
40
|
+
return stats.uniform(loc=val1, scale=val2 - val1)
|
|
41
|
+
if dist_string == "gauss":
|
|
42
|
+
return stats.norm(loc=val1, scale=val2)
|
|
43
|
+
if dist_string == "log_uniform":
|
|
44
|
+
return stats.loguniform(val1, val2)
|
|
45
|
+
raise ValueError(f"distribution {dist_string} not supported")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class Param(object):
|
|
49
|
+
"""A Param needs a starting value, a current value, and a prior
|
|
50
|
+
and a flag to state whether is should vary"""
|
|
51
|
+
|
|
52
|
+
def __init__(self, name, startVal, prior, isVar=True):
|
|
53
|
+
self.name = name
|
|
54
|
+
self.startVal = startVal
|
|
55
|
+
self.prior = prior
|
|
56
|
+
self.currVal = startVal
|
|
57
|
+
self.isVar = isVar
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def fromString(cls, name, parString):
|
|
61
|
+
fields = parString.split()
|
|
62
|
+
val = float(fields[0])
|
|
63
|
+
priorType = fields[1].strip()
|
|
64
|
+
priorP1 = float(fields[2])
|
|
65
|
+
priorP2 = float(fields[3])
|
|
66
|
+
prior = scipy_dist(priorType, priorP1, priorP2)
|
|
67
|
+
if len(fields) == 5:
|
|
68
|
+
isVar = bool(int(fields[4]))
|
|
69
|
+
else:
|
|
70
|
+
isVar = True
|
|
71
|
+
return cls(name, val, prior, isVar)
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def isValid(self):
|
|
75
|
+
return np.isfinite(self.prior.logpdf(self.currVal))
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class Node:
|
|
79
|
+
r"""
|
|
80
|
+
Inputs:
|
|
81
|
+
-------
|
|
82
|
+
label, str:
|
|
83
|
+
A label to apply to the node. Mostly used when searching trees.
|
|
84
|
+
parameter_objects; list(Param), or Param:
|
|
85
|
+
The parameter objects that correspond to this node. Single Param is
|
|
86
|
+
also accepted.
|
|
87
|
+
parent; Node, optional:
|
|
88
|
+
The parent of this node.
|
|
89
|
+
children; list(Node), or Node:
|
|
90
|
+
The children of this node. Single Node is also accepted
|
|
91
|
+
|
|
92
|
+
Description:
|
|
93
|
+
------------
|
|
94
|
+
Base class for the hierarchical model interface. This functions as a node,
|
|
95
|
+
and can have children and a parent.
|
|
96
|
+
|
|
97
|
+
Can have any number of children, but at most one parent.
|
|
98
|
+
|
|
99
|
+
Parameters can be retrieved from the bottom-up, and can be set from the
|
|
100
|
+
top-down. With some fiddling, the opposite is also possible, but not
|
|
101
|
+
recommended!
|
|
102
|
+
|
|
103
|
+
This is a block used to build mode structures, something like:
|
|
104
|
+
Trunk
|
|
105
|
+
|
|
|
106
|
+
/ \
|
|
107
|
+
Branch1 --- --- Branch2
|
|
108
|
+
| |
|
|
109
|
+
/ \ / \
|
|
110
|
+
leaf1 leaf2 leaf3 leaf4
|
|
111
|
+
|
|
112
|
+
Leaves inherit Params from their branches, which inherit from their Trunk.
|
|
113
|
+
This can be arbitrarily deep, and leaves need to have a leaf.calc()
|
|
114
|
+
function defined in order to terminate the recursive chisq function.
|
|
115
|
+
|
|
116
|
+
Parameter lists for the tree can be retrieved and set from any level.
|
|
117
|
+
e.g., Trunk.dynasty_par_vals contains the parameters for all nodes, but
|
|
118
|
+
Branch2.dynasty_par_vals contains only those of Branch2, leaf3, and leaf4.
|
|
119
|
+
Setting X.dynasty_par_vals sorts the parameters to the correct nodes,
|
|
120
|
+
provided it's in the correct order (which can be retrieved with
|
|
121
|
+
X.dynasty_par_names)
|
|
122
|
+
|
|
123
|
+
Conversely, leaf4.ancestor_param_dict moves the other way. It will contain
|
|
124
|
+
ONLY the parameters of leaf4, Branch2, and Trunk.
|
|
125
|
+
|
|
126
|
+
Should be subclassed with the self.node_par_names variable defined, as this
|
|
127
|
+
is a blank slate. Without that variable, this model cannot store
|
|
128
|
+
parameters. There may be usecases where this can be exploited to group
|
|
129
|
+
branches or leaves without them sharing any parameters.
|
|
130
|
+
"""
|
|
131
|
+
|
|
132
|
+
# Init the node_par_names to be empty and a tuple.
|
|
133
|
+
# Change this when you subclass Node!
|
|
134
|
+
node_par_names = ()
|
|
135
|
+
|
|
136
|
+
def __init__(
|
|
137
|
+
self, label, parameter_objects, parent=None, children=None, DEBUG=None
|
|
138
|
+
):
|
|
139
|
+
"""Initialse the node. Does the following:
|
|
140
|
+
|
|
141
|
+
- Store parameter values to attributes named after the parameter names
|
|
142
|
+
- Store the object defined as my parent
|
|
143
|
+
- Store a list of objects defined as my children
|
|
144
|
+
- Checks that my Param objects were stored correctly.
|
|
145
|
+
|
|
146
|
+
Inputs:
|
|
147
|
+
-------
|
|
148
|
+
label: str
|
|
149
|
+
A label for this node. The name attribute will be the node class
|
|
150
|
+
name joined with this label.
|
|
151
|
+
parameter_objects: list of Param
|
|
152
|
+
The parameters to be stored on this node.
|
|
153
|
+
parent: Node object, Optional
|
|
154
|
+
The node that this node is a child of.
|
|
155
|
+
children: Node, list of Node, Optional
|
|
156
|
+
The children of this node.
|
|
157
|
+
DEBUG: bool
|
|
158
|
+
A useful debugging flag for you to use.
|
|
159
|
+
"""
|
|
160
|
+
# Handle the family
|
|
161
|
+
if children is None:
|
|
162
|
+
children = []
|
|
163
|
+
self.children = children
|
|
164
|
+
self.parent = parent
|
|
165
|
+
|
|
166
|
+
# If the user tells us a debugging flag, use it.
|
|
167
|
+
if isinstance(DEBUG, bool):
|
|
168
|
+
self.DEBUG = DEBUG
|
|
169
|
+
# Otherwise, inherit my parent's debugging flag
|
|
170
|
+
elif self.parent is not None:
|
|
171
|
+
self.DEBUG = self.parent.DEBUG
|
|
172
|
+
# unless I don't have one. Then default to False
|
|
173
|
+
else:
|
|
174
|
+
self.DEBUG = False
|
|
175
|
+
|
|
176
|
+
# I expect my parameter values to be fed in as a list. If they're not
|
|
177
|
+
# a list, assume I have a single Param object, and wrap it in a list.
|
|
178
|
+
parameter_objects = list(parameter_objects)
|
|
179
|
+
|
|
180
|
+
# Make sure our label is valid
|
|
181
|
+
if not isinstance(label, str):
|
|
182
|
+
raise TypeError("Label must be a string, not {}".format(type(label)))
|
|
183
|
+
|
|
184
|
+
self.label = label
|
|
185
|
+
|
|
186
|
+
# Check that the user defined their parameter names!
|
|
187
|
+
if len(self.node_par_names) != len(parameter_objects):
|
|
188
|
+
fail_msg = "I recieved the wrong number of parameters!"
|
|
189
|
+
fail_msg += " Expect: \n{}\nGot:\n{}".format(
|
|
190
|
+
self.node_par_names,
|
|
191
|
+
[getattr(param, "name") for param in parameter_objects],
|
|
192
|
+
)
|
|
193
|
+
raise TypeError(fail_msg)
|
|
194
|
+
|
|
195
|
+
# Add the parameters to the self.XXX.
|
|
196
|
+
for par in parameter_objects:
|
|
197
|
+
setattr(self, par.name, par)
|
|
198
|
+
|
|
199
|
+
self.log("base.__init__", "Successfully did the base Node init")
|
|
200
|
+
|
|
201
|
+
# Tree handling methods
|
|
202
|
+
def search_par(self, label, name):
|
|
203
|
+
"""Search the tree recursively downwards, and return the Param.
|
|
204
|
+
Returns None if the Param is not found.
|
|
205
|
+
|
|
206
|
+
Inputs:
|
|
207
|
+
-------
|
|
208
|
+
label: str
|
|
209
|
+
The Param I'm searching for will be associated with a node
|
|
210
|
+
having this label.
|
|
211
|
+
name: str
|
|
212
|
+
The name of the Param object. I'm looking for
|
|
213
|
+
|
|
214
|
+
Returns:
|
|
215
|
+
--------
|
|
216
|
+
Param, None if the search fails
|
|
217
|
+
The Param object to be searched.
|
|
218
|
+
"""
|
|
219
|
+
|
|
220
|
+
self.log(
|
|
221
|
+
"base.search_par",
|
|
222
|
+
"Searching for a Param called {}, on a Node labelled {}".format(
|
|
223
|
+
name, label
|
|
224
|
+
),
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
# If I'm the desired node, get my parameter
|
|
228
|
+
if self.label == label:
|
|
229
|
+
self.log("base.search_par", "I am that Node!")
|
|
230
|
+
return getattr(self, name)
|
|
231
|
+
# Otherwise, check my children.
|
|
232
|
+
else:
|
|
233
|
+
self.log("base.search_par", "Searching my children for that Node.")
|
|
234
|
+
for child in self.children:
|
|
235
|
+
val = child.search_par(label, name)
|
|
236
|
+
if val is not None:
|
|
237
|
+
return val
|
|
238
|
+
self.log("base.search_par", "Could not find that node.")
|
|
239
|
+
return None
|
|
240
|
+
|
|
241
|
+
def search_Node(self, class_type, label):
|
|
242
|
+
"""Search for a node below me of class_type, with the label requested.
|
|
243
|
+
Returns None if this is not found.
|
|
244
|
+
|
|
245
|
+
Inputs:
|
|
246
|
+
-------
|
|
247
|
+
class_type: str
|
|
248
|
+
The nodes will be checked that their class name is this string
|
|
249
|
+
label: str
|
|
250
|
+
The nodes will be checked that their label is this string
|
|
251
|
+
|
|
252
|
+
Outputs:
|
|
253
|
+
--------
|
|
254
|
+
Node, None is the search fails
|
|
255
|
+
The node that was requested.
|
|
256
|
+
"""
|
|
257
|
+
self.log(
|
|
258
|
+
"base.search_Node",
|
|
259
|
+
"Searching for a Node of class type {}, with a label {}".format(
|
|
260
|
+
class_type, label
|
|
261
|
+
),
|
|
262
|
+
)
|
|
263
|
+
if self.name == "{}_{}".format(class_type, label):
|
|
264
|
+
self.log("base.search_Node", "I am that node. Returning self")
|
|
265
|
+
return self
|
|
266
|
+
else:
|
|
267
|
+
self.log("base.search_Node", "Checking my children")
|
|
268
|
+
for child in self.children:
|
|
269
|
+
val = child.search_Node(class_type, label)
|
|
270
|
+
if val is not None:
|
|
271
|
+
return val
|
|
272
|
+
else:
|
|
273
|
+
pass
|
|
274
|
+
self.log("base.search_Node", "Could not find that node.")
|
|
275
|
+
return None
|
|
276
|
+
|
|
277
|
+
def search_node_type(self, class_type, nodes=None):
|
|
278
|
+
"""Construct a set of all the nodes of a given type below me
|
|
279
|
+
|
|
280
|
+
Inputs:
|
|
281
|
+
-------
|
|
282
|
+
class_type: str
|
|
283
|
+
If the node class contains this string, it will be added.
|
|
284
|
+
nodes: set of Node, Optional
|
|
285
|
+
The existing list of nodes that will be extended with my result.
|
|
286
|
+
|
|
287
|
+
Outputs:
|
|
288
|
+
--------
|
|
289
|
+
nodes: set of Node
|
|
290
|
+
The search result.
|
|
291
|
+
"""
|
|
292
|
+
self.log(
|
|
293
|
+
"base.search_node_type",
|
|
294
|
+
"Constructing a set of Nodes of type {}".format(class_type),
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
if nodes is None:
|
|
298
|
+
nodes = set()
|
|
299
|
+
|
|
300
|
+
for child in self.children:
|
|
301
|
+
child_nodes = child.search_node_type(class_type, nodes)
|
|
302
|
+
nodes = nodes.union(child_nodes)
|
|
303
|
+
|
|
304
|
+
if class_type in str(self.__class__.__name__):
|
|
305
|
+
nodes.add(self)
|
|
306
|
+
|
|
307
|
+
self.log("base.search_node_type", "Returning: \n{}".format(nodes))
|
|
308
|
+
return nodes
|
|
309
|
+
|
|
310
|
+
def add_child(self, children):
|
|
311
|
+
"""Add children to my list of children
|
|
312
|
+
|
|
313
|
+
Inputs:
|
|
314
|
+
-------
|
|
315
|
+
children: Node, or list of Node
|
|
316
|
+
Add this to my list of children. They will be altered to
|
|
317
|
+
have this node as a parent.
|
|
318
|
+
"""
|
|
319
|
+
self.log(
|
|
320
|
+
"base.add_child",
|
|
321
|
+
"Adding: \n{}\nto my existing list of children, which was \n{}".format(
|
|
322
|
+
children, self.children
|
|
323
|
+
),
|
|
324
|
+
)
|
|
325
|
+
if not isinstance(children, list):
|
|
326
|
+
children = [children]
|
|
327
|
+
|
|
328
|
+
# Set the children.
|
|
329
|
+
self.children.extend(children)
|
|
330
|
+
|
|
331
|
+
# # # # # # # # # # # # # #
|
|
332
|
+
# Tree evaluation methods #
|
|
333
|
+
# # # # # # # # # # # # # #
|
|
334
|
+
|
|
335
|
+
def __call_recursive_func__(self, name, *args, **kwargs):
|
|
336
|
+
"""
|
|
337
|
+
Descend the model heirarchy, calling a function at each leaf.
|
|
338
|
+
|
|
339
|
+
This is used, for example, to evaluate chisq or ln_like for a given model,
|
|
340
|
+
where we want to sum this quantity for all fully defined models.
|
|
341
|
+
|
|
342
|
+
Inputs:
|
|
343
|
+
-------
|
|
344
|
+
name: str
|
|
345
|
+
The name of the function to be called
|
|
346
|
+
*args, **kwargs
|
|
347
|
+
Arguments to be passed to the function.
|
|
348
|
+
|
|
349
|
+
Outputs:
|
|
350
|
+
--------
|
|
351
|
+
float:
|
|
352
|
+
The sum of the function called at each relevant node.
|
|
353
|
+
"""
|
|
354
|
+
# self.log("base.__call_recursive_func", "Calling the function {} recursively, passing it the args:\n{}\nkwargs:\n{}".format(name, args, kwargs))
|
|
355
|
+
val = 0.0
|
|
356
|
+
if self.is_leaf:
|
|
357
|
+
self.log(
|
|
358
|
+
"base.__call_recursive_func",
|
|
359
|
+
"Reached the bottom of the Tree with no function by that name.",
|
|
360
|
+
)
|
|
361
|
+
raise NotImplementedError(
|
|
362
|
+
"must overwrite {} on leaf nodes of model".format(name)
|
|
363
|
+
)
|
|
364
|
+
for child in self.children:
|
|
365
|
+
func = getattr(child, name)
|
|
366
|
+
val += func(*args, **kwargs)
|
|
367
|
+
if np.any(np.isinf(val)):
|
|
368
|
+
# we've got an invalid model, no need to evaluate other leaves
|
|
369
|
+
self.log(
|
|
370
|
+
"base.__call_recursive_func",
|
|
371
|
+
"The function {} called on {}, but returned an inf.".format(
|
|
372
|
+
name, child.name
|
|
373
|
+
),
|
|
374
|
+
)
|
|
375
|
+
return val
|
|
376
|
+
return val
|
|
377
|
+
|
|
378
|
+
def __call_recursive_bool_func__(self, name, *args, **kwargs) -> bool:
|
|
379
|
+
"""
|
|
380
|
+
Descend the model heirarchy, calling a function at each leaf.
|
|
381
|
+
|
|
382
|
+
This is used, for example, to evaluate check_validity for a given model,
|
|
383
|
+
where we want to check that all nodes are valid.
|
|
384
|
+
|
|
385
|
+
Inputs:
|
|
386
|
+
-------
|
|
387
|
+
name: str
|
|
388
|
+
The name of the function to be called
|
|
389
|
+
*args, **kwargs
|
|
390
|
+
Arguments to be passed to the function.
|
|
391
|
+
|
|
392
|
+
Outputs:
|
|
393
|
+
--------
|
|
394
|
+
bool:
|
|
395
|
+
True if all nodes are valid, False otherwise.
|
|
396
|
+
"""
|
|
397
|
+
val = True
|
|
398
|
+
if self.is_leaf:
|
|
399
|
+
raise NotImplementedError(
|
|
400
|
+
"must overwrite {} on leaf nodes of model".format(name)
|
|
401
|
+
)
|
|
402
|
+
for child in self.children:
|
|
403
|
+
func = getattr(child, name)
|
|
404
|
+
val = val and func(*args, **kwargs)
|
|
405
|
+
if not val:
|
|
406
|
+
# we've got an invalid model, no need to evaluate other leaves
|
|
407
|
+
return val
|
|
408
|
+
return val
|
|
409
|
+
|
|
410
|
+
def check_validity(self):
|
|
411
|
+
"""Returns the sum of my children's validity checks. Must be overwritten on
|
|
412
|
+
leaf nodes, or nodes capable of evaluating a model."""
|
|
413
|
+
# val is sum of validity checks of children, which are True/False.
|
|
414
|
+
# if all are valid, val should be equal to the number of children, and thus True.
|
|
415
|
+
return self.__call_recursive_bool_func__("check_validity")
|
|
416
|
+
|
|
417
|
+
def chisq(self, *args, **kwargs):
|
|
418
|
+
"""Returns the sum of my children's chisqs. Must be overwritten on
|
|
419
|
+
leaf nodes, or nodes capable of evaluating a model."""
|
|
420
|
+
return self.__call_recursive_func__("chisq", *args, **kwargs)
|
|
421
|
+
|
|
422
|
+
def ln_like(self, *args, **kwargs):
|
|
423
|
+
"""Calculate the log likelihood"""
|
|
424
|
+
return self.__call_recursive_func__("ln_like", *args, **kwargs)
|
|
425
|
+
|
|
426
|
+
# Dunder methods that are generally hidden from the user.
|
|
427
|
+
def __get_inherited_parameter_names__(self):
|
|
428
|
+
"""Construct a list of the variable parameters that I have, and append
|
|
429
|
+
it with the names of those stored in my parents.
|
|
430
|
+
|
|
431
|
+
This is a list of ONLY the names of the parameters, regardless of if
|
|
432
|
+
they're variable.
|
|
433
|
+
"""
|
|
434
|
+
names = []
|
|
435
|
+
|
|
436
|
+
# First, get my own parameter names
|
|
437
|
+
names += self.node_par_names
|
|
438
|
+
|
|
439
|
+
# Then, fetch the names of my parent's parameters - in order!
|
|
440
|
+
if self.parent is not None:
|
|
441
|
+
names += self.parent.__get_inherited_parameter_names__()
|
|
442
|
+
|
|
443
|
+
return names
|
|
444
|
+
|
|
445
|
+
def __get_inherited_parameter_vector__(self):
|
|
446
|
+
"""Query all my parents for their parameter vectors. When they've all
|
|
447
|
+
given me them, return the full list.
|
|
448
|
+
|
|
449
|
+
Outputs:
|
|
450
|
+
--------
|
|
451
|
+
list of Param objects
|
|
452
|
+
"""
|
|
453
|
+
|
|
454
|
+
# This is where I'll build my list of parameters
|
|
455
|
+
vector = []
|
|
456
|
+
|
|
457
|
+
# What are my parameters?
|
|
458
|
+
vector += [getattr(self, name) for name in self.node_par_names]
|
|
459
|
+
|
|
460
|
+
# Get my parent's vectors...
|
|
461
|
+
if self.parent is not None:
|
|
462
|
+
vector += self.parent.__get_inherited_parameter_vector__()
|
|
463
|
+
|
|
464
|
+
return vector
|
|
465
|
+
|
|
466
|
+
def __get_descendant_params__(self):
|
|
467
|
+
"""Get all the Param objects at or below this node
|
|
468
|
+
|
|
469
|
+
Outputs:
|
|
470
|
+
--------
|
|
471
|
+
list of Params,
|
|
472
|
+
All the Param objects of the nodes descended from this node.
|
|
473
|
+
list of node labels,
|
|
474
|
+
The node label corresponding to the Param at the corresponding
|
|
475
|
+
index. Has the same shape as the list of Params.
|
|
476
|
+
"""
|
|
477
|
+
params = []
|
|
478
|
+
node_names = []
|
|
479
|
+
|
|
480
|
+
params += [getattr(self, par) for par in self.node_par_names]
|
|
481
|
+
node_names += [self.label for par in self.node_par_names]
|
|
482
|
+
|
|
483
|
+
for child in self.children:
|
|
484
|
+
child_params, child_node_names = child.__get_descendant_params__()
|
|
485
|
+
params.extend(child_params)
|
|
486
|
+
node_names.extend(child_node_names)
|
|
487
|
+
|
|
488
|
+
return params, node_names
|
|
489
|
+
|
|
490
|
+
def __get_descendant_parameter_vector__(self):
|
|
491
|
+
"""Get a list of the values of the Param objects at or below this node
|
|
492
|
+
|
|
493
|
+
The (V)ector contains the (V)alues
|
|
494
|
+
"""
|
|
495
|
+
params, _ = self.__get_descendant_params__()
|
|
496
|
+
|
|
497
|
+
# Filter out the entries that are non-variable
|
|
498
|
+
vector = [v.currVal for v in params if v.isVar]
|
|
499
|
+
|
|
500
|
+
return vector
|
|
501
|
+
|
|
502
|
+
def __get_descendant_parameter_priors__(self):
|
|
503
|
+
"""Get a list of the prior distributions of the Param objects at or below this node
|
|
504
|
+
|
|
505
|
+
The (V)ector contains the (V)alues
|
|
506
|
+
"""
|
|
507
|
+
params, _ = self.__get_descendant_params__()
|
|
508
|
+
|
|
509
|
+
# Filter out the entries that are non-variable
|
|
510
|
+
vector = [v.prior for v in params if v.isVar]
|
|
511
|
+
|
|
512
|
+
return vector
|
|
513
|
+
|
|
514
|
+
def __get_descendant_parameter_names__(self):
|
|
515
|
+
"""Get the keys for the lower parameter vector"""
|
|
516
|
+
|
|
517
|
+
params, names = self.__get_descendant_params__()
|
|
518
|
+
|
|
519
|
+
# Filter out the entries that are non-variable
|
|
520
|
+
vector = [v.name + "_" + n for v, n in zip(params, names) if v.isVar]
|
|
521
|
+
|
|
522
|
+
return vector
|
|
523
|
+
|
|
524
|
+
def __set_parameter_vector__(self, vector_values):
|
|
525
|
+
"""Take a parameter vector, and pop values off the back until all this
|
|
526
|
+
models' variables are set. Then pass the remainder to the children of
|
|
527
|
+
this model, in order."""
|
|
528
|
+
vector = list(vector_values)
|
|
529
|
+
|
|
530
|
+
# I need to read off the children backwards
|
|
531
|
+
for child in self.children[::-1]:
|
|
532
|
+
vector = child.__set_parameter_vector__(vector)
|
|
533
|
+
|
|
534
|
+
# Now, add my own.
|
|
535
|
+
# Remember, backwards!
|
|
536
|
+
for name, val in zip(self.node_varpars[::-1], vector[::-1]):
|
|
537
|
+
par = getattr(self, name)
|
|
538
|
+
par.currVal = val
|
|
539
|
+
|
|
540
|
+
n_used = len(vector) - len(self.node_varpars)
|
|
541
|
+
return vector[:n_used]
|
|
542
|
+
|
|
543
|
+
def __check_par_assignments__(self):
|
|
544
|
+
"""Loop through my variables, and make sure that the Param.name is the
|
|
545
|
+
same as what I've got listed in self.node_par_names. This is probably
|
|
546
|
+
paranoid, but it makes me feel safer"""
|
|
547
|
+
|
|
548
|
+
param_dict = {key: getattr(self, key) for key in self.node_par_names}
|
|
549
|
+
|
|
550
|
+
for key, value in param_dict.items():
|
|
551
|
+
if key != value.name:
|
|
552
|
+
fail_msg = "Incorrect parameter name, {} assigned to {}. \nParameters are taken in the order {}".format(
|
|
553
|
+
value.name, key, self.node_par_names
|
|
554
|
+
)
|
|
555
|
+
raise NameError(fail_msg)
|
|
556
|
+
|
|
557
|
+
def __getitem__(self, index):
|
|
558
|
+
name, label = extract_par_and_key(index)
|
|
559
|
+
par = self.search_par(label, name)
|
|
560
|
+
return par
|
|
561
|
+
|
|
562
|
+
def __setitem__(self, index, value):
|
|
563
|
+
name, label = extract_par_and_key(index)
|
|
564
|
+
self.search_par(label, name).currVal = value
|
|
565
|
+
|
|
566
|
+
# Properties to make everything cleaner
|
|
567
|
+
@property
|
|
568
|
+
def name(self):
|
|
569
|
+
'''The name of this object, of the form "<class name>_<label>"'''
|
|
570
|
+
return "{}_{}".format(self.__class__.__name__, self.label)
|
|
571
|
+
|
|
572
|
+
@property
|
|
573
|
+
def parent(self):
|
|
574
|
+
"""My parent <3"""
|
|
575
|
+
return self.__parent
|
|
576
|
+
|
|
577
|
+
@parent.setter
|
|
578
|
+
def parent(self, parent):
|
|
579
|
+
"""When setting the parent, I also need to add myself to their list of
|
|
580
|
+
children"""
|
|
581
|
+
self.__parent = parent
|
|
582
|
+
if self.__parent is None:
|
|
583
|
+
pass
|
|
584
|
+
else:
|
|
585
|
+
self.__parent.add_child(self)
|
|
586
|
+
|
|
587
|
+
@property
|
|
588
|
+
def children(self):
|
|
589
|
+
return self.__children
|
|
590
|
+
|
|
591
|
+
@children.setter
|
|
592
|
+
def children(self, children):
|
|
593
|
+
"""Set the children list to children.
|
|
594
|
+
|
|
595
|
+
If the child already has a parent, remove the child from the
|
|
596
|
+
ex-parent's children list.
|
|
597
|
+
|
|
598
|
+
Set the childs parent to this node.
|
|
599
|
+
"""
|
|
600
|
+
|
|
601
|
+
# I need to preserve the order of the children, so keep as a list.
|
|
602
|
+
if not isinstance(children, list):
|
|
603
|
+
children = list(children)
|
|
604
|
+
|
|
605
|
+
# Set the internal variable
|
|
606
|
+
self.__children = children
|
|
607
|
+
|
|
608
|
+
# Make sure my children know who's in charge
|
|
609
|
+
for child in self.__children:
|
|
610
|
+
child.__parent = self
|
|
611
|
+
|
|
612
|
+
@property
|
|
613
|
+
def dynasty_par_names(self):
|
|
614
|
+
"""A list of the keys to self.dynasty_par_vals"""
|
|
615
|
+
return self.__get_descendant_parameter_names__()
|
|
616
|
+
|
|
617
|
+
@property
|
|
618
|
+
def dynasty_par_vals(self):
|
|
619
|
+
"""A list of the variable parameter values below this node"""
|
|
620
|
+
return self.__get_descendant_parameter_vector__()
|
|
621
|
+
|
|
622
|
+
@dynasty_par_vals.setter
|
|
623
|
+
def dynasty_par_vals(self, dynasty_par_vals):
|
|
624
|
+
if not len(dynasty_par_vals) == len(self.dynasty_par_vals):
|
|
625
|
+
raise ValueError(
|
|
626
|
+
"Wrong vector length on {} - Expected {}, got {}".format(
|
|
627
|
+
self.name, len(self.dynasty_par_vals), len(dynasty_par_vals)
|
|
628
|
+
)
|
|
629
|
+
)
|
|
630
|
+
self.__set_parameter_vector__(dynasty_par_vals)
|
|
631
|
+
|
|
632
|
+
@property
|
|
633
|
+
def priors(self):
|
|
634
|
+
"""A list of the prior distributions of the variable parameters below this node"""
|
|
635
|
+
return self.__get_descendant_parameter_priors__()
|
|
636
|
+
|
|
637
|
+
@property
|
|
638
|
+
def dynasty_par_dict(self):
|
|
639
|
+
"""Returns a dict of the Param objects held at or below this node"""
|
|
640
|
+
return {k: v for k, v in zip(self.dynasty_par_names, self.dynasty_par_vals)}
|
|
641
|
+
|
|
642
|
+
@dynasty_par_dict.setter
|
|
643
|
+
def dynasty_par_dict(self, par_dict):
|
|
644
|
+
"""Set the parameter vector by a dict of values, in the form:
|
|
645
|
+
{"<parname>_<nodename>": <value, int>}
|
|
646
|
+
"""
|
|
647
|
+
for key, value in par_dict.items():
|
|
648
|
+
try:
|
|
649
|
+
self[key].currVal = value
|
|
650
|
+
except AttributeError as e:
|
|
651
|
+
print(repr(e))
|
|
652
|
+
|
|
653
|
+
@property
|
|
654
|
+
def ancestor_param_dict(self):
|
|
655
|
+
"""A dict of the Param objects ABOVE! this node
|
|
656
|
+
Gets all params, regardless of if ther're variable"""
|
|
657
|
+
return {
|
|
658
|
+
key: val
|
|
659
|
+
for key, val in zip(
|
|
660
|
+
self.__get_inherited_parameter_names__(),
|
|
661
|
+
self.__get_inherited_parameter_vector__(),
|
|
662
|
+
)
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
@property
|
|
666
|
+
def ancestor_par_names(self):
|
|
667
|
+
"""Construct a list of the variable parameters that I have, and append
|
|
668
|
+
it with the names of those stored in my parents.
|
|
669
|
+
|
|
670
|
+
This is a list of ONLY the names of the parameters, regardless of if
|
|
671
|
+
they're variable.
|
|
672
|
+
"""
|
|
673
|
+
return self.__get_inherited_parameter_names__()
|
|
674
|
+
|
|
675
|
+
@property
|
|
676
|
+
def node_varpars(self):
|
|
677
|
+
"""Returns the list of THIS node's variable parameter names."""
|
|
678
|
+
varpars = []
|
|
679
|
+
for name in self.node_par_names:
|
|
680
|
+
par = getattr(self, name)
|
|
681
|
+
if par.isVar:
|
|
682
|
+
varpars.append(par.name)
|
|
683
|
+
|
|
684
|
+
return varpars
|
|
685
|
+
|
|
686
|
+
@property
|
|
687
|
+
def is_root(self):
|
|
688
|
+
"""True if I have no parents"""
|
|
689
|
+
return self.parent is None
|
|
690
|
+
|
|
691
|
+
@property
|
|
692
|
+
def is_leaf(self):
|
|
693
|
+
"""True if I have no children"""
|
|
694
|
+
return len(self.children) == 0
|
|
695
|
+
|
|
696
|
+
# Diagnostic methods
|
|
697
|
+
@property
|
|
698
|
+
def structure(self):
|
|
699
|
+
"""Return the tree structure below me as a str, generated from nx."""
|
|
700
|
+
self.create_tree()
|
|
701
|
+
|
|
702
|
+
return nx.readwrite.tree_data(self.nx_graph, self.name)
|
|
703
|
+
|
|
704
|
+
@property
|
|
705
|
+
def DEBUG(self):
|
|
706
|
+
return self.__DEBUG
|
|
707
|
+
|
|
708
|
+
@DEBUG.setter
|
|
709
|
+
def DEBUG(self, flag):
|
|
710
|
+
for child in self.children:
|
|
711
|
+
child.DEBUG = flag
|
|
712
|
+
self.__DEBUG = flag
|
|
713
|
+
|
|
714
|
+
def log(self, called_by, message="\n", log_stack=False):
|
|
715
|
+
"""
|
|
716
|
+
Logging function. Writes the node name, and the current function stack
|
|
717
|
+
so the dev can trace what functions are calling what. Writes a message
|
|
718
|
+
if the user asks it to.
|
|
719
|
+
"""
|
|
720
|
+
if (self.DEBUG is None) or (not self.DEBUG):
|
|
721
|
+
return
|
|
722
|
+
|
|
723
|
+
# the call to inspect.stack() takes a looooong time (~ms)
|
|
724
|
+
if log_stack:
|
|
725
|
+
stack = [
|
|
726
|
+
"File {}, line {}, function {}".format(x.filename, x.lineno, x.function)
|
|
727
|
+
for x in inspect.stack()
|
|
728
|
+
][::-1]
|
|
729
|
+
stack = "\n ".join(stack)
|
|
730
|
+
|
|
731
|
+
# Construct an output filename
|
|
732
|
+
my_fname = "{}.txt".format(os.getpid())
|
|
733
|
+
oname = os.path.join("DEBUGGING", my_fname)
|
|
734
|
+
|
|
735
|
+
if not os.path.isdir("DEBUGGING"):
|
|
736
|
+
os.mkdir("DEBUGGING")
|
|
737
|
+
|
|
738
|
+
if not message.endswith("\n"):
|
|
739
|
+
message += "\n"
|
|
740
|
+
|
|
741
|
+
with open(oname, "a+") as f:
|
|
742
|
+
f.write("*" * 150 + "\n")
|
|
743
|
+
f.write(
|
|
744
|
+
"--> Logger called by function {} in node {}\n".format(
|
|
745
|
+
called_by, self.name
|
|
746
|
+
)
|
|
747
|
+
)
|
|
748
|
+
if log_stack:
|
|
749
|
+
f.write("--> The function stack is \n {}\n".format(stack))
|
|
750
|
+
f.write(message)
|
|
751
|
+
f.write("~" * 150 + "\n\n\n")
|
|
752
|
+
|
|
753
|
+
def report_relatives(self):
|
|
754
|
+
"""This is a pretty crappy, inflexible way of doing this. Can I
|
|
755
|
+
come up with a nicer, perhaps recursive way of it?"""
|
|
756
|
+
print("Reporting family tree of {}:".format(self.name))
|
|
757
|
+
try:
|
|
758
|
+
parent = self.parent.name
|
|
759
|
+
except AttributeError:
|
|
760
|
+
parent = "None"
|
|
761
|
+
print(" Parent: {}".format(parent))
|
|
762
|
+
print(" Children:")
|
|
763
|
+
for child in self.children:
|
|
764
|
+
print(" {}".format(child.name))
|
|
765
|
+
for grandchild in child.children:
|
|
766
|
+
print(" - {}".format(grandchild.name))
|
|
767
|
+
|
|
768
|
+
def report(self, also_relatives=True):
|
|
769
|
+
if also_relatives:
|
|
770
|
+
self.report_relatives()
|
|
771
|
+
print(" Parameter vector, and labels:")
|
|
772
|
+
for par, val in zip(self.dynasty_par_names, self.dynasty_par_vals):
|
|
773
|
+
print(" {:>10s} = {:<.3f}".format(par, val))
|
|
774
|
+
print("\n")
|
|
775
|
+
|
|
776
|
+
def create_tree(self, G=None, called=True):
|
|
777
|
+
"""Construct a tree node graph of the model structure.
|
|
778
|
+
Start from the called tier, and work down from there."""
|
|
779
|
+
if called:
|
|
780
|
+
G = nx.DiGraph()
|
|
781
|
+
G.add_node(self.name)
|
|
782
|
+
|
|
783
|
+
for child in self.children:
|
|
784
|
+
# Add the child's children to the graph
|
|
785
|
+
G = child.create_tree(G, called=False)
|
|
786
|
+
# Connect myself to the child
|
|
787
|
+
G.add_edge(self.name, child.name)
|
|
788
|
+
|
|
789
|
+
else:
|
|
790
|
+
# Add myself to the graph
|
|
791
|
+
G.add_node(self.name)
|
|
792
|
+
for child in self.children:
|
|
793
|
+
# Add my child as a node, and connect it to me
|
|
794
|
+
G.add_node(child.name)
|
|
795
|
+
G.add_edge(self.name, child.name)
|
|
796
|
+
G = child.create_tree(G, called=False)
|
|
797
|
+
|
|
798
|
+
return G
|
|
799
|
+
|
|
800
|
+
self.nx_graph = G
|
|
801
|
+
return G
|