getting_started_4_CorrelatedFields.ipynb 14.9 KB
Newer Older
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
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Notebook showcasing the NIFTy 6 Correlated Field model\n",
    "\n",
    "**Skip to `Parameter Showcases` for the meat/veggies ;)**\n",
    "\n",
    "The field model roughly works like this:\n",
    "\n",
    "`f = HT( A * zero_mode * xi ) + offset`\n",
    "\n",
    "`A` is a spectral power field which is constructed from power spectra that hold on subdomains of the target domain.\n",
    "It is scaled by a zero mode operator and then pointwise multiplied by a gaussian excitation field, yielding\n",
    "a representation of the field in harmonic space.\n",
    "It is then transformed into the target real space and a offset added.\n",
    "\n",
    "The power spectra `A` is constructed of are in turn constructed as the sum of a power law component\n",
    "and an integrated Wiener process whose amplitude and roughness can be set.\n",
    "\n",
    "## Setup code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
Philipp Arras's avatar
Philipp Arras committed
32
    "import nifty8 as ift\n",
33
    "import matplotlib.pyplot as plt\n",
Martin Reinecke's avatar
Martin Reinecke committed
34
35
    "plt.rcParams['figure.dpi'] = 100\n",
    "plt.style.use(\"seaborn-notebook\")\n",
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
    "import numpy as np\n",
    "ift.random.push_sseq_from_seed(43)\n",
    "\n",
    "n_pix = 256\n",
    "x_space = ift.RGSpace(n_pix)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Plotting routine\n",
    "def plot(fields, spectra, title=None):\n",
Philipp Arras's avatar
Philipp Arras committed
51
    "    # Plotting preparation is normally handled by nifty8.Plot\n",
52
53
    "    # It is done manually here to be able to tweak details\n",
    "    # Fields are assumed to have identical domains\n",
Martin Reinecke's avatar
Martin Reinecke committed
54
    "    fig = plt.figure(tight_layout=True, figsize=(10, 3))\n",
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
    "    if title is not None:\n",
    "        fig.suptitle(title, fontsize=14)\n",
    "    \n",
    "    # Field\n",
    "    ax1 = fig.add_subplot(1, 2, 1)\n",
    "    ax1.axhline(y=0., color='k', linestyle='--', alpha=0.25)\n",
    "    for field in fields:\n",
    "        dom = field.domain[0]\n",
    "        xcoord = np.arange(dom.shape[0]) * dom.distances[0]\n",
    "        ax1.plot(xcoord, field.val)\n",
    "    ax1.set_xlim(xcoord[0], xcoord[-1])\n",
    "    ax1.set_ylim(-5., 5.)\n",
    "    ax1.set_xlabel('x')\n",
    "    ax1.set_ylabel('f(x)')\n",
    "    ax1.set_title('Field realizations')\n",
    "    \n",
    "    # Spectrum\n",
    "    ax2 = fig.add_subplot(1, 2, 2)\n",
    "    for spectrum in spectra:\n",
    "        xcoord = spectrum.domain[0].k_lengths\n",
    "        ycoord = spectrum.val_rw()\n",
    "        ycoord[0] = ycoord[1]\n",
    "        ax2.plot(xcoord, ycoord)\n",
    "    ax2.set_ylim(1e-6, 10.)\n",
    "    ax2.set_xscale('log')\n",
    "    ax2.set_yscale('log')\n",
    "    ax2.set_xlabel('k')\n",
    "    ax2.set_ylabel('p(k)')\n",
    "    ax2.set_title('Power Spectrum')\n",
    "    \n",
    "    fig.align_labels()\n",
    "    plt.show()\n",
    "\n",
    "# Helper: draw main sample\n",
    "main_sample = None\n",
    "def init_model(m_pars, fl_pars):\n",
    "    global main_sample\n",
