Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisjsewell committed May 5, 2022
1 parent 10b6204 commit 7783a03
Show file tree
Hide file tree
Showing 6 changed files with 155 additions and 72 deletions.
2 changes: 1 addition & 1 deletion docs/computation/execute.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Notebooks can either be run each time the documentation is built, or cached loca
Execution and caching behaviour is controlled with configuration at a global or per-file level, as outlined in the [configuration section](config/intro).
See the sections below for a description of each configuration option and their effect.

(execute/config)=
(execute/modes)=

## Notebook execution modes

Expand Down
100 changes: 45 additions & 55 deletions docs/render/glue.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,10 @@ kernelspec:

(glue/main)=

# Saving variables to embed (IPython only)
# Saving variables to embed (glue)

You often wish to run analyses in a notebook and insert them into your
documents text elsewhere.
For example, if you'd like to include a figure,
or if you want to cite a statistic that you have run.

The **`glue` submodule** allows you to add a key to variables in a notebook code cell,
then display those variables in a Markdown cell by referencing the key.

This page describes how to add keys to variables in notebooks, and how to insert them
into your book's content in a variety of ways.[^download]
The `glue` submodule allows you to store variables in the notebooks outputs, by keys,
then reference those keys to embed the outputs inline of your text content.[^download]

[^download]: This notebook can be downloaded as **{nb-download}`glue.ipynb`** and {download}`glue.md`

Expand All @@ -30,11 +22,10 @@ To glue keys from other notebooks, see {ref}`glue/crossdoc`.

(glue/gluing)=

## Gluing variables in your notebook
## Save variables in code cells

You can use `myst_nb.glue()` to assign value of a variable to
a key of your choice. `glue` will store all of the information that is normally used to **display**
that variable (ie, whatever happens when you display the variable by putting it at the end of a cell).
You can use `myst_nb.glue()` to assign the output of a variable to a key of your choice.
`glue` will store all of the information that is normally used to display that variable (ie, whatever happens when you display the variable by putting it at the end of a cell).
Choose a key that you will remember, as you will use it later.

The following code glues a variable inside the notebook:
Expand All @@ -45,16 +36,16 @@ a = "my variable!"
glue("my_variable", a)
```

You can then insert it into your text like so: {glue:}`my_variable`.
You can then insert it into your text like so: {glue}`my_variable`.

That was accomplished with the following code: `` {glue:}`my_variable` ``.
That was accomplished with the following code: `` {glue}`my_variable` ``.

### Gluing numbers, plots, and tables
### Saving different variable types

You can glue anything in your notebook and display it later with `{glue:}`. Here
we'll show how to glue and paste **numbers and images**. We'll simulate some
data and run a simple bootstrap on it. We'll hide most of this process below,
to focus on the glueing part.
You can glue anything in your notebook and display it later with `{glue}`.
Here we'll show how to glue and paste **numbers and images**.
We'll simulate some data and run a simple bootstrap on it.
We'll hide most of this process below, to focus on the glueing part.

+++

Expand All @@ -73,8 +64,8 @@ data = sd*np.random.randn(n_points) + mean
bootstrap_indices = np.random.randint(0, n_points, n_points*n_boots).reshape((n_boots, n_points))
```

In the cell below, `data` contains our data, and `bootstrap_indices` is a collection of sample indices in each bootstrap. Below we'll calculate a few statistics of interest, and
**`glue()`** them into the notebook.
In the cell below, `data` contains our data, and `bootstrap_indices` is a collection of sample indices in each bootstrap.
Below we'll calculate a few statistics of interest, and `glue()` them into the notebook.

```{code-cell} ipython3
# Calculate the mean of a bunch of random samples
Expand All @@ -88,10 +79,10 @@ glue("boot_clo", clo)
glue("boot_chi", chi)
```

By default, `glue` will display the value of the variable you are gluing. This
is useful for sanity-checking its value at glue-time. If you'd like to **prevent display**,
use the `display=False` option. Note that below, we also *overwrite* the value of
`boot_chi` (but using the same value):
By default, `glue` will display the value of the variable you are gluing.
This is useful for sanity-checking its value at glue-time.
If you'd like to **prevent display**, use the `display=False` option.
Note that below, we also *overwrite* the value of `boot_chi` (but using the same value):

```{code-cell} ipython3
glue("boot_chi_notdisplayed", chi, display=False)
Expand Down Expand Up @@ -134,7 +125,7 @@ you may wish to remove the output here, using the `remove-output` tag

(glue/pasting)=

## Pasting glued variables into your page
## Embedding variables in the page

Once you have glued variables into a notebook, you can then **paste**
those variables into your text in your book anywhere you like (even on other pages).
Expand All @@ -144,41 +135,40 @@ These variables can be pasted using one of the roles or directives in the `glue:

