Reading ipython's magic "precision" value - ipython

You can set printing precision in ipython by using magic function precision:
In [1]: %precision 2
Out[1]: '%.2f'
In [2]: 5/7
Out[2]: 0.71
You can also issue a command through ipython object:
ipython = get_ipython()
ipython.run_line_magic("precision", "2")
But how do you obtain the string '%.2f'?
Is there a command like ipython.get_magic_value('precision')?

Found the solution:
from IPython import get_ipython
ipython = get_ipython()
ipython.run_line_magic("precision", "3")
# you could also type %precision 3
form = ipython.display_formatter.formatters['text/plain']
form.float_format
#yields: '%.3f'
form.float_precision
#yields '3'

Related

How to use numba in Colaboratory

Anybody tried to use numba in google collaboratory? I just can not figure out how to set it up in this environment.
At the moment, I'm stuck with the error library nvvm not found.
Copy this code into cell. It works for me.
!apt-get install nvidia-cuda-toolkit
!pip3 install numba
import os
os.environ['NUMBAPRO_LIBDEVICE'] = "/usr/lib/nvidia-cuda-toolkit/libdevice"
os.environ['NUMBAPRO_NVVM'] = "/usr/lib/x86_64-linux-gnu/libnvvm.so"
from numba import cuda
import numpy as np
import time
#cuda.jit
def hello(data):
data[cuda.blockIdx.x, cuda.threadIdx.x] = cuda.blockIdx.x
numBlocks = 5
threadsPerBlock = 10
data = np.ones((numBlocks, threadsPerBlock), dtype=np.uint8)
hello[numBlocks, threadsPerBlock](data)
print(data)
I didn't have to install the packages #Algis suggested, but the paths to the drivers were different. So I had to do the following.
First determine the correct paths for the drivers
!find / -iname 'libdevice'
!find / -iname 'libnvvm.so'
# Output:
# /usr/local/cuda-9.2/nvvm/lib64/libnvvm.so
# /usr/local/cuda-9.2/nvvm/libdevice
Then set the paths as #Algis described
import os
os.environ['NUMBAPRO_LIBDEVICE'] = "/usr/local/cuda-9.2/nvvm/libdevice"
os.environ['NUMBAPRO_NVVM'] = "/usr/local/cuda-9.2/nvvm/lib64/libnvvm.so"
You can do #Stan's work in one simple sweep if you have this block at the beginning of your colab notebook (this also automatically updates as CUDA gets updated)
import os
dev_lib_path = !find / -iname 'libdevice'
nvvm_lib_path = !find / -iname 'libnvvm.so'
assert len(dev_lib_path)>0, "Device Lib Missing"
assert len(nvvm_lib_path)>0, "NVVM Missing"
os.environ['NUMBAPRO_LIBDEVICE'] = dev_lib_path[0]
os.environ['NUMBAPRO_NVVM'] = nvvm_lib_path[0]

use pep8 to check the coding style in jupyter notebook

I have a problem in using pep8 to check the coding style in jupyter notebook.
install by:
in[1]
%install_ext https://raw.githubusercontent.com/SiggyF/notebooks/master/pep8_magic.py
out
Installed pep8_magic.py. To use it, type:
%load_ext pep8_magic
load by
in[2]
%load_ext pep8_magic
out
The pep8_magic extension is already loaded. To reload it, use:
%reload_ext pep8_magic
use it by
in[3]
%%pep8
a=1
out
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-3b6f6dbc7761> in <module>()
----> 1 get_ipython().run_cell_magic(u'pep8', u'', u'\na = 1')
/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.pyc in run_cell_magic(self, magic_name, line, cell)
2118 magic_arg_s = self.var_expand(line, stack_depth)
2119 with self.builtin_trap:
-> 2120 result = fn(magic_arg_s, cell)
2121 return result
2122
/home/cs/.ipython/extensions/pep8_magic.pyc in pep8(line, cell)
38 with tempfile.NamedTemporaryFile() as f:
39 # save to file
---> 40 f.write(bytes(cell + '\n', 'UTF-8'))
41 # make sure it's written
42 f.flush()
TypeError: str() takes at most 1 argument (2 given)
It seems that I have installed and loaded it successfully but I can not run the cell magic.
Later I found the problem was caused by some differences between python2 and python3. By using io.Bytes and f.write(cell+'\n') in pep2_magic.py, it worked. But unfortunately, it still can't output information of pep8, like the example here pep8 style guide