92
93
    "    cf = ift.CorrelatedFieldMaker(m_pars[\"prefix\"])\n",
    "    cf.set_amplitude_total_offset(m_pars[\"offset_mean\"], m_pars[\"offset_std\"])\n",
94
    "    cf.add_fluctuations(**fl_pars)\n",
95
    "    field = cf.finalize(prior_info=0)\n",
96
97
98
99
100
    "    main_sample = ift.from_random(field.domain)\n",
    "    print(\"model domain keys:\", field.domain.keys())\n",
    "    \n",
    "# Helper: field and spectrum from parameter dictionaries + plotting\n",
    "def eval_model(m_pars, fl_pars, title=None, samples=None):\n",
101
102
    "    cf = ift.CorrelatedFieldMaker(m_pars[\"prefix\"])\n",
    "    cf.set_amplitude_total_offset(m_pars[\"offset_mean\"], m_pars[\"offset_std\"])\n",
103
    "    cf.add_fluctuations(**fl_pars)\n",
104
    "    field = cf.finalize(prior_info=0)\n",
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
    "    spectrum = cf.amplitude\n",
    "    if samples is None:\n",
    "        samples = [main_sample]\n",
    "    field_realizations = [field(s) for s in samples]\n",
    "    spectrum_realizations = [spectrum.force(s) for s in samples]\n",
    "    plot(field_realizations, spectrum_realizations, title)\n",
    "\n",
    "def gen_samples(key_to_vary):\n",
    "    if key_to_vary is None:\n",
    "        return [main_sample]\n",
    "    dct = main_sample.to_dict()\n",
    "    subdom_to_vary = dct.pop(key_to_vary).domain\n",
    "    samples = []\n",
    "    for i in range(8):\n",
    "        d = dct.copy()\n",
    "        d[key_to_vary] = ift.from_random(subdom_to_vary)\n",
    "        samples.append(ift.MultiField.from_dict(d))\n",
    "    return samples\n",
    "        \n",
    "def vary_parameter(parameter_key, values, samples_vary_in=None):\n",
    "    s = gen_samples(samples_vary_in)\n",
    "    for v in values:\n",
    "        if parameter_key in cf_make_pars.keys():\n",
    "            m_pars = {**cf_make_pars, parameter_key: v}\n",
    "            eval_model(m_pars, cf_x_fluct_pars, f\"{parameter_key} = {v}\", s)\n",
    "        else:\n",
    "            fl_pars = {**cf_x_fluct_pars, parameter_key: v}\n",
    "            eval_model(cf_make_pars, fl_pars, f\"{parameter_key} = {v}\", s)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Before the Action: The Moment-Matched Log-Normal Distribution\n",
    "Many properties of the correlated field are modelled as being lognormally distributed.\n",
    "\n",
142
    "The distribution models are parametrized via their means and standard-deviations (first and second position in tuple).\n",
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
    "\n",
    "To get a feeling of how the ratio of the `mean` and `stddev` parameters influences the distribution shape,\n",
    "here are a few example histograms: (observe the x-axis!)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = plt.figure(figsize=(13, 3.5))\n",
    "mean = 1.0\n",
    "sigmas = [1.0, 0.5, 0.1]\n",
    "\n",
    "for i in range(3):\n",
Lukas Platz's avatar
Lukas Platz committed
159
160
    "    op = ift.LognormalTransform(mean=mean, sigma=sigmas[i],\n",
    "                                key='foo', N_copies=0)\n",
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
    "    op_samples = np.array(\n",
    "        [op(s).val for s in [ift.from_random(op.domain) for i in range(10000)]])\n",
    "\n",
    "    ax = fig.add_subplot(1, 3, i + 1)\n",
    "    ax.hist(op_samples, bins=50)\n",
    "    ax.set_title(f\"mean = {mean}, sigma = {sigmas[i]}\")\n",
    "    ax.set_xlabel('x')\n",
    "    del op_samples\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The Neutral Field\n",
    "\n",
    "To demonstrate the effect of all parameters, first a 'neutral' set of parameters\n",
    "is defined which then are varied one by one, showing the effect of the variation\n",
    "on the generated field realizations and the underlying power spectrum from which\n",
    "they were drawn.\n",
    "\n",
    "As a neutral field, a model with a white power spectrum and vanishing spectral power was chosen."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Neutral model parameters yielding a quasi-constant field\n",
    "cf_make_pars = {\n",
    "    'offset_mean': 0.,\n",
