diff --git a/.gitignore b/.gitignore index 1e6dd11..0ac043a 100644 --- a/.gitignore +++ b/.gitignore @@ -73,3 +73,7 @@ archive_notebooks # memo for codeship setting codeship_settings.txt + +# sphinx directories +_build +_static diff --git a/chapter2/Makefile b/chapter2/Makefile new file mode 100644 index 0000000..6cee37b --- /dev/null +++ b/chapter2/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +SPHINXPROJ = jupyter-notebook +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file diff --git a/chapter2/conf.py b/chapter2/conf.py new file mode 100644 index 0000000..3a5305b --- /dev/null +++ b/chapter2/conf.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# +# jupyter-notebook documentation build configuration file, created by +# sphinx-quickstart on Sat Apr 22 16:07:08 2017. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +# import os +# import sys +# sys.path.insert(0, os.path.abspath('.')) + + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = ['IPython.sphinxext.ipython_directive', + 'IPython.sphinxext.ipython_console_highlighting', + 'sphinx.ext.mathjax', + 'sphinx.ext.autodoc', + 'sphinx.ext.doctest', + 'sphinx.ext.inheritance_diagram', + ] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = 'jupyter-notebook' +copyright = '2017, Keisuke Fujii' +author = 'Keisuke Fujii' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '' +# The full version, including alpha/beta/rc tags. +release = '' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = 'ja' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'alabaster' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + + +# -- Options for HTMLHelp output ------------------------------------------ + +# Output file base name for HTML help builder. +htmlhelp_basename = 'jupyter-notebookdoc' + + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'jupyter-notebook.tex', 'jupyter-notebook Documentation', + 'Keisuke Fujii', 'manual'), +] + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'jupyter-notebook', 'jupyter-notebook Documentation', + [author], 1) +] + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'jupyter-notebook', 'jupyter-notebook Documentation', + author, 'jupyter-notebook', 'One line description of project.', + 'Miscellaneous'), +] diff --git a/chapter2/index.rst b/chapter2/index.rst new file mode 100644 index 0000000..50b2543 --- /dev/null +++ b/chapter2/index.rst @@ -0,0 +1,19 @@ +.. jupyter-notebook documentation master file, created by + sphinx-quickstart on Sat Apr 22 16:07:08 2017. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to jupyter-notebook's documentation! +============================================ + +.. toctree:: + :maxdepth: 2 + :caption: Contents: + + src/introduction.rst + src/tutorial.rst + src/tutorial2.rst + src/tutorial3.rst + src/tutorial4.rst + src/tutorial5.rst + src/summary.rst diff --git a/chapter2/make.bat b/chapter2/make.bat new file mode 100644 index 0000000..0b98259 --- /dev/null +++ b/chapter2/make.bat @@ -0,0 +1,36 @@ +@ECHO OFF + +pushd %~dp0 + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set SOURCEDIR=. +set BUILDDIR=_build +set SPHINXPROJ=jupyter-notebook + +if "%1" == "" goto help + +%SPHINXBUILD% >NUL 2>NUL +if errorlevel 9009 ( + echo. + echo.The 'sphinx-build' command was not found. Make sure you have Sphinx + echo.installed, then set the SPHINXBUILD environment variable to point + echo.to the full path of the 'sphinx-build' executable. Alternatively you + echo.may add the Sphinx directory to PATH. + echo. + echo.If you don't have Sphinx installed, grab it from + echo.http://sphinx-doc.org/ + exit /b 1 +) + +%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% +goto end + +:help +%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% + +:end +popd diff --git a/chapter2/savefig/tutorial2_plot1.png b/chapter2/savefig/tutorial2_plot1.png new file mode 100644 index 0000000..72a7d47 Binary files /dev/null and b/chapter2/savefig/tutorial2_plot1.png differ diff --git a/chapter2/savefig/tutorial2_plot2.png b/chapter2/savefig/tutorial2_plot2.png new file mode 100644 index 0000000..f4872b2 Binary files /dev/null and b/chapter2/savefig/tutorial2_plot2.png differ diff --git a/chapter2/savefig/tutorial3_plot1.png b/chapter2/savefig/tutorial3_plot1.png new file mode 100644 index 0000000..86c30dd Binary files /dev/null and b/chapter2/savefig/tutorial3_plot1.png differ diff --git a/chapter2/src/figs/np_suggest.png b/chapter2/src/figs/np_suggest.png new file mode 100644 index 0000000..7f59715 Binary files /dev/null and b/chapter2/src/figs/np_suggest.png differ diff --git a/chapter2/src/figs/np_suggest2.png b/chapter2/src/figs/np_suggest2.png new file mode 100644 index 0000000..31d6fa1 Binary files /dev/null and b/chapter2/src/figs/np_suggest2.png differ diff --git a/chapter2/src/figs/try_jupyter.png b/chapter2/src/figs/try_jupyter.png new file mode 100644 index 0000000..36eba55 Binary files /dev/null and b/chapter2/src/figs/try_jupyter.png differ diff --git a/chapter2/src/figs/try_jupyter_plot.png b/chapter2/src/figs/try_jupyter_plot.png new file mode 100644 index 0000000..ed51481 Binary files /dev/null and b/chapter2/src/figs/try_jupyter_plot.png differ diff --git a/chapter2/src/figs/try_jupyter_start.png b/chapter2/src/figs/try_jupyter_start.png new file mode 100644 index 0000000..81ae06c Binary files /dev/null and b/chapter2/src/figs/try_jupyter_start.png differ diff --git a/chapter2/src/introduction.rst b/chapter2/src/introduction.rst new file mode 100644 index 0000000..abf1618 --- /dev/null +++ b/chapter2/src/introduction.rst @@ -0,0 +1,226 @@ +Jupyter-notebook +====================== + +Jupyter-notebookは、 +対話的プログラミング環境を提供するオープンソース・ソフトウェアである。 + ++ 実行結果を可視化しながらデータ解析を進めることができる ++ ソースコード、実行結果、数式、文書を1つのファイルに保存することができる + +などが特徴であり、近年利用が広まっている。 + +.. 歴史 + +元々 Jupyter-notebook は IPython というPythonの対話的プログラム環境の一部の +IPython-notebookとして開発が進められてきたが、 +その有用性が認められ、現在はPythonに限らず +Julia, R, ruby など他のインタープリタ言語でも利用可能な +汎用ソフトウェアとして開発が続けられている。 + +上記の特徴は、試行錯誤しながらすすめる研究活動を進めるのに効果的なだけでなく、 +研究成果をデータ・解析コード・結果をまとめて公開するのにも有用である。 +例えば、2016年に重力波が初めて発見された時の計測データ・解析プログラムは +https://losc.ligo.org/s/events/GW150914/GW150914_tutorial.html +に Jupyter-notebook 形式で公開されており、 +誰でもその結果を追試することができる。 + +さらにソースコードの実行結果をすぐに可視化できることは、 +プログラムスキルを身に付けるためにも非常に効果的である。 + +本章では、Jupyter-notebookを用いてPythonの基本的な文法・使用法を学ぶ。 + + +---------------------------------------- +Jupyter-notebookを体験する +---------------------------------------- + +本講座で紹介したPython環境の1つであるAnacondaにはすでにJupyter-notebookは含まれており、 +前章に従って環境を整えた読者はすぐに利用が可能である。 +さらに、インストールがされていない環境からもその使用感が体験できるサービスが用意されている。 + +ウェブブラウザで +https://try.jupyter.org/ +にアクセスすると、図1のようなページが表示される。 + +.. figure:: figs/try_jupyter.png + :scale: 50 % + :alt: home of try-jupyter + +右上の New ボタンから Python 3 を選択すると、 +新しいノートブックファイルが作成され、図2のような新しいノートブックページが開かれる。 + +.. figure:: figs/try_jupyter_start.png + :scale: 50 % + :alt: blank notebook + +Jupyter-notebook では、セルと呼ばれるボックス内にスクリプトを入力する。 +スクリプトはセル単位で実行することができる。 +まずは、図3にあるように、ひとつ目のセルに以下を入力してみよう。 + +.. code-block:: python + + print('Hello world!') + +このセルを実行するためには、再生ボタンを押すか、 +キーボードの Shift + Enter を同時に押下する。 + +実際に実行すると、入力したセルの下に"Hello world!" が表示される。 +C言語などのコンパイル言語では、print 文を実行するためにも +ソースコードの作成、コンパイル、実行が必要なことに比べて、 +インタープリタ言語である Python は非常に簡潔に実行できることが理解できると思う。 + +内容は後ほど説明するので、まずは図3のように以下の内容を入力してみよう。 + +.. figure:: figs/try_jupyter_plot.png + :scale: 50 % + :alt: example of jupyter-notebook + + +.. あ + + .. code-block:: python + + import numpy as np + import matplotlib.pyplot as plt + + .. code-block:: python + + x = np.linspace(-10,10,21) + x + + .. code-block:: python + + y = np.exp(-x*x / 2) + y + + .. code-block:: python + + plt.plot(x, y) + + +上記では、ベクトル変数 x と y を定義し、 +その内容を画面に表示したあと、グラフに描画している。 + +セルの操作 +---------------------------------------- + +Jupyter-notebook には、セルという概念がある。 +上記でスクリプトを記入したボックスがセルである。 +以下の3種類のセルが提供されている。 + + 1. コードセル (Code cell) + 2. マークダウンセル (Markdown cell) + 3. テキストセル (Raw NBconvert cell) + +セルの種類は、ツールバーの Cell > Cell type から変更することができる。 +マークダウンセル*では、ノートブック内にマークダウン記法により、 +構造化された文章、例えば見出しや数式などを記録できる。 + +以下のようにマークダウンセルを追加してみよう。 +Cell > Cell type からマークダウンセルを選択する。 +セル内に + +.. code-block:: none + + Y is a Gaussian function with 0 mean 1 standard deviation + $$ + Y = \exp \left\[ - \frac{-x^2}{2} \right] + $$ + +を記入し、同様にセル内で Shift + Enter を押下する。 +文章と数式が表示されたと思う。 +本講座ではマークダウンについての説明は省略するが、すごく単純化されたHTMLやTeXを想像すれば +よい。 +特にこのマークダウンセルは、 +ノートブックを公開する時などデータ解析の内容を詳細に記述するときに重要である。 +現に、上記の重力波検出データのノートブックでは、マークダウンセルが半数以上を占める。 + +このようにJupyter-notebookは変数などの状態を簡単に可視化しながら、 +プログラムの開発・データの解析が可能であり、 +さらにそのデータ解析の様子をデータ・コード・結果・文書をまとめて記録することが可能である。 + + +---------------------------------------- +Jupyter-notebookのインストール +---------------------------------------- + +本講座で紹介したPython環境の1つであるAnacondaには、 +すでにJupyter-notebookが含まれている。 + +インストールされていない別の環境などはターミナルから + +.. code-block:: bash + + pip install jupyter-notebook + + +を実行することでインストールできる。 + +---------------------------------------- +Jupyter-notebookの起動と終了 +---------------------------------------- + +Windowsでの起動 +---------------------------------------- + +WindowsからJupyter-notebookを起動するための手順は、以下のとおりである。 + + 1. コマンドプロンプトを立ち上げる (必要に応じてディレクトリに移動する) + 2. 起動コマンド jupyter-notebook を入力する + +これにより、自動的にブラウザが立ち上がり、Jupyter-notebookのホーム画面が表示される。 + + +Mac、Linuxでの起動 +---------------------------------------- + +Mac, Linuxの場合も同様に + + 1. ターミナルを立ち上げる (必要に応じてディレクトリに移動する) + 2. 起動コマンド jupyter-notebook を入力する + +上記操作を行うことで、図2と同様の画面がブラウザに表示される。 +なお、ブラウザを誤って閉じてしまった場合も、 + +.. code-block:: bash + + http://localhost:8888 + +にアクセスすることで、Jupyer-notebookのホーム画面に再度アクセスできる。 + + +ノートブックファイルの新規作成 +---------------------------------------- + +表示されているホーム画面は、Jupyter-notebook を起動したディレクトリがツリー表示される。 +フォルダ間の移動、ファイル・フォルダの名前の新規作成・名前の変更・削除など、 +シンプルなファイル操作は一通りできるようになっている。 + +ディレクトリを適宜移動すれば、ノートブックファイルを新たに作成して学習を始めよう。 + +上記で体験したように、 +右上の New から Python 3 を選択すると、 +新しいノートブックファイルが作成され、図2のようなページが開かれる。 + +作成されるファイルはデフォルトでは Untitled であるので、 +これをクリックすると図4のようにファイル名を変更するダイアログが表示される。 +ここでは、python_tutorial と変更した。 + +Jupyter-notebook の終了 +---------------------------------------- + +Jupyter-notebook には、 +個別のノートブックファイル(カーネル)の終了とJupyter-notebook 自体の終了の2つがある。 +カーネルとはPythonの実行を行っているソフトウェアのことであり、 +オブジェクトの内容を格納していたり、 +何か計算をしていたりする。 +ブラウザ画面を閉じるだけではカーネルは終了されない。 +カーネルを終了するには、ツールバーの File > Close and halt を実行する。 +もしくは、 +Jupyter-notebook ホーム画面で Running タブを見ると、 +カーネルが実行中であるノートブックファイル一覧が表示されるため、 +そこで該当するノートブックファイルの shutdown ボタンを押すことで、 +メモリ内に格納されているデータなどが消去される。 + +Jupyter-notebook 自体を終了するには起動したコマンドプロンプトもしくはターミナルにて +Ctrl+C を実行する。 diff --git a/chapter2/src/summary.rst b/chapter2/src/summary.rst new file mode 100644 index 0000000..1b1d598 --- /dev/null +++ b/chapter2/src/summary.rst @@ -0,0 +1,7 @@ +まとめ +=========== + +本章では、Jupyter-notebook を用いたPythonの基本的な文法と使用法を概観した。 +Jupyter-notebookのような対話的な環境では書き間違いなどによるバグがすぐに見つかるため、 +特にプログラミングに不慣れな人にとっても効果的である。 +本章で紹介した例などをぜひ実行してほしい。 diff --git a/chapter2/src/tutorial.rst b/chapter2/src/tutorial.rst new file mode 100644 index 0000000..a48c36d --- /dev/null +++ b/chapter2/src/tutorial.rst @@ -0,0 +1,254 @@ +Python 入門 +=================== + +本章では、Jupyter-notebookを使って、Pythonの文法を学ぶ。 + +-------------------------- +Pythonの基本変数 +-------------------------- + + +C言語やFortranのようなコンパイラ言語と異なり、 +変数(オブジェクト)を定義する際その型を指定する必要がない。 + +.. ipython:: python + + x = 'Hello python!' + y = 2 + x + y + +上記の場合 x は文字列(str)であり、yは整数(int)となる。 +オブジェクトの型を知りたい場合は、 + +.. ipython:: python + + type(x) + type(y) + +を実行すれば良い。 +なお、type() 関数は、引数のオブジェクトのクラス名を返す関数である。 + +Python の基本的な型には主に以下が挙げられる。 + ++ 整数, int ++ 浮動小数点実数, float ++ 文字列, str ++ リスト, list ++ タプル, tuple ++ 辞書(連想配列), dict + +Python はオブジェクト指向の言語であり、 +実際には後ほど説明する Numpy などのパッケージに含まれる上記とは別の型(オブジェクト) +を多様することになるが、 +まずは上記の基本形を学ぶ + + +整数・浮動小数点 +-------------------------- + +他のプログラム言語と同様、整数や浮動小数点といった型をサポートしており、 +四則演算や階乗等は一般的な書き方で計算できる。 + +.. ipython:: python + + 1 + 3 + 3.0 ** 2.0 # ** は階乗を表す。 + + +文字列 +-------------------------- + +文字列を格納するオブジェクトである。 +シングルコーテーションもしくはダブルコーテーションで囲うことで文字列となる。 +なお、3連のシングルコーテーションで囲うと、改行を含めた文字列として扱うことができる。 +各要素にアクセスするためには、 [] 演算子を利用する。 +このようなアクセスの方法を Indexing (インデクシング)と呼ぶ。 + +.. ipython:: python + + x = 'Hello python!' + x[0] + x[2] + x[-1] + + +Python の インデクシングの特徴は + ++ 一番最初の要素は 0 でアクセスする + ++ 負のインデクスを指定することで、末尾から数えることもできる。例えば、インデクスとして -1 を指定すると、末尾の要素、-2 を指定すると 末尾から2つ目の要素にアクセスできる。 + +さらに、同時に複数の要素にアクセスする(Slicing)スライシングも可能である。 + +.. ipython:: python + + x[1:4] + + x[:5] + + x[-3:] + + +1:4 という表記は、1~3番目の要素を示し、元のオブジェクトの部分要素が選択される。 +片方を省略した :5 などは、0:5 と同値である。 + +ここで x は文字列(str)であるが、文字列は以下のように + 記号で結合できる。 + +.. ipython:: python + + x2 = x + ' I love you !' + x2 + + +リスト +-------------------------- + +複数のオブジェクトを格納するオブジェクトである。 +リストオブジェクトを作成するためには、[]内に複数の要素をコンマ区切りで記述すればよい。 +なお、それぞれのオブジェクトは型が異なってもよい。 + +.. ipython:: python + + z_list = [x, 3.0, x2] + z_list + +文字列の場合と同様に、インデクシングやスライシングに対応している。 + +.. ipython:: python + + z_list[-1] + +リストの末尾に新しいオブジェクトを追加するためには .append を用いる。 + +.. ipython:: python + + z_list.append(5.0) + z_list + +また、要素数は len 関数により知ることができる。 + + +.. ipython:: python + + len(z_list) + + +タプル +-------------------------- + +タプルはリストと似ているが、要素数が後から変更できないという点でリストと異なる。 +タプルオブジェクトを作成するには、()内に複数の要素を記述するか、 +あるいは単純にコンマ区切りで記述する。 + +.. ipython:: python + + t = (1, 3.0, x) + + t + + a, b = 2.0, 3.0 # (a, b) に (2.0, 3.0) を代入していることに相当する。 + + a, b + +辞書 +-------------------------- + +辞書は連想配列とも呼ばれ、 +リストと同様に複数の要素を格納できるオブジェクトであるが、 +引数(キーと呼ぶ)に任意のオブジェクトを用いることができる。 +一般的には以下のように、文字列をキーにする場合が多い。 + +.. ipython:: python + + d = {'a': 1.0, 'b': 3.0} + + d['a'] + + d['c'] = 5.0 # 新しい要素を追加するには、単に新しいキーを指定して値を代入する。 + + d + +上記のように、{} 内に、キーと要素を:で対応させて記述する。 + + +-------------------------- +Pythonの基本文法 +-------------------------- + +この節では、Python の主な文法を簡単に述べる。 +C言語やFortran などでは例えば if 文の及ぶ範囲を{} や IF - END IF で囲って表記するが、 +Pythonではそれらをインデントで表す。 +Pythonの標準的な記法ではインデントは4つのスペースを用いる。 + +if 文 +-------------------------- + +if 文は以下のように、if [条件] : (コロン) と書き、条件が真の場合に実行する内容を +次の行から新たなインデントを用いて記述する。 + +.. code-block:: python + + if a < b: + print(a) + + +while ループ +------------ + +while ループも同様に、繰り返し実行する内容をインデントにより区別して記述する。 + +.. code-block:: python + + while a < b: + a += 1 + print(a) + + +for ループ +------------ + +Python の for ループは、C言語や Fortran の do ループより少し一般的である。 +C言語や Fortran では整数を1ずつ増やしながら実行することが多いが、 +Python では リスト(やタプル)を1つずつ変更しながら繰り返すことになる。 + +.. ipython:: python + + for z in z_list: + print(z) + +上記は、z_list の各要素を1つずつzに代入し、 +それをz_listの最初の要素から最後の要素まで繰り返す、 +という意味である。 + +C言語やFortranのforループと同様の操作は、 +0から指定した値までの整数を順に並べたオブジェクトを返す range 関数を用いることで実現できる。 + +.. ipython:: python + + for i in range(len(z_list)): + print(z_list[i]) + + +内包表記 +-------------------------- + +ソースコードは一般的に短いほど可読性が上がる。 +Pythonには内包表記と呼ばれる記述方法がある。これは、ループを簡略的に記述するものである。 + +.. ipython:: python + + x_list = [1.0, 2.0, 4.0] + y_list = [x**2 for x in x_list] + y_list + +上記の例の2行目は、 +x_list から 1つ要素を取ってきて x に代入し、 +それぞれの二乗の値を要素にもつリストをy_list に代入する、という意味であり、 +以下を一行で記述したものに相当する。 + +.. ipython:: python + + y_list = [] + for x in x_list: + y_list.append(x**2) diff --git a/chapter2/src/tutorial2.rst b/chapter2/src/tutorial2.rst new file mode 100644 index 0000000..ac7a504 --- /dev/null +++ b/chapter2/src/tutorial2.rst @@ -0,0 +1,211 @@ +外部パッケージの使用 +============================= + +Pythonの特徴は、多様なパッケージ(いくつかの機能をまとめたライブラリ)が +豊富に開発されていることが特徴である。 + +実際には生のPythonだけで用いることは少なく、基本的な数値計算機能を提供する Numpy や +グラフ描画ライブラリである Matplotlib を始めとして外部パッケージを多量に用いることになる。 + +------------------------------------------ +Numpy を利用する +------------------------------------------ + +Numpy や Matplotlib は最も基本的なパッケージなので、 +本講座の方法に従って Anaconda をインストールした環境では、 +これらは既にインストールされている。 + +こういったパッケージを 各自で開発するスクリプトで用いるためには以下のように +import 文により宣言する必要がある。 + +.. ipython:: python + + import numpy as np + +ここで import numpy as np は、numpy パッケージを np という名前で用いる +という宣言である。 +なお、asの後ろの名前はユーザが勝手に決めてよいものだが、 +混乱を避けるため、広く用いられている略称を用いることが望ましい。 +このようにしてインポートした後は、np.*** という形で用いることができる。 + +Numpy は線形代数演算や特殊関数の計算など、 +多くの基本的な数学操作を含む科学技術計算用ライブラリである。 + +多くのアルゴリズムは、これまで C や Fortran で開発されてきた Netlib などのライブラリの +Pythonラッパーであるため、 +非常に安定しているほか、CやFortranと同等の高速演算が可能である。 + + +Numpy の代表的な関数 +------------------------------------------------------------------ + +Numpy を用いることで、多くの種類の算術演算を行うことができる。 +例えば sinc 関数は以下のようにして用いる。 + +.. ipython:: python + + x = np.sin(0.5 * np.pi) + x + +Numpy では非常に多くの種類の関数やクラスが用意されている。 +そのためどのような関数が用意されているか全てを把握することも難しく、 +それらの使用法を暗記することはほとんど不可能である。 + +Python などのオープンソースソフトウェアでは、 +開発に際して、使用法などの文書を同時に残していく文化が形成されており、 +ユーザがある関数の使い方を知りたいと思った場合もすぐに情報にアクセスできる。 + +Jupyter-notebook では、図*のように `np.` まで記入してから Tab を押下すると、 +np.内にある関数一覧が表示されるほか、`np.s` まで記入してから Tab を押下すると +それに合う候補を表示してくれる。 +使用法がわからない関数でも、カーソルが括弧内にあるときに +Shift + Tab を押下するとで、それぞれの関数の使い方に関する文書(docstringsと言う) +にアクセスできるため、使い方をすぐに理解することができる。 + +.. figure:: figs/np_suggest.png + :scale: 50 % + :alt: suggestion for np functions + +.. figure:: figs/np_suggest2.png + :scale: 50 % + :alt: docstrings for np.sinc + +さらに、科学技術用途以外も含め Python は広く用いられている汎用言語なので、 +インターネットで検索するだけでも多くの情報を見つけることができる。 + + +多次元配列型 np.ndarray +------------------------ + +Numpy は、多次元配列用のクラス(クラスについては後述する)である np.ndarray を提供している +(なお、"nd"array は、n-dimensional の略である)。 +np.ndarray は配列の大きさを後から変更できない、 +全ての要素の型が同一なものに限られる、という点はリストと異なるが、 +同様にインデクシング・スライシングに対応している。 + +np.ndarray は、多次元配列の基礎となるクラスで、 +線形演算を含む多くのNumpy関数で利用する他、 +だけでなくpandasなど他のライブラリでも広く利用されている +基本的なオブジェクト形式となっている。 + +以下では、その利用法について簡単に触れる。 +np.ndarray を定義するためには、`np.ndarray` から用意するか、 +np.ones や np.linspace などの関数を用いる。 + +.. ipython:: python + + # [5 x 3 x 2] の大きさの配列をxとして確保する。 + x = np.ndarray((5, 3, 2)) + + # [2 x 3] の大きさで、要素がすべて1のint型の配列をyとして確保する。 + y = np.ones((2, 3), dtype=int) + y + +np.ndarray とスカラー、np.ndarray 同士の計算は、要素ごとの計算として定義されている。 + +.. ipython:: python + + y * 3 + + y + y + +また、np.abs() や np.square() などスカラーを引数に持つ関数に渡した場合は、 +要素ごとに該当する演算が行われた np.ndarray が返される。 + +.. ipython:: python + + np.sin(y) + +二次元配列としての内積は `np.dot(x, y)` や Python 3 では `x @ y` として計算できる。 + + +Numpy を用いて効率よく計算を行う +------------------------------------------------------------------ + +上述したように、Numpyの内部ではFortranによる演算を行うため高速である。 +逆に言うと、Numpyの内部に任せられることを自前でPythonで記述すると非常に低速になる。 +例えば + +.. ipython:: python + + z = np.ndarray(y.shape) + for i in range(y.shape[0]): + for j in range(y.shape[1]): + z[i,j] = np.sin(y[i,j]) + +は、z = np.sin(y) に比べて冗長になるだけでなく、低速になる。 +Pythonではできるだけループを用いないこと(外部ライブラリができる部分はそれに任せる)が、 +高速な演算を行うコツである。 + +Numpy の詳しい使い方は、別章にに譲ることにする。 + + +ファイルへの読み込み・書き出し +------------------------------------------------------------------ + + +Pythonでファイルの読み込み・書き出しを行う場合、C言語の時に行ってきたような +ファイルを開く > 1行ずつ内容を読み込む・書き出す > ファイルを閉じる +のように、低レベルの操作を行うことは少ない。 +多くのパターンのファイル操作が用意されているので、 +そちらを用いるほうが高速でありバグも少ないからである。 + +例えば単純なCSVデータの読み込みには、np.loadtxt、np.savetxt +などを用いることが多い。 + +------------------------------------------ +Matplotlib を利用する +------------------------------------------ + +Matplotlib は、広く持ちいられているグラフ描画ライブラリである。 +Matlabのグラフ描画機能を参考にして開発されたようで、よく似た命名規則を持っている。 + +Matlab の詳しい使い方自体は別章の***に譲り、 +ここでは単純な描画についてのみ述べる。 + +.. ipython:: python + + import matplotlib.pyplot as plt + +import matplotlib.pyplot as plt は、 +matplotlib パッケージの中の pyplot モジュールを plt という名前で用いる +という意味である。 + +最も基本的な用法は、1次元データを表示することである。 + +.. ipython:: python + + x = np.linspace(0,1,11) # 0 ~ 1 を11等分した要素を持つ np.ndarray を返す関数 + y = np.sin(np.pi * x) + + @savefig tutorial2_plot1.png width=4in + plt.plot(y) + + +plt.plot の引数に1次元データを渡すことで、 +横軸が要素番号、縦軸が要素の値のグラフを描画できる。 + +x軸を指定するには、 + +.. ipython:: python + + @savefig tutorial2_plot2.png width=4in + plt.plot(x, y, '-o') + +というように、x軸の値とy軸の値を引数として渡す。 +なお、3つ目の引数には描画の様式を指定する。ここで、’-o’を渡すと、 +丸印のマーカを線で繋いだグラフが描画できる。 + + +--------------------------------- +外部パッケージのインストール +--------------------------------- + + +インストールされていない環境では + +.. code-block:: bash + + pip install numpy + +を実行することで、環境にインストールすることができる。 diff --git a/chapter2/src/tutorial3.rst b/chapter2/src/tutorial3.rst new file mode 100644 index 0000000..2d8a9dc --- /dev/null +++ b/chapter2/src/tutorial3.rst @@ -0,0 +1,59 @@ +関数を定義して使う +======================= + +.. ipython:: python + :suppress: + + import numpy as np + import matplotlib.pyplot as plt + np.random.seed(123456) + + +これまで、np.sin を始めとする関数を用いてきた。 +このように、何か操作をして値を返すもの(ファイルを保存するなど値を返さないものもある) +を関数と呼ぶ。 +本節ではこのような関数を定義して用いる方法について述べる。 + +なお、もし Numpy などの外部パッケージが同様の操作を行う関数を定義している場合は +そちらを用いるべきである。 +一人のユーザが作成するものよりもバグが圧倒的に少ないだけでなく、 +C や Fortranを裏で利用している場合は圧倒的に高速になる。 + +以下に、例として極座標変数 (r, theta) から直行座標での値 (x, y) への変換を行う +関数の定義を示す。 + +.. ipython:: python + + def get_xy(r, theta): + """ + Returns x, y values from polar coordinate variable r (radial coordinate) + and theta (angular coordinate). + """ + x = r * np.cos(theta) + y = r * np.sin(theta) + return x, y + +上記のように、関数の定義は`def`文から始め、関数名(get_xy)の次にカッコ内に引数(r, theta) を +指定し、コロンの後に改行する。 +関数の範囲は、インデントにより示すことが必要である。 +慣習として関数名は小文字で始めることが多い。 +必須ではないが、 def 文の次の行にはその関数の説明(docstringsという)を +3つのダブルコーテーションで囲った文字列として書いておくことが推奨される +メンテナンス性に優れるだけでなく、 +Jupyter-notebookなどの開発環境ではユーザが使用法に簡単にアクセスできるようになる。 +インデント内では必要な計算を行い、`return` 文でその値を返す。 +なお、Pythonの関数は複数の値を返すことができる。 +その場合、戻り値はそれらを含むタプルとなる。 + + +定義した関数を用いるためには + +.. ipython:: python + + r = np.linspace(0, 1, 21) + theta = np.linspace(0, 4.0 * np.pi, 21) + x, y = get_xy(r, theta) + @savefig tutorial3_plot1.png width=4in + plt.plot(x, y) + +というようにして用いる。 diff --git a/chapter2/src/tutorial4.rst b/chapter2/src/tutorial4.rst new file mode 100644 index 0000000..71b9254 --- /dev/null +++ b/chapter2/src/tutorial4.rst @@ -0,0 +1,55 @@ +スクリプトファイルを読み込む +================================== + +.. ipython:: python + :suppress: + + import numpy as np + import matplotlib.pyplot as plt + np.random.seed(123456) + +上記の関数など、作成したスクリプトを再利用するためには、 +スクリプトファイルとして作成しておくほうが良い。 + +スクリプトファイルと言っても、これまで学習した内容を .py ファイルに保存するだけである。 +なお、ファイルをまたいで import 文や変数の定義は持ち込まれないため、 +スクリプトファイルごと適宜記入する必要がある。 + +前節で定義した関数をスクリプトファイルとして保存するには、 +以下のような内容をファイルとして保存する。 +今回は、これを polar.py として保存したとする。 + +.. code-block:: python + + import numpy as np + + def get_xy(r, theta): + """ + Returns x, y values from polar coordinate variable r (radial coordinate) + and theta (angular coordinate). + """ + x = r * np.cos(theta) + y = r * np.sin(theta) + return x, y + +このスクリプトファイルを読み込むためには、以下のように import 文を用いる。 + +.. code-block:: python + + import polar + + r = np.linspace(0, 1, 31) + theta = np.linspace(0, 4.0 * np.pi, 31) + x, y = polar.get_xy(r, theta) + +なお、import 文で読み込めるスクリプトファイルは、実行するスクリプトと同じディレクトリ内か +パスの通ったディレクトリのみとなる。 +任意の場所にあるスクリプトファイルを読み込むためには + +.. code-block:: python + + import sys + sys.path.append('[path/to/script]') + import polar + +というようにパスを通す必要がある。 diff --git a/chapter2/src/tutorial5.rst b/chapter2/src/tutorial5.rst new file mode 100644 index 0000000..24bfcca --- /dev/null +++ b/chapter2/src/tutorial5.rst @@ -0,0 +1,109 @@ +クラスを定義して使う +============================ + +.. ipython:: python + :suppress: + + import numpy as np + import matplotlib.pyplot as plt + np.random.seed(123456) + +クラス(class)とは、(複数の)データと +そのデータに関する関数(メソッドと言う)をひとまとめにした +オブジェクトである。 +オブジェクト指向プログラミングの第一歩はクラスを学ぶところから始まる。 +ここでは、そのさわりを簡単に述べる。 + + +クラスの例 np.ndarray +------------------------------- + +まずは、クラスがどのようなものか理解するため、その例として`np.ndarray`のメソッドを紹介する。 + +.. ipython:: python + + x = np.linspace(0,1,12) + x + y = x.reshape(4,3) # Here, we constructed a 4 x 3 matrix. + y + +ここで reshape はメソッドであり、x の持つ値を変形したものを返すものである。 +もちろん同様の操作は関数だけを用いても行うことができるが、その場合 +get_reshaped_array(src, src_shape, dtype, target_shape) +というように、変形したいデータ(src)に関するたくさんの変数(srcの値、srcの大きさ、変数の型) +を全て指定する必要があり、ソースコードが冗長になる。 + +クラスという概念では、 +np.ndarray というオブジェクトの中に、データの他、 +変数の型や大きさなど必要な情報をひとまとめにして格納しておく。 +そのオブジェクトのメソッドでは、それらの値を用いることができるため、 +プログラムが簡潔になり、バグが少なくなる。 +(複雑なプログラムを作成するためのコツは、 + くだらないバグをなくす行為にできるだけリソースを割かないようなシステムにすることである。) + + +クラスの定義 +--------------------- + +ここでは例のため、極座標のクラスを作成しよう。 + +.. ipython:: python + + class PolarCoordinate(object): + def __init__(self, r, theta): + """ + An object that handles polar coordinate in 2d-space, + a radial coordinate(s) r and angular coordinate(s) theta. + """ + self.r = r + self.theta = theta + | + def to_xy(self): + """ + Convert to polar coordinate (r, theta) to x-y coordinate values. + Returns x and y as a tuple. + """ + return self.r * np.cos(self.theta), self.r * np.sin(self.theta) + | + def to_complex(self): + """ + Convert to complex values. + """ + return np.complex(self.r * np.cos(self.theta), + self.r * np.sin(self.theta)) + + +__init__ メソッドは、 +クラスをインスタンス化(実体を持つ変数として確保すること)時に実行されるメソッドである。 +今回作成したクラスの__init__メソッドは self, r, theta の3つの引数を必要とする。 +self は、このオブジェクト自体を指すものであり、 +Python のメソッドのひとつ目の引数は基本的には self とすることになっている。 + +メソッド内では、self を通して自らのオブジェクトにアクセスする。 +例えば + +.. code-block :: python + + self.r = r + +では、PolarCOordinate 内に変数 r を定義し、その値として__init__メソッドに渡された +rを代入することを示している。 + +クラスオブジェクトをインスタンス化するためには + +.. ipython:: python + + polar = PolarCoordinate(1.0, 0.5 * np.pi) + +というように、クラス名(引数) を実行する。なお、self引数は省略する。 +クラス内の変数には . (ドット)を通してアクセスできる。 + +.. ipython:: python + + polar.r + +また、to_xy などもメソッドであり、. を通して呼び出すことができる。 + +.. ipython:: python + + polar.to_xy()