In [ ]:
%pylab qt

In [ ]:
from PyQt4 import QtCore, QtGui
n_calc = [0]
def calculate():
    sin(rand(1000))
    n_calc[0]+=1
    timer.start()

timer = QtCore.QTimer()
timer.setInterval(0)
timer.setSingleShot(True)
timer.timeout.connect(calculate)

In [ ]:
from PyQt4 import QtCore, QtGui
from psutil import cpu_percent
from time import sleep
from timeit import default_timer
APP = QtGui.QApplication.instance()

close('all')

n_calc[0] = 0

from time import time
def sleep_loop(delay):
   loop = QtCore.QEventLoop()
   timer = QtCore.QTimer()
   timer.setInterval(delay*1000)
   timer.setSingleShot(True)
   timer.timeout.connect(loop.quit)
   timer.start()
   loop.exec() # la loop prend en charge elle-même l'évenement du timer qui va la faire mourir après delay.

def sleep_pe(delay):
   tic = default_timer()
   while(default_timer()<tic+delay):
       APP.processEvents()

def my_sleep(delay):
    tic = default_timer()
    if delay>1e-3:
        sleep_loop(delay - 1e-3)
    while(default_timer()<tic+delay):
        APP.processEvents()
        
import asyncio

async def sleep_coroutine(delay):
    await asyncio.sleep(delay)
    #loop.stop()

loop = asyncio.get_event_loop()

def sleep_asyncio(delay):
    asyncio.ensure_future(sleep_coroutine(delay))
    loop.run_forever()
   
MAX_TIME = 0.005



for timer_on_off in (False, True):
    for index, (func, label) in enumerate([ (sleep_asyncio, "asyncio"),
                                            (sleep_loop, "qeventloop"),
                                            (sleep_pe, "processEvents"),
                                            (sleep, "time.sleep"),
                                            (my_sleep, "my_sleep"), 
                                           ]):
        if timer_on_off:
            timer.start()
        fig = figure()
        times_measured = []
        times_asked = []

        n_calc_before = n_calc[0]
        tic_for_func = default_timer()
        cpu_percent() # call starts the cpu_percent averaging
        for time_asked in linspace(0., MAX_TIME, 200):
            #if int(time_asked*10000)%10==0:
            #    print(time_asked)
            for i in range(10):
                tic = default_timer()
                func(time_asked)
                toc = default_timer()
                times_measured.append(toc - tic)
                times_asked.append(time_asked)
        cpu_percents = cpu_percent()
        toc_for_func = default_timer()
        calc_done = (n_calc[0] - n_calc_before)/(toc_for_func - tic_for_func)
        plot(times_asked, times_measured, '.')
        plot([0, MAX_TIME], [0, MAX_TIME])
        xlabel("time asked")
        ylabel("time measured")
        xlim(0, MAX_TIME)
        ylim(0, MAX_TIME)
        title(label + ' cpu_percent=' + str(cpu_percents) + ' calc/s=' + str(int(calc_done)))
        if timer_on_off:
            dirname = './images/with_timer/'
        else:
            dirname = './images/without_timer/'
        fig.savefig(dirname + label + '.png')
        timer.stop()
        close('all')
        for i in range(1000000):
            APP.processEvents()
timer.stop()

In [ ]:
%pylab qt
import quamash
from PyQt4 import QtCore, QtGui
import asyncio

from psutil import cpu_percent
from time import sleep
from timeit import default_timer
APP = QtGui.QApplication.instance()


n_calc = [0]
def calculate():
    sin(rand(1000))
    n_calc[0]+=1
    timer.start()

timer = QtCore.QTimer()
timer.setInterval(0)
timer.setSingleShot(True)
timer.timeout.connect(calculate)

MAX_TIME = 0.005
loop = quamash.QEventLoop()
asyncio.set_event_loop(loop) 

async def sleep_coroutine(delay):
    await asyncio.sleep(delay)
    #tic = default_timer()
    #if delay>0.001:
        #await asyncio.sleep(delay - 0.001)
    #while default_timer() < tic + delay:
    #    APP.processEvents()

timer.start()

label = "asyncio"
async def run():
    fig = figure()
    times_measured = []
    times_asked = []

    n_calc_before = n_calc[0]
    tic_for_func = default_timer()
    cpu_percent() # call starts the cpu_percent averaging
    for time_asked in linspace(0., MAX_TIME, 200):
        #if int(time_asked*10000)%10==0:
        #    print(time_asked)
        for i in range(10):
            tic = default_timer()
            await sleep_coroutine(time_asked)
            toc = default_timer()
            times_measured.append(toc - tic)
            times_asked.append(time_asked)
    cpu_percents = cpu_percent()
    toc_for_func = default_timer()
    calc_done = (n_calc[0] - n_calc_before)/(toc_for_func - tic_for_func)
    plot(times_asked, times_measured, '.')
    plot([0, MAX_TIME], [0, MAX_TIME])
    xlabel("time asked")
    ylabel("time measured")
    xlim(0, MAX_TIME)
    ylim(0, MAX_TIME)
    title(label + ' cpu_percent=' + str(cpu_percents) + ' calc/s=' + str(int(calc_done)))
    timer.stop()
    fig.savefig('asyncio_no_correction.png')

In [ ]:
asyncio.ensure_future(run())
#loop.run_forever() # this would be to launch the

