1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 """Module for performing Monte Carlo simulations for error analysis."""
24
25
26 from numpy import ndarray
27 from random import gauss
28
29
30 from lib import statistics
31 from lib.errors import RelaxError
32 from pipe_control import pipes
33 from specific_analyses.api import return_api
34
35
37 """Function for creating simulation data.
38
39 @keyword method: The type of Monte Carlo simulation to perform.
40 @type method: str
41 """
42
43
44 pipes.test()
45
46
47 if not hasattr(cdp, 'sim_state'):
48 raise RelaxError("Monte Carlo simulations have not been set up.")
49
50
51 valid_methods = ['back_calc', 'direct']
52 if method not in valid_methods:
53 raise RelaxError("The simulation creation method " + repr(method) + " is not valid.")
54
55
56 api = return_api()
57
58
59 for data_index in api.base_data_loop():
60
61 if method == 'back_calc':
62 data = api.create_mc_data(data_index)
63
64
65 else:
66 data = api.return_data(data_index)
67
68
69 if data == None:
70 continue
71
72
73 error = api.return_error(data_index)
74
75
76 if isinstance(data, list) or isinstance(data, ndarray):
77
78 random = []
79 for j in range(cdp.sim_number):
80
81 random.append([])
82 for k in range(len(data)):
83
84 if data[k] == None or error[k] == None:
85 random[j].append(None)
86 continue
87
88
89 random[j].append(gauss(data[k], error[k]))
90
91
92 if isinstance(data, dict):
93
94 random = []
95 for j in range(cdp.sim_number):
96
97 random.append({})
98 for id in data.keys():
99
100 if data[id] == None or error[id] == None:
101 random[j][id] = None
102 continue
103
104
105 random[j][id] = gauss(data[id], error[id])
106
107
108 api.sim_pack_data(data_index, random)
109
110
112 """Function for calculating errors from the Monte Carlo simulations.
113
114 The standard deviation formula used to calculate the errors is the square root of the
115 bias-corrected variance, given by the formula::
116
117 __________________________
118 / 1
119 sd = / ----- * sum({Xi - Xav}^2)
120 \/ n - 1
121
122 where
123 - n is the total number of simulations.
124 - Xi is the parameter value for simulation i.
125 - Xav is the mean parameter value for all simulations.
126 """
127
128
129 pipes.test()
130
131
132 if not hasattr(cdp, 'sim_state'):
133 raise RelaxError("Monte Carlo simulations have not been set up.")
134
135
136 api = return_api()
137
138
139 for model_info in api.model_loop():
140
141 select_sim = api.sim_return_selected(model_info)
142
143
144 index = 0
145 while True:
146
147 param_array = api.sim_return_param(model_info, index)
148
149
150 if param_array == None:
151 break
152
153
154 if isinstance(param_array[0], dict):
155
156 sd = {}
157
158
159 for key in param_array[0].keys():
160
161 data = []
162 for i in range(len(param_array)):
163 data.append(param_array[i][key])
164
165
166 sd[key] = statistics.std(values=data, skip=select_sim)
167
168
169 elif isinstance(param_array[0], list):
170
171 sd = []
172
173
174 for j in range(len(param_array[0])):
175
176 data = []
177 for i in range(len(param_array)):
178 data.append(param_array[i][j])
179
180
181 sd.append(statistics.std(values=data, skip=select_sim))
182
183
184 elif param_array[0] != None:
185 sd = statistics.std(values=param_array, skip=select_sim)
186
187
188 else:
189 sd = None
190
191
192 api.set_error(model_info, index, sd)
193
194
195 index = index + 1
196
197
198 cdp.sim_state = False
199
200
202 """Set the initial simulation parameter values."""
203
204
205 pipes.test()
206
207
208 if not hasattr(cdp, 'sim_state'):
209 raise RelaxError("Monte Carlo simulations have not been set up.")
210
211
212 api = return_api()
213
214
215 api.sim_init_values()
216
217
219 """Turn simulations off."""
220
221
222 pipes.test()
223
224
225 if not hasattr(cdp, 'sim_state'):
226 raise RelaxError("Monte Carlo simulations have not been set up.")
227
228
229 cdp.sim_state = False
230
231
233 """Turn simulations on."""
234
235
236 pipes.test()
237
238
239 if not hasattr(cdp, 'sim_state'):
240 raise RelaxError("Monte Carlo simulations have not been set up.")
241
242
243 cdp.sim_state = True
244
245
247 """Set the select flag of all simulations of all models to one.
248
249 @keyword number: The number of Monte Carlo simulations to set up.
250 @type number: int
251 @keyword all_select_sim: The selection status of the Monte Carlo simulations. The first
252 dimension of this matrix corresponds to the simulation and the
253 second corresponds to the models.
254 @type all_select_sim: list of lists of bool
255 """
256
257
258 api = return_api()
259
260
261 if all_select_sim == None:
262 select_sim = [True]*number
263
264
265 i = 0
266 for model_info in api.model_loop():
267
268 if api.skip_function(model_info):
269 continue
270
271
272 if all_select_sim != None:
273 select_sim = all_select_sim[i]
274
275
276 api.set_selected_sim(model_info, select_sim)
277
278
279 i += 1
280
281
282 -def setup(number=None, all_select_sim=None):
283 """Function for setting up Monte Carlo simulations.
284
285 @keyword number: The number of Monte Carlo simulations to set up.
286 @type number: int
287 @keyword all_select_sim: The selection status of the Monte Carlo simulations. The first
288 dimension of this matrix corresponds to the simulation and the
289 second corresponds to the instance.
290 @type all_select_sim: list of lists of bool
291 """
292
293
294 pipes.test()
295
296
297 cdp.sim_number = number
298 cdp.sim_state = True
299
300
301 select_all_sims(number=number, all_select_sim=all_select_sim)
302