Jupyter Notebook Tools & Setup

pyetest: Electronics Testing Tool & Method

Improving PDF Output

Plots are by default PNG. When possible I prefer vector graphics as it allows you to upscale as much as necessary with no quality penalty. The following sets the exporting image format to PDF. The inline images remain PNGs but the export to PDF or LaTeX will use the PDFs.

from IPython.display import set_matplotlib_formats
import matplotlib
set_matplotlib_formats('png', 'pdf') # use PNG inline and PDFs when printing
matplotlib.rcParams['figure.figsize'] = [10, 5] # Change size to fit width

Adding Title & Author

By default no author is shown and the title is the name of the notebook file. You can address this by writing your own templates or by editing the metadata.

Menu Location: Edit -> Edit Notebook Metadata

A window will pop-up. Add the title and authors to the end of the JSON as shown below.

{
  "kernelspec": {

...
  },
  "language_info": {
...
  },
  "title": "Notebook Title",
  "authors": [
    {
      "name": "Your Name"
    },
    {
      "name": "Other name or Company name"
    }
  ]
}

Remove Code

It is often the case that the source code inline is a distraction. The output and discussion is what is important. The inline code (i.e. the input) can be removed when exporting with the flag –no-input to nbconvert:

jupyter nbconvert <notebook name>.ipynb --to pdf --no-input

Render Sympy LaTeX

def print_sympy(*args):
    '''
    Print the sympy argument in a way that jupyter notebook can print as latex
    Takes argument list of
    '''
    import sympy
    import IPython.display

    st = []
    for arg in args:
        if isinstance(arg, str):
            st.append(arg)
        else:
            try:
                st.append(sympy.latex(arg))
            except:
                raise
    IPython.display.display(IPython.display.Math("".join(st)))

Strip Out Output for Version Control

We usually care about version control on the source and not the output, nbstripout is a tool for removing notebook outputs for well behaved version control.

nbstripout {filename}.ipynb

The tool will install a git filter to make sure you don’t accidentally commit the file without stripping. Run nbstripout –help for exact method.

nbstripout --install 

Removing Sources When Exporting

To export the output cells only run:

jupyter nbconvert --to {format} --execute --TemplateExporter.exclude_input=True --TemplateExporter.exclude_raw=True {filename}.ipynb --output-dir ./

This is great for making an executable notebook like a photon budget where the math and the output matters but not the exact code. Run –execute especially if using nbstripout.

Exporting Using Config

jupyter nbconvert --to latex --config convert.py --TemplateExporter.exclude_input=True merge.ipynb

convert.py

from pathlib import Path


# Read list of file names from a text file, separated by new lines
def read_toc(toc_file: Path):
    files = []
    with open(toc_file, "r") as f:
        for line in f.readlines():
            line = line.strip()
            if line and line[0] != "#":
                files.append(Path(line))
                return files
def main(f):
    files = read_toc(f)
    c = get_config()
    # https://nbconvert.readthedocs.io/en/latest/usage.html#converting-multiple-notebooks
    c.NbConvertApp.notebooks = list(map(str, files))
    # https://nbconvert.readthedocs.io/en/latest/removing_cells.html                                                                                
    c.TemplateExporter.exclude_input=True


main(f="toc.txt")

Merging Multiple Sources Into a Single File

nbmerge --sources {filename1}.ipynb {filename2}.ipynb --out merge.ipynb

nbmerge "$(cat toc.txt)" --out merge.ipynb

Jupyter Book

jupyter book create book
  • Build
jupyter book build ./ 

Resources

Examples

Tools