How do you make NLTK draw() trees that are inline in iPython/Jupyter

For Matplotlib plots in iPython/Jupyter you can make the notebook plot plots inline with
%matplotlib inline
How can one do the same for NLTK draw() for trees? Here is the documentation http://www.nltk.org/api/nltk.draw.html
Based on this answer:
import os
from IPython.display import Image, display
from nltk.draw import TreeWidget
from nltk.draw.util import CanvasFrame
def jupyter_draw_nltk_tree(tree):
cf = CanvasFrame()
tc = TreeWidget(cf.canvas(), tree)
tc['node_font'] = 'arial 13 bold'
tc['leaf_font'] = 'arial 14'
tc['node_color'] = '#005990'
tc['leaf_color'] = '#3F8F57'
tc['line_color'] = '#175252'
cf.add_widget(tc, 10, 10)
cf.print_to_file('tmp_tree_output.ps')
cf.destroy()
os.system('convert tmp_tree_output.ps tmp_tree_output.png')
display(Image(filename='tmp_tree_output.png'))
os.system('rm tmp_tree_output.ps tmp_tree_output.png')
Little slow, but does the job. If you're doing it remotely, don't forget to run your ssh session with -X key (like ssh -X user#server.com) so that Tk could initialize itself (no display name and no $DISPLAY environment variable-kind of error)
UPD: it seems like last versions of jupyter and nltk work nicely together, so you can just do IPython.core.display.display(tree) to get a nice-looking tree-render embedded into the output.
2019 Update:
This runs on Jupyter Notebook:
from nltk.tree import Tree
from IPython.display import display
tree = Tree.fromstring('(S (NP this tree) (VP (V is) (AdjP pretty)))')
display(tree)
Requirements:
NLTK
Ghostscript

Print proper mathematical formatting

When I use sympy to get the square root of 8, the output is ugly:
2*2**(1/2)
import sympy
In [2]: sympy.sqrt(8)
Out[2]: 2*2**(1/2)
Is there any way to make sympy print output in proper mathematical notation (i.e. using the proper symbol for square root) ?
UPDATE:
when I follow the suggestions from #pqnet:
from sympy import *
x, y, z = symbols('x y z')
init_printing()
init_session()
I get following error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-23-21d886bf3e54> in <module>()
2 x, y, z = symbols('x y z')
3 init_printing()
----> 4 init_session()
/usr/lib/python2.7/dist-packages/sympy/interactive/session.pyc in init_session(ipython, pretty_print, order, use_unicode, quiet, argv)
154 # and False means don't add the line to IPython's history.
155 ip.runsource = lambda src, symbol='exec': ip.run_cell(src, False)
--> 156 mainloop = ip.mainloop
157 else:
158 mainloop = ip.interact
AttributeError: 'ZMQInteractiveShell' object has no attribute 'mainloop'
In an ipython notebook you can enable Sympy's graphical math typesetting with the init_printing function:
import sympy
sympy.init_printing(use_latex='mathjax')
After that, sympy will intercept the output of each cell and format it using math fonts and symbols. Try:
sympy.sqrt(8)
See also:
Printing section in the Sympy Tutorial.
The simplest way to do it is this:
sympy.pprint(sympy.sqrt(8))
For me (using rxvt-unicode and ipython) it gives
___
2⋅╲╱ 2

iPython prompt confusion

I am having trouble getting the prompt to show the current working directory in iPython 0.13.1 running in windows. As you can see below, after changing the current working directory to 'C:\Users\Lou\Documents\Lou's Software\projects\loutilities', the \Y3 only shows 'C:/Users/Lou'. The same behavior is seen with \w and {cwd} configurations.
I'm sure this is something dumb I'm doing, but I haven't been able to figure it out, or find anything through Google or Stack Overflow.
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.
IPython 0.13.1 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
[IPKernelApp] To connect another client to this kernel, use:
[IPKernelApp] --existing kernel-9572.json
C:/Users/Lou> cd "C:\Users\Lou\Documents\Lou's Software\projects\loutilities"
C:\Users\Lou\Documents\Lou's Software\projects\loutilities
C:/Users/Lou> config PromptManager
PromptManager options
-------------------
PromptManager.color_scheme=<Unicode>
Current: u'Linux'
PromptManager.in2_template=<Unicode>
Current: u' .\\D.: '
Continuation prompt.
PromptManager.in_template=<Unicode>
Current: u'\\Y3> '
Input prompt. '\#' will be transformed to the prompt number
PromptManager.justify=<Bool>
Current: False
If True (default), each prompt will be right-aligned with the preceding one.
PromptManager.out_template=<Unicode>
Current: u'Out[\\#]: '
Output prompt. '\#' will be transformed to the prompt number
Thomas asked for output of os.getcwdu(). I used config command to change the prompt (I'd gone back to In [#n] prompt), and In [#n] prompt remained. A clue?
In [1]: config PromptManager.in_template='\\Y3'
In [3]: config PromptManager
PromptManager options
-------------------
PromptManager.color_scheme=<Unicode>
Current: u'Linux'
PromptManager.in2_template=<Unicode>
Current: u' .\\D.: '
Continuation prompt.
PromptManager.in_template=<Unicode>
Current: u'\\Y3'
Input prompt. '\#' will be transformed to the prompt number
PromptManager.justify=<Bool>
Current: True
If True (default), each prompt will be right-aligned with the preceding one.
PromptManager.out_template=<Unicode>
Current: u'Out[\\#]: '
Output prompt. '\#' will be transformed to the prompt number
In [4]: import os
In [5]: os.getcwdu()
Out[5]: u'C:\\Users\\Lou'
In [6]: cd weather
(bookmark:weather) -> C:\Users\Lou\Documents\Lou's Software\projects\weather
C:\Users\Lou\Documents\Lou's Software\projects\weather
In [7]: os.getcwdu()
Out[7]: u"C:\\Users\\Lou\\Documents\\Lou's Software\\projects\\weather"
And the original test duplicated...
C:/Users/Lou> cd weather
(bookmark:weather) -> C:\Users\Lou\Documents\Lou's Software\projects\weather
C:\Users\Lou\Documents\Lou's Software\projects\weather
C:/Users/Lou> import os
C:/Users/Lou> os.getcwdu()
Out[3]: u"C:\\Users\\Lou\\Documents\\Lou's Software\\projects\\weather"
C:/Users/Lou> config PromptManager
PromptManager options
-------------------
PromptManager.color_scheme=<Unicode>
Current: u'Linux'
PromptManager.in2_template=<Unicode>
Current: u' .\\D.: '
Continuation prompt.
PromptManager.in_template=<Unicode>
Current: u'\\Y3> '
Input prompt. '\#' will be transformed to the prompt number
PromptManager.justify=<Bool>
Current: True
If True (default), each prompt will be right-aligned with the preceding one.
PromptManager.out_template=<Unicode>
Current: u'Out[\\#]: '
Output prompt. '\#' will be transformed to the prompt number
11/21/12 - check get_ipython().prompt_manager.templates:
C:/Users/Lou> pwd
Out[1]: u'C:\\Users\\Lou'
C:/Users/Lou> get_ipython().prompt_manager.templates
Out[2]:
{'in': u'{cwd_y[3]}> ',
'in2': u' .{dots}.: ',
'out': u'Out[{color.number}{count}{color.prompt}]: '}
C:/Users/Lou> cd weather
(bookmark:weather) -> C:\Users\Lou\Documents\Lou's Software\projects\weather
C:\Users\Lou\Documents\Lou's Software\projects\weather
C:/Users/Lou> pwd
Out[4]: u"C:\\Users\\Lou\\Documents\\Lou's Software\\projects\\weather"
C:/Users/Lou> get_ipython().prompt_manager.templates
Out[5]:
{'in': u'{cwd_y[3]}> ',
'in2': u' .{dots}.: ',
'out': u'Out[{color.number}{count}{color.prompt}]: '}