Search code examples
pythonpython-3.xmultiprocessingreal-timesensors

How to update a variable in "realtime" using functions which take many seconds to return a value


What logic should be used to update a variable such as a current mean in real time?

For example in the script below obs_mean() produces a mean by listening to incoming sensor data. The function listen_to_observations() is an example function which behaves similarly to the real sensor data function.

How can the value current_mean be updated every second/realtime using obs_mean(5) (which takes 5 seconds worth of data and takes 5 seconds to return a value)?

import numpy as np
import random
import time

current_mean = None

def listen_to_observations():
    #listen to a stream of observations
    time.sleep(1)
    yield random.random()

def obs_mean(seconds):
    array = [listen_to_observations().next() for i in range(seconds)]
    return np.array(array).mean()

How would the logic look like? I am using Python 3.5.


Solution

  • You could just break up your array line into separate statements, and compute the mean after every observation:

    import numpy as np
    import random
    import time
    
    current_mean = None
    
    def listen_to_observations():
        #listen to a stream of observations
        time.sleep(1)
        yield random.random()
    
    def obs_mean(seconds):
        array = []
        for i in range(seconds):    
            array.append(listen_to_observations().next())
            current_mean = np.array(array).mean()
            print('current_mean = {}'.format(current_mean))
        return current_mean
    
    if __name__ == '__main__':
        obs_mean(5)
    

    My output:

    current_mean = 0.193142347659
    current_mean = 0.212120380098
    current_mean = 0.355774933848
    current_mean = 0.362840457341
    current_mean = 0.312662693142