### The `glue` role/directive

The simplest role and directive are `glue:any`,
The simplest role and directive are `glue` (a.k.a. `glue:any`),
which paste the glued output inline or as a block respectively,
with no additional formatting.
Simply add this:
Simply add:

````
```{glue:} your-key
```{glue} your-key
```
````

For example, we'll paste the plot we generated above with the following text:

````md
```{glue:} boot_fig
```{glue} boot_fig
```
````

Here's how it looks:

```{glue:} boot_fig
```{glue} boot_fig
```

Or we can paste inline objects like so:


```md
Inline text; {glue:}`boot_mean`, and figure; {glue:}`boot_fig`.
Inline text; {glue}`boot_mean`, and figure; {glue}`boot_fig`.
```

Inline text; {glue:}`boot_mean`, and figure; {glue:}`boot_fig`.
Inline text; {glue}`boot_mean`, and figure; {glue}`boot_fig`.

```{tip}
We recommend using wider, shorter figures when plotting in-line, with a ratio
around 6x2. For example, here's is an in-line figure of sorted means
from our bootstrap: {glue:}`sorted_means_fig`.
from our bootstrap: {glue}`sorted_means_fig`.
It can be used to make a visual point that isn't too complex! For more
ideas, check out [how sparklines are used](https://en.wikipedia.org/wiki/Sparkline).
```
Expand All @@ -188,14 +178,14 @@ control over how the outputs look in your pages.

+++

## Controlling the pasted outputs
## Controlling the output format

You can control the pasted outputs by using a sub-command of `{glue:}`. These are called like so:
`` {glue:subcommand}`key` ``. These subcommands allow you to control more of the look, feel, and
content of the pasted output.
You can control the pasted outputs by using a sub-command of `{glue}`.
These are called like so: `` {glue:subcommand}`key` ``.
These subcommands allow you to control more of the look, feel, and content of the pasted output.

```{tip}
When you use `{glue:}` you are actually using a short-hand for `{glue:any}`. This is a
When you use `{glue}` you are actually using a short-hand for `{glue:any}`. This is a
generic command that doesn't make many assumptions about what you are gluing.
```

Expand Down Expand Up @@ -347,7 +337,7 @@ With `glue:md`, you can output `text/markdown`, that will be integrated into you
from IPython.display import Markdown
glue("inline_md", Markdown(
"inline **markdown** with a [link](glue/main), "
"and a nested glue value: {glue:}`boot_mean`"
"and a nested glue value: {glue}`boot_mean`"
), display=False)
glue("block_md", Markdown("""
#### A heading
Expand Down Expand Up @@ -387,7 +377,7 @@ Here is some {glue:md}`inline_md:myst`!
+++

(glue/crossdoc)=
## Pasting from other notebooks
## Embedding outputs from other pages

Certain `glue` roles and directives can be used to paste content from other notebooks,
by specifying the (relative) path to them.
Expand All @@ -400,32 +390,32 @@ In this case, you should bundle the notebook with the rest of your content pages
For example, the following example pastes glue variables from {ref}`orphaned-nb`:

````markdown
- A cross-pasted `any` role: {glue:}`orphaned_nb.ipynb::var_text`
- A cross-pasted `any` role: {glue}`orphaned_nb.ipynb::var_text`
- A cross-pasted `text` role: {glue:text}`orphaned_nb.ipynb::var_float:.2E`

A cross-pasted `any` directive:

```{glue:} var_text
```{glue} var_text
:doc: orphaned_nb.ipynb
```
````

- A cross-pasted `any` role: {glue:}`orphaned_nb.ipynb::var_text`
- A cross-pasted `any` role: {glue}`orphaned_nb.ipynb::var_text`
- A cross-pasted `text` role: {glue:text}`orphaned_nb.ipynb::var_float:.2E`

A cross-pasted `any` directive:

```{glue:} var_text
```{glue} var_text
:doc: orphaned_nb.ipynb
```

+++

## Advanced glue usecases
## Advanced use-cases

Here are a few more specific and advanced uses of the `glue` submodule.

### Pasting into tables
### Embedding into tables

In addition to pasting blocks of outputs, or in-line with text, you can also paste directly
into tables. This allows you to compose complex collections of structured data using outputs
Expand All @@ -434,13 +424,13 @@ that were generated in other notebooks. For example the following table:
````md
| name | plot | mean | ci |
|:-------------------------------:|:---------------------------:|---------------------------|----------------------------------------------------|
| histogram and raw text | {glue:}`boot_fig` | {glue:}`boot_mean` | {glue:}`boot_clo`-{glue:}`boot_chi` |
| sorted means and formatted text | {glue:}`sorted_means_fig` | {glue:text}`boot_mean:.3f`| {glue:text}`boot_clo:.3f`-{glue:text}`boot_chi:.3f`|
| histogram and raw text | {glue}`boot_fig` | {glue}`boot_mean` | {glue}`boot_clo`-{glue}`boot_chi` |
| sorted means and formatted text | {glue}`sorted_means_fig` | {glue:text}`boot_mean:.3f`| {glue:text}`boot_clo:.3f`-{glue:text}`boot_chi:.3f`|
````

Results in:

| name | plot | mean | ci |
|:-------------------------------:|:---------------------------:|---------------------------|---------------------------------------------------|
| histogram and raw text | {glue:}`boot_fig` | {glue:}`boot_mean` | {glue:}`boot_clo`-{glue:}`boot_chi` |
| sorted means and formatted text | {glue:}`sorted_means_fig` | {glue:text}`boot_mean:.3f` | {glue:text}`boot_clo:.3f`-{glue:text}`boot_chi:.3f` |
| histogram and raw text | {glue}`boot_fig` | {glue}`boot_mean` | {glue}`boot_clo`-{glue}`boot_chi` |
| sorted means and formatted text | {glue}`sorted_means_fig` | {glue:text}`boot_mean:.3f` | {glue:text}`boot_clo:.3f`-{glue:text}`boot_chi:.3f` |
108 changes: 93 additions & 15 deletions docs/render/inline.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,43 +8,121 @@ mystnb:

(render/eval)=

# Inline variable evaluation
# Inline variable evaluation (eval)

```{versionadded} 0.15.0
```

The `eval` submodule allows you to insert code variables directly into the text flow of your documentation.

Use of `eval` requires that the [notebook execution mode](execute/modes) is set to `inline`, since the variables are evaluated by the notebook kernel.
For example, using the [top-matter](authoring/text-notebooks):

```yaml
---
file_format: mystnb
kernelspec:
name: python3
mystnb:
execution_mode: 'inline'
---
```

## Basic example

Below we set a variable `v1` within a code cell.

```{code-cell} ipython3
a = 1
v1 = "My variable"
```

Using the `eval` role, we can insert the variable `v1` into the text of a paragraph:

`` {eval}`v1` `` -> {eval}`v1`

If we update the variable, we can see the change reflected in subsequent evaluation:

```{code-cell} ipython3
v1 = "My new variable"
```

`` {eval}`v1` `` -> {eval}`v1`

:::{important}
Variable names must match the regex `[a-zA-Z][a-zA-Z0-9_]*`
:::

## Inserting different output types

Any variable type can be inserted into the text flow using the `eval` role,
and the most suitable output type will be used, based on the output format (see {ref}`render/output/priority` for more information).
For example:

```{code-cell} ipython3
import ipywidgets as widgets
slider = widgets.IntSlider(value=5, min=0, max=10)
```

An inline slider (`` {eval}`slider` ``): {eval}`slider`

You can also use the `eval` directive to insert variables as blocks:

```{code-cell} ipython3
import matplotlib.pyplot as plt
myplot, ax = plt.subplots(figsize=(6, 2))
mean = 2.0
ax.plot([1,2,3])
ax.grid()
plt.close()
```

using:

````markdown
```{eval} myplot
```
````

gives:

```{eval} myplot
```

## Embedding outputs in figures

The `eval:figure` directive allows you to embed outputs in a figure,
with an optional caption and other formatting options.

For example, we can embed the output of the above plot in a figure:

`````markdown
````{note}
```{eval:figure} myplot
My figure caption, with an inline variable: {eval}`a`.
:name: myplot
My plot with a mean value of {eval}`mean`.
```
````
`````

````{note}
which gives:

```{eval:figure} myplot
My figure caption, with an inline variable: {eval}`a`.
:name: myplot
My plot with a mean value of {eval}`mean`.
```
````

```{code-cell} ipython3
a = 2
```
That can be referenced with `` {ref}`myplot` ``: {ref}`myplot`

`````markdown
Updated inline variable: {eval}`a`.
`````
The following directive options are available:

Updated inline variable: {eval}`a`.
:::{table} `eval:figure` directive options
| Option | Type | Description |
| ------ | ---- | ----------- |
| figwidth | length or percentage | The width of the figure |
| figclass | text | A space-separated list of class names for the figure |
| name | text | referenceable label for the figure |
| alt | text | Alternate text of an image |
| height | length | The desired height of an image |
| width | length or percentage | The width of an image |
| scale | percentage | The uniform scaling factor of an image |
| class | text | A space-separated list of class names for the image |
| align | text | left, center, or right |
:::
Loading

0 comments on commit 7783a03

Please sign in to comment.