Friday, March 23, 2012

Debugging and Profiling in Python

To debug hello.py, do
$ python -m pdb hello.py

You will immediately get the debug prompt, with the execution stopped before the first line of the program. You can now use:

l - to display source code around the line to be executed next
n - to execute the next line of code
s - to step into the next line of code
b <line no.> - to set breakpoints
b - to list breakpoints
clear <breakpt no.> - to clear breakpoints
c - to continue execution
tbreak <line no.> followed by c - to execute till a particular line
p <var> - to print contents of variables,
vars(obj) - to print contents of objects (same as obj.__dict__)
dir(obj) - to list attributes/methods of objects
help - to get more help.


 To profile hello.py, do
 $ python -m cProfile hello.py

The program will be run and you will get a profiler report on the console.

To debug a particular part of the code, do
import cProfile
profile = cProfile.Profile()
profile.enable()
# do something
profile.disable()
profile.dump_stats('something.prof')

To view the dump file, use cprofilev.

Monday, March 12, 2012

Lagrangian duality

Given an minimization problem

min f(x)
s.t. g_i(x)  = 0,     i=1..m
      h_j(x) <=  0,  j=1..p,

the Lagrangian function is

L = f(x) + \sum_i \alpha_i g_i(x) + \sum_j \beta_j h_j(x)

where \alpha_i is unconstrained, and \beta_j >= 0.

See more on Wikipedia.