196
    "    'offset_std': (1e-3, 1e-16),\n",
197
198
199
200
201
    "    'prefix': ''\n",
    "}\n",
    "\n",
    "cf_x_fluct_pars = {\n",
    "    'target_subdomain': x_space,\n",
202
203
204
205
    "    'fluctuations': (1e-3, 1e-16),\n",
    "    'flexibility': (1e-3, 1e-16),\n",
    "    'asperity': (1e-3, 1e-16),\n",
    "    'loglogavgslope': (0., 1e-16)\n",
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
    "}\n",
    "\n",
    "init_model(cf_make_pars, cf_x_fluct_pars)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Show neutral field\n",
    "eval_model(cf_make_pars, cf_x_fluct_pars, \"Neutral Field\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Parameter Showcases\n",
    "\n",
227
    "## The `fluctuations` parameters of `add_fluctuations()`\n",
228
229
230
231
    "\n",
    "determine the **amplitude of variations along the field dimension**\n",
    "for which `add_fluctuations` is called.\n",
    "\n",
232
233
    "`fluctuations[0]` set the _average_ amplitude of the fields fluctuations along the given dimension,\\\n",
    "`fluctuations[1]` sets the width and shape of the amplitude distribution.\n",
234
235
236
237
    "\n",
    "The amplitude is modelled as being log-normally distributed,\n",
    "see `The Moment-Matched Log-Normal Distribution` above for details.\n",
    "\n",
238
    "#### `fluctuations` mean:"
239
240
241
242
243
244
245
246
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
247
    "vary_parameter('fluctuations', [(0.05, 1e-16), (0.5, 1e-16), (2., 1e-16)], samples_vary_in='xi')"
248
249
250
251
252
253
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
254
    "#### `fluctuations` std:"
255
256
257
258
259
260
261
262
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
263
264
    "vary_parameter('fluctuations', [(1., 0.01), (1., 0.1), (1., 1.)], samples_vary_in='fluctuations')\n",
    "cf_x_fluct_pars['fluctuations'] = (1., 1e-16)"
265
266
267
268
269
270
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
271
    "## The `loglogavgslope` parameters of `add_fluctuations()`\n",
272
273
274
275
276
    "\n",
    "determine **the slope of the loglog-linear (power law) component of the power spectrum**.\n",
    "\n",
    "The slope is modelled to be normally distributed.\n",
    "\n",
277
    "#### `loglogavgslope` mean:"
278
279
280
281
282
283
284
285
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
286
    "vary_parameter('loglogavgslope', [(-6., 1e-16), (-2., 1e-16), (2., 1e-16)], samples_vary_in='xi')"
287
288
289
290
291
292
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
293
    "#### `loglogavgslope` std:"
294
295
296
297
298
299
300
301
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
302
303
    "vary_parameter('loglogavgslope', [(-2., 0.02), (-2., 0.2), (-2., 2.0)], samples_vary_in='loglogavgslope')\n",
    "cf_x_fluct_pars['loglogavgslope'] = (-2., 1e-16)"
304
305
306
307
308
309
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
310
    "## The `flexibility` parameters of `add_fluctuations()`\n",
311
312
313
314
    "\n",
    "determine **the amplitude of the integrated Wiener process component of the power spectrum**\n",
    "(how strong the power spectrum varies besides the power-law).\n",
    "\n",
315
316
    "`flexibility[0]` sets the _average_ amplitude of the i.g.p. component,\\\n",
    "`flexibility[1]` sets how much the amplitude can vary.\\\n",
317
318
319
    "These two parameters feed into a moment-matched log-normal distribution model,\n",
    "see above for a demo of its behavior.\n",
    "\n",
320
    "#### `flexibility` mean:"
321
322
323
324
325
326
327
328
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
329
    "vary_parameter('flexibility', [(0.4, 1e-16), (4.0, 1e-16), (12.0, 1e-16)], samples_vary_in='spectrum')"
330
331
332
333
334
335
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
336
    "#### `flexibility` std:"
337
338
339
340
341
342
343
344
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
345
346
    "vary_parameter('flexibility', [(4., 0.02), (4., 0.2), (4., 2.)], samples_vary_in='flexibility')\n",
    "cf_x_fluct_pars['flexibility'] = (4., 1e-16)"
347
348
349
350
351
352
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
353
    "## The `asperity` parameters of `add_fluctuations()`\n",
354
    "\n",
355
    "`asperity` determines **how rough the integrated Wiener process component of the power spectrum is**.\n",
356
    "\n",
357
    "`asperity[0]` sets the average roughness, `asperity[1]` sets how much the roughness can vary.\\\n",
358
359
360
    "These two parameters feed into a moment-matched log-normal distribution model,\n",
    "see above for a demo of its behavior.\n",
    "\n",
361
    "#### `asperity` mean:"
362
363
364
365
366
367
368
369
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
370
    "vary_parameter('asperity', [(0.001, 1e-16), (1.0, 1e-16), (5., 1e-16)], samples_vary_in='spectrum')"
371
372
373
374
375
376
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
377
    "#### `asperity` std:"
378
379
380
381
382
383
384
385
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
386
387
    "vary_parameter('asperity', [(1., 0.01), (1., 0.1), (1., 1.)], samples_vary_in='asperity')\n",
    "cf_x_fluct_pars['asperity'] = (1., 1e-16)"
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The `offset_mean` parameter of `CorrelatedFieldMaker.make()`\n",
    "\n",
    "The `offset_mean` parameter defines a global additive offset on the field realizations.\n",
    "\n",
    "If the field is used for a lognormal model `f = field.exp()`, this acts as a global signal magnitude offset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Reset model to neutral\n",
408
409
410
411
    "cf_x_fluct_pars['fluctuations'] = (1e-3, 1e-16)\n",
    "cf_x_fluct_pars['flexibility'] = (1e-3, 1e-16)\n",
    "cf_x_fluct_pars['asperity'] = (1e-3, 1e-16)\n",
    "cf_x_fluct_pars['loglogavgslope'] = (1e-3, 1e-16)"
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "vary_parameter('offset_mean', [3., 0., -2.])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
427
    "## The `offset_std` parameters of `CorrelatedFieldMaker.make()`\n",
428
429
430
431
    "\n",
    "Variation of the global offset of the field are modelled as being log-normally distributed.\n",
    "See `The Moment-Matched Log-Normal Distribution` above for details.\n",
    "\n",
432
433
    "The `offset_std[0]` parameter sets how much NIFTy will vary the offset *on average*.\\\n",
    "The `offset_std[1]` parameters defines the with and shape of the offset variation distribution.\n",
434
    "\n",
435
    "#### `offset_std` mean:"
436
437
438
439
440
441
442
443
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
444
    "vary_parameter('offset_std', [(1e-16, 1e-16), (0.5, 1e-16), (2., 1e-16)], samples_vary_in='xi')"
445
446
447
448
449
450
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
451
    "#### `offset_std` std:"
452
453
454
455
456
457
458
459
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
460
    "vary_parameter('offset_std', [(1., 0.01), (1., 0.1), (1., 1.)], samples_vary_in='zeromode')"
461
462
463
464
465
466
467
468
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
469
470
471
472
473
474
475
476
477
478
479
480
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.2"
481
482
483
484
485
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}