Search code examples
python-2.7enthoughttraits

traits ui (enthought) and callback from C


I have the code:

import time
import numpy as np
from scipy.optimize import fmin_tnc
from enthought.traits.api import *
from enthought.traits.ui.api import *

class Minimizer(HasTraits):
    iteration = Int(0)
    run = Button

    def callback(self, x):
        self.iteration += 1
        print self.iteration
        time.sleep(0.5)

    def func(self, x):
        return (x**2).sum()

    def fprime(self, x):
        return 2*x

    def minimize(self):
        x0 = np.random.rand(50)
        fmin_tnc(self.func, x0, fprime=self.fprime, messages=0, callback = self.callback) 

    def _run_fired(self):
        self.minimize()

    traits_view = View(Item('iteration'), UItem('run'))

m = Minimizer()
m.configure_traits()

After running the above and pressing Run button i expected the 'iteration' attribute will be updated in the GUI at each iteration, but this is not the case. I suspect that this is because this value is changed by callback from C. What should be done to update the user interface in these circumstances?

Regards, Marek


Solution

  • I found the solution. Simply, 'minimize' method have to be non-blocking, so implementing minimization in separate thread, like this:

    def minimize(self):
        x0 = np.random.rand(50)
        #fmin_tnc(self.func, x0, fprime=self.fprime, messages=0, callback = self.callback) 
        import thread
        thread.start_new_thread(fmin_tnc, (self.func, x0), {'fprime':self.fprime, 'messages':0, 'callback':self.callback})
    

    will result in updating the UI at real-time...

    Thanks, Marek