* debugの基礎,basic debug

スクリプト作成前の準備(実行時エラーが出てからここに戻ることもある)

    1. 何をどう計算するかを明確にする.具体的には,計算するべき内容を数式に書く.この際,独立変数(x,y,z,tなど)を,省略せずに書く.これは,pythonでは通常配列を使って計算し,その配列の使い方が不適切であることが間違いの原因であることが多いためである.指導教員に見せる場合には,第三者が分かるように,さらに全ての変数が何であるかを地の文で書く.この変数の説明の書き方は,数式を使っている教科書を参考にする.

文法エラー

    1. 文法エラーは,示された行だけではなく,一つ前の行も正しいかどうかをチェックする.たとえばfor 文の行で末尾に":"を忘れると,次の行にエラーが出る.

実行時エラー

    1. 計算の中身を,最終結果のみならず,途中の計算結果についても適切かどうかを調べる.これを調べるには,以下の方法がある.表示にはinteractiveに行う方法と,print文を使う方法がある.前者は一旦値が定まると変らない変数を調べるのに,後者はループの中などで大くの情報を表示させるのに適している.

      1. 変数の中身,type, shape (numpy array の場合)をコンソールに表示する.

      2. 変数の中身を,図として表示する.なお,matplotlib でinteractiveに図を表示するには,ion()を使う.

  1. ある場所までpython scriptの実行を進めて,その場所でのあるいはそこから1行づつ実行しつつ,変数を調べるには標準のデバッガーであるpdbを使う.この方法は,特に関数の中で使われている変数を調べるのに有効である.

    1. 関数の中でスクリプト実行が停止して,その関数の中で使われている変数を"とりあえず"調べるのには,%debugを使う.とりあえずと書いたのは,pdbを使うには,当該関数を編集する(自分がread権限しかない場合には,自分のディレクトリにコピーして編集する)手間がかかるが,%debugはそういった編集なしに実行できるためだ.ただし,%debugで十分な情報が得られない場合には,pdbを使う必要がある.

Preparation before writing a script (you can back here when you have a execution error)

  1. Clarify what and how do you calculate. The best way is to write equations of calculation. It is better not to omit independent variables (x, y, z, t, etc) in the equation. When you ask your mentor to check those equations, you need to clarify all dependent and independent variables with text.

Syntax error

    1. You should check the line of error message and one line above. For example, if you forget to add ":" at the end of the "for" statement, the error message will be shown for one line after the line of the statement.

Execution error

  1. You will check calculations are OK by knowing the values, either interactively or adding printout.

    1. You will show type and shapes (in the case of numpy array) of variables to your console.

    2. You will show values of variables by plotting them (line plot (e.g. matplotlib.pyplt.plot) or shading (e.g. matplotlib.pyplot.pcolormesh) are the most common).

  2. You will use pdb to know variables at a specific line of script or later. This is very useful to check errors that occur in functions.

    1. You can use %debug, when a script stop in a function. This is easier to do than pdb, which requires editing of the function, but information you can be by %debug is not as good as that by pdb.