diff --git a/notebooks/cookbooks/model.ipynb b/notebooks/cookbooks/model.ipynb index e61a8caf..cfa2018c 100644 --- a/notebooks/cookbooks/model.ipynb +++ b/notebooks/cookbooks/model.ipynb @@ -202,6 +202,27 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also draw the model, via `af.ModelPlotter`. The figure is the **map** of a model and the `info` above is its \n", + "**legend**: the map shows the structure, meaning which component owns which parameter and which of those parameters \n", + "are fixed, shared, related to one another or constrained, whereas the `info` lists the priors and values themselves.\n", + "\n", + "This first model is the simplest map there is, a single `Gaussian` card carrying one pill per free parameter, and it \n", + "is the baseline every customization below is drawn against." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -451,12 +472,8 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "We can also draw the model, via `af.ModelPlotter`. The figure is the **map** of a model and the `info` above is its \n", - "**legend**: the map shows the structure, meaning which component owns which parameter and which of those parameters \n", - "are fixed, shared, related to one another or constrained, whereas the `info` lists the priors and values themselves.\n", - "\n", - "Customization is where the map earns its place, because linking a parameter to another or adding an assertion changes \n", - "a model's structure and not just its numbers. The `centre` pill states the expression `centre = normalization + sigma` \n", + "Customization is where the model figure earns its place, because linking a parameter to another or adding an \n", + "assertion changes a model's structure and not just its numbers. The `centre` pill states the expression `centre = normalization + sigma` \n", "that defines it and the assertions are drawn as constraints, which the `info` above does not print at all." ] }, @@ -685,6 +702,23 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The model loaded back from the `.json` file is a single `Gaussian` again, and its map is the one the file was written \n", + "from, which is the quickest check that a round trip through hard disk preserved the structure and not just the values." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -770,6 +804,24 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A `Collection` is drawn as one card per component, so the `Gaussian` and `Exponential` sit side by side and the footer \n", + "counts the six free parameters they have between them. Each card is titled by the key (`gaussian`, `exponential`) used \n", + "to access that component on an instance, which is the naming the list-based API further below gives up." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -939,6 +991,24 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Fixing `normalization` and `centre` and adding an assertion changes the structure and not just the numbers, so the map \n", + "changes with it: the fixed parameters are greyed out on their cards and the assertion is drawn as a constraint on \n", + "the `Exponential`." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -965,6 +1035,23 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This is the same model composed a different way, so it is the same map. The figure is a statement about the model and \n", + "not about the API used to build it, which makes it the quickest way to confirm two composition styles are equivalent." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -1130,7 +1217,24 @@ "metadata": {}, "source": [ "model = af.Collection(gaussian_0=Gaussian, gaussian_1=Gaussian)\n", - "print(model.info)\n", + "print(model.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Two `Gaussian`'s given different keys are drawn as two cards titled `gaussian_0` and `gaussian_1`, whose parameters \n", + "are marked `independent`, meaning one prior per card." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()\n", "\n", "model_dict = {\"gaussian_0\": Gaussian, \"gaussian_1\": Gaussian}\n", "model = af.Collection(**model_dict)\n", @@ -1139,6 +1243,22 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The dictionary form builds exactly the same model, so the map is unchanged; only the code that made it moved." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -1185,6 +1305,23 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Passing a list rather than keyword arguments leaves the components unnamed, and the map says so: the cards are titled \n", + "by their index in the list, which is why the `instance` below can only be accessed by indexing." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -1277,6 +1414,23 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "An `af.Array` is drawn as a single card whose pills are the elements of the array, titled by their index, so \n", + "a `shape=(2,2)` array is four pills and the footer counts the four free parameters they make." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -1319,6 +1473,23 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Customizing the prior of individual elements does not change the shape of the array, so the map is unchanged; only \n", + "the legend moved." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -1421,6 +1592,24 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here the customization is structural rather than numerical, and all three kinds of it appear on one card: the fixed \n", + "element is greyed out, the element set equal to another states that relation on its pill, and the assertion is drawn \n", + "as a constraint. The `info` above prints none of the three as structure." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -1530,6 +1719,23 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Combining the two gives one card per kind of component, the `Gaussian` with its named pills beside the array with its \n", + "indexed ones, and the fixed `sigma` and `[0, 0]` element greyed out on each." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, diff --git a/notebooks/cookbooks/multi_level_model.ipynb b/notebooks/cookbooks/multi_level_model.ipynb index 1d88f9f6..d2ff13ff 100644 --- a/notebooks/cookbooks/multi_level_model.ipynb +++ b/notebooks/cookbooks/multi_level_model.ipynb @@ -202,6 +202,28 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also draw the model, via `af.ModelPlotter`. The figure is the **map** of a model and the `info` above is its \n", + "**legend**: the map shows the structure, meaning which component owns which parameter and which of those parameters \n", + "are fixed, shared, related to one another or constrained, whereas the `info` lists the priors and values themselves.\n", + "\n", + "A multi-level model is drawn as containment: the `higher_level_centre` sits on the outer `MultiLevelGaussians` card \n", + "whereas the two `Gaussian`'s sit inside the `gaussian_list` frame nested within it. That hierarchy is the reason to \n", + "use a multi-level model, and the `info` above can only express it as indentation." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -323,9 +345,7 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "The model figure draws this hierarchy as containment. The figure is the **map** of a model and the `info` above is its \n", - "**legend**: the map shows the structure, meaning which component owns which parameter and which of those parameters \n", - "are fixed, shared, related to one another or constrained, whereas the `info` lists the priors and values themselves.\n", + "The model figure draws this hierarchy as containment.\n", "\n", "Each group's `higher_level_centre` sits in the outer `MultiLevelGaussians` card whereas its `Gaussian`s sit inside \n", "the `gaussian_list` frame nested within it, which is exactly the reason to use a multi-level model, drawn rather than \n", @@ -632,6 +652,23 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The model loaded back from the `.json` file is a single `Gaussian` again, and its map is the one the file was written \n", + "from, which is the quickest check that the round trip through hard disk preserved the structure." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, diff --git a/notebooks/cookbooks/result.ipynb b/notebooks/cookbooks/result.ipynb index 83d766e3..03e919bb 100644 --- a/notebooks/cookbooks/result.ipynb +++ b/notebooks/cookbooks/result.ipynb @@ -597,6 +597,30 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also draw a loaded model, via `af.ModelPlotter`. The figure is the **map** of a model and the `info` above is \n", + "its **legend**: the map shows the structure, meaning which component owns which parameter and which of those \n", + "parameters are fixed, shared, related to one another or constrained, whereas the `info` lists the priors and values \n", + "themselves.\n", + "\n", + "The three datasets were fitted with the same model, so the three loaded models share one structure and one figure \n", + "stands for all of them. It is therefore drawn once here, for the last model the generator returned, rather than \n", + "inside the loop above. That its map is the `gaussian` card composed at the top of this script is the check that the \n", + "model came back off hard disk intact." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, diff --git a/notebooks/features/expectation_propagation.ipynb b/notebooks/features/expectation_propagation.ipynb index 59787edd..8304b9ae 100644 --- a/notebooks/features/expectation_propagation.ipynb +++ b/notebooks/features/expectation_propagation.ipynb @@ -233,6 +233,49 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To inspect the global model the EP fit will approximate, we print `factor_graph.global_prior_model.info`." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "print(factor_graph.global_prior_model.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also draw this global model, via `af.ModelPlotter`. The figure is the **map** of a model and the `info` above\n", + "is its **legend**: the map shows the structure, meaning which dataset gets which component and which parameters are\n", + "shared between them, whereas the `info` lists the priors and values themselves.\n", + "\n", + "The shared `centre` is what makes this a graphical model rather than three independent fits, and the map says so\n", + "directly: the three datasets collapse into one dashed plate badged with the number of datasets, `centre` is hoisted\n", + "out of the plate into a card of its own with the plate linked back to it, and `normalization` and `sigma` stay inside\n", + "the plate marked `independent`, meaning one prior per dataset. The `info` above can only express the sharing by\n", + "grouping `centre` under a `0 - 2` heading.\n", + "\n", + "This is the model. The factor graph EP actually sweeps is a different object, with a node per factor and a node per\n", + "prior, and it is drawn after the fit below." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(factor_graph.global_prior_model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -464,11 +507,52 @@ " ep_history=af.EPHistory(kl_tol=0.05),\n", " # updater=af.SimplerUpdater(delta=0.7), # Optional; no damping by default.\n", " max_steps=5,\n", + " visualise_interval=1, # Refresh the EP state figure every sweep (default 100).\n", ")" ], "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Seeing The Sweep__\n", + "\n", + "`af.EPPlotter` draws the factor graph the optimiser swept with what the run did painted onto it, which turns the\n", + "failure mode this script exists to explain into something you look at rather than something you infer: a factor whose\n", + "update is rejected every sweep, whose reported posterior is therefore the message it started with.\n", + "\n", + "The graph itself is the structure. Boxes are factors, pills are variables, and a line between them is\n", + "an incidence, meaning this variable is one of that factor's arguments. Datasets fitted by identically shaped factors\n", + "collapse into a dashed plate badged with how many of them it stands for, exactly as on the model figure above, and a\n", + "plate never hides a member that departs from the aggregate: it names that member and draws it as a node of its own\n", + "beside the plate.\n", + "\n", + "The state is the overlay, and it is what `graph.info` cannot give you. Each factor carries how many updates it took\n", + "over how many sweeps, how many sweeps ago it last moved (its update age), and its status: **working**, **converged**\n", + "in green from the same KL test `EPHistory` stops the fit on, and **stale** in grey, meaning the factor completed\n", + "sweeps and none of them updated it, which is the condition the optimiser prints as its `STALE FACTORS` warning.\n", + "A **reverted** update is a dashed red edge, marking a `(factor, variable)` pair whose projection was confirmed\n", + "rejected -- a stronger statement than a message that merely happens not to have moved.\n", + "\n", + "We pass `factor_graph_result.factor_graph`, which is the graph the optimiser actually swept and the one\n", + "`factor_graph_result.ep_history` is keyed by. Never pass `factor_graph.graph`: that property builds a fresh graph,\n", + "renaming every prior factor as it goes, on every access, so the history would match nothing on it. Passing\n", + "`kind=\"model\"` instead draws the structure alone and needs no history." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.EPPlotter(\n", + " factor_graph_result.factor_graph, ep_history=factor_graph_result.ep_history\n", + ").figure(kind=\"state\")" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -544,6 +628,14 @@ "\n", " - `graph.results`: the current mean-field summary.\n", "\n", + " - `graph_model.png`: the factor graph drawn as structure alone, written once at the start of the run.\n", + "\n", + " - `graph_state.png`: the same graph with the state overlay described above, rewritten every `visualise_interval`\n", + " sweeps (every sweep, for the fit above) so the file on disk always shows the sweep that just finished.\n", + "\n", + "Both PNGs are written only when `model_figure: true` in the workspace's `config/output.yaml`, which is `false` by\n", + "default.\n", + "\n", "__Wrap Up__\n", "\n", "You have now run every statistical step of EP by hand: the mean-field approximation, the cavity, the tilted fit,\n", diff --git a/notebooks/features/model_comparison.ipynb b/notebooks/features/model_comparison.ipynb index 02a77d00..96239d57 100644 --- a/notebooks/features/model_comparison.ipynb +++ b/notebooks/features/model_comparison.ipynb @@ -229,6 +229,27 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also draw the model, via `af.ModelPlotter`. The figure is the **map** of a model and the `info` above is its \n", + "**legend**: the map shows the structure, meaning which component owns which parameter and which of those parameters \n", + "are fixed, shared, related to one another or constrained, whereas the `info` lists the priors and values themselves.\n", + "\n", + "Model comparison is the clearest case for reading the map before the legend, because the three models fitted below \n", + "differ only in how many `Gaussian` cards they carry. This first one is a single card of three free parameters." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -399,6 +420,23 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The second model is the same card drawn twice, `gaussian_0` and `gaussian_1`, and the footer counts six free \n", + "parameters instead of three. That increase in complexity is what the Bayesian evidence computed below has to pay for." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -548,6 +586,23 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The third model adds a third card and three more free parameters. Putting the three figures side by side states \n", + "exactly what is being compared: the same component, repeated one more time each fit." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, diff --git a/notebooks/features/search_chaining.ipynb b/notebooks/features/search_chaining.ipynb index 99e4988e..83472574 100644 --- a/notebooks/features/search_chaining.ipynb +++ b/notebooks/features/search_chaining.ipynb @@ -273,6 +273,27 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also draw the model, via `af.ModelPlotter`. The figure is the **map** of a model and the `info` above is its \n", + "**legend**: the map shows the structure, meaning which component owns which parameter and which of those parameters \n", + "are fixed, shared, related to one another or constrained, whereas the `info` lists the priors and values themselves.\n", + "\n", + "Search chaining is a sequence of models, so keep this first map in mind: one `gaussian_left` card of three free \n", + "parameters, fitted to the left half of the data." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model_1).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -414,6 +435,24 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The map now has two cards but only `gaussian_right` is free: every parameter of `gaussian_left` was passed as \n", + "an `instance` and is drawn greyed out as a fixed value, which is why the footer still counts three free parameters \n", + "and not six. Passing a result as an instance is a statement about structure, and the map is where it shows." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model_2).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -542,6 +581,24 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Both cards are free again, so the map is back to six free parameters and the difference from the first two searches \n", + "is in the legend: the priors are now the `TruncatedGaussianPrior`'s passed from `result_1` and `result_2` rather than \n", + "the defaults loaded from the config files." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model_3).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -800,6 +857,24 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Prior passing is the case where the map and the legend say the most different things. The `gaussian` card is greyed \n", + "out because it was passed as an `instance`, whereas the `exponential` card stays free because it was passed as \n", + "a `model`, so the three free and three fixed parameters described above are visible at a glance." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -869,6 +944,24 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Passing individual parameters rather than whole components gives the same two cards with the greying now inside them: \n", + "each card mixes fixed pills with free ones, exactly as the parameters were passed above. The map has the same shape \n", + "as the one before it; only which pills are fixed has moved." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, diff --git a/notebooks/features/search_grid_search.ipynb b/notebooks/features/search_grid_search.ipynb index c8ec7e32..929258c0 100644 --- a/notebooks/features/search_grid_search.ipynb +++ b/notebooks/features/search_grid_search.ipynb @@ -234,6 +234,27 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also draw the model, via `af.ModelPlotter`. The figure is the **map** of a model and the `info` above is its \n", + "**legend**: the map shows the structure, meaning which component owns which parameter and which of those parameters \n", + "are fixed, shared, related to one another or constrained, whereas the `info` lists the priors and values themselves.\n", + "\n", + "The grid search below steps over one pill of this map, `gaussian_feature.centre`, whilst every other parameter on the \n", + "figure is fitted by a non-linear search at each cell of the grid." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, diff --git a/notebooks/overview/overview_1_the_basics.ipynb b/notebooks/overview/overview_1_the_basics.ipynb index c84e1452..758fc438 100644 --- a/notebooks/overview/overview_1_the_basics.ipynb +++ b/notebooks/overview/overview_1_the_basics.ipynb @@ -348,6 +348,27 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also draw the model, via `af.ModelPlotter`. The figure is the **map** of a model and the `info` above is its \n", + "**legend**: the map shows the structure, meaning which component owns which parameter and which of those parameters \n", + "are fixed, shared, related to one another or constrained, whereas the `info` lists the priors and values themselves.\n", + "\n", + "This model is the simplest map there is, one `Gaussian` card carrying one pill per free parameter, with the footer \n", + "counting the three parameters a non-linear search will fit for." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -383,6 +404,22 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Updating priors changes values and not structure, so the map is unchanged; only the legend moved." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -872,6 +909,25 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Fitting two datasets copies the model once per dataset, and the map shows the copies: one `Gaussian` card per \n", + "`AnalysisFactor`, with their parameters marked `independent` because each dataset has priors of its own. Tying a \n", + "parameter across datasets, by sharing one prior object between the copies, would appear here as a shared badge, which \n", + "is how you check that a global fit is really global." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(factor_graph.global_prior_model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -1117,6 +1173,24 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A `Collection` is drawn as one card per component, so the `Gaussian` and the `Exponential` sit side by side and the \n", + "footer counts the six free parameters the search will fit for. The priors customized above are values, so they are in \n", + "the legend and not on the map." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, diff --git a/notebooks/searches/start_point.ipynb b/notebooks/searches/start_point.ipynb index 2936343d..49efd38d 100644 --- a/notebooks/searches/start_point.ipynb +++ b/notebooks/searches/start_point.ipynb @@ -214,7 +214,28 @@ "cell_type": "code", "metadata": {}, "source": [ - "print(model.info)\n" + "print(model.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also draw the model, via `af.ModelPlotter`. The figure is the **map** of a model and the `info` above is its \n", + "**legend**: the map shows the structure, meaning which component owns which parameter and which of those parameters \n", + "are fixed, shared, related to one another or constrained, whereas the `info` lists the priors and values themselves.\n", + "\n", + "The customized priors are values rather than structure, so they appear in the legend above and not on the map, which \n", + "is one `Gaussian` card of three free pills." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()\n" ], "outputs": [], "execution_count": null @@ -263,6 +284,24 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A start point is a property of the search's initializer and not of the model, so neither the map nor the legend \n", + "changed: this is the same figure drawn above, which is the quickest confirmation that setting start points has not \n", + "quietly altered the priors." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, diff --git a/scripts/cookbooks/model.py b/scripts/cookbooks/model.py index bc47ba55..66073596 100644 --- a/scripts/cookbooks/model.py +++ b/scripts/cookbooks/model.py @@ -108,6 +108,16 @@ def __init__( """ print(model.info) +""" +We can also draw the model, via `af.ModelPlotter`. The figure is the **map** of a model and the `info` above is its +**legend**: the map shows the structure, meaning which component owns which parameter and which of those parameters +are fixed, shared, related to one another or constrained, whereas the `info` lists the priors and values themselves. + +This first model is the simplest map there is, a single `Gaussian` card carrying one pill per free parameter, and it +is the baseline every customization below is drawn against. +""" +af.ModelPlotter(model).figure() + """ __Priors (Model)__ @@ -233,12 +243,8 @@ def __init__( print(model.info) """ -We can also draw the model, via `af.ModelPlotter`. The figure is the **map** of a model and the `info` above is its -**legend**: the map shows the structure, meaning which component owns which parameter and which of those parameters -are fixed, shared, related to one another or constrained, whereas the `info` lists the priors and values themselves. - -Customization is where the map earns its place, because linking a parameter to another or adding an assertion changes -a model's structure and not just its numbers. The `centre` pill states the expression `centre = normalization + sigma` +Customization is where the model figure earns its place, because linking a parameter to another or adding an +assertion changes a model's structure and not just its numbers. The `centre` pill states the expression `centre = normalization + sigma` that defines it and the assertions are drawn as constraints, which the `info` above does not print at all. """ af.ModelPlotter(model).figure() @@ -351,6 +357,12 @@ def __init__( print(model.info) +""" +The model loaded back from the `.json` file is a single `Gaussian` again, and its map is the one the file was written +from, which is the quickest check that a round trip through hard disk preserved the structure and not just the values. +""" +af.ModelPlotter(model).figure() + """ __Model Composition (Collection)__ @@ -393,6 +405,13 @@ def __init__( """ print(model.info) +""" +A `Collection` is drawn as one card per component, so the `Gaussian` and `Exponential` sit side by side and the footer +counts the six free parameters they have between them. Each card is titled by the key (`gaussian`, `exponential`) used +to access that component on an instance, which is the naming the list-based API further below gives up. +""" +af.ModelPlotter(model).figure() + """ __Priors (Collection)__ @@ -485,6 +504,13 @@ def __init__( print(model.info) +""" +Fixing `normalization` and `centre` and adding an assertion changes the structure and not just the numbers, so the map +changes with it: the fixed parameters are greyed out on their cards and the assertion is drawn as a constraint on +the `Exponential`. +""" +af.ModelPlotter(model).figure() + """ Below is an alternative API that can be used to create the same model as above. @@ -500,6 +526,12 @@ def __init__( print(model.info) +""" +This is the same model composed a different way, so it is the same map. The figure is a statement about the model and +not about the API used to build it, which makes it the quickest way to confirm two composition styles are equivalent. +""" +af.ModelPlotter(model).figure() + """ After creating the model as a `Collection` we can customize it afterwards: """ @@ -583,10 +615,21 @@ def __init__( model = af.Collection(gaussian_0=Gaussian, gaussian_1=Gaussian) print(model.info) +""" +Two `Gaussian`'s given different keys are drawn as two cards titled `gaussian_0` and `gaussian_1`, whose parameters +are marked `independent`, meaning one prior per card. +""" +af.ModelPlotter(model).figure() + model_dict = {"gaussian_0": Gaussian, "gaussian_1": Gaussian} model = af.Collection(**model_dict) print(model.info) +""" +The dictionary form builds exactly the same model, so the map is unchanged; only the code that made it moved. +""" +af.ModelPlotter(model).figure() + """ The keys of the dictionary passed to the model (e.g. `gaussian_0` and `gaussian_1` above) are used to create the names of the attributes of instances of the model. @@ -611,6 +654,12 @@ def __init__( print(model.info) +""" +Passing a list rather than keyword arguments leaves the components unnamed, and the map says so: the cards are titled +by their index in the list, which is why the `instance` below can only be accessed by indexing. +""" +af.ModelPlotter(model).figure() + """ When a list is used, there is no string with which to name the model components (e.g. we do not input `gaussian_0` and `gaussian_1` anywhere. @@ -659,6 +708,12 @@ def __init__( """ print(model.info) +""" +An `af.Array` is drawn as a single card whose pills are the elements of the array, titled by their index, so +a `shape=(2,2)` array is four pills and the footer counts the four free parameters they make. +""" +af.ModelPlotter(model).figure() + """ __Prior Customization (af.Array)__ @@ -679,6 +734,12 @@ def __init__( """ print(model.info) +""" +Customizing the prior of individual elements does not change the shape of the array, so the map is unchanged; only +the legend moved. +""" +af.ModelPlotter(model).figure() + """ __Instances (af.Array)__ @@ -737,6 +798,13 @@ def __init__( print(model.info) +""" +Here the customization is structural rather than numerical, and all three kinds of it appear on one card: the fixed +element is greyed out, the element set equal to another states that relation on its pill, and the assertion is drawn +as a constraint. The `info` above prints none of the three as structure. +""" +af.ModelPlotter(model).figure() + """ __JSon Outputs (af.Array)__ @@ -802,6 +870,12 @@ def __init__( print(model.info) +""" +Combining the two gives one card per kind of component, the `Gaussian` with its named pills beside the array with its +indexed ones, and the fixed `sigma` and `[0, 0]` element greyed out on each. +""" +af.ModelPlotter(model).figure() + """ __Wrap Up__ diff --git a/scripts/cookbooks/multi_level_model.py b/scripts/cookbooks/multi_level_model.py index 5d7c6107..50527356 100644 --- a/scripts/cookbooks/multi_level_model.py +++ b/scripts/cookbooks/multi_level_model.py @@ -98,6 +98,17 @@ def __init__( """ print(model.info) +""" +We can also draw the model, via `af.ModelPlotter`. The figure is the **map** of a model and the `info` above is its +**legend**: the map shows the structure, meaning which component owns which parameter and which of those parameters +are fixed, shared, related to one another or constrained, whereas the `info` lists the priors and values themselves. + +A multi-level model is drawn as containment: the `higher_level_centre` sits on the outer `MultiLevelGaussians` card +whereas the two `Gaussian`'s sit inside the `gaussian_list` frame nested within it. That hierarchy is the reason to +use a multi-level model, and the `info` above can only express it as indentation. +""" +af.ModelPlotter(model).figure() + """ __Instances__ @@ -172,9 +183,7 @@ def __init__( print(model.info) """ -The model figure draws this hierarchy as containment. The figure is the **map** of a model and the `info` above is its -**legend**: the map shows the structure, meaning which component owns which parameter and which of those parameters -are fixed, shared, related to one another or constrained, whereas the `info` lists the priors and values themselves. +The model figure draws this hierarchy as containment. Each group's `higher_level_centre` sits in the outer `MultiLevelGaussians` card whereas its `Gaussian`s sit inside the `gaussian_list` frame nested within it, which is exactly the reason to use a multi-level model, drawn rather than @@ -353,6 +362,12 @@ def __init__(self, higher_level_centre=1.0, **kwargs): print(model.info) +""" +The model loaded back from the `.json` file is a single `Gaussian` again, and its map is the one the file was written +from, which is the quickest check that the round trip through hard disk preserved the structure. +""" +af.ModelPlotter(model).figure() + """ __Wrap Up__ diff --git a/scripts/cookbooks/result.py b/scripts/cookbooks/result.py index 8807e047..871652a5 100644 --- a/scripts/cookbooks/result.py +++ b/scripts/cookbooks/result.py @@ -405,6 +405,19 @@ def make_result( for model in model_gen: print(model.info) +""" +We can also draw a loaded model, via `af.ModelPlotter`. The figure is the **map** of a model and the `info` above is +its **legend**: the map shows the structure, meaning which component owns which parameter and which of those +parameters are fixed, shared, related to one another or constrained, whereas the `info` lists the priors and values +themselves. + +The three datasets were fitted with the same model, so the three loaded models share one structure and one figure +stands for all of them. It is therefore drawn once here, for the last model the generator returned, rather than +inside the loop above. That its map is the `gaussian` card composed at the top of this script is the check that the +model came back off hard disk intact. +""" +af.ModelPlotter(model).figure() + """ __Loading Search__ diff --git a/scripts/features/expectation_propagation.py b/scripts/features/expectation_propagation.py index 601dfe07..3eee4761 100644 --- a/scripts/features/expectation_propagation.py +++ b/scripts/features/expectation_propagation.py @@ -149,6 +149,27 @@ factor_graph = af.FactorGraphModel(*analysis_factor_list) +""" +To inspect the global model the EP fit will approximate, we print `factor_graph.global_prior_model.info`. +""" +print(factor_graph.global_prior_model.info) + +""" +We can also draw this global model, via `af.ModelPlotter`. The figure is the **map** of a model and the `info` above +is its **legend**: the map shows the structure, meaning which dataset gets which component and which parameters are +shared between them, whereas the `info` lists the priors and values themselves. + +The shared `centre` is what makes this a graphical model rather than three independent fits, and the map says so +directly: the three datasets collapse into one dashed plate badged with the number of datasets, `centre` is hoisted +out of the plate into a card of its own with the plate linked back to it, and `normalization` and `sigma` stay inside +the plate marked `independent`, meaning one prior per dataset. The `info` above can only express the sharing by +grouping `centre` under a `0 - 2` heading. + +This is the model. The factor graph EP actually sweeps is a different object, with a node per factor and a node per +prior, and it is drawn after the fit below. +""" +af.ModelPlotter(factor_graph.global_prior_model).figure() + """ __Mean Field__ @@ -306,8 +327,38 @@ ep_history=af.EPHistory(kl_tol=0.05), # updater=af.SimplerUpdater(delta=0.7), # Optional; no damping by default. max_steps=5, + visualise_interval=1, # Refresh the EP state figure every sweep (default 100). ) +""" +__Seeing The Sweep__ + +`af.EPPlotter` draws the factor graph the optimiser swept with what the run did painted onto it, which turns the +failure mode this script exists to explain into something you look at rather than something you infer: a factor whose +update is rejected every sweep, whose reported posterior is therefore the message it started with. + +The graph itself is the structure. Boxes are factors, pills are variables, and a line between them is +an incidence, meaning this variable is one of that factor's arguments. Datasets fitted by identically shaped factors +collapse into a dashed plate badged with how many of them it stands for, exactly as on the model figure above, and a +plate never hides a member that departs from the aggregate: it names that member and draws it as a node of its own +beside the plate. + +The state is the overlay, and it is what `graph.info` cannot give you. Each factor carries how many updates it took +over how many sweeps, how many sweeps ago it last moved (its update age), and its status: **working**, **converged** +in green from the same KL test `EPHistory` stops the fit on, and **stale** in grey, meaning the factor completed +sweeps and none of them updated it, which is the condition the optimiser prints as its `STALE FACTORS` warning. +A **reverted** update is a dashed red edge, marking a `(factor, variable)` pair whose projection was confirmed +rejected -- a stronger statement than a message that merely happens not to have moved. + +We pass `factor_graph_result.factor_graph`, which is the graph the optimiser actually swept and the one +`factor_graph_result.ep_history` is keyed by. Never pass `factor_graph.graph`: that property builds a fresh graph, +renaming every prior factor as it goes, on every access, so the history would match nothing on it. Passing +`kind="model"` instead draws the structure alone and needs no history. +""" +af.EPPlotter( + factor_graph_result.factor_graph, ep_history=factor_graph_result.ep_history +).figure(kind="state") + """ The result contains the converged mean field — the EP approximation to the joint posterior. Its `mean`, `variance` and `scale` dictionaries give the marginal posterior of every parameter; the shared centre's entry is the global @@ -358,6 +409,14 @@ - `graph.results`: the current mean-field summary. + - `graph_model.png`: the factor graph drawn as structure alone, written once at the start of the run. + + - `graph_state.png`: the same graph with the state overlay described above, rewritten every `visualise_interval` + sweeps (every sweep, for the fit above) so the file on disk always shows the sweep that just finished. + +Both PNGs are written only when `model_figure: true` in the workspace's `config/output.yaml`, which is `false` by +default. + __Wrap Up__ You have now run every statistical step of EP by hand: the mean-field approximation, the cavity, the tilted fit, diff --git a/scripts/features/model_comparison.py b/scripts/features/model_comparison.py index 5dd1b89f..38c9e88f 100644 --- a/scripts/features/model_comparison.py +++ b/scripts/features/model_comparison.py @@ -123,6 +123,16 @@ """ print(model.info) +""" +We can also draw the model, via `af.ModelPlotter`. The figure is the **map** of a model and the `info` above is its +**legend**: the map shows the structure, meaning which component owns which parameter and which of those parameters +are fixed, shared, related to one another or constrained, whereas the `info` lists the priors and values themselves. + +Model comparison is the clearest case for reading the map before the legend, because the three models fitted below +differ only in how many `Gaussian` cards they carry. This first one is a single card of three free parameters. +""" +af.ModelPlotter(model).figure() + """ Create the analysis which fits the model to the data. """ @@ -205,6 +215,12 @@ """ print(model.info) +""" +The second model is the same card drawn twice, `gaussian_0` and `gaussian_1`, and the footer counts six free +parameters instead of three. That increase in complexity is what the Bayesian evidence computed below has to pay for. +""" +af.ModelPlotter(model).figure() + """ We repeat the steps above to create the non-linear search and perform the model-fit. """ @@ -288,6 +304,12 @@ """ print(model.info) +""" +The third model adds a third card and three more free parameters. Putting the three figures side by side states +exactly what is being compared: the same component, repeated one more time each fit. +""" +af.ModelPlotter(model).figure() + """ We repeat the steps above to create the non-linear search and perform the model-fit. """ diff --git a/scripts/features/search_chaining.py b/scripts/features/search_chaining.py index 2c4dcf94..ad559d01 100644 --- a/scripts/features/search_chaining.py +++ b/scripts/features/search_chaining.py @@ -156,6 +156,16 @@ """ print(model_1.info) +""" +We can also draw the model, via `af.ModelPlotter`. The figure is the **map** of a model and the `info` above is its +**legend**: the map shows the structure, meaning which component owns which parameter and which of those parameters +are fixed, shared, related to one another or constrained, whereas the `info` lists the priors and values themselves. + +Search chaining is a sequence of models, so keep this first map in mind: one `gaussian_left` card of three free +parameters, fitted to the left half of the data. +""" +af.ModelPlotter(model_1).figure() + """ __Search 1__ @@ -231,6 +241,13 @@ """ print(model_2.info) +""" +The map now has two cards but only `gaussian_right` is free: every parameter of `gaussian_left` was passed as +an `instance` and is drawn greyed out as a fixed value, which is why the footer still counts three free parameters +and not six. Passing a result as an instance is a statement about structure, and the map is where it shows. +""" +af.ModelPlotter(model_2).figure() + """ We now run our second Dynesty search to fit the right `Gaussian`. @@ -304,6 +321,13 @@ """ print(model_3.info) +""" +Both cards are free again, so the map is back to six free parameters and the difference from the first two searches +is in the legend: the priors are now the `TruncatedGaussianPrior`'s passed from `result_1` and `result_2` rather than +the defaults loaded from the config files. +""" +af.ModelPlotter(model_3).figure() + """ We now perform the search. """ @@ -496,6 +520,13 @@ """ print(model.info) +""" +Prior passing is the case where the map and the legend say the most different things. The `gaussian` card is greyed +out because it was passed as an `instance`, whereas the `exponential` card stays free because it was passed as +a `model`, so the three free and three fixed parameters described above are visible at a glance. +""" +af.ModelPlotter(model).figure() + """ We can print the priors of the exponenital: """ @@ -532,6 +563,13 @@ """ print(model.info) +""" +Passing individual parameters rather than whole components gives the same two cards with the greying now inside them: +each card mixes fixed pills with free ones, exactly as the parameters were passed above. The map has the same shape +as the one before it; only which pills are fixed has moved. +""" +af.ModelPlotter(model).figure() + """ __Take Attributes__ diff --git a/scripts/features/search_grid_search.py b/scripts/features/search_grid_search.py index 1a8a7b6a..8a3c443d 100644 --- a/scripts/features/search_grid_search.py +++ b/scripts/features/search_grid_search.py @@ -128,6 +128,16 @@ """ print(model.info) +""" +We can also draw the model, via `af.ModelPlotter`. The figure is the **map** of a model and the `info` above is its +**legend**: the map shows the structure, meaning which component owns which parameter and which of those parameters +are fixed, shared, related to one another or constrained, whereas the `info` lists the priors and values themselves. + +The grid search below steps over one pill of this map, `gaussian_feature.centre`, whilst every other parameter on the +figure is fitted by a non-linear search at each cell of the grid. +""" +af.ModelPlotter(model).figure() + """ __Analysis__ diff --git a/scripts/overview/overview_1_the_basics.py b/scripts/overview/overview_1_the_basics.py index 9e5656f6..1e38f175 100644 --- a/scripts/overview/overview_1_the_basics.py +++ b/scripts/overview/overview_1_the_basics.py @@ -221,6 +221,16 @@ def fwhm(self) -> float: """ print(model.info) +""" +We can also draw the model, via `af.ModelPlotter`. The figure is the **map** of a model and the `info` above is its +**legend**: the map shows the structure, meaning which component owns which parameter and which of those parameters +are fixed, shared, related to one another or constrained, whereas the `info` lists the priors and values themselves. + +This model is the simplest map there is, one `Gaussian` card carrying one pill per free parameter, with the footer +counting the three parameters a non-linear search will fit for. +""" +af.ModelPlotter(model).figure() + """ The priors can be manually altered as follows, noting that these updated priors will be used below when we fit the model to data. @@ -234,6 +244,11 @@ def fwhm(self) -> float: """ print(model.info) +""" +Updating priors changes values and not structure, so the map is unchanged; only the legend moved. +""" +af.ModelPlotter(model).figure() + """ The example above uses the most basic PyAutoFit API to compose a simple model. The API is highly extensible and can scale to models with thousands of parameters, complex hierarchies and relationships between parameters. @@ -548,6 +563,14 @@ def log_likelihood_function(self, instance) -> float: """ print(factor_graph.global_prior_model.info) +""" +Fitting two datasets copies the model once per dataset, and the map shows the copies: one `Gaussian` card per +`AnalysisFactor`, with their parameters marked `independent` because each dataset has priors of its own. Tying a +parameter across datasets, by sharing one prior object between the copies, would appear here as a shared badge, which +is how you check that a global fit is really global. +""" +af.ModelPlotter(factor_graph.global_prior_model).figure() + """ To fit multiple datasets, we pass the `FactorGraphModel` to a non-linear search. @@ -717,6 +740,13 @@ def model_data_from(self, xvalues: np.ndarray, xp=np): """ print(model.info) +""" +A `Collection` is drawn as one card per component, so the `Gaussian` and the `Exponential` sit side by side and the +footer counts the six free parameters the search will fit for. The priors customized above are values, so they are in +the legend and not on the map. +""" +af.ModelPlotter(model).figure() + """ A model instance can again be created by mapping an input `vector`, which now has 6 entries. """ diff --git a/scripts/searches/start_point.py b/scripts/searches/start_point.py index 3dba874c..a3e98818 100644 --- a/scripts/searches/start_point.py +++ b/scripts/searches/start_point.py @@ -124,6 +124,16 @@ """ print(model.info) +""" +We can also draw the model, via `af.ModelPlotter`. The figure is the **map** of a model and the `info` above is its +**legend**: the map shows the structure, meaning which component owns which parameter and which of those parameters +are fixed, shared, related to one another or constrained, whereas the `info` lists the priors and values themselves. + +The customized priors are values rather than structure, so they appear in the legend above and not on the map, which +is one `Gaussian` card of three free pills. +""" +af.ModelPlotter(model).figure() + """ __Start Point__ @@ -147,6 +157,13 @@ """ print(model.info) +""" +A start point is a property of the search's initializer and not of the model, so neither the map nor the legend +changed: this is the same figure drawn above, which is the quickest confirmation that setting start points has not +quietly altered the priors. +""" +af.ModelPlotter(model).figure() + """ Information on the initializer can be extracted and printed, which is shown below, where the start points are clearly visible.