{ "metadata": { "name": "", "signature": "sha256:8dc13f12af2c61baa3d7327bac85b0078c0d6cb4beca7b087a7b191f994fc3c6" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Introduction" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

This iPython notebook walks you through reading data from a Fluxtream data channel, computing a function on it, and uploading a new computed channel back to Fluxtream. This particular example reads data from a nonin SpO2 sensor channel and writes back a thresholded channel called SpO2_thresh_X, where X is the value of a given threshold, for data points that are below that threshold.\n", "\n", "

The real value of this notebook, I hope, is to provide an example of how to read data from a Fluxtream datastore channel, do something to it, and write it back. If you have a Nonin 3150, you can import and run the Nonin-WristOx2-3150 notebook to upload your channels to try this on. Otherwise, if you email me at info@fluxtream.org I can add you as a buddy to access the Nonin 3150 channels uploaded to the test account (Guest ID=1). Or you can just modify the channel names and function to do something interesting to your own data channels.\n", "\n", "

If you are new to iPython notebooks, here is the main IP[y] website. You will need to install python and iPython notebook on your local system, run a local ipython kernel, and install a local copy of this notebook to be able to execute and modify the code below. Install instructions are here. On osx systems, you can start the server by going to Terminal and calling 'ipython notebook'. This will start a local web server and open a an IP[y] page talking to it in a web browser. Within the IP[y] page, you can open a saved iPython notebooy by going to File/Open.\n", "\n", "

Once you have IP[y] generally working on your system, here's a brief intro in how to use it: \n", "

\n", "\n", "

When a given cell is executed, it may print output which appears below the cell, and the cursor will continue to the next cell. If the next cell is tall, you might need to scroll back up to see the previous cell's output.\n", "\n", "

Each cell in this notebook pertains to a particular step in the process, topic, or action requiring your input and contains comments at the top saying what it's about and what you should do. \n", "\n", "

Cells that require entry of sensitive information, such as passwords, start with a phrase like \"Execute and fill in the fields below\". These generally create entry forms in the output area below the cell that you need to fill in. Generally, the cell will clear the sensitive input boxes after clicking the button. It may also print out suggestions about how you could set up a new cell for future use if you're confident other's won't see your copy of the notebook.\n", "\n", "

Cells that require customization for your own setup start with \"Modify\". These include cells where you configure which channels you want to process and what you want to call the resulting data. These require some thought.\n", "\n", "

Cells that define functions or do other things that don't require user input or modification generally just start with \"Execute\". These can just be executed without much consideration, though you may want to go back later to understand or modify them. \n", "\n", "

Please enjoy, tinker, modify, etc. Feel free to contact info@fluxtream.org if you have questions. \n", "\n", "

Note that uploading data multiple times to a given device and channel with identical time values each time will safely overwrite the previous values. However, there is no API or user interaction component in Fluxtream that allows the deletion of a previously-uploaded device or channel, and you can't delete data points already uploaded to a given channel. If you create device names or channel names, or upload data at incorrect timepoints within a given channel, and later regret it, please send the info about your situation, including your Fluxtream username, guest ID, and the details of which devices and or channels you want deleted to info@fluxtream.org. You can get your Guest ID by doing the step below to set up your Fluxtream credentials and looking at the value of fluxtream_guest_id. Also note that the Fluxtream upload API cannot currently handle empty cells within the data array used in an upload call. I'm hoping to fix this in the future." ] }, { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Setup for uploading to Fluxtream" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Execute this cell to define the functions for calling the Fluxtream upload API for the \n", "# credentials entered below\n", "import json, subprocess, urllib, csv\n", "\n", "# By default, the upload function will send data to the main server at fluxtream.org. \n", "# If you want to have this use a different fluxtream server, change it here\n", "# and make sure the username and password entered below are valid on that server.\n", "global fluxtream_server\n", "fluxtream_server = \"fluxtream.org\"\n", "\n", "def setup_fluxtream_credentials():\n", " # Call the Fluxtream guest API, documented at \n", " # https://fluxtream.atlassian.net/wiki/display/FLX/BodyTrack+server+APIs#BodyTrackserverAPIs-GettheIDfortheguest\n", "\n", " # Make sure it works and harvest the Guest ID for future use\n", " global fluxtream_server, fluxtream_username, fluxtream_password, fluxtream_guest_id\n", "\n", " # Make sure we have fluxtream credentials set properly\n", " if not('fluxtream_server' in globals() and \n", " 'fluxtream_username' in globals() and\n", " 'fluxtream_password' in globals()):\n", " raise Exception(\"Need to enter Fluxtream credentials before uploading data. See above.\")\n", "\n", " cmd = ['curl', '-v']\n", " cmd += ['-u', '%s:%s' % (fluxtream_username, fluxtream_password)]\n", " cmd += ['https://%s/api/guest' % fluxtream_server]\n", "\n", " result_str = subprocess.check_output(cmd)\n", " #print ' Result=%s' % (result_str)\n", "\n", " try:\n", " response = json.loads(result_str)\n", "\n", " if 'id' in response:\n", " fluxtream_guest_id = int(response['id'])\n", " else:\n", " raise Exception('Received unexpected response %s while trying to check credentials for %s on %s' % (response, \n", " fluxtream_username, \n", " fluxtream_server))\n", "\n", " print 'Verified credentials for user %s on %s work. Guest ID=%d' % (fluxtream_username, fluxtream_server, fluxtream_guest_id)\n", " except:\n", " print \"Attempt to check credentials of user %s failed\" % (fluxtream_username)\n", " print \"Server returned response of: %s\" % (result_str)\n", " print \"Check login to https://%s works and re-enter your Fluxtream credentials above\" % (fluxtream_server)\n", " raise\n", " \n", "def fluxtream_upload(dev_nickname, channel_names, data):\n", " global fluxtream_server, fluxtream_username, fluxtream_password\n", " \n", " # Make sure we have some data to send\n", " if data == None or len(data)<1:\n", " print 'Nothing to upload to %s %s' % (dev_nickname, channel_names) \n", " return\n", "\n", " # Make sure we have fluxtream credentials set properly\n", " if not('fluxtream_server' in globals() and \n", " 'fluxtream_username' in globals() and\n", " 'fluxtream_password' in globals()):\n", " raise Exception(\"Need to enter Fluxtream credentials before uploading data. See above.\")\n", "\n", " # Send to BodyTrack upload API, documented at \n", " # https://fluxtream.atlassian.net/wiki/display/FLX/BodyTrack+server+APIs#BodyTrackserverAPIs-Storingdata\n", " cmd = ['curl', '-v']\n", " cmd += ['-u', '%s:%s' % (fluxtream_username, fluxtream_password)]\n", " cmd += ['-d', 'dev_nickname=%s' % dev_nickname]\n", " cmd += ['-d', 'channel_names=%s' % json.dumps(channel_names)]\n", " cmd += ['-d', 'data=%s' % json.dumps(data)]\n", " cmd += ['https://%s/api/bodytrack/upload' % fluxtream_server]\n", "\n", " print 'Uploading %d data points to %s\\'s account on server %s, device %s, channels %s' % (len(data), \n", " fluxtream_username,\n", " fluxtream_server, \n", " dev_nickname,\n", " channel_names)\n", " \n", " # If you're having trouble debugging this function, uncomment the following two print statements \n", " # to see the exact curl command and result string\n", " #print ' Cmd=%s' % (cmd)\n", " result_str = subprocess.check_output(cmd)\n", " #print ' Result=%s' % (result_str)\n", "\n", " try:\n", " response = json.loads(result_str)\n", " if response['result'] != 'OK':\n", " raise Exception('Received non-OK response %s while trying to upload to %s' % (response, dev_nickname))\n", " \n", " print 'Upload to %s %s (%d rows, %d to %d) succeeded' % (dev_nickname, channel_names, len(data), data[0][0], data[-1][0])\n", " except:\n", " print \"Attempt to upload to %s as user %s failed. Check that your credentials are ok\" % (fluxtream_server, \n", " fluxtream_username)\n", " print \"Server returned response: %s\" % (result_str)\n", " raise\n", " \n", "# To get your own data, pass in the global fluxtream_guest_id which is computed \n", "# in setup_fluxtream_credentials() when you execute the Fluxtream login cell.\n", "# To get a buddy's data, you first need to figure out what their Guest ID is.\n", "# This will show up in the Chrome developer console in tile requests when you \n", "# look at their data in the timeline or BodyTrack app. \n", "\n", "# For example, if the test account is my buddy, I would select \n", "# 'View test test's data' from the upper right \n", "# hand menu, turn on developer tools, and go to the Fluxtream\n", "# timeline tab. In the developer tools' network tab I would \n", "# see fetches that look like:\n", "# 7.21370.json\n", "# /api/bodytrack/tiles/1/BodyMedia.activityType\n", "# The value between 'tiles' and the device_name.channel_name is\n", "# that account's Guest ID. In that case, I would call\n", "# fluxtream_get_sources_list with an arg of 1.\n", "def fluxtream_get_sources_list(guest_id):\n", " global fluxtream_server, fluxtream_username, fluxtream_password\n", "\n", " # Make sure we have fluxtream credentials set properly. \n", " if not('fluxtream_server' in globals() and \n", " 'fluxtream_username' in globals() and\n", " 'fluxtream_password' in globals()):\n", " raise Exception(\"Need to enter Fluxtream credentials. See above.\")\n", "\n", " # Send to BodyTrack upload API, documented at \n", " # https://fluxtream.atlassian.net/wiki/display/FLX/BodyTrack+server+APIs#BodyTrackserverAPIs-Storingdata\n", " cmd = ['curl', '-v']\n", " cmd += ['-u', '%s:%s' % (fluxtream_username, fluxtream_password)]\n", " cmd += ['https://%s/api/bodytrack/users/%d/sources/list' % (fluxtream_server, guest_id)]\n", "\n", " result_str = subprocess.check_output(cmd)\n", " #print ' Result=%s' % (result_str)\n", "\n", " try:\n", " response = json.loads(result_str)\n", " print 'Read of sources list for guest_id=%d succeeded' % (guest_id)\n", " return response\n", " except:\n", " print \"Attempt to upload to %s as user %s failed. Check that your credentials are ok\" % (fluxtream_server, \n", " fluxtream_username)\n", " print \"Server returned response: %s\" % (result_str)\n", " raise\n", "\n", "def fluxtream_get_device_names(sources_list):\n", " device_names = []\n", " for dev in sources_list['sources']:\n", " device_names.append(dev['name'])\n", " \n", " return device_names\n", "\n", "def fluxtream_get_device_info(device_name, sources_list):\n", " for dev in sources_list['sources']:\n", " if(dev['name'] == device_name):\n", " return dev\n", " \n", " return None\n", "\n", "def fluxtream_get_channel_names(device_name, sources_list):\n", " dev_info = fluxtream_get_device_info(device_name, sources_list)\n", "\n", " channel_names = []\n", " \n", " for channel in dev_info['channels']:\n", " channel_names.append(channel['name'])\n", " \n", " return channel_names\n", "\n", "def fluxtream_get_channel_info(device_name, channel_name, sources_list):\n", " dev_info = fluxtream_get_device_info(device_name, sources_list)\n", " \n", " # Check to make sure that we found info for the requested device.\n", " # If not, return None\n", " if not dev_info:\n", " return None\n", " \n", " for channel_info in dev_info['channels']:\n", " if(channel_info['name'] == channel_name):\n", " return channel_info\n", " \n", " return None\n", "\n", "# Takes a guest_id, an array of . strings, and a time range and returns a CSV reader.\n", "# Iterate over the rows using reader.next(), which returns a row array with entries corresponding to \n", "# Epoch, [dev_ch_names]\n", "# Where Epoch is the epoch timestamp (aka unixtime) for the values in the row, and the i+1'th column of the row \n", "# corresponds to the channel in dev_ch_names[i]\n", "\n", "# See comment on fluxtream_get_sources_list for info about how to choose the value for guest_id\n", "def fluxtream_get_csv(guest_id, dev_ch_names, start_time, end_time):\n", " global fluxtream_server, fluxtream_username, fluxtream_password\n", "\n", " # Make sure we have fluxtream credentials set properly. \n", " if not('fluxtream_server' in globals() and \n", " 'fluxtream_username' in globals() and\n", " 'fluxtream_password' in globals()):\n", " raise Exception(\"Need to enter Fluxtream credentials. See above.\")\n", "\n", " # Send to BodyTrack upload API, documented at \n", " # https://fluxtream.atlassian.net/wiki/display/FLX/BodyTrack+server+APIs#BodyTrackserverAPIs-Storingdata\n", " cmd = ['curl', '-v']\n", " cmd += ['-u', '%s:%s' % (fluxtream_username, fluxtream_password)]\n", " # Need to convert the dev_ch_names array into json and URL encode it to create the channels arg\n", " # TODO: how do we confirm that dev_ch_names is in fact an array?\n", " ch_spec_str = json.dumps(dev_ch_names)\n", " ch_spec_str = urllib.quote(ch_spec_str)\n", " cmd += ['https://%s/api/bodytrack/exportCSV/%d/fluxtream-export-from-%d-to-%d.csv?channels=%s' % (fluxtream_server, guest_id, \n", " int(start_time), int(end_time), \n", " ch_spec_str)]\n", " #print ' cmd=%s' % (cmd)\n", " result_str = subprocess.check_output(cmd)\n", " #print ' Result=%s' % (result_str)\n", " # If the API call worked, result_str should be a CSV file\n", " # with the first line a header consisting of EpochTime, [dev_ch_names]\n", " # TODO: how do we check if it did work?\n", "\n", " # Create a CSV reader that iterates over the lines of the response\n", " csv_reader = csv.reader(result_str.splitlines(), delimiter=',')\n", " header = csv_reader.next()\n", " \n", " # Do some checks to make sure we got something reasonable\n", " if len(header) != len(dev_ch_names)+1:\n", " raise Exception(\"Expected header for CSV export of %s to contain %d columns, but only found %d. Please double check that dev_ch_names are all valid\" % (dev_ch_names, len(dev_ch_names)+1, len(header)))\n", "\n", " # Check the columns are what we expect\n", " for i in range(0,len(dev_ch_names)):\n", " if(dev_ch_names[i] != header[i+1]):\n", " raise Exception(\"Expected column %d of CSV header to be %s, but found %s instead. Please double check that dev_ch_names are all valid\" % (i+1, dev_ch_names[i], header[i+1]))\n", " \n", " # At this point, we can be confident that the columns map to Epoch, [dev_ch_names] as expected.\n", " # Return the csv reader. Iterate over the rows using reader.next()\n", " return csv_reader\n", " " ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "code", "collapsed": false, "input": [ "# Execute and fill in the fields below to set your Fluxtream credentials. \n", "\n", "from IPython.html import widgets # Widget definitions\n", "from IPython.display import display # Used to display widgets in the notebook\n", "\n", "def set_fluxtream_password(this):\n", " global fluxtream_username, fluxtream_password\n", " fluxtream_username = fluxtream_username_widget.value\n", " fluxtream_password = fluxtream_password_widget.value\n", " fluxtream_password_widget.value = ''\n", " setup_fluxtream_credentials()\n", "\n", " print \"To make persistent for future restarts, insert a cell, paste in:\"\n", " print \"\"\n", " print \"global fluxtream_username, fluxtream_password\"\n", " print \"fluxtream_username = \\\"%s\\\"\" % (fluxtream_username)\n", " print \"fluxtream_password = \\\"xxx\\\"\"\n", " print \"setup_fluxtream_credentials()\"\n", " print \"\"\n", " print \"replace xxx with your password, and execute that cell instead.\"\n", " print \"Only do this if you're keeping this copy of your iPython notebook private,\"\n", " print \"and remove that cell before sharing\" \n", " \n", "display(widgets.HTMLWidget(value='Fluxtream Username'))\n", "fluxtream_username_widget = widgets.TextWidget()\n", "display(fluxtream_username_widget)\n", "display(widgets.HTMLWidget(value='Fluxtream Password'))\n", "fluxtream_password_widget = widgets.TextWidget()\n", "display(fluxtream_password_widget)\n", "\n", "set_fluxtream_login_button = widgets.ButtonWidget(description='Set Fluxtream credentials')\n", "set_fluxtream_login_button.on_click(set_fluxtream_password)\n", "display(set_fluxtream_login_button)\n", "\n", "# Enter Fluxtream username and password and click \"Set Fluxtream credentials\" button. \n", "# Password field will blank afterwards, but variables will be set" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Verified credentials for user rsargent on fluxtream.org work. Guest ID=14\n", "To make persistent for future restarts, insert a cell, paste in:\n", "\n", "global fluxtream_username, fluxtream_password\n", "fluxtream_username = \"rsargent\"\n", "fluxtream_password = \"xxx\"\n", "setup_fluxtream_credentials()\n", "\n", "replace xxx with your password, and execute that cell instead.\n", "Only do this if you're keeping this copy of your iPython notebook private,\n", "and remove that cell before sharing\n" ] } ], "prompt_number": 2 }, { "cell_type": "code", "collapsed": false, "input": [ "# Execute to list the devices and channel names available in this Fluxtream account\n", "# Note that you will need to re-execute this cell after new data is uploaded \n", "# if you want to use up-to-date time bounds for a given channel\n", "import pprint\n", "\n", "global fluxtream_guest_id, guest_id, sources_list, dev_name_list\n", "\n", "# Default to using the data of the currently logged in user.\n", "# To use data for someone else, modify the line below to set\n", "# guest_id to some other value. See comments above \n", "# fluxtream_get_sources_list definition above for details.\n", "guest_id = fluxtream_guest_id \n", "\n", "# Get the info about all the sources that this user has\n", "# in their account\n", "sources_list = fluxtream_get_sources_list(guest_id)\n", "# Uncomment this if you want to see more details about the \n", "# structure of sources_list\n", "#pprint.pprint(sources_list)\n", "\n", "# Get the list of devices and channel names for this guest\n", "dev_name_list = fluxtream_get_device_names(sources_list)\n", "for dev_name in dev_name_list:\n", " channel_names = fluxtream_get_channel_names(dev_name, sources_list)\n", " print \"Device '%s', %d channels:\" % (dev_name, len(channel_names))\n", " print \" %s\" % (channel_names)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Read of sources list for guest_id=14 succeeded\n", "Device 'ACHD_Avalon', 18 channels:\n", " [u'BP_MM_HG', u'H2S_PPM', u'INT_T_DEGC', u'OUT_T_DEGC', u'PM25B_UG_M3', u'SIGTHETA_DEG', u'SO2_PPM', u'SONICWD_DEG', u'SONICWS_MPH', u'BP_MM_HG', u'H2S_PPM', u'INT_T_DEGC', u'OUT_T_DEGC', u'PM25B_UG_M3', u'SIGTHETA_DEG', u'SO2_PPM', u'SONICWD_DEG', u'SONICWS_MPH']\n", "Device 'ACHD_Court_House', 3 channels:\n", " [u'CO_PPM', u'INT_T_DEGC', u'CO_PPM']\n", "Device 'ACHD_Flag_Plaza', 7 channels:\n", " [u'CO_PPM', u'INT_T_DEGC', u'OUT_T_DEGC', u'PER_F_PERCENT', u'PM10_UG_M3', u'PER_F_PERCENT', u'PM10_UG_M3']\n", "Device 'ACHD_Glassport_High_Street', 2 channels:\n", " [u'PER_F_PERCENT', u'PM10_UG_M3']\n", "Device 'ACHD_Harrison_Township', 11 channels:\n", " [u'INT_T_DEGC', u'NO2_PPM', u'NOX_PPM', u'NO_PPM', u'OZONE2_PPM', u'OZONE_PPM', u'NO2_PPM', u'NOX_PPM', u'NO_PPM', u'OZONE2_PPM', u'OZONE_PPM']\n", "Device 'ACHD_Lawrenceville', 26 channels:\n", " [u'BP_MM_HG', u'INT_T_DEGC', u'NO2_PPB', u'NOX_PPB', u'NO_PPB', u'OUT_RH_PERCENT', u'OUT_T_DEGC', u'OZONE2_PPM', u'OZONE_PPM', u'PER_F2_PERCENT', u'PM25_2__UG_M3', u'PM25_UG_M3', u'RWD_DEG', u'RWS_MPH', u'SIGTHETA_DEG', u'SONICWD_DEG', u'SONICWS_MPH', u'NO2_PPB', u'NOX_PPB', u'NO_PPB', u'OUT_RH_PERCENT', u'PER_F2_PERCENT', u'PM25_2__UG_M3', u'PM25_UG_M3', u'RWD_DEG', u'RWS_MPH']\n", "Device 'ACHD_Lawrenceville_2', 13 channels:\n", " [u'CO_PPB', u'INT_T_DEGC', u'NOYDIF_PPB', u'NOY_PPB', u'NO_PPB', u'PM10B_UG_M3', u'PM25B_UG_M3', u'SO2_PPB', u'CO_PPB', u'NOYDIF_PPB', u'NOY_PPB', u'PM10B_UG_M3', u'SO2_PPB']\n", "Device 'ACHD_Liberty', 7 channels:\n", " [u'H2S_PPM', u'INT_T_DEGC', u'OUT_T_DEGC', u'SIGTHETA_DEG', u'SO2_PPM', u'SONICWD_DEG', u'SONICWS_MPH']\n", "Device 'ACHD_Liberty_2', 7 channels:\n", " [u'PM10_FL_PERCENT', u'PM10_UG_M3', u'PM25_2__UG_M3', u'PM25_FL_PERCENT', u'PM25_UG_M3', u'PM10_FL_PERCENT', u'PM25_FL_PERCENT']\n", "Device 'ACHD_Lincoln', 4 channels:\n", " [u'PER_F2_PERCENT', u'PER_F_PERCENT', u'PM10_UG_M3', u'PM25_UG_M3']\n", "Device 'ACHD_Monroeville', 4 channels:\n", " [u'BP_MM_HG', u'INT_T_DEGC', u'OUT_T_DEGC', u'PM10B_UG_M3']\n", "Device 'ACHD_North_Braddock', 8 channels:\n", " [u'BP_MM_HG', u'INT_T_DEGC', u'OUT_T_DEGC', u'PM10B_UG_M3', u'SIGTHETA_DEG', u'SO2_PPM', u'SONICWD_DEG', u'SONICWS_MPH']\n", "Device 'ACHD_South_Fayette', 8 channels:\n", " [u'INT_T_DEGC', u'OUT_T_DEGC', u'OZONE2_PPM', u'OZONE_PPM', u'SIGTHETA_DEG', u'SO2_PPM', u'SONICWD_DEG', u'SONICWS_MPH']\n", "Device 'ACHD_West_Allegheny', 2 channels:\n", " [u'H2S_PPB', u'H2S_PPB']\n", "Device 'Anne_PolarStrap', 5 channels:\n", " [u'BeatSpacing', u'HeartBeat', u'HeartRate', u'BeatSpacing', u'HeartRate']\n", "Device 'BodyMedia', 14 channels:\n", " [u'activityType', u'caloriesBurned', u'efficiency', u'estimatedCalories', u'lying', u'mets', u'onBody', u'predictedCalories', u'sleeping', u'stepsGraph', u'totalCalories', u'totalLying', u'totalSleeping', u'totalSteps']\n", "Device 'BodyMedia_old', 28 channels:\n", " [u'activityType', u'caloriesBurned', u'efficiency', u'estimatedCalories', u'lying', u'mets', u'onBody', u'predictedCalories', u'sleeping', u'stepsGraph', u'totalCalories', u'totalLying', u'totalSleeping', u'totalSteps', u'activityType', u'caloriesBurned', u'efficiency', u'estimatedCalories', u'lying', u'mets', u'onBody', u'predictedCalories', u'sleeping', u'stepsGraph', u'totalCalories', u'totalLying', u'totalSleeping', u'totalSteps']\n", "Device 'Fitbit', 36 channels:\n", " [u'bmi', u'caloriesIntraday', u'caloriesOut', u'elevation', u'fairlyActiveMinutes', u'fat', u'floors', u'floorsIntraday', u'levelsIntraday', u'lightlyActiveDistance', u'lightlyActiveMinutes', u'loggedActivitiesDistance', u'metsIntraday', u'moderatelyActiveDistance', u'sedentaryActiveDistance', u'sedentaryMinutes', u'steps', u'stepsIntraday', u'totalDistance', u'trackerDistance', u'veryActiveDistance', u'veryActiveMinutes', u'weight', u'sleep', u'stepsIntraday', u'caloriesIntraday', u'levelsIntraday', u'metsIntraday', u'floorsIntraday', u'caloriesIn', u'water', u'caloriesInGoal', u'caloriesOutGoal', u'weight', u' fat', u' bmi']\n", "Device 'FluxtreamCapture', 70 channels:\n", " [u'AccelX', u'AccelY', u'AccelZ', u'Altitude', u'AppResidentMemory', u'AppTotalCPUUsage', u'AppUserCPUUsage', u'AppVirtualMemory', u'BackgroundTimeRemaining', u'Course', u'Drift', u'HorizontalAccuracy', u'InBackground', u'Lag', u'Latitude', u'Longitude', u'MobileBatteryCharging', u'MobileBatteryLevel', u'RotW', u'RotX', u'RotY', u'RotZ', u'Speed', u'SystemActiveMemory', u'SystemFreeMemory', u'SystemWiredMemory', u'SystemwideActiveMemory', u'SystemwideFreeMemory', u'SystemwideTotalCPUUsage', u'SystemwideUserCPUUsage', u'SystemwideWiredMemory', u'TimeZoneName', u'TimeZoneOffset', u'VerticalAccuracy', u'photo', u'AccelX', u'AccelY', u'AccelZ', u'Altitude', u'AppResidentMemory', u'AppTotalCPUUsage', u'AppUserCPUUsage', u'AppVirtualMemory', u'BackgroundTimeRemaining', u'Course', u'Drift', u'HorizontalAccuracy', u'InBackground', u'Lag', u'Latitude', u'Longitude', u'MobileBatteryCharging', u'MobileBatteryLevel', u'RotW', u'RotX', u'RotY', u'RotZ', u'Speed', u'SystemActiveMemory', u'SystemFreeMemory', u'SystemWiredMemory', u'SystemwideActiveMemory', u'SystemwideFreeMemory', u'SystemwideTotalCPUUsage', u'SystemwideUserCPUUsage', u'SystemwideWiredMemory', u'TimeZoneName', u'TimeZoneOffset', u'VerticalAccuracy', u'photo']\n", "Device 'Hexoskin', 11 channels:\n", " [u'AccelX', u'AccelY', u'AccelZ', u'BeatSpacing', u'HeartRate', u'RespAbdomen', u'RespChest', u'TidalVolume', u'RespAbdomen', u'RespChest', u'TidalVolume']\n", "Device 'Netatmo_Basement', 6 channels:\n", " [u'H2O_ppm', u'RH', u'Temp_F', u'H2O_ppm', u'RH', u'Temp_F']\n", "Device 'Netatmo_Bedroom', 3 channels:\n", " [u'H2O_ppm', u'RH', u'Temp_F']\n", "Device 'Netatmo_CREATE_Lab', 3 channels:\n", " [u'H2O_ppm', u'RH', u'Temp_F']\n", "Device 'Netatmo_CREATE_MR', 3 channels:\n", " [u'H2O_ppm', u'RH', u'Temp_F']\n", "Device 'Netatmo_Office', 3 channels:\n", " [u'H2O_ppm', u'RH', u'Temp_F']\n", "Device 'Netatmo_Porch', 3 channels:\n", " [u'H2O_ppm', u'RH', u'Temp_F']\n", "Device 'Nonin3150', 8 channels:\n", " [u'Pulse', u'SpO2', u'SpO2_thresh_90', u'SpO2_thresh_93', u'Pulse', u'SpO2', u'SpO2_thresh_90', u'SpO2_thresh_93']\n", "Device 'PolarStrap', 2 channels:\n", " [u'BeatSpacing', u'HeartRate']\n", "Device 'Smells_1', 5 channels:\n", " [u'Any_notes', u'Rate_the_smell_1_5', u'Rate_the_smell_1_5', u'Any_notes', u'1_No_smell_2_Barely_noticeable_3_Definitely_noticeable_4_It_s_pretty_bad_5_About_as_bad_as_it_gets']\n", "Device 'SnoreLab', 2 channels:\n", " [u'SnoreIntensity', u'SnoreIntensity']\n", "Device 'Speck04191928011013000000', 6 channels:\n", " [u'humidity', u'particles', u'raw_particles', u'humidity', u'particles', u'raw_particles']\n", "Device 'Speck42271924050513000000', 5 channels:\n", " [u'humidity', u'particles', u'raw_particles', u'temperature', u'temperature']\n", "Device 'Withings', 8 channels:\n", " [u'cuffHeartRate', u'diastolic', u'fatFreeMass', u'fatMassWeight', u'fatRatio', u'scaleHeartRate', u'systolic', u'weight']\n", "Device 'calibration_speck', 4 channels:\n", " [u'humidity', u'particles', u'raw_particles', u'temperature']\n", "Device 'junk', 40 channels:\n", " [u'BP', u'CO', u'H2S', u'INT_T', u'NO', u'NO2', u'NOX', u'OUT_RH', u'OUT_T', u'OZONE', u'OZONE2', u'PER_F', u'PER_F2', u'PM10', u'PM25', u'PM25B', u'SIGTHETA', u'SO2', u'SONICWD', u'SONICWS', u'BP', u'CO', u'H2S', u'INT_T', u'NO', u'NO2', u'NOX', u'OUT_RH', u'OUT_T', u'OZONE', u'OZONE2', u'PER_F', u'PER_F2', u'PM10', u'PM25', u'PM25B', u'SIGTHETA', u'SO2', u'SONICWD', u'SONICWS']\n", "Device 'stoop_speck_130409', 4 channels:\n", " [u'humidity', u'particles', u'raw_particles', u'temperature']\n", "Device 'Last_FM', 1 channels:\n", " [u'tracks']\n", "Device 'Calendar', 1 channels:\n", " [u'entries']\n", "Device 'All', 1 channels:\n", " [u'photo']\n" ] } ], "prompt_number": 3 }, { "cell_type": "code", "collapsed": false, "input": [ "# Modify the values below for setting up which source \n", "# channels you want to process, and where to put the resulting computed values. \n", "\n", "# The naming scheme is . to specify a given channel of a given device.\n", "# Change the keys of channel_proc_map to the channel names you want to use for input. \n", "# Change the values in channel_proc_map to the channel name you want to use for output\n", "# of the values computed for a given input channel.\n", "# Execute to setup module_info_map based on those settings.\n", "\n", "# The output of the cell above shows what the station and modules names are for the\n", "# Netatmo account you've bound the access_token to.\n", "\n", "global guest_id, sources_list, dev_name_list, channel_proc_map, channel_info_map\n", "\n", "channel_proc_map = {'Nonin3150.SpO2': 'Nonin3150.SpO2_thresh_93', \n", " 'Nonin3150.SpO2': 'Nonin3150.SpO2_thresh_90'}" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 4 }, { "cell_type": "code", "collapsed": false, "input": [ "# Modify this cell to change the function computed for a given source channel.\n", "# This one computes how much an SpO2 reading drops below a threshold. \n", "\n", "# The input args are the epoch timestamp, the source value, the source channel name, \n", "# and the destination channel name. In this case, we don't care about the timestamp \n", "# and parse the threshold to use from the channel name.\n", "\n", "# Note that the type of source_value may be a string, since some sources of input, \n", "# such as CSV resaders, are unable to distinguish the type of a a value and always return \n", "# strings. If you need to treat the value as a numeric type, you'll \n", "# need to convert it yourself\n", "def compute_channel_fn(timestamp, source_value, source_ch_name, dest_ch_name):\n", " thresh = 93.0\n", " \n", " dest_ch_elts = dest_ch_name.split('.')[1].split('_')\n", " if len(dest_ch_elts) == 3 and dest_ch_elts[0] == \"SpO2\" and dest_ch_elts[1] == \"thresh\":\n", " thresh = float(dest_ch_elts[2])\n", " \n", " #print \"Thresh = %d (dest channel = %s)\" % (thresh, dest_ch_name)\n", " \n", " source_f = float(source_value)\n", " if(source_f>thresh):\n", " return None\n", " else:\n", " dest_f = thresh-source_f\n", " #print \"Source = %f, dest = %f\" % (source_f, dest_f)\n", " return dest_f" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 5 }, { "cell_type": "code", "collapsed": false, "input": [ "# Modify this cell to choose whether to just run compute_channel_fn for \n", "# new data (timestamps from the source_ch that are > the max timestamp \n", "# in dest_ch) (recompute_all=False), or force a recompute everything\n", "# (recompute_all=True).\n", "\n", "# If compute_channel_fn is the same as it's been and you just want to run it \n", "# on new data that's come in, do the former (recompute_all=False).\n", "\n", "# If you've changed compute_channel_fn and want to run it on everything, \n", "# do the latter (recompute_all=True)\n", "recompute_all=False\n", "#recompute_all=True" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 6 }, { "cell_type": "code", "collapsed": false, "input": [ "# Execute this cell to read in the selected range of data from all the \n", "# source channels based on recompute_all, run compute_channel_fn on each \n", "# data point, and upload the result to the dest channel\n", "\n", "global guest_id, sources_list, dev_name_list, channel_proc_map, channel_info_map, csv_reader_map\n", "\n", "# Update sources_list in case there's new data available on any \n", "# of the relevant channels (current min_time and max_time for each channel are\n", "# part of what gets returned by the Fluxtream get sources API call)\n", "sources_list = fluxtream_get_sources_list(guest_id)\n", "\n", "# Parse populate channel_info_map with keys for each source/dest channel name\n", "# and values with the info on that channel as provided by sources_list\n", "channel_info_map = {}\n", "for dev_ch_name in channel_proc_map.keys() + channel_proc_map.values():\n", " # Split the device and module names\n", " dev_ch_name_elts = dev_ch_name.split('.')\n", " # Get the channel_info object for this\n", " channel_info = fluxtream_get_channel_info(dev_ch_name_elts[0], dev_ch_name_elts[1], sources_list)\n", " if channel_info == None:\n", " # This is ok for a destination channel, but not a source channel\n", " if dev_ch_name in channel_proc_map.keys():\n", " raise Exception(\"Can't find channel info for source channel %s; recheck device and channel names list\" % dev_ch_name)\n", " else:\n", " print \"Can't find channel info for dest channel %s; will create it\" % dev_ch_name\n", " \n", " # Store the channel info in channel_info_map\n", " channel_info_map[dev_ch_name]=channel_info\n", " \n", "print \"\"\n", "print \"Successfully setup channel_info_map\"\n", "print \"\"\n", "\n", "# Next, iterate over the source channels. For each, compute time ranges to process.\n", "# If the dest channel doesn't exist, use the full time range of the source channel.\n", "# If the dest channel does exist, by default just compute the data points that are \n", "# later than the last timestamp in the dest channel. \n", "\n", "# Read the CSV files for all the source channels.\n", "# The keys of csv_reader_map are the source channels.\n", "# The values are csv_reader objects. Each call to \n", "# csv_reader.next() will return a row consisting of \n", "# t, source_ch[t]\n", "# Where t is the epoch timestamp (aka unixtime) for the sensor reading in that row, \n", "# and source_ch[t] is the value of the source sensor channel at time t\n", "\n", "csv_reader_map = {}\n", "for dev_ch_name in channel_proc_map.keys():\n", " source_ch = dev_ch_name\n", " source_info = channel_info_map[source_ch]\n", " dest_ch = channel_proc_map[dev_ch_name]\n", " dest_info = channel_info_map[dest_ch]\n", " \n", " # End time is always the max_time for the source channel\n", " end_time = source_info['max_time']\n", " # Start time is min_time for the source channel if the\n", " # the dest_ch doesn't exist yet or if recompute_all is set.\n", " # Otherwise it is max_time of the dest channel so only new\n", " # values are computed\n", " start_time = source_info['min_time']\n", " if recompute_all==False and dest_info != None:\n", " start_time = dest_info['max_time']\n", " print \"Processing only new data in %s that isn't in %s: %f to %f\" %(source_ch, dest_ch, start_time, end_time)\n", " else:\n", " print \"Processing all data for %s: %f to %f\" % (source_ch, start_time, end_time)\n", " \n", " if end_time <= start_time:\n", " print \" No time range to process for guest %d, channel %s\" % (guest_id, dev_ch_name)\n", " else:\n", " # Get a CSV for the source channel for the desired time range\n", " csv_reader_map[source_ch] = fluxtream_get_csv(guest_id, [source_ch], start_time, end_time)\n", " print \"Successfully read data for guest %d, channel %s: %f to %f\" % (guest_id, source_ch, start_time, end_time)\n", "\n", "print \"\"\n", "print \"Done: Read CSV data for %d source channels: %s\" % (len(csv_reader_map.keys()), csv_reader_map.keys())\n", "print \"\"\n", "\n", "# Now process the data from all the source channels and upload \n", "# the results to the corresponding destination channels.\n", "\n", "# The csv_reader objects the previous cell created are used in this cell to \n", "# compute and upload data. \n", "\n", "# Note that this you need to execute the previous cell each time before executing this one\n", "# because the process of iterating over a given csv_reader object \n", "# In the loop below consumes the entries and they're not available to a subsequent run of the \n", "# loop\n", "\n", "\n", "# Define a function for doing a partial upload of data to a given dest_ch\n", "def partial_upload(dest_ch, upload_data):\n", " if len(upload_data)>0:\n", " # For upload, we need to split the device and channel name \n", " # pieces of dest_ch apart, and put the channel name part in \n", " # an array\n", " dest_dev_nickname, dest_ch_name = dest_ch.split('.')\n", " # print \"Uploading %d data points to dest %s\" % (len(upload_data), dest_ch)\n", " fluxtream_upload(dest_dev_nickname, [dest_ch_name], upload_data)\n", " else:\n", " # No data\n", " print \"No data to upload for dest %s\" % (dest_ch)\n", " \n", "# For each csv_reader returned, call \n", "# compute_channel_fn(timestamp, source_value, source_ch_name, dest_ch_name)\n", "# create an output data array for upload, and upload it to the Fluxtream server\n", "# and account set up in the credentials entry section above\n", "for source_ch in csv_reader_map.keys():\n", " # Get the name of the output channel from channel_proc_map\n", " dest_ch = channel_proc_map[source_ch]\n", "\n", " print \"Processing %s -> %s\" % (source_ch, dest_ch)\n", "\n", " # Retrieve the csv_reader object for this source channel from csv_reader_map,\n", " # which was set up in the previous loop\n", " csv_reader = csv_reader_map[source_ch]\n", " \n", " # Iterate over the lines in the CSV file for the source channel.\n", " # Call compute_channel_fn on each, and add each line that returns \n", " # non-null to upload_data for the given timestamp\n", " \n", " # We may need to do this in multiple batches if there are too many rows for \n", " # a reasonable upload.\n", "\n", " # Setup the upload data array\n", " upload_data=[]\n", "\n", " for row in csv_reader:\n", " # Make sure the row has two entries: timestamp and source value\n", " # and read them into local variables\n", " assert(len(row)==2) \n", " timestamp = float(row[0])\n", " source_value = row[1]\n", " comp_val = compute_channel_fn(timestamp, source_value, source_ch, dest_ch)\n", "\n", " if comp_val != None:\n", " #print \"%d (%f): %s -> %d\" % (csv_reader.line_num, timestamp, source_value, comp_val)\n", " upload_data.append([timestamp,comp_val])\n", " # Check if upload_data is big enough we should upload now,\n", " # and if so clear upload_data afterwards\n", " if(len(upload_data)>=1000):\n", " partial_upload(dest_ch, upload_data)\n", " upload_data = []\n", " \n", " # Upload any remaining rows in upload_data\n", " partial_upload(dest_ch, upload_data)\n", " \n", "print \"\"\n", "print \"Done: Uploaded computed data for %d source channels: %s\" % (len(csv_reader_map.keys()), csv_reader_map.keys())" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Read of sources list for guest_id=14 succeeded\n", "\n", "Successfully setup channel_info_map\n", "\n", "Processing only new data in Nonin3150.SpO2 that isn't in Nonin3150.SpO2_thresh_90: 1427357063.000000 to 1427799406.000000\n", "Successfully read data for guest 14, channel Nonin3150.SpO2: 1427357063.000000 to 1427799406.000000" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "\n", "Done: Read CSV data for 1 source channels: ['Nonin3150.SpO2']\n", "\n", "Processing Nonin3150.SpO2 -> Nonin3150.SpO2_thresh_90\n", "Uploading 1000 data points to rsargent's account on server fluxtream.org, device Nonin3150, channels ['SpO2_thresh_90']" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "Upload to Nonin3150 ['SpO2_thresh_90'] (1000 rows, 1427357063 to 1427779000) succeeded" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "Uploading 1000 data points to rsargent's account on server fluxtream.org, device Nonin3150, channels ['SpO2_thresh_90']" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "Upload to Nonin3150 ['SpO2_thresh_90'] (1000 rows, 1427779001 to 1427794536) succeeded" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "Uploading 1000 data points to rsargent's account on server fluxtream.org, device Nonin3150, channels ['SpO2_thresh_90']\n", "Upload to Nonin3150 ['SpO2_thresh_90'] (1000 rows, 1427794537 to 1427797390) succeeded" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "Uploading 244 data points to rsargent's account on server fluxtream.org, device Nonin3150, channels ['SpO2_thresh_90']\n", "Upload to Nonin3150 ['SpO2_thresh_90'] (244 rows, 1427797391 to 1427799365) succeeded" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "\n", "Done: Uploaded computed data for 1 source channels: ['Nonin3150.SpO2']\n" ] } ], "prompt_number": 8 }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }