File size: 23,329 Bytes
9562e16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
[NbConvertApp] Converting notebook run_full_21model.ipynb to notebook
[NbConvertApp] ERROR | Notebook JSON is invalid: Additional properties are not allowed ('execution_count', 'outputs' were unexpected)

Failed validating 'additionalProperties' in markdown_cell:

On instance['cells'][0]:
{'cell_type': 'markdown',
 'execution_count': None,
 'id': 'p0c000',
 'metadata': {},
 'outputs': ['...0 outputs...'],
 'source': '# Structural aliasing in Chronos-Bolt, Bayesian analysis\n'
           '\n'
           '**PATC...'}
C:\Users\feder\AppData\Local\Programs\Python\Python312\Lib\site-packages\zmq\_future.py:718: RuntimeWarning: Proactor event loop does not implement add_reader family of methods required for zmq. Registering an additional selector thread for add_reader support via tornado. Use `asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy())` to avoid this warning.
  self._get_loop()
[IPKernelApp] WARNING | Kernel is running over TCP without encryption. All communication (including code and outputs) is sent in plain text and is susceptible to eavesdropping. Use IPC transport or launch with kernel manager-provisioned CurveZMQ keys to enable transport encryption.
Traceback (most recent call last):
  File "<frozen runpy>", line 198, in _run_module_as_main
  File "<frozen runpy>", line 88, in _run_code
  File "C:\Users\feder\AppData\Local\Programs\Python\Python312\Scripts\jupyter-nbconvert.EXE\__main__.py", line 7, in <module>
  File "C:\Users\feder\AppData\Local\Programs\Python\Python312\Lib\site-packages\jupyter_core\application.py", line 284, in launch_instance
    super().launch_instance(argv=argv, **kwargs)
  File "C:\Users\feder\AppData\Local\Programs\Python\Python312\Lib\site-packages\traitlets\config\application.py", line 1080, in launch_instance
    app.start()
  File "C:\Users\feder\AppData\Local\Programs\Python\Python312\Lib\site-packages\nbconvert\nbconvertapp.py", line 420, in start
    self.convert_notebooks()
  File "C:\Users\feder\AppData\Local\Programs\Python\Python312\Lib\site-packages\nbconvert\nbconvertapp.py", line 597, in convert_notebooks
    self.convert_single_notebook(notebook_filename)
  File "C:\Users\feder\AppData\Local\Programs\Python\Python312\Lib\site-packages\nbconvert\nbconvertapp.py", line 563, in convert_single_notebook
    output, resources = self.export_single_notebook(
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\feder\AppData\Local\Programs\Python\Python312\Lib\site-packages\nbconvert\nbconvertapp.py", line 487, in export_single_notebook
    output, resources = self.exporter.from_filename(
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\feder\AppData\Local\Programs\Python\Python312\Lib\site-packages\nbconvert\exporters\exporter.py", line 201, in from_filename
    return self.from_file(f, resources=resources, **kw)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\feder\AppData\Local\Programs\Python\Python312\Lib\site-packages\nbconvert\exporters\exporter.py", line 220, in from_file
    return self.from_notebook_node(
           ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\feder\AppData\Local\Programs\Python\Python312\Lib\site-packages\nbconvert\exporters\notebook.py", line 36, in from_notebook_node
    nb_copy, resources = super().from_notebook_node(nb, resources, **kw)
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\feder\AppData\Local\Programs\Python\Python312\Lib\site-packages\nbconvert\exporters\exporter.py", line 154, in from_notebook_node
    nb_copy, resources = self._preprocess(nb_copy, resources)
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\feder\AppData\Local\Programs\Python\Python312\Lib\site-packages\nbconvert\exporters\exporter.py", line 353, in _preprocess
    nbc, resc = preprocessor(nbc, resc)
                ^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\feder\AppData\Local\Programs\Python\Python312\Lib\site-packages\nbconvert\preprocessors\base.py", line 48, in __call__
    return self.preprocess(nb, resources)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\feder\AppData\Local\Programs\Python\Python312\Lib\site-packages\nbconvert\preprocessors\execute.py", line 103, in preprocess
    self.preprocess_cell(cell, resources, index)
  File "C:\Users\feder\AppData\Local\Programs\Python\Python312\Lib\site-packages\nbconvert\preprocessors\execute.py", line 124, in preprocess_cell
    cell = self.execute_cell(cell, index, store_history=True)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\feder\AppData\Local\Programs\Python\Python312\Lib\site-packages\jupyter_core\utils\__init__.py", line 165, in wrapped
    return loop.run_until_complete(inner)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\feder\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py", line 691, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Users\feder\AppData\Local\Programs\Python\Python312\Lib\site-packages\nbclient\client.py", line 1062, in async_execute_cell
    await self._check_raise_for_error(cell, cell_index, exec_reply)
  File "C:\Users\feder\AppData\Local\Programs\Python\Python312\Lib\site-packages\nbclient\client.py", line 918, in _check_raise_for_error
    raise CellExecutionError.from_cell_and_msg(cell, exec_reply_content)
nbclient.exceptions.CellExecutionError: An error occurred while executing the following cell:
------------------
idata_A = cached_fit("04_A.nc", lambda: sample(model_A_contrast(live), "A"))

print("\nModel A, H1 behavioural")
rowsA = [report(idata_A, "beta_bar", label="beta_bar (log ratio)"),
         report(idata_A, "beta_bar", np.exp, label="recovery ratio exp(beta_bar)"),
         report(idata_A, "delta_O", label="delta_O (overlap slope, M1)"),
         report(idata_A, "delta_P", label="delta_P (log patch-size slope)")]
pA_att = prob(idata_A, "beta_bar", lambda x: x < ATTENUATION_20)
pA_rope = prob(idata_A, "beta_bar", lambda x: np.abs(x) < ROPE_LOG)
pA_neg = prob(idata_A, "beta_bar", lambda x: x < 0)
print(f"\n  P(at least 20% attenuation | D) = {pA_att:.3f}   (prior: "
      f"{prior_summary['p_attenuation20_prior']:.3f})")
print(f"  P(practically no effect  | D)   = {pA_rope:.3f}   (ROPE |beta| < log 1.1)")
print(f"  P(beta_bar < 0 | D)             = {pA_neg:.3f}   (any attenuation at all)")

pA_mit = prob(idata_A, "delta_O", lambda x: x < 0)
print(f"  P(delta_O < 0 | D)              = {pA_mit:.3f}   (M1: overlap reduces the deficit)")

display(az.summary(idata_A.posterior, var_names=["beta_bar", "delta_O", "delta_P", "tau", "sigma",
                                       "sigma_harm", "sigma_bg"], ci_prob=0.95).round(3))

# M1, second half: which description of the configuration level does the data prefer?
# deliverable2.tex, Mitigation: "the overlap ratio, the absolute stride, or the patch size".
# idata_A IS the config_level="both" fit (it is the default), so it is reused rather than
# sampled a second time: on the full design that is one avoidable fit of the largest model.
fitsM1 = {"overlap + patch size": idata_A}
fitsM1.update({lbl: cached_fit(f"04_A_{lvl}.nc",
                               lambda l=lvl, n=lbl: sample(model_A_contrast(live, config_level=l), n))
               for lvl, lbl in (("overlap", "overlap only"), ("patch", "patch size only"),
                                ("none", "neither"))})
cmpM1 = az.compare(fitsM1)
display(cmpM1)

# plot_forest: ArviZ 1.x changed the API; draw manually
post_beta = idata_A.posterior["beta"].values.reshape(-1, idata_A.posterior.sizes["config"])
cfg_names = list(idata_A.posterior.coords["config"].values)
fig, ax = plt.subplots(figsize=(8, 3.4))
for j, name in enumerate(cfg_names):
    lo, med, hi = np.quantile(post_beta[:, j], [0.025, 0.5, 0.975])
    ax.plot([lo, hi], [j, j], color="steelblue", lw=2)
    ax.plot(med, j, "o", color="steelblue", ms=5)
ax.axvline(0, color="k", lw=.9)
ax.axvline(ATTENUATION_20, color="crimson", ls="--", lw=1)
ax.set_yticks(range(len(cfg_names))); ax.set_yticklabels(cfg_names, fontsize=8)
ax.set_title("Model A: per-configuration phase-lock effect $\\beta_c$\n"
             "(left of the dashed line = at least 20% attenuation)")
plt.tight_layout(); plt.savefig(FIG_DIR / "P4_A_forest.png", dpi=140, bbox_inches="tight"); plt.show()

------------------

----- stderr -----
NUTS[nutpie]: [beta_bar, delta_O, delta_P, tau, z_cfg, sigma_harm, z_harm, sigma_bg, z_bg, sigma]
----- stdout -----
  checkpoint -> 04_A.nc

Model A, H1 behavioural
  beta_bar (log ratio)     median +0.0185   95% CrI [-0.4954, +0.5329]
  recovery ratio exp(beta_bar) median +1.0187   95% CrI [+0.6094, +1.7039]
  delta_O (overlap slope, M1) median +0.3791   95% CrI [+0.0091, +0.7166]
  delta_P (log patch-size slope) median -0.7530   95% CrI [-1.1491, -0.2461]

  P(at least 20% attenuation | D) = 0.212   (prior: 0.336)
  P(practically no effect  | D)   = 0.244   (ROPE |beta| < log 1.1)
  P(beta_bar < 0 | D)             = 0.478   (any attenuation at all)
  P(delta_O < 0 | D)              = 0.023   (M1: overlap reduces the deficit)
----- stderr -----
NUTS[nutpie]: [beta_bar, delta_O, tau, z_cfg, sigma_harm, z_harm, sigma_bg, z_bg, sigma]
----- stdout -----
  checkpoint -> 04_A_overlap.nc
----- stderr -----
NUTS[nutpie]: [beta_bar, delta_P, tau, z_cfg, sigma_harm, z_harm, sigma_bg, z_bg, sigma]
----- stdout -----
  checkpoint -> 04_A_patch.nc
----- stderr -----
NUTS[nutpie]: [beta_bar, tau, z_cfg, sigma_harm, z_harm, sigma_bg, z_bg, sigma]
----- stdout -----
  checkpoint -> 04_A_none.nc
------------------

---------------------------------------------------------------------------
MemoryError                               Traceback (most recent call last)
File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\arviz_stats\loo\compare.py:636, in _calculate_ics(compare_dict, var_name)
    635 try:
--> 636     new_compare_dict[name] = loo(
    637         dataset,
    638         pointwise=True,
    639         var_name=var_name,
    640     )
    641 except Exception as e:

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\arviz_stats\loo\loo.py:227, in loo(data, pointwise, var_name, reff, log_lik_fn, log_weights, pareto_k, log_jacobian, mixture, moment_match, model)
    226 if log_weights is None and pareto_k is None:
--> 227     log_weights, pareto_k = loo_inputs.log_likelihood.azstats.psislw(
    228         r_eff=reff, dim=loo_inputs.sample_dims
    229     )
    231 if mixture:

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\arviz_stats\accessors.py:170, in _BaseAccessor.psislw(self, dim, **kwargs)
    169 """Pareto smoothed importance sampling."""
--> 170 return self._apply("psislw", dim=dim, **kwargs)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\arviz_stats\accessors.py:398, in AzStatsDaAccessor._apply(self, func, **kwargs)
    397     func = get_function(func)
--> 398 return func(self._obj, **kwargs)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\arviz_stats\base\dataarray.py:546, in BaseDataArray.psislw(self, da, r_eff, dim)
    545 dims = validate_dims(dim)
--> 546 return apply_ufunc(
    547     self.array_class.psislw,
    548     da,
    549     r_eff,
    550     input_core_dims=[dims, []],
    551     output_core_dims=[dims, []],
    552     kwargs={"axis": np.arange(-len(dims), 0, 1)},
    553 )

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\xarray\computation\apply_ufunc.py:1267, in apply_ufunc(func, input_core_dims, output_core_dims, exclude_dims, vectorize, join, dataset_join, dataset_fill_value, keep_attrs, kwargs, dask, output_dtypes, output_sizes, meta, dask_gufunc_kwargs, on_missing_core_dim, *args)
   1266 elif any(isinstance(a, DataArray) for a in args):
-> 1267     return apply_dataarray_vfunc(
   1268         variables_vfunc,
   1269         *args,
   1270         signature=signature,
   1271         join=join,
   1272         exclude_dims=exclude_dims,
   1273         keep_attrs=keep_attrs,
   1274     )
   1275 # feed Variables directly through apply_variable_ufunc

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\xarray\computation\apply_ufunc.py:312, in apply_dataarray_vfunc(func, signature, join, exclude_dims, keep_attrs, *args)
    311 data_vars = [getattr(a, "variable", a) for a in args]
--> 312 result_var = func(*data_vars)
    314 out: tuple[DataArray, ...] | DataArray

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\xarray\computation\apply_ufunc.py:820, in apply_variable_ufunc(func, signature, exclude_dims, dask, output_dtypes, vectorize, keep_attrs, dask_gufunc_kwargs, *args)
    816     func = _vectorize(
    817         func, signature, output_dtypes=output_dtypes, exclude_dims=exclude_dims
    818     )
--> 820 result_data = func(*input_data)
    822 if signature.num_outputs == 1:

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\arviz_stats\base\array.py:306, in BaseArray.psislw(self, ary, r_eff, axis)
    299 psl_ufunc = make_ufunc(
    300     self._psislw,
    301     n_output=2,
   (...)    304     ravel=False,
    305 )
--> 306 return psl_ufunc(ary, out_shape=[(ary.shape[i] for i in axes), []], r_eff=r_eff)

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\arviz_stats\base\stats_utils.py:89, in make_ufunc.<locals>._multi_ufunc(out, out_shape, shape_from_1st, *args, **kwargs)
     88     else:
---> 89         out = tuple(np.empty((*element_shape, *out_shape[i])) for i in range(n_output))
     91 elif check_shape:

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\arviz_stats\base\stats_utils.py:89, in <genexpr>(.0)
     88     else:
---> 89         out = tuple(np.empty((*element_shape, *out_shape[i])) for i in range(n_output))
     91 elif check_shape:

MemoryError: Unable to allocate 10.2 GiB for an array with shape (171259, 4, 2000) and data type float64

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
Cell In[22], line 31
     27 fitsM1.update({lbl: cached_fit(f"04_A_{lvl}.nc",
     28                                lambda l=lvl, n=lbl: sample(model_A_contrast(live, config_level=l), n))
     29                for lvl, lbl in (("overlap", "overlap only"), ("patch", "patch size only"),
     30                                 ("none", "neither"))})
---> 31 cmpM1 = az.compare(fitsM1)
     32 display(cmpM1)
     33 
     34 # plot_forest: ArviZ 1.x changed the API; draw manually

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\arviz_stats\loo\compare.py:202, in compare(compare_dict, method, var_name, reference, round_to)
    199 else:
    200     round_val = round_to
--> 202 ics_dict = _calculate_ics(compare_dict, var_name=var_name)
    203 names = list(ics_dict.keys())
    205 has_subsampling = any(
    206     getattr(elpd, "subsample_size", None) is not None for elpd in ics_dict.values()
    207 )

File ~\AppData\Local\Programs\Python\Python312\Lib\site-packages\arviz_stats\loo\compare.py:642, in _calculate_ics(compare_dict, var_name)
    636             new_compare_dict[name] = loo(
    637                 dataset,
    638                 pointwise=True,
    639                 var_name=var_name,
    640             )
    641         except Exception as e:
--> 642             raise e.__class__(
    643                 f"Encountered error trying to compute ELPD from model {name}."
    644             ) from e
    645 return new_compare_dict

TypeError: _ArrayMemoryError.__init__() missing 1 required positional argument: 'dtype'