What are my options for rendering diagrams in a Jupyter notebook? - jupyter-notebook

I'm making a .ipynb as a tutorial for neural networks.
Sometimes I need to add diagrams.
What I'm doing currently is drawing them on paper, taking a photo with my iPhone and rendering the .png in a markdown cell with e.g. ![BackProp](backprop.png).
However this sucks on a few different levels. It means I have to supply a bunch of media files when distributing the notebook. Also tweaking a diagram requires from-scratch--reworking. And it looks clumsy.
I tried a couple of approaches, but couldn't get anything to work:
It should be possible to render diagrams in LaTeX, and VSCode's .ipynb renderer handles stuff like $x^2 + y^2$. ChatGPT gave me:
\begin{tikzpicture}[x=1.5cm, y=1.5cm, >=stealth]
\draw[->] (-0.5,0) -- (4.5,0) node[right] {$x_1, x_2, \dots, x_N$};
\draw[->] (0,-0.5) -- (0,2.5);
\foreach \i in {1,2,...,4}
{
\filldraw[black] (\i,0) circle (0.1);
}
\draw[black, ->] (2,-0.3) -- (2,0.3);
\draw[black, ->] (2,0.3) -- (2,1.7) node[above] {$\sum_{i=1}^{N}w_ix_i + b$};
\draw[black, ->] (2,1.7) -- (2,2.2) node[above] {$\sigma(\cdot)$};
\draw[->] (2,2.2) -- (4.5,2.2) node[right] {Output};
\end{tikzpicture}
... but this gives "ParseError: no such environment: tikzpicture" -- and it looks like I'd have to pip-install https://github.com/mkrphys/ipython-tikzmagic
graphviz might be possible, however (1) I can't get it working with a markdown cell, and (2) even though it does work in a Python cell (after brew install graphviz and pip install graphviz),
import graphviz as gv
dot = gv.Digraph()
dot.edge("X6", "X7", label="$\sigma(\cdot)$")
dot
... still won't render LaTeX in the diagram.
Is there any out-of-the-box solution that wouldn't require my students having to fiddle with installations?
And if not, is there a recommended path?

Related

What is the best way to write down in-line math equations in a jupyter notebook to have best LaTeX results?

