Integrated the optimization code into the python version