2. Keeping states
In this section, you will keep the state of the heart rate readings from the patient data stream. For each new tuple that comes in, you will calculate the moving average of the last 10 tuples.
You can continue your development for this step in the same coding cell as the previous step.
- Import the getReadingValue function from the ingest.Observation module. It takes a tuple as input and returns the reading value for you.
- Create a new callable class called Avg.
- Specify the __init__ function:
- Give it one parameter: n
- Declare two variables: n for the number of tuples to average (assigned from the input) and last_n that will store a list of the last n tuples, which will be empty when initialized.
def __init__ (self, n):
self.n = n
self.last_n = 
- Specify the
- Give it one parameter: tuple
- Append the heart rate reading of the input tuple to the list by using the getReadingValue function:
- If the length of the list is greater than n, pop the oldest tuple in the list
- Return the average of all the values in the list:
Your completed Avg class should look like this:
- Using your new class, calculate the moving average heart rate for the last 10 tuples. Call the new stream avgHr.
avgHr = heartRate.map(Avg(10))
- Make the appropriate downstream changes to your code.
- Submit over Bluemix, run the cell, and view your output.When you run the application, the patient’s data will not appear anymore. Instead, you will have an output of the average heart rate readings.That’s the end of this lab. Now your application is fully functional. Not only does it anonymize and select important data from the input stream, it also performs an aggregation of this data and returns its real-time average value, greatly simplifying the output. In the next and final lab, you’ll have the chance to use MatPlotLib to visualize this data on the Python Notebook.