diff --git a/config/output.yaml b/config/output.yaml index d36a9e1..69cd826 100644 --- a/config/output.yaml +++ b/config/output.yaml @@ -99,4 +99,8 @@ covariance: true # `covariance.csv`: The [free parameters x free parameters] cov data: true # `data.json`: The value of every data point in the data. noise_map: true # `noise_map.json`: The value of every RMS noise map value. -search_log: true # `search.log`: logging produced whilst running the fit method \ No newline at end of file +search_log: true # `search.log`: logging produced whilst running the fit method + +# `model.png`: the model figure drawn beside `model.info` (af.ModelPlotter). Opt-in until the +# model-figures epic's phase-3 acceptance renders pass. Unlike other keys an absent key means off. +model_figure: false diff --git a/notebooks/chapter_1_introduction/tutorial_1_models.ipynb b/notebooks/chapter_1_introduction/tutorial_1_models.ipynb index fd4d8ee..d63e5c4 100644 --- a/notebooks/chapter_1_introduction/tutorial_1_models.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_1_models.ipynb @@ -327,6 +327,39 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The same model can also be drawn, via `af.ModelPlotter`.\n", + "\n", + "The figure and the `info` are two views of the same object, and it is worth being precise about the division of\n", + "labour between them. The figure is the **map**: it shows the structure of the model, meaning which component owns\n", + "which parameter and, in the models we build later, which parameters are fixed, shared between components, related to\n", + "one another by an expression or constrained by an assertion. The `info` is the **legend**: it lists the priors and\n", + "values themselves, the numbers that the map has no room for.\n", + "\n", + "For this first model the map is about as simple as a map gets. There is a single card, titled `model` and `Gaussian`\n", + "after the class it was composed from, holding one pill per parameter: `centre`, `normalization` and `sigma`. The\n", + "footer counts them for you, `3 unique sampled scalars`, which is the same number the `total_free_parameters`\n", + "attribute printed above. Read the card as the answer to \"what is this model made of?\", and the `info` above it as the\n", + "answer to \"and what values may each of those parts take?\".\n", + "\n", + "Right now both views fit on one screen and the figure may look like a redundant restatement of the `info`. Draw it\n", + "anyway, because the two views scale very differently. By the end of this chapter our models have five components, in\n", + "chapter 3 they span five datasets at once, and at that point the `info` runs to hundreds of lines whilst the map\n", + "still fits in a glance." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -561,6 +594,25 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Drawing the model shows what a `Collection` does to the map. There are now two cards side by side,\n", + "`gaussian` and `exponential`, each titled with the class it was composed from and each owning its own pills, and the\n", + "footer counts `6 unique sampled scalars` across the pair. Components sit beside one another, and nothing yet joins\n", + "them: the two `centre` parameters are separate parameters that happen to share a name." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -596,6 +648,25 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The figure is identical to the previous one too, and that is the point worth taking from this example. The two ways\n", + "of writing the composition look different on the page, but they build the same structure, and structure is all the\n", + "map draws. Whenever you change how a model is written, draw it: if the map does not move then nothing about the model\n", + "moved either, and any difference between the two fits has to be hiding in the legend rather than in the model." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -764,6 +835,25 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The map shows how a tuple is handled. `centre` is still drawn as one pill, because it is one input argument of the\n", + "`Gaussian2D` class, but it now carries a `2D` badge marking it as a tuple, and the footer counts `4 unique sampled\n", + "scalars` rather than 3. The `paths` printed below unpack that badge into the two entries, one per coordinate, which\n", + "the input vector must supply." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, diff --git a/notebooks/chapter_1_introduction/tutorial_3_non_linear_search.ipynb b/notebooks/chapter_1_introduction/tutorial_3_non_linear_search.ipynb index a39ea4c..bfe0963 100644 --- a/notebooks/chapter_1_introduction/tutorial_3_non_linear_search.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_3_non_linear_search.ipynb @@ -358,6 +358,30 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "As in tutorial 1, the model can also be drawn via `af.ModelPlotter`. The figure is the **map** of the model, showing\n", + "its structure, meaning which component owns which parameter, and the `info` above is its **legend**, listing the\n", + "prior placed on each of those parameters.\n", + "\n", + "The map here is the single card we drew in tutorial 1, with a pill for `centre`, `normalization` and `sigma` and a\n", + "footer counting `3 unique sampled scalars`. Those three scalars are exactly the three dimensions of the parameter\n", + "space that the non-linear search is about to explore, so the card is a picture of how large the search's job is. The\n", + "priors discussed below are the legend for that map: they do not change its shape, they set how far along each of its\n", + "three axes the search is allowed to wander." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, diff --git a/notebooks/chapter_1_introduction/tutorial_4_why_modeling_is_hard.ipynb b/notebooks/chapter_1_introduction/tutorial_4_why_modeling_is_hard.ipynb index 45d83bc..997d266 100644 --- a/notebooks/chapter_1_introduction/tutorial_4_why_modeling_is_hard.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_4_why_modeling_is_hard.ipynb @@ -434,6 +434,35 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Drawing the model makes the jump in complexity easier to see than counting lines of `info` does. The figure is the\n", + "**map** of the model, showing its structure, and the `info` above is the **legend**, listing the priors on every\n", + "parameter.\n", + "\n", + "The five `Gaussian`'s do not appear as five separate cards. Because they are the same component repeated with the\n", + "same priors, they collapse into a single dashed frame badged `5 components` and subtitled `gaussian_0 - gaussian_4`,\n", + "inside which `centre`, `normalization` and `sigma` are each drawn once and badged `independent`, meaning one prior per\n", + "member rather than one prior shared between the members. The legend line below the figure spells that convention\n", + "out, `independent = one prior per member` and `dashed frame = repeated components`, and the footer does the\n", + "arithmetic: `15 unique sampled scalars`, `0 shared priors` and `1 plate standing for 5 components`.\n", + "\n", + "That footer is the difficulty of this tutorial stated in one line. Tutorial 3 searched 3 dimensions; this search has\n", + "15 of them, and parameter space grows in volume so quickly with that number that the same search which comfortably\n", + "found the single `Gaussian` is about to struggle." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -764,6 +793,25 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The map is worth drawing again precisely because it has not changed: the same dashed frame badged `5 components`, the\n", + "same three `independent` pills, the same `15 unique sampled scalars` in the footer. Tuning the priors moved the\n", + "legend, not the map. We are still fitting the same 15 parameter model, we have simply told the search a smaller\n", + "region of it to look in." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -918,6 +966,28 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This time the map itself changes, and it changes in one pill. The `centre` pill inside the frame is now badged\n", + "`shared across group` instead of `independent`, the legend below gains the entry `blue badge = shared prior`, and the\n", + "footer reads `11 unique sampled scalars` and `1 shared prior` where before it read 15 and none.\n", + "\n", + "That is the difference between the two approaches drawn side by side. Tuning the priors left the map alone and\n", + "narrowed the legend; assuming a shared `centre` shrinks the map itself, because four of its parameters have stopped\n", + "existing." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -1058,6 +1128,25 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The map is back where it started: one dashed frame badged `5 components`, three `independent` pills, no shared badge\n", + "anywhere and `15 unique sampled scalars` in the footer. Approaches 1 and 2 each changed something that the map or its\n", + "legend could show. This third approach changes neither, because searching parameter space more thoroughly is a\n", + "property of the search, not of the model." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, diff --git a/notebooks/chapter_1_introduction/tutorial_7_the_details.ipynb b/notebooks/chapter_1_introduction/tutorial_7_the_details.ipynb index 0bfa242..3a87180 100644 --- a/notebooks/chapter_1_introduction/tutorial_7_the_details.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_7_the_details.ipynb @@ -375,6 +375,28 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Draw the model and the problem is already on the page. The figure is the **map** of the model, showing its structure,\n", + "and the `info` above is the **legend**, listing the priors.\n", + "\n", + "The two `Gaussian`'s do not get a card each. Because they are the same component carrying identical priors, they\n", + "collapse into a single dashed frame badged `2 components` and subtitled `gaussian_0 - gaussian_1`, with one\n", + "`independent` pill per parameter. The figure is drawn that way because there is genuinely nothing in the model that\n", + "tells the two apart, which is exactly the property the next few cells are about to exploit." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, diff --git a/notebooks/chapter_1_introduction/tutorial_optional_bayesian_formalism.ipynb b/notebooks/chapter_1_introduction/tutorial_optional_bayesian_formalism.ipynb index fcd6463..6c27411 100644 --- a/notebooks/chapter_1_introduction/tutorial_optional_bayesian_formalism.ipynb +++ b/notebooks/chapter_1_introduction/tutorial_optional_bayesian_formalism.ipynb @@ -392,7 +392,30 @@ "cell_type": "code", "metadata": {}, "source": [ - "print(model.info)\n", + "print(model.info)" + ], + "outputs": [], + "execution_count": null + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The model can also be drawn, via `af.ModelPlotter`. The figure is the **map** of the model, showing its structure,\n", + "meaning which component owns which parameter, and the `info` above is the **legend**, naming the prior on each of\n", + "them.\n", + "\n", + "Read against the formalism of this tutorial the map has a precise meaning: the pills on the card are the entries of\n", + "the parameter vector, the footer's `3 unique sampled scalars` is its dimension, and the sum over j in the expression\n", + "above runs over exactly those pills. The prior is one distribution per pill, and the legend is where their names and\n", + "limits live." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(model).figure()\n", "\n", "print(\"Log prior of each parameter, theta = [50.0, 25.0, 10.0]:\")\n", "print(model.log_prior_list_from_vector(vector=[50.0, 25.0, 10.0]))\n", diff --git a/notebooks/chapter_3_graphical_models/tutorial_3_graphical_benefits.ipynb b/notebooks/chapter_3_graphical_models/tutorial_3_graphical_benefits.ipynb index 58cb806..ee54e77 100644 --- a/notebooks/chapter_3_graphical_models/tutorial_3_graphical_benefits.ipynb +++ b/notebooks/chapter_3_graphical_models/tutorial_3_graphical_benefits.ipynb @@ -545,6 +545,35 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Drawing this model next to tutorial 2's figure shows what the second shared parameter bought us. The figure is the\n", + "**map** of the model, showing which dataset gets which components and which parameters are shared between them, and\n", + "the `info` above is the **legend** of priors.\n", + "\n", + "Two things have changed. The hoisted card at the top is titled `shared across datasets` and subtitled `one value\n", + "across 5 datasets`, and it now holds two `centre` pills rather than one, because each of the two `Gaussian`'s has its\n", + "own shared `centre`. Below it, every dataset is drawn as its own card, `0` through `4`, each containing a\n", + "`gaussian_0` and a `gaussian_1`, and inside them the `centre` pill carries a blue `shared` badge with a line running\n", + "back up to the hoisted card. The `normalization` and `sigma` pills carry no badge and no line, because those\n", + "parameters belong to their own dataset alone.\n", + "\n", + "The footer draws the dimensionality claim made above rather than asserting it: `2 shared across datasets`,\n", + "`4 per dataset \u00d7 5 datasets`, `22 unique sampled scalars`. That is the N=22 of the text, and the map shows where each\n", + "of those numbers comes from." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(factor_graph.global_prior_model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, diff --git a/notebooks/chapter_3_graphical_models/tutorial_5_expectation_propagation.ipynb b/notebooks/chapter_3_graphical_models/tutorial_5_expectation_propagation.ipynb index 8edc053..764bf47 100644 --- a/notebooks/chapter_3_graphical_models/tutorial_5_expectation_propagation.ipynb +++ b/notebooks/chapter_3_graphical_models/tutorial_5_expectation_propagation.ipynb @@ -359,6 +359,33 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Drawing the model shows the graph that EP is about to sweep. The figure is the **map**, showing which dataset gets\n", + "which components and what joins them, and the `info` above is the **legend** of priors.\n", + "\n", + "There are four cards. The first three, `0` to `2`, are the `AnalysisFactor`'s, one per dataset, each holding a\n", + "`gaussian` card with its `centre`, `normalization` and `sigma` pills. The fourth card, numbered `3`, is the\n", + "`linear_regression` factor, and its pills are drawn in orange rather than as plain free priors because they are not\n", + "free parameters at all: each one shows the expression it is computed from, a constant times that dataset's\n", + "`gaussian.sigma`, which is the FWHM we built out of `fwhm_list` above. The legend names this kind of pill,\n", + "`relation (expression shown)`, and a line runs from each dataset's `sigma` into the relation built on it.\n", + "\n", + "Those lines are the thing to hold on to for the rest of the tutorial. EP never fits this whole map in one go. It\n", + "visits one card at a time, and the lines drawn here are the paths its messages travel along." + ] + }, + { + "cell_type": "code", + "metadata": {}, + "source": [ + "af.ModelPlotter(factor_graph.global_prior_model).figure()" + ], + "outputs": [], + "execution_count": null + }, { "cell_type": "markdown", "metadata": {}, @@ -398,7 +425,12 @@ "produce the same estimate of the shared parameter `centre`. \n", "\n", "When we fit the factor graph a `name` is passed, which determines the folder all results of the factor graph are\n", - "stored in." + "stored in.\n", + "\n", + "We also pass `visualise_interval=1`. The EP fit draws the factor graph with the state of the run painted onto it and\n", + "writes it to the output folder, and this input sets how many sweeps pass between refreshes of that figure. Its\n", + "default is 100, which over the 5 sweeps below would draw it exactly once, so we set it to 1 and get a fresh picture\n", + "of the graph after every sweep." ] }, { @@ -408,7 +440,11 @@ "laplace = af.LaplaceOptimiser()\n", "\n", "factor_graph_result = factor_graph.optimise(\n", - " optimiser=laplace, paths=paths, ep_history=af.EPHistory(kl_tol=0.05), max_steps=5\n", + " optimiser=laplace,\n", + " paths=paths,\n", + " ep_history=af.EPHistory(kl_tol=0.05),\n", + " max_steps=5,\n", + " visualise_interval=1,\n", ")" ], "outputs": [], @@ -434,6 +470,62 @@ "outputs": [], "execution_count": null }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "__Seeing the EP run__\n", + "\n", + "Until that `info` exists, the figure is how we read an EP fit back. `af.EPPlotter` draws the same factor graph as\n", + "before, but now with the state of the run painted onto it.\n", + "\n", + "The graph it draws is not the map we drew earlier, it is the factor graph itself, and its legend says how to read\n", + "it: `box = factor`, `pill = variable`, `dashed frame = repeated structure`. Every `AnalysisFactor` is a box, every\n", + "parameter it touches is a pill, and an edge between them means \"this factor has something to say about this\n", + "variable\". That is the picture the message passing above lives on: a message leaves a box, arrives at a pill, and is\n", + "read by every other box attached to it. The three datasets sit inside a dashed plate badged `3 datasets`, drawn once\n", + "as an aggregate `AnalysisFactor` box, with the individual `dataset_0`, `dataset_1` and `dataset_2` boxes expanded\n", + "alongside it because their states differ from one another.\n", + "\n", + "Onto that structure the `ep_history` paints what the sweeps actually did. Every box carries a status:\n", + "\n", + " - `working`: it is updating, nothing was rejected, and it has not yet converged.\n", + " - `converged`, drawn green: the `EPHistory` convergence test, our `kl_tol=0.05` above, passes for this factor.\n", + " - `stale`, drawn grey: the sweeps reached it but it never landed a single update, so the posterior reported for its\n", + " variables is still the message it started with.\n", + " - `reverting`, drawn with red dashed edges: its latest projection was rejected for at least one variable and that\n", + " variable's message was put back, so the box updated but that marginal did not move.\n", + "\n", + "Each box is also badged with how many updates it landed out of how many sweeps, an `age` counting the sweeps since\n", + "it last moved, and the reason code of its last rejection, such as `BAD_PROJECTION`. The footer totals the whole\n", + "graph: how many factors, variables and plates it has, and how many are stale, reverting, converged and working after\n", + "the sweeps that were run.\n", + "\n", + "Look at the grey boxes first. A `stale` factor means a dataset contributed nothing at all to the shared inference,\n", + "which is a very different failure from a fit that simply has not converged yet, and it is easy to miss in the numbers\n", + "printed below because EP can report convergence in exactly that state: if no factor updates, the step between sweeps\n", + "is zero.\n", + "\n", + "Note which factor graph we hand the plotter. `factor_graph_result.factor_graph` is the graph the optimiser actually\n", + "swept, and the `ep_history` is keyed by its factor objects. Do not pass `factor_graph.graph` instead: that property\n", + "builds a fresh graph and renames its factors on every access, so the history would match nothing and every node would\n", + "be drawn as `absent`.\n", + "\n", + "Passing `kind=\"model\"` instead draws the structure alone, with no run painted on it, which is the view to use before\n", + "a fit starts." + ] + }, + { + "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": {}, @@ -456,6 +548,16 @@ " over each cycle, whereas the `model.results` file should indicate the improved estimate of model parameters over each\n", " cycle.\n", "\n", + " - `graph_model.png`: the factor graph drawn as structure alone, written once at the start of the fit beside\n", + " `graph.info`.\n", + "\n", + " - `graph_state.png`: the same graph with the state of the run painted onto it, rewritten every `visualise_interval`\n", + " sweeps and therefore, with the `visualise_interval=1` we passed above, after every sweep. Flicking through it as the\n", + " fit runs is the quickest way to see which factors are moving and which have gone stale.\n", + "\n", + "Both `.png` files are only written when `model_figure` is set to `true` in `config/output.yaml`; it ships as\n", + "`false`, so switch it on before the fit if you want them.\n", + "\n", "__Results__\n", "\n", "The `MeanField` object represent the posterior of the entire factor graph and is used to infer estimates of the \n", diff --git a/scripts/chapter_1_introduction/tutorial_1_models.py b/scripts/chapter_1_introduction/tutorial_1_models.py index 815e4a5..1f9e292 100644 --- a/scripts/chapter_1_introduction/tutorial_1_models.py +++ b/scripts/chapter_1_introduction/tutorial_1_models.py @@ -233,6 +233,28 @@ def model_data_from(self, xvalues: np.ndarray) -> np.ndarray: """ print(model.info) +""" +The same model can also be drawn, via `af.ModelPlotter`. + +The figure and the `info` are two views of the same object, and it is worth being precise about the division of +labour between them. The figure is the **map**: it shows the structure of the model, meaning which component owns +which parameter and, in the models we build later, which parameters are fixed, shared between components, related to +one another by an expression or constrained by an assertion. The `info` is the **legend**: it lists the priors and +values themselves, the numbers that the map has no room for. + +For this first model the map is about as simple as a map gets. There is a single card, titled `model` and `Gaussian` +after the class it was composed from, holding one pill per parameter: `centre`, `normalization` and `sigma`. The +footer counts them for you, `3 unique sampled scalars`, which is the same number the `total_free_parameters` +attribute printed above. Read the card as the answer to "what is this model made of?", and the `info` above it as the +answer to "and what values may each of those parts take?". + +Right now both views fit on one screen and the figure may look like a redundant restatement of the `info`. Draw it +anyway, because the two views scale very differently. By the end of this chapter our models have five components, in +chapter 3 they span five datasets at once, and at that point the `info` runs to hundreds of lines whilst the map +still fits in a glance. +""" +af.ModelPlotter(model).figure() + """ __Model Mapping__ @@ -380,6 +402,14 @@ def model_data_from(self, xvalues: np.ndarray): """ print(model.info) +""" +Drawing the model shows what a `Collection` does to the map. There are now two cards side by side, +`gaussian` and `exponential`, each titled with the class it was composed from and each owning its own pills, and the +footer counts `6 unique sampled scalars` across the pair. Components sit beside one another, and nothing yet joins +them: the two `centre` parameters are separate parameters that happen to share a name. +""" +af.ModelPlotter(model).figure() + """ When `Gaussian` and `Exponential` are added to a `Collection`, they are automatically assigned as `Model` objects. @@ -393,6 +423,14 @@ def model_data_from(self, xvalues: np.ndarray): """ print(model.info) +""" +The figure is identical to the previous one too, and that is the point worth taking from this example. The two ways +of writing the composition look different on the page, but they build the same structure, and structure is all the +map draws. Whenever you change how a model is written, draw it: if the map does not move then nothing about the model +moved either, and any difference between the two fits has to be hiding in the legend rather than in the model. +""" +af.ModelPlotter(model).figure() + """ A `Collection` functions analogously to a `Model`, but it includes multiple model components. @@ -485,6 +523,14 @@ def __init__( print("\nInfo:") print(model.info) +""" +The map shows how a tuple is handled. `centre` is still drawn as one pill, because it is one input argument of the +`Gaussian2D` class, but it now carries a `2D` badge marking it as a tuple, and the footer counts `4 unique sampled +scalars` rather than 3. The `paths` printed below unpack that badge into the two entries, one per coordinate, which +the input vector must supply. +""" +af.ModelPlotter(model).figure() + """ The `paths` attribute provides information on the order of parameters in the model, illustrating how the `centre` tuple is split into two parameters. diff --git a/scripts/chapter_1_introduction/tutorial_3_non_linear_search.py b/scripts/chapter_1_introduction/tutorial_3_non_linear_search.py index b4b7bf3..58af460 100644 --- a/scripts/chapter_1_introduction/tutorial_3_non_linear_search.py +++ b/scripts/chapter_1_introduction/tutorial_3_non_linear_search.py @@ -264,6 +264,19 @@ def model_data_from(self, xvalues: np.ndarray) -> np.ndarray: print(model.info) +""" +As in tutorial 1, the model can also be drawn via `af.ModelPlotter`. The figure is the **map** of the model, showing +its structure, meaning which component owns which parameter, and the `info` above is its **legend**, listing the +prior placed on each of those parameters. + +The map here is the single card we drew in tutorial 1, with a pill for `centre`, `normalization` and `sigma` and a +footer counting `3 unique sampled scalars`. Those three scalars are exactly the three dimensions of the parameter +space that the non-linear search is about to explore, so the card is a picture of how large the search's job is. The +priors discussed below are the legend for that map: they do not change its shape, they set how far along each of its +three axes the search is allowed to wander. +""" +af.ModelPlotter(model).figure() + """ __Priors__ diff --git a/scripts/chapter_1_introduction/tutorial_4_why_modeling_is_hard.py b/scripts/chapter_1_introduction/tutorial_4_why_modeling_is_hard.py index 03bb035..6b6b98a 100644 --- a/scripts/chapter_1_introduction/tutorial_4_why_modeling_is_hard.py +++ b/scripts/chapter_1_introduction/tutorial_4_why_modeling_is_hard.py @@ -308,6 +308,24 @@ def model_data_from_instance(self, instance): """ print(model.info) +""" +Drawing the model makes the jump in complexity easier to see than counting lines of `info` does. The figure is the +**map** of the model, showing its structure, and the `info` above is the **legend**, listing the priors on every +parameter. + +The five `Gaussian`'s do not appear as five separate cards. Because they are the same component repeated with the +same priors, they collapse into a single dashed frame badged `5 components` and subtitled `gaussian_0 - gaussian_4`, +inside which `centre`, `normalization` and `sigma` are each drawn once and badged `independent`, meaning one prior per +member rather than one prior shared between the members. The legend line below the figure spells that convention +out, `independent = one prior per member` and `dashed frame = repeated components`, and the footer does the +arithmetic: `15 unique sampled scalars`, `0 shared priors` and `1 plate standing for 5 components`. + +That footer is the difficulty of this tutorial stated in one line. Tutorial 3 searched 3 dimensions; this search has +15 of them, and parameter space grows in volume so quickly with that number that the same search which comfortably +found the single `Gaussian` is about to struggle. +""" +af.ModelPlotter(model).figure() + """ __Search__ @@ -550,6 +568,14 @@ def model_data_from_instance(self, instance): """ print(model.info) +""" +The map is worth drawing again precisely because it has not changed: the same dashed frame badged `5 components`, the +same three `independent` pills, the same `15 unique sampled scalars` in the footer. Tuning the priors moved the +legend, not the map. We are still fitting the same 15 parameter model, we have simply told the search a smaller +region of it to look in. +""" +af.ModelPlotter(model).figure() + """ We now repeat the model-fit using these updated priors. @@ -660,6 +686,17 @@ def model_data_from_instance(self, instance): """ print(model.info) +""" +This time the map itself changes, and it changes in one pill. The `centre` pill inside the frame is now badged +`shared across group` instead of `independent`, the legend below gains the entry `blue badge = shared prior`, and the +footer reads `11 unique sampled scalars` and `1 shared prior` where before it read 15 and none. + +That is the difference between the two approaches drawn side by side. Tuning the priors left the map alone and +narrowed the legend; assuming a shared `centre` shrinks the map itself, because four of its parameters have stopped +existing. +""" +af.ModelPlotter(model).figure() + """ We now repeat the model-fit using this updated model where the `centre` of each `Gaussian` is the same. @@ -756,6 +793,14 @@ def model_data_from_instance(self, instance): """ print(model.info) +""" +The map is back where it started: one dashed frame badged `5 components`, three `independent` pills, no shared badge +anywhere and `15 unique sampled scalars` in the footer. Approaches 1 and 2 each changed something that the map or its +legend could show. This third approach changes neither, because searching parameter space more thoroughly is a +property of the search, not of the model. +""" +af.ModelPlotter(model).figure() + """ __Search__ diff --git a/scripts/chapter_1_introduction/tutorial_7_the_details.py b/scripts/chapter_1_introduction/tutorial_7_the_details.py index 544d92d..2258498 100644 --- a/scripts/chapter_1_introduction/tutorial_7_the_details.py +++ b/scripts/chapter_1_introduction/tutorial_7_the_details.py @@ -270,6 +270,17 @@ def log_likelihood_function(self, instance) -> float: print(model.info) +""" +Draw the model and the problem is already on the page. The figure is the **map** of the model, showing its structure, +and the `info` above is the **legend**, listing the priors. + +The two `Gaussian`'s do not get a card each. Because they are the same component carrying identical priors, they +collapse into a single dashed frame badged `2 components` and subtitled `gaussian_0 - gaussian_1`, with one +`independent` pill per parameter. The figure is drawn that way because there is genuinely nothing in the model that +tells the two apart, which is exactly the property the next few cells are about to exploit. +""" +af.ModelPlotter(model).figure() + """ There is a problem hiding in that model. The two components are interchangeable: nothing says `gaussian_0` is the narrow one and `gaussian_1` the broad one. Swap all six values over and we get exactly the same summed model data, diff --git a/scripts/chapter_1_introduction/tutorial_optional_bayesian_formalism.py b/scripts/chapter_1_introduction/tutorial_optional_bayesian_formalism.py index 41a96e7..64ac91f 100644 --- a/scripts/chapter_1_introduction/tutorial_optional_bayesian_formalism.py +++ b/scripts/chapter_1_introduction/tutorial_optional_bayesian_formalism.py @@ -270,6 +270,18 @@ def model_data_from(self, xvalues: np.ndarray) -> np.ndarray: """ print(model.info) +""" +The model can also be drawn, via `af.ModelPlotter`. The figure is the **map** of the model, showing its structure, +meaning which component owns which parameter, and the `info` above is the **legend**, naming the prior on each of +them. + +Read against the formalism of this tutorial the map has a precise meaning: the pills on the card are the entries of +the parameter vector, the footer's `3 unique sampled scalars` is its dimension, and the sum over j in the expression +above runs over exactly those pills. The prior is one distribution per pill, and the legend is where their names and +limits live. +""" +af.ModelPlotter(model).figure() + print("Log prior of each parameter, theta = [50.0, 25.0, 10.0]:") print(model.log_prior_list_from_vector(vector=[50.0, 25.0, 10.0])) diff --git a/scripts/chapter_3_graphical_models/tutorial_3_graphical_benefits.py b/scripts/chapter_3_graphical_models/tutorial_3_graphical_benefits.py index 60709a3..6e58d57 100644 --- a/scripts/chapter_3_graphical_models/tutorial_3_graphical_benefits.py +++ b/scripts/chapter_3_graphical_models/tutorial_3_graphical_benefits.py @@ -351,6 +351,24 @@ """ print(factor_graph.global_prior_model.info) +""" +Drawing this model next to tutorial 2's figure shows what the second shared parameter bought us. The figure is the +**map** of the model, showing which dataset gets which components and which parameters are shared between them, and +the `info` above is the **legend** of priors. + +Two things have changed. The hoisted card at the top is titled `shared across datasets` and subtitled `one value +across 5 datasets`, and it now holds two `centre` pills rather than one, because each of the two `Gaussian`'s has its +own shared `centre`. Below it, every dataset is drawn as its own card, `0` through `4`, each containing a +`gaussian_0` and a `gaussian_1`, and inside them the `centre` pill carries a blue `shared` badge with a line running +back up to the hoisted card. The `normalization` and `sigma` pills carry no badge and no line, because those +parameters belong to their own dataset alone. + +The footer draws the dimensionality claim made above rather than asserting it: `2 shared across datasets`, +`4 per dataset × 5 datasets`, `22 unique sampled scalars`. That is the N=22 of the text, and the map shows where each +of those numbers comes from. +""" +af.ModelPlotter(factor_graph.global_prior_model).figure() + """ __Search__ diff --git a/scripts/chapter_3_graphical_models/tutorial_5_expectation_propagation.py b/scripts/chapter_3_graphical_models/tutorial_5_expectation_propagation.py index 6c71032..270a258 100644 --- a/scripts/chapter_3_graphical_models/tutorial_5_expectation_propagation.py +++ b/scripts/chapter_3_graphical_models/tutorial_5_expectation_propagation.py @@ -220,6 +220,22 @@ def log_likelihood_function(self, instance, xp=np): """ print(factor_graph.global_prior_model.info) +""" +Drawing the model shows the graph that EP is about to sweep. The figure is the **map**, showing which dataset gets +which components and what joins them, and the `info` above is the **legend** of priors. + +There are four cards. The first three, `0` to `2`, are the `AnalysisFactor`'s, one per dataset, each holding a +`gaussian` card with its `centre`, `normalization` and `sigma` pills. The fourth card, numbered `3`, is the +`linear_regression` factor, and its pills are drawn in orange rather than as plain free priors because they are not +free parameters at all: each one shows the expression it is computed from, a constant times that dataset's +`gaussian.sigma`, which is the FWHM we built out of `fwhm_list` above. The legend names this kind of pill, +`relation (expression shown)`, and a line runs from each dataset's `sigma` into the relation built on it. + +Those lines are the thing to hold on to for the rest of the tutorial. EP never fits this whole map in one go. It +visits one card at a time, and the lines drawn here are the paths its messages travel along. +""" +af.ModelPlotter(factor_graph.global_prior_model).figure() + """ __Expectation Propagation__ @@ -257,11 +273,20 @@ def log_likelihood_function(self, instance, xp=np): When we fit the factor graph a `name` is passed, which determines the folder all results of the factor graph are stored in. + +We also pass `visualise_interval=1`. The EP fit draws the factor graph with the state of the run painted onto it and +writes it to the output folder, and this input sets how many sweeps pass between refreshes of that figure. Its +default is 100, which over the 5 sweeps below would draw it exactly once, so we set it to 1 and get a fresh picture +of the graph after every sweep. """ laplace = af.LaplaceOptimiser() factor_graph_result = factor_graph.optimise( - optimiser=laplace, paths=paths, ep_history=af.EPHistory(kl_tol=0.05), max_steps=5 + optimiser=laplace, + paths=paths, + ep_history=af.EPHistory(kl_tol=0.05), + max_steps=5, + visualise_interval=1, ) """ @@ -273,6 +298,51 @@ def log_likelihood_function(self, instance, xp=np): """ ### print(factor_graph_result.info)## +""" +__Seeing the EP run__ + +Until that `info` exists, the figure is how we read an EP fit back. `af.EPPlotter` draws the same factor graph as +before, but now with the state of the run painted onto it. + +The graph it draws is not the map we drew earlier, it is the factor graph itself, and its legend says how to read +it: `box = factor`, `pill = variable`, `dashed frame = repeated structure`. Every `AnalysisFactor` is a box, every +parameter it touches is a pill, and an edge between them means "this factor has something to say about this +variable". That is the picture the message passing above lives on: a message leaves a box, arrives at a pill, and is +read by every other box attached to it. The three datasets sit inside a dashed plate badged `3 datasets`, drawn once +as an aggregate `AnalysisFactor` box, with the individual `dataset_0`, `dataset_1` and `dataset_2` boxes expanded +alongside it because their states differ from one another. + +Onto that structure the `ep_history` paints what the sweeps actually did. Every box carries a status: + + - `working`: it is updating, nothing was rejected, and it has not yet converged. + - `converged`, drawn green: the `EPHistory` convergence test, our `kl_tol=0.05` above, passes for this factor. + - `stale`, drawn grey: the sweeps reached it but it never landed a single update, so the posterior reported for its + variables is still the message it started with. + - `reverting`, drawn with red dashed edges: its latest projection was rejected for at least one variable and that + variable's message was put back, so the box updated but that marginal did not move. + +Each box is also badged with how many updates it landed out of how many sweeps, an `age` counting the sweeps since +it last moved, and the reason code of its last rejection, such as `BAD_PROJECTION`. The footer totals the whole +graph: how many factors, variables and plates it has, and how many are stale, reverting, converged and working after +the sweeps that were run. + +Look at the grey boxes first. A `stale` factor means a dataset contributed nothing at all to the shared inference, +which is a very different failure from a fit that simply has not converged yet, and it is easy to miss in the numbers +printed below because EP can report convergence in exactly that state: if no factor updates, the step between sweeps +is zero. + +Note which factor graph we hand the plotter. `factor_graph_result.factor_graph` is the graph the optimiser actually +swept, and the `ep_history` is keyed by its factor objects. Do not pass `factor_graph.graph` instead: that property +builds a fresh graph and renames its factors on every access, so the history would match nothing and every node would +be drawn as `absent`. + +Passing `kind="model"` instead draws the structure alone, with no run painted on it, which is the view to use before +a fit starts. +""" +af.EPPlotter( + factor_graph_result.factor_graph, ep_history=factor_graph_result.ep_history +).figure(kind="state") + """ __Output__ @@ -292,6 +362,16 @@ def log_likelihood_function(self, instance, xp=np): over each cycle, whereas the `model.results` file should indicate the improved estimate of model parameters over each cycle. + - `graph_model.png`: the factor graph drawn as structure alone, written once at the start of the fit beside + `graph.info`. + + - `graph_state.png`: the same graph with the state of the run painted onto it, rewritten every `visualise_interval` + sweeps and therefore, with the `visualise_interval=1` we passed above, after every sweep. Flicking through it as the + fit runs is the quickest way to see which factors are moving and which have gone stale. + +Both `.png` files are only written when `model_figure` is set to `true` in `config/output.yaml`; it ships as +`false`, so switch it on before the fit if you want them. + __Results__ The `MeanField` object represent the posterior of the entire factor graph and is used to infer estimates of the