官术网_书友最值得收藏!

Teaching programming in the notebook with IPython blocks

The IPython notebook is not only a tool for scientific research and data analysis but also a great tool for teaching. In this recipe, we show a simple and fun Python library for teaching programming notions: IPython Blocks (available at http://ipythonblocks.org). This library allows you or your students to create grids of colorful blocks. You can change the color and size of individual blocks, and you can even animate your grids. There are many basic technical notions you can illustrate with this tool. The visual aspect of this tool makes the learning process more effective and engaging.

In this recipe, we will notably perform the following tasks:

  • Illustrate matrix multiplication with an animation
  • Display an image as a block grid

This recipe is partly inspired by the example at http://nbviewer.ipython.org/gist/picken19/b0034ba7ec690e89ea79.

Getting ready

You need to install IPython Blocks for this recipe. You can just type in a terminal pip install ipythonblocks. Note that you can also execute this shell command from the IPython notebook by prefixing this command with !.

In [1]: !pip install ipythonblocks

For the last part of this recipe, you also need to install Pillow, available at http://pillow.readthedocs.org/en/latest/; you will find more instructions in Chapter 11, Image and Audio Processing. With Anaconda, you can execute conda install pillow in a terminal.

Finally, you need to download the Portrait dataset from the book's website (https://github.com/ipython-books/cookbook-data) and extract it in the current directory. You can also play with your own images!

How to do it...

  1. First, we import some modules as follows:
    In [1]: import time
            from IPython.display import clear_output
            from ipythonblocks import BlockGrid, colors
  2. Now, we create a block grid with five columns and five rows, and we fill each block in purple:
    In [2]: grid = BlockGrid(width=5, height=5,
                             fill=colors['Purple'])
            grid.show()
  3. We can access individual blocks with 2D indexing. This illustrates the indexing syntax in Python. We can also access an entire row or line with a : (colon). Each block is represented by an RGB color. The library comes with a handy dictionary of colors, assigning RGB tuples to standard color names as follows:
    In [3]: grid[0,0] = colors['Lime']
            grid[-1,0] = colors['Lime']
            grid[:,-1] = colors['Lime']
            grid.show()
  4. Now, we are going to illustrate matrix multiplication, a fundamental notion in linear algebra. We will represent two (n,n) matrices, A (in cyan) and B (lime) aligned with C = A B (yellow). To do this, we use a small trick of creating a big white grid of size (2n+1,2n+1). The matrices A, B, and C are just views on parts of the grid.
    In [4]: n = 5
            grid = BlockGrid(width=2*n+1, 
                             height=2*n+1, 
                             fill=colors['White'])
            A = grid[n+1:,:n]
            B = grid[:n,n+1:]
            C = grid[n+1:,n+1:]
            A[:,:] = colors['Cyan']
            B[:,:] = colors['Lime']
            C[:,:] = colors['Yellow']
            grid.show()
  5. Let's turn to matrix multiplication itself. We perform a loop over all rows and columns, and we highlight the corresponding rows and columns in A and B that are multiplied together during the matrix product. We combine IPython's clear_output() method with grid.show() and time.sleep() (pause) to implement the animation as follows:
    In [5]: for i in range(n):
                for j in range(n):
                    # We reset the matrix colors.
                    A[:,:] = colors['Cyan']
                    B[:,:] = colors['Lime']
                    C[:,:] = colors['Yellow']
                    # We highlight the adequate rows
                    # and columns in red.
                    A[i,:] = colors['Red']
                    B[:,j] = colors['Red']
                    C[i,j] = colors['Red']
                    # We animate the grid in the loop.
                    clear_output()
                    grid.show()
                    time.sleep(0.25)
  6. Finally, we will display an image with IPython Blocks. We import the JPG image with Image.open() and we retrieve the data with getdata() as follows:
    In [6]: from PIL import Image
            imdata = Image.open('data/photo.jpg').getdata()
  7. Now, we create a BlockGrid instance with the appropriate number of rows and columns, and we set each block's color to the corresponding pixel's color in the image. We use a small block size, and we remove the lines between the blocks as follows:
    In [7]: rows, cols = imdata.size
            grid = BlockGrid(width=rows, height=cols,
                             block_size=4, lines_on=False)
            for block, rgb in zip(grid, imdata):
                block.rgb = rgb
            grid.show()

There's more...

As demonstrated in this recipe, the notebook is an ideal platform for education activities at all levels.

This library has been developed prior to the interactive notebook features brought by IPython 2.0. We can now expect even more interactive developments.

主站蜘蛛池模板: 吴川市| 淮南市| 亚东县| 郴州市| 五寨县| 肥城市| 平利县| 酒泉市| 承德县| 霍州市| 清徐县| 凤阳县| 建瓯市| 磐安县| 西乌珠穆沁旗| 大竹县| 措美县| 永丰县| 昆山市| 辽宁省| 汾阳市| 桐梓县| 阳信县| 清河县| 忻城县| 耿马| 增城市| 房山区| 昭觉县| 鹤岗市| 蓬安县| 赤城县| 正定县| 旺苍县| 容城县| 咸宁市| 贞丰县| 迁安市| 武宁县| 稻城县| 玉田县|