When I am writing math equations in a markdown cell of a jupyter notebook, I casually put all of that in $ ... $. Today, I converted an .ipynb file to .tex, and realized most of these equations are converted into messy stuff in the output pdf. For instance, I realized it is converting all '$'s into '$'s.
This is an example of what has happened:
Jupyter Notebook markdown:
$ \nabla ^{2} f(x) = \frac{-1}{(x+1)^{2}} $
Tex Output:
\$ \nabla \^{}\{2\} f(x) = \frac{-1}{(x+1)^{2}} \$
Does anyone have any ideas why this is happening? Is there a better way to write down in-line math equations so that it is more compatible with LaTeX?
If you are eventually going to LaTeX version, the traditional advice is spelled out in minrk's comment from November 8 of 2012:
"The best solution for that right now would be to use 'raw' cells instead of markdown, and just type LaTeX as you would. Then use nbconvert to turn the ipynb to TeX (code, figures and all), and run latex to render that to PDF, etc. You don't get live-rendered TeX in the browser like you do with MathJax / Markdown, but you do still have TeX / code in one document."
The step where you are converting now is probably using nbconvert under the hood even if you aren't directly. (You may be using it directly since you tagged with 'nbconvert`.)
Alternatively, if you are going to LaTeX ultimately, you may want to use a code cell and use the LaTeX magic cell line at the start of that cell. See here and here about %%latex cell magic. (You'll note it is also mentioned among the StackOverflow thread I referenced earlier.) In regards to the %%latex cell magic, I suggest actually consulting the link that leads use in an example notebook in this post because it seems it has to be full-blown LaTeX code and not just simple equations that work easily elsewhere with just dollar signs bracketing them, i.e., MathJax.
I tried that option with your equation and when I output the notebook as LaTeX, I didn't see additional backslashes added. (I didn't however actually try rendering the LaTeX, and so I cannot address if all the cruft/boilerplate that Jupyter is adding causes any issues for downstream useability.)

Octave -- Plotting from Terminal Command Line

Background:
I'm new to Octave, as of today.
I am running GNU Octave, version 4.0.2 on Ubuntu 16.04 LTS
I'm using the command-line interface at the terminal (ie, open the terminal and, type "octave").
I'm aware that there is a GUI, but I want to see if I can get this working in the terminal [such a setup is my preference in most applications]
PROBLEM:
Plots are plotted in text. As in:
How can I get a good-looking plot in a plotting window? I genuinely haven't been able to find this information in 10 minutes of Googling...I think it should be easier than that....maybe someday this post will be the easy solution for others.
Best,
-Ryan
I personally do this a lot; it looks like you have it installed in a *nix environment... Octave can produce nice looking figures through cooperation with a couple graphic toolkits, GNUPlot being the one i'm more familiar with.
Check out the documentation at: https://www.gnu.org/software/octave/doc/v4.0.1/Plotting.html
Without seeing your code we're kind of just guessing. I would try something like
figure();
to see if you get a fresh plot window, or try
available_graphics_toolkits()
to ensure that you actually have something installed to generate separate figures.

Enable "linestyle" functionality for Gnuplot in Octave?

In Octave there is the problem that with fltk and qt greek letters in figures are not printed, only with gnuplot as graphics_toolkit. But then with gnuplot all lines are solid, no dashed lines.
I found a page which says that other linestyles can be enabled:
http://wiki.octave.org/Enable_%22linestyle%22_functionality_for_Gnuplot%27s_x11_terminal
I added the lines there to my ~/.Xdefaults and did xrdb -merge .Xdefaults as said there,
but no success.
I am running octave 4.0.2 on Ubuntu 16.04.
Any hints?
Thanks
Karl
It seems you cannot do it for the time being. But if you're happy for workarounds, your best choice seems to be to create an image of greek text and use that as your title etc.
Here's a way. Go to the codecogs online latex editor and write your greek title using their tool in tedious math mode :p If you copy the link to the resulting image, you can use that straight into imread if you prefer to saving a file (this also makes your code automatic such that it can be used in a script, assuming you have an internet connection.
e.g. I used the following math tex to generate the greek title:
\Pi\acute\alpha\lambda\iota~\sigma\kappa\alpha\tau\acute\alpha~\tau\alpha~\kappa\acute\alpha\nu\alpha\mu\epsilon~\mu\epsilon~\tau\alpha~E\lambda\lambda\eta\nu\iota\kappa\acute\alpha~\rho\epsilon~\mu\alpha\lambda\acute\alpha\kappa\epsilon\varsigma
and then using the link to the resulting image (or saving locally)
>> image % draw octave logo
>> greektitle = imread('http://latex.codecogs.com/png.latex?%5Cdpi%7B300%7D%20%5Chuge%20%5CPi%5Cacute%5Calpha%5Clambda%5Ciota%7E%5Csigma%5Ckappa%5Calpha%5Ctau%5Cacute%5Calpha%7E%5Ctau%5Calpha%7E%5Ckappa%5Cacute%5Calpha%5Cnu%5Calpha%5Cmu%5Cepsilon%7E%5Cmu%5Cepsilon%7E%5Ctau%5Calpha%7EE%5Clambda%5Clambda%5Ceta%5Cnu%5Ciota%5Ckappa%5Cacute%5Calpha%7E%5Crho%5Cepsilon%7E%5Cmu%5Calpha%5Clambda%5Cacute%5Calpha%5Ckappa%5Cepsilon%5Cvarsigma');
>> greektitle = repmat(greektitle,[1,1,3]); % make rgb so unaffected by colormap
>> axes; imagesc(greektitle); axis equal off;
>> P=get(gca,'position'); set(gca,'position',[P(1),0.9,P(3),0.1]); % place on top
>> saveas(gcf,'out.png','png')

Jupyter: how to make simple illustrations

I am learning to use Jupyter/IPython Notebook as an electronic notebook. Sometimes I need simple illustrations to go along with my calculations, e.g. arrows to represent vector quantities. That's the kind of illustration for which TikZ would be used if we were in Latex. Having tried the TikZ magic extension and failed, I wonder if there's a more native (Python) way to do this. I don't see Matplotlib as the right tool for this sort of thing (correct me if I'm wrong).
If you think TikZ magic is indeed the way to go and I should try to get it to work, then do say so. Thanks.
TikZ (prefered solution)
If you're already familiar with TikZ the respective magic is probably the best option. To use it, simply follow the installation instruction in this repo (pip install git+git://github.com/mkrphys/ipython-tikzmagic.git) and load the extension as shown in on the githib page with %load_ext tikzmagic.
I just tried with IPython 3.1 and it works fine. Of course you have to have pdflatex available.
Matplotlib
If you want to draw simple arrows matplotlib can be used as well and is, of course, more pythonic than TikZ. A really simple example based on this example could look like
import matplotlib.pyplot as plt
%matplotlib inline
plt.axis('off')
plt.arrow(0, 0, 0.5, 0.5, head_width=0.05, head_length=0.1, fc='k', ec='k');
For more technical plots with lots of arrows and dimensions, I totally agree with you that matplotlib is not be preferred.
Other alternatives
There is also an asymptote magic found here. I haven't tried this yet, though.
Finally, you could use svgs either written in the notebook (hints see this question, or using Inkscape or similar and embed the resulting svg-file via the from IPython.display import SVG.

emacs: using mmm-mode to combine markdown-mode and ESS for editing rmarkdown files

I'm playing with mmm-mode to combine markdown-mode and ESS for editing Rmarkdown files. I'm using gnu emacs 24.3 on Windows 7 and up-to-date version of the aforementioned modes. This is what I've got in my .emacs file:
(require 'mmm-mode) ;;; possibly init with (require 'mmm-auto) instead
(mmm-add-classes
'((rmarkdown
:submode r-mode
:face mmm-declaration-submode-face
:front "^```[{]r.*[}] *$"
:back "^``` *$")))
(setq mmm-global-mode 'maybe)
(mmm-add-mode-ext-class 'markdown-mode "\\.rmd\\'" 'rmarkdown)
That works so far as within a buffer showing an rmarkdown file, R code blocks are recognized and I get proper syntactically aware font-locking within both R code blocks and markdown blocks. More, when I have the point in an R code block I get ESS and Imenu-R menus and when it's in a markdown region I get a markdown menu. So far so good.
Here are my issues. Within R code blocks electric left assignment doesn't work. I can't simply hit the underscore key to get '<-' and to toggle between that and '_'.
Also, I don't get syntactically aware auto indentation for R code.
Both of these things work when I'm using ESS to edit files containing pure R code.
Any thoughts on how to tune this up? I'm aware of this previous post from nearly a year ago: How can I use Emacs ESS mode with R markdown? and the pointer to polymode, but polymode seems to be advancing slowly. I've also seen other pointers to org-mode for similar functionality and while that's a plunge I may take at some point, today my questions are about getting the most out of the combination of mmm-mode, markdown-mode and ESS. Thanks for your help.
Polymode is the way to go. Unfortunately still in development, but works for most of the things.

Resources