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.

  1. Import the getReadingValue function from the ingest.Observation module. It takes a tuple as input and returns the reading value for you.
  2. Create a new callable class called Avg.
  3. 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 = []
  4. Specify the __call__ function:
    • Give it one parameter: tuple
    • Append the heart rate reading of the input tuple to the list by using the getReadingValue function:self.last_n.append(getReadingValue(tuple))
    • 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:return sum(self.last_n)/len(self.last_n)

    Your completed Avg class should look like this:

  5. 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))
  6. Make the appropriate downstream changes to your code.
  7. 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.