How do I configure mathjax for iPython notebooks?

Question:

I’m trying to find a way for mathjax to not use STIX fonts for math in my iPython notebook. Instead, I’d much rather have it use the ‘TeX’ fonts. According to the documentation for Mathjax I should use:

MathJax.Hub.Config({
  "HTML-CSS": {
    preferredFont: "TeX"
  }
});

That being said, I’m not sure where to put this. I’ve already tried putting this chunk of code into my custom.js file pertaining to my own ipython profile, but it doesn’t work. Ideally, I’d like to make ipython profile specific adjustments for mathjax.

Asked By: Black Milk

||

Answers:

Take a look at some of the numericalmooc lessons such as this one where the MathJax configuration is included through a css file which is imported at some point in the notebook.

Answered By: Ian

A simple test to make sure that you’re getting the configuration correct is to change preferredFont: "TeX" to scale: 200. Then save and reload a notebook. The math should be obviously way bigger than before. So assuming that worked, it means your config.js is doing what it needs to.

Now, more to the point, try adding another line so that your configuration looks like

MathJax.Hub.Config({
  "HTML-CSS": {
    availableFonts: ["TeX"],
    preferredFont: "TeX",
  }
});

Don’t forget to fully refresh the notebook page after you’ve saved that. This overrides (what I’m guessing is) the default value of that availableFonts variable, which would allow STIX if mathjax can’t find TeX. I’m not sure why it seems to ignore the preferred font, but this seems more like a mathjax issue than an ipython issue.

So now, if it still isn’t in TeX font (which mathjax seems to call MathJax_Math-Italic.otf, or similar), I would guess that mathjax just can’t find that font, and may have fallen back on something else. If that is the case, there’s something messed up about your mathjax installation.

Answered By: Mike

I recently had the exact problem. I really don’t like the default STIX-Web font to render equation. After experimenting for a little while, I found a way to change the MathJax font in Jupyter Notebook. My Jupyter Notebook version is 4.3.1 and it is shipped with Anaconda. I assume the solutions for other versions should be similar.

I tried to edit custom.js both in /notebook/static/custom/custom.js and ~/.jupyter/custom/custom.js. Doesn’t work. I also tried to edit mathjaxutils.js. It does nothing. Finaly I saw this post https://github.com/jupyter/help/issues/109. I realize Jupyter uses main.min.js to read MathJax configuration. So here is the solutions:

  • Download MathJax(https://github.com/mathjax/MathJax) from Github.
  • Unzip the MathJax file and go into the folder
    • copy jax/output/HTML-CSS/fonts/TeX into directoy ../notebook/static/components/MathJax/jax/output/HTML-CSS/fonts/
    • copy fonts/HTML-CSS/TeX into ../notebook/static/components/MathJax/fonts/HTML-CSS/
  • open ../notebook/static/notebook/js/main.min.js, search for availableFonts. It should be around line 14894. Change it to

    ...
    availableFonts: ["STIX-Web","TeX"],
    imageFont: null;
    preferredFont: "TeX",
    webFont: "TeX"
    ...
    
  • Refresh the notebook.
Answered By: Stefan Shi

I’ve tweaked @Stefan Shi’s answer to something a little easier, at least if you have the command-line svn installed.

  • Put the following into a script file called install_tex_fonts (install_tex_fonts.bat in Windows-land):

    svn export https://github.com/mathjax/MathJax/trunk/fonts/HTML-CSS/TeX/woff fonts/HTML-CSS/TeX/woff
    svn export https://github.com/mathjax/MathJax/trunk/jax/output/HTML-CSS/fonts/TeX jax/output/HTML-CSS/fonts/TeX
    
  • Move the script file into {PYTHON}/Lib/site-packages/notebook/static/components/MathJax where {PYTHON} is the root directory where you installed Python

  • Open a shell (command prompt) in this directory
  • Run the script by typing install_tex_fonts (or ./install_tex_fonts on *nix systems; I guess you also have to chmod a+x it)
  • Add the following section in your ~/.jupyter/custom/custom.js file (the $([IPython.events]).on('app_initialized.NotebookApp') line should already be there):

    $([IPython.events]).on('app_initialized.NotebookApp', function(){
    
      MathJax.Hub.Config({
        "HTML-CSS": {
            availableFonts: ["TeX"],
            preferredFont: "TeX",
            webFont: "TeX"
        }
       });
    
Answered By: Jason S

Jupyter ships with its own (smaller) version of MathJax. This is why it is not able to find the (Computer Modern) ‘TeX’ font — there only is the STIX font.

To fix this, I was able to do the following:

  1. Download MathJax 2.7 and copy the jax directory.
  2. Replace Jupyter’s jax directory with the copied one:
  • For the default environment: ~/anaconda3/lib/python3.7/site-packages/notebook/static/components/MathJax/jax
  • For a different environment: ~/anaconda3/envs/<ENVIRONMENT>/lib/python3.7/site-packages/notebook/static/components/MathJax/jax
  1. Restart Jupyter, right-click on a piece of math and switch the ‘Math Renderer’ to SVG.

(Adjust python version in path if yours is not 3.7; If you are using miniconda the path should be ~/opt/miniconda3/lib/...)

Answered By: Onno Eberhard

Following @Ian’s information, you can get your initial HTML-CSS MathJax configuration from python with the below code (demjson is a soft requirement which allows us to partially process json in a javascript file: pip install demjson):

import sys
from pathlib import Path

MathJax_cfg_pth = (
    Path(sys.executable).parents[0] /
    # below path may differ
    'Lib/site-packages/notebook/static/components/MathJax/jax/output/HTML-CSS/config.js'
)
with open(MathJax_cfg_pth, 'r') as f:
    MathJax_cfg = f.read()

import demjson
start_cfg = MathJax_cfg.find("config:{") + 7
open_braces = 0
for i, c in enumerate(MathJax_cfg[start_cfg:]):
    if c == '{':
        open_braces += 1
    elif c == '}':
        if open_braces == 0:
            break
        open_braces -= 1
initial_configuration = demjson.decode(
    MathJax_cfg[
        start_cfg : start_cfg + i
    ].replace("(", "'(").replace(")", ")'")
)

Having this will be helpful if you want to revert any changes without restarting your notebook kernel. For the curious, my initial_configuration is here: https://pastebin.com/JkatcrAC

Next we can update a HTML-CSS MathJax setting in our current runtime by displaying HTML containing a short script. If you wanted to update the size of HTML-CSS displays you could use the following function:

from IPython.core.display import HTML
MathJax_scale_script = """
<script>
    MathJax.Hub.Config({
        "HTML-CSS": {
            scale: %s
        }
    });
</script>
"""
def update_Math_size(size):
    # 100 is default
    display(HTML(MathJax_scale_script%size))

For example, update_Math_size(200) for double the size, and update_Math_size(100) to revert back to my default setting.

Answered By: Maxwell Schmidt