Magic commands
(5 minutes)
Why are we doing magic when this is physics?
In Jupyter, “magic” refers to additional commands added by Jupyter to the kernel environment that aren’t normally part of that kernel’s language.1 I’m going to start with a slightly exotic magic command because I think you’ll find it useful.
In a new cell in the Python notebook we just worked with, execute this command:2
%jsroot on
How we know it’s magic
As a general rule, magic commands begin with the percent sign “%”.3
Draw the canvas again:
my_canvas.Draw()
Move the cursor over the new plot.
Interactive plots
Ah, that’s more like it! The plot is now interactive, though not quite in the same way as in X-Windows ROOT. Play around a bit, looking at tooltips and right-clicking. In particular, if you right-click on the axes you’ll be able to set their titles in a way that’s much more intuitive than before.
Note the faint icon below the lower left-hand corner of the plot. Hover/click the mouse on it to see some options.
More magic
If you execute %lsmagic you’ll see a list of available magic
commands. There’s probably more here than you can absorb right now.4
These are examples of magic commands I find to be the most useful:
%mkdir subdirectory
%cp ~seligman/root-class/jsroot-test.ipynb subdirectory
%ls subdirectory
%less c1.C
%man root
%cd subdirectory
The above commands are “line magics,” which are executed line-by-line within a cell. There are also “cell magics” that affect the contents of the entire cell in which they appear; they must appear as the first line in a cell. They begin with a double “%”. Examples:
%%writefile filename(write the cell to filefilename);%%timeit(execute the cell many times and determine the average execution time);%%sh(execute the cell as a UNIX shell script).
- 1
No, nothing to do with Doctor Strange or Gandalf, though you may find yourself muttering “You shall not pass!” as you work with ROOT.
- 2
Note that the
%jsrootmagic command is only available in Python-based notebooks after you’ve executedimport ROOTorfrom ROOT import...In ROOT C++ notebooks it’s built-in.“JSROOT” is short for “Javascript ROOT”; it’s an evolving project to bring more interactivity of ROOT graphics into web browsers.
- 3
Well… not really. There’s an option
(%automagic on|off) that allows you to omit the leading %. In this tutorial I’ll always include the % prefix to make it clear when a command is “magic”.- 4
Here are more details about magic commands.