In [ ]:
%pylab qt
import asyncio
import scipy.fftpack
import quamash
from PyQt4 import QtCore, QtGui
import asyncio
loop = quamash.QEventLoop()
asyncio.set_event_loop(loop) 


class Scope(object):
    async def run_single(self, avg):
        y_avg = zeros(100)
        for i in range(avg):
            await asyncio.sleep(1)
            y_avg+=rand(100)
        return y_avg

class SpecAn(object):
    scope = Scope()
    
    async def run_single(self, avg):
        y = zeros(100, dtype=complex)
        for i in range(avg):
            trace = await self.scope.run_single(1)
            y+= scipy.fftpack.fft(trace)
        return y
            
sa = SpecAn()
scope = Scope()

In [ ]:
v = asyncio.ensure_future(sa.run_single(10))

In [ ]:
v.result()

In [ ]:
async def my_loop():
    for i in range(10):

In [ ]:
%pylab qt
import asyncio
import scipy.fftpack
import quamash
from PyQt4 import QtCore, QtGui
APP = QtGui.QApplication.instance()
import asyncio
from promise import Promise
loop = quamash.QEventLoop()
asyncio.set_event_loop(loop) 


class MyPromise(Promise):
    def get(self):
        while self.is_pending:
            APP.processEvents()
        return super(MyPromise, self).get()


class Scope(object):
    def __init__(self):
        self.timer = QtCore.QTimer()
        self.timer.setSingleShot(True)
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.check_for_curve)

    def run_single(self, avg):
        self.current_avg = 0
        self.avg = avg
        self.y_avg = zeros(100)
        self.p = MyPromise()
        self.timer.start()
        return self.p

    def check_for_curve(self):
        if self.current_avg<self.avg:
            self.y_avg += rand(100)
            self.current_avg += 1
            self.timer.start()
        else:
            self.p.fulfill(self.y_avg)


class SpecAn(object):
    scope = Scope()

    def __init__(self):
        timer = QtCore.QTimer()
        timer.setSingleShot(True)
        timer.setInterval(1000)

    def run_single(self, avg):
        self.avg = avg
        self.current_avg = 0
        self.y_avg = zeros(100, dtype=complex)
        p = self.scope.run_single(1)
        p.then(self.average_one_curve)
        self.p = MyPromise()
        return self.p

    def average_one_curve(self, trace):
        print('av')
        self.current_avg+=1
        self.y_avg+=scipy.fftpack.fft(trace)
        if self.current_avg>=self.avg:
            self.p.fulfill(self.y_avg)
        else:
            p = self.scope.run_single(1)
            p.then(self.average_one_curve)

sa = SpecAn()

In [ ]:
p = sa.run_single(3)

In [ ]:
p.is_fulfilled

In [ ]:
p.get()

In [ ]:
sa.avg

In [ ]:
s

In [ ]:
%pylab qt
import asyncio
import scipy.fftpack
import quamash
from PyQt4 import QtCore, QtGui
import asyncio
loop = quamash.QEventLoop()
asyncio.set_event_loop(loop) 


class Scope(object):
    async def run_single(self, avg):
        y_avg = zeros(100)
        for i in range(avg):
            await asyncio.sleep(1)
            y_avg+=rand(100)
        return y_avg


class Na(object):
    async def run_single(self, avg):
        y_avg = zeros(100)
        for i in range(avg):
            await asyncio.sleep(1)
            y_avg+=rand(100)
        return y_avg

scope = Scope()
na = Na()

In [ ]:
async def my_coroutine(n):
    c1 = zeros(100)
    c2 = zeros(100)

    for i in range(n):
        print("launching f")
        f = asyncio.ensure_future(scope.run_single(1))
        print("launching g")
        g = asyncio.ensure_future(na.run_single(1))
        print("=======")
        c1+= await f
        c2+= await g
        print("f returned")
        print("g returned")

    return c1 + c2

In [ ]:
p = asyncio.ensure_future(my_coroutine(3))

In [ ]:
p.result()

In [ ]:
p.result?

In [ ]:
my_coroutine

In [ ]:
asyncio.ensure_future(my_coroutine(1))

In [ ]:
obj = my_coroutine(1)

In [ ]:
obj.__await__

In [ ]:
class MyAwaitable(object):
    def __await__(self):
        return ((x for x in range(5)))

In [ ]:
m = MyAwaitable()

In [ ]:
p = asyncio.ensure_future(m)

In [ ]:
p.result()

In [ ]:


In [ ]:


In [ ]:
m = MyFuture()

In [ ]:
p = asyncio.ensure_future(m)

In [ ]:
p.done()

In [ ]:
m.set_result(5)

In [ ]:
p

In [ ]:
p.result()

In [ ]:
from asyncio.futures import Future

class MyFuture(Future):
    def __await__(self):
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(lambda : self.set_result(rand(100)))
        self.timer.setSingleShot(True)
        self.timer.setInterval(1000)
        self.timer.start()
        print('awaiting')
        
class AsyncScope(object):
    def run_single(self, avg):
        self.f = MyFuture()
        return self.f
    
a = AsyncScope()

In [ ]:
f

In [ ]:
f = a.run_single(3)

In [ ]:
a.f.set_result(6)

In [ ]:
f

In [ ]:
p = asyncio.ensure_future(a.run_single(3))

In [ ]:
p.done()

In [ ]:
p.__await__()

In [ ]:
p.result()

In [ ]: