[IPython-User] unfold a function in ipython?

Robert Kern robert.kern@gmail....
Wed Apr 11 08:03:37 CDT 2012

```On 4/11/12 12:32 PM, Chao YUE wrote:
> Dear all,
>
> suppose I have a function defined within ipython interactive session:
>
> In [19]: %psource day_length
> def day_length(L,J):
>      #D = daylength
>      #L = latitude (in degree, north positive and south negative)
>      #J = day of the year
>
>      P = np.arcsin(0.39795*np.cos(0.2163108 +
> 2*np.arctan(0.9671396*np.tan(0.00860*(J-186)))))
>      x1=np.sin(0.8333*np.pi/180) + np.sin(L*np.pi/180)*np.sin(P)
>      x2=np.cos(L*np.pi/180)*np.cos(P)
>      D = 24 - (24/np.pi)*np.arccos(x1/x2)
>      return D
>
> Now I want to see explicitly the process of variables when I call the function with
>
> In [18]: day_length(89.5,180)
> Out[18]: nan
>
> Is there some way to do this?

Use the Python debugger pdb:

http://docs.python.org/library/pdb

[~]
|1> def day_length(L,J):
..>         #D = daylength
..>         #L = latitude (in degree, north positive and south negative)
..>         #J = day of the year
..>
..>         P = np.arcsin(0.39795*np.cos(0.2163108 +
2*np.arctan(0.9671396*np.tan(0.00860*(J-186)))))
..>         x1=np.sin(0.8333*np.pi/180) + np.sin(L*np.pi/180)*np.sin(P)
..>         x2=np.cos(L*np.pi/180)*np.cos(P)
..>         D = 24 - (24/np.pi)*np.arccos(x1/x2)
..>         return D
..>

[~]
|2> import pdb

[~]
|3> pdb.runcall(day_length, 89.5,180)
> <ipython-input-1-32a5e1a00879>(6)day_length()
-> P = np.arcsin(0.39795*np.cos(0.2163108 +
2*np.arctan(0.9671396*np.tan(0.00860*(J-186)))))
(Pdb) n
> <ipython-input-1-32a5e1a00879>(7)day_length()
-> x1=np.sin(0.8333*np.pi/180) + np.sin(L*np.pi/180)*np.sin(P)
(Pdb) p P
0.40634292151355766
(Pdb) n
> <ipython-input-1-32a5e1a00879>(8)day_length()
-> x2=np.cos(L*np.pi/180)*np.cos(P)
(Pdb) p x1
0.40978095301341172
(Pdb) n
> <ipython-input-1-32a5e1a00879>(9)day_length()
-> D = 24 - (24/np.pi)*np.arccos(x1/x2)
(Pdb) p x2
0.0080159549381427515
(Pdb) n
> <ipython-input-1-32a5e1a00879>(10)day_length()
-> return D
(Pdb) p D
nan
(Pdb) p np.arccos(x1 / x2)
/Library/Frameworks/Python.framework/Versions/Current/bin/ipython:1:
RuntimeWarning: invalid value encountered in arccos

#!/Library/Frameworks/Python.framework/Versions/7.1/Resources/Python.app/Contents/MacOS/Python
nan
(Pdb) p x1 / x2
51.12066574420583
(Pdb)

x1 / x2 is well out of range for arccos.

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma