Category Archives: Data-betes

Retrospective

I’ve been gathering all of my diabetes related data for more than a year now: carbs, boluses, BG readings, CGM traces, exercise data, insulin changes, etc. Almost all of this data is automatically generated and captured through my pump/CGM, and I don’t have to do much of anything to aggregate it. Making use of it is another matter entirely.

Collecting all of this diabetes data is just hoarding unless I actually use it to make my diabetes better. And do I ever need to make improvements. For reasons that I’m trying to figure out, the last six months have not been kind to my BGs, and the last three have been even worse, giving me my highest A1c since I was diagnosed with diabetes almost 15 years ago. Tomorrow morning I will meet with my endocrinologist, and I know the question of “What changed?” is going to come up. In order to answer “What?” I’m first trying to answer the question “When?” How have my BG readings changed throughout the day compared to six months ago? Looking at that information, I can move on to the question of “What’s different at those times of day?”

Here are the statistics from six months to three months ago, and then from three months ago to yesterday (when I had my blood drawn).

There’s a lot of data there, but you can see that I’m lower overnight and slightly unchanged during the first half of the day, but then the rest of the day is up, with the afternoon and evening readings quite a bit higher. All of this combined to raise my overall BG average by about 20-25 mg/dL (1-1.4 mmol/L). The variability is more or less unchanged, so if we subtract the mean and median values from these sets of data, we can see the changes more clearly.

And that is pretty much what I know. Tomorrow the trial-and-error phase of figuring out what to change begins, but at least we can start from the data.

Posted in Data-betes, Diabetes | Leave a comment

Working on the A1c

I was really early for my endocrinology appointment this morning. It was one of those “arrive really early or struggle to make it on time” choices that had me sitting around in the hospital cafeteria, leisurely eating a muffin and reviewing my diabetes data. The hospital has free Wi-Fi, so I uploaded my data from my pump and meter into CareLink and then exported it from there back to MATLAB. (It’s an inelegant process, but it’s the best I can do . . . for now.) My endo’s staff was going to download all of it again when I got to her office, but I wanted to look it over myself so that we could talk about what’s going on.

My last couple of A1c blood draws have been near all-time (that is to say, “post-diagnosis”) highs. My endo is remarkably judgement-free, and she’s really eager to help me figure out what’s going on and what changes to make. It’s a partnership, and we both bring our own perspective and fresh ideas. I have the context behind the numbers, and she has experience with other type-1 patients.

For this visit, I decided that Saturday and yesterday were two good case studies that we might investigate.

Saturday was a typical weekend day: sleep in a little, clean house a bit, have lunch out, do some shopping, etc. The thing that made it interesting was that I slid into lunch a bit low and then I had a lot of trouble getting myself out of the hypoglycemic zone. We decided that it may have been because my Indian food lunch was rather “complex,” causing the carbohydrates to take longer to get absorbed into my bloodstream. She also noticed that I have a lot of “bolus stacking” going on, which I had also seen from my graphs. (She observed a lot of stacking on Halloween and the day after, too. “Yeah, you can see when the Tooth Decay Fairy showed up,” I said to much amusement.) The stacking isn’t a problem per se, but it does make digging myself out of an insulin hole harder.

Yesterday was typical of some of the other issues I’ve been having. I had good BGs overnight and before swimming. I ate a little bit before heading to the pool and finished my swim an hour later at about the same place I started. So far, so good. But then I didn’t bolus enough for the extra muffin at breakfast. I knew the amount was probably too little, but even with all those carbs it just felt like a lot of insulin. I was going to be walking around the campus a fair bit, going to meetings and preparing for a very important meeting of my own later in the day. I didn’t want to go high, but I also couldn’t afford losing time to the lows. Not surprisingly, I went way up before lunch and then really had to work to bring it back down. By dinner I was in a happy place, except (once again) I was worried about lows, so I delivered less insulin than required. This time it was totally the right thing, since I kept sliding lower throughout the evening, and I ended up in the low 60s (3.3 mmol/L) twice overnight.

That story garnered some more suggestions, and I have a bolus test or two to do. In a couple weeks I will send her more data.

The interesting thing, we both thought, is that if you look at the last two weeks (and take out the 24 hours after the trick-or-treaters left) my BGs look pretty good. We think that with a few changes, my next A1c will be much better. Let’s hope so.

Posted in Data-betes, Diabetes, NaBloPoMo, NaBloPoMo 2013 | Leave a comment

All Together Now: Integrating the Diabetes App

Hey, y’all. Sorry I’ve been mostly absent recently. I’ve been making stuff, and it feels pretty good. I don’t get to code quite as much as I used to at work, and this (*ahem*) little project has been giving me the outlet I need.

I started building an app to integrate all of my diabetes and exercise data right after my last endocrinology appointment, when I decided I finally wanted to do something about (1) the abysmal lack of context in the data I share with my doctor, despite having so much of it automatically logged for me, and (2) the highs and lows that I see associated with exercise. I’ve had a bad track record with personal software development projects, but I was able to get some good traction with this one. After some early brainstorming and design sessions, a couple of productive plane rides, numerous conversations with a few coworkers, one Boston Quantified Self meet-up, and many evenings of hacking/coding/fixing/designing/refactoring/playing—including not a few where I stayed up way past “pumpkin time”—I feel like I have something I can actually use to start making real conclusions. Of course I’ve been using the data throughout the project, leading to a few “Ah ha!” moments, but the last bit of integration makes it so easy to really see what’s going on.

Here’s what I’ve got. (Click for a larger image.)


You’re looking at four windows in my app. There will probably be more, but this is all I can really wrangle now. Soon I will figure out how to use the awesome, undocumented stuff under development at work and put these parts into a more polished application. (This project is really helping me know more about the bleeding-edge parts of MATLAB. While I’ve worked with it more or less every day for the last fifteen years, I never really had the chance of use many of its newer features.) Here’s are description of the four parts.

(1) The upper left-hand window is a data browser, focusing on the highest level details for each day. This should look pretty familiar to most of us with diabetes. This part and the next one are the most quantitative, and I’m trying to work more contextual, qualitative information into the other pieces of the app. Clicking on any cell in the table changes what is shown in the other windows, and it’s possible to compare multiple days at once.

(2) The lower left window presents more details for the selected days: minimum, maximum, average, and standard deviation for both blood glucose readings and CGM data; the estimated number of carbs I ate (including the ones, like glucose tablets and food during exercise, that I didn’t bolus for) and the amount of insulin I dosed; and the amount of exercise. I have also thrown in a couple of computed values: my average blood glucose divided by the number of carbs and my effective carb:insulin ratio for the day. They might be useful as I look through the data. Or maybe they won’t. We shall see.

(3) The graphs in the upper right are the big picture view of the data. If you’re a visual person (like me) and want to see how the parts fit together, this is it. It’s all there: sensor and BG data, carbs, insulin, temporary and regular basal rates, . . . even the estimated amount of insulin concentration in my bloodstream waiting to be used. The bright blue boxes are exercise. They’re not the most beautiful graphs (yet), but I’ve already managed to see some trends in them.

(4) While looking for these trends, I found myself always going back to the raw data to see exactly what that number was or exactly when that other thing happened. So I made the fourth window—the one in the lower right—which contains the actual events logged by all of my devices. It’s the rawest form of the data that I’ve exposed in the app. (There’s even more “raw” data stored in what I’m calling “the timeline,” or database, but it’s so hard to use as-is. That’s why I wrote the app, eh?)

And that’s the big picture of what I’ve made.

Oh, I guess there’s also this other stuff, just in case you think I’ve been slacking:

  • There’s a nice box plot tool that can be configured to show averages, distributions, and other statistical goodies for different times of day. When I threw enough data at it, it became pretty clear where the most challenging part of my day are (blood sugar wise, at least).
  • It integrates with Dropbox, so I can use it wherever I have both MATLAB and Dropbox installed. The data is always sync’ed up.
  • It has one of the fastest .fit file parsers around. :-)
  • There’s a good deal of date-oriented subsetting functionality. Maybe I want to look at what happened in the last 90 days since my endo appointment. Perhaps I just want to examine weekdays . . . or weekends. I might only be interested in seeing the five hours before and two hours after exercise. Easy peasy.
  • It’s possible to look for and report specific kinds of events. Only want to see CGM or pump alarms? Okay. Want to see all the details about swims lasting longer than 30 minutes. No problem.
  • I liked the free-form nature of Microsoft Outlook’s date/time entry so much that I implemented the same thing for myself. I like saying “yesterday” or “tomorrow” when talking to MATLAB’s datenum function.

There’s more stuff, but they are mostly building blocks.


Now the really exciting work begins to automate the search for trends. . . . finding those insulin needles in the haystack, if you will. I hope to be able to answer questions like these soon: What is happening on days when I climb wicked high in the afternoon? What happens on days when I don’t? How much does my blood glucose typically drop when I ride my bike in the afternoon? What did I do on afternoons when my blood sugar was really stable while I was out running or cycling? What is my actual carb:insulin ratio on days where my blood glucose is well-managed? How does my overnight basal rate look?

I’ll let you know how the data mining turns out!


p.s. — Yes, I’m thinking about how to share this functionality with the whole world (or at the very least the MATLAB-speaking part). But before I do that, I need to ruminate much, much, much more about what it means to provide the building blocks for medical analytics to people (like me) who have to make most/all of our medical decisions without much decision-support tooling and yet are expected to get it right most of the time. It’s not something I take lightly.

Posted in Data-betes, Diabetes, Software Engineering | 7 Comments

Uploading OneTouch Meters to CareLink in MacOS 10.8

You know what sucks? Not being able to connect to CareLink from your nifty, modern Mac because Lifescan and/or Minimed decided it wasn’t worth creating a new driver for the cable that connects a OneTouch blood glucose meter to your USB port. Now, it is cool that they gave me a free Bayer USB Contour meter, but I haven’t switched over my prescriptions yet. So, yeah.

You know what else sucks? Needing to use CareLink at all, when what I really want to do is to communicate with my meter from MATLAB directly. I did this in the past with a Freestyle meter, and that showed me how much better the world can be if programmers have direct access to the medical device data. Not everybody’s thing, of course, but what one of my college professors told another guy in the lab when I was inexplicably trying to configure the “broken” HP machine to run X-Windows still holds true: “Some people are high-level people. Some people are low-level people. Jeff is a low-level person.”

Well, I’d finally had it with the “You can’t upload to CareLink or download into MATLAB” bullshit, so I decided to try to fix this problem with a few pointers from the Test and Measurement team (a.k.a., the Data Acquisition Toolbox and Instrument Control Toolbox folks) at the office. I’m a hardware newbie so I prepared to learn a lot. Fortunately, there wasn’t a lot to learn. Mostly just the role of the hardware driver.

I’m happy to report that it is completely possible to connect a OneTouch meter to CareLink using the USB-to-serial meter that you can buy from Lifescan. It does require obtaining and installing a driver on your system, but that’s pretty straightforward. You only need the nerve to open a terminal window on your Mac and use the sudo command. Sounds scary, but it’s not. (Still, it was enough to prompt me to do the weekly computer backup before starting. I needed to do it anyway.) Pretty easy stuff. Here we go.

For the record, there’s a third-party vendor that makes a USB-to-serial cable for OneTouch meters that ships with a CD that should take care of all of this for you. I haven’t used it, but they pointed me to the right drivers that they thought might work with the cable I already had. I thought was a pretty stand-up thing to do. (BTW, they and Lifescan use different chipsets in their cables–Prolific PL2303 chip for Lifescan vs. FTDI for Celeritous. The important thing to note: Different chips in the cables require different drivers.)

Okay, how to get the Lifescan USB-to-serial cable working with MacOS 10.8 . . . and maybe 10.6 and 10.7.

  1. Download the PL2303 driver from Prolific. I needed to get the file md_PL2303_MacOSX-10.6up_v1.5.0.zip, which was the latest version at the time.
  2. Remove any previously installed ProlificUsbSerial.kext drivers. Why is it there when it won’t work? I don’t know. I do know that mine was from 2006, which was probably from my previous MacBook. The instructions tell which “sudo” command to use. This is the trickiest part, and it’s pretty easy. (For the record, I moved mine with the following command just in case things went south:
    sudo mv /System/Library/Extensions/ProlificUsbSerial.kext ~/tmp/
    You will need to know the administrator password, which is probably the same as your login password.
  3. Right click to “Open” and run the installer package.
  4. Reboot. Why? Because installing drivers requires a reboot.
  5. Go to CareLink and enjoy uploading all of your data again.

As for me, I’m going to get reading that Lifescan document. You know, the super-secret one that talks about how low-level people like me can interface with the OneTouch meters via serial port. More on how that’s going another day.

Posted in Computing, Data-betes, Diabetes, Fodder for Techno-weenies | 1 Comment

Visualizing Exercise with Diabetes

Well, well, well. That’s done.

The visualization of exercise data proved to involve much more work than I had originally anticipated, mainly because it involved so many different data events: .fit file data, sensor readings, BG fingerstick values, basal rates (both regular and temporary), carb intake (whether covered by boluses or not), bolused insulin, and insulin concentration. That’s almost everything that I had already built for the app plus several new parts. It also led me to create some routines to find “interesting” events and then retrieve a subset of values around those events.

Here’s last Sunday’s 2.5-hour, 40-mile bike ride along with five hours of context before and two after:


The curve in the top chart is my continuous glucose monitor (CGM) sensor data. The red X’s are the “ground truth” fingerstick readings. (Some of the values are duplicates, and I need to remove those.) The blue box is the actual duration of the bike ride. The numbers along the bottom of the upper plot show carbs that I ate before, during, and after the ride.

The lower chart shows insulin events. The horizontal step plot is basal (background) insulin delivery. The red portion of that plot is when I had a temporary basal rate in place. The green spikes are larger bolused insulin doses. You can see a small one before the ride and a larger one afterward to cover my recovery snack. (Evidently, that bolus didn’t do its job very well, since my BG shot way up immediately after I finished cycling.) The dashed curves are estimates of the insulin concentration in my blood.

Now that I’ve done this for one day, I can start looking at more days. But that has to wait until tomorrow (or later) because it’s way past my bedtime.

Posted in Cycling, Data-betes, Diabetes, Fodder for Techno-weenies | Leave a comment

Insulin Concentration Redux

I figured out the right way to average the insulin concentration in my blood at different times of the day. The chart is below. The red curve is the average for weekend days, while the blue curve averages weekdays. (The scale on the Y axis doesn’t mean anything, and I should probably get rid of it.)


You can see that I don’t eat a regular breakfast on most weekends. Instead, I go for a long bike ride or head to the track for a run, and when I’m done it’s time for a snack or lunch. I guess that’s why my insulin concentration starts rising steadily after 10 AM. (Remember we’re looking at an average of many weekends.) The weekday curve is much smoother and more clearly defined, as shown below:


The chart above shows my average insulin concentration for each day of the week. (It pays to click through to the full-size image.) Once again, red is the weekend, and blue tracks weekdays. I’ve repeated the “weekdays vs. weekend” plot to make it easier to see the big picture and to highlight the curve that’s going to be repeated on each of the following days as the dashed line. Most individual weekdays are like their average, as are the weekend days. I am a creature of habit, I guess.

If you look closely, you can see that my IOB/active insulin is higher on Monday afternoons because I take it off from training and am not so worried about having extra insulin around. You can also see that the free Wednesday breakfast at the office leads to higher insulin concentrations all the way through to lunchtime. I also want to believe that I can see a higher lunch peak on Tuesdays, when Gourmet India makes its biweekly appearance in the cafe at work, and a delayed peak at lunch on Friday because of an extra bolus for weekly cookies. (It’s no wonder some people call us “The FatWorks.”)

Surely there are more stories to be told from the data, but those are for me to figure out another day. For now, it’s time to move on to looking at carbs. Until next time. . . .

Posted in Data-betes, Diabetes, Fodder for Techno-weenies | 1 Comment

The Quantified Self

I’m getting ready to dive deep into this site and the places it links to: QuantifiedSelf.com.

Posted in Data-betes, Diabetes, Fodder for Techno-weenies | 1 Comment

Insulin Concentration

The following plot shows three day’s worth of insulin boluses. (What’s a bolus? It’s the insulin dose given at mealtime or as a correction to bring down blood sugar. It differs from the continuously delivered background insulin by being a much larger dose and being manually delivered.)


The spikes are the “normal” boluses, and there are about a dozen per day. (The one rectangular box on the 9th is a “square bolus” delivered over an extended period.) It’s kind of amazing how quickly insulin gets from where it’s delivered subcutaneously to the blood stream, but it isn’t instantaneous. And several hours pass between when the insulin enters the blood stream and when it is fully cleared through metabolism or by the liver. (Yay, liver!)

In signal processing terms, the normal boluses are essentially impulse signals that yield a response. (You can see the response curve in a previous post.) Here are the impulse responses for the normal boluses.


But this isn’t exactly how insulin works. All of those curves build on top of each other. Figuring out how to add all of those contributions into one “signal” is my project for the evening. When I asked a coworker about a good way to do this today, he suggested convolution, and then we prototyped a couple things. Now I’m working on doing that. It’s supposed to look a bit like this . . .


. . . but it isn’t quite right, since it seems shifted earlier in time relative to the boluses:


I will provide an update when we figure it out.

Updated a few minutes later: Of course! Because the convolution operation acts symmetrically about the impulse, the kernel needs to be pre-padded with an equal number of zeros. That shifts the result appropriately.


And some code. . . .

timelineAll = load('database_all.mat');
timelineSubset = findByDate(timelineAll, '2013-06-09', '2013-06-12');
timeStamps = [timelineSubset.bolusEvents{:,1}];
bolusAmts = [timelineSubset.bolusEvents{:,3}];

% Create a linearly spaced timeline.
resolution = 10;
spacing = resolution/60/24;

inputTime = floor(min(timeStamps)):spacing:ceil(max(timeStamps));
inputSignal = zeros(size(inputTime));

% Put the normal boluses into the signal.
for p = 1:numel(bolusAmts)
    % Find closest inputTime location to this time.
    absoluteTime = timeStamps(p);
    fractionalPart = absoluteTime - floor(absoluteTime);
    fractionalPart = round(fractionalPart * 24 * 6) / 6 / 24;
    roundedTime = floor(absoluteTime) + fractionalPart;

    % Assign the bolus.
    inputSignal(inputTime == roundedTime) = bolusAmts(p);
end

% Resample the insulin action curve.
scaleFactors = [0.0, 0.73, 1.0, 0.93, 0.67, 0.47, 0.27, 0.22, 0.18, 0.13, 0.07];
curveTimes = 0:0.5:5;
resampledCurveTimes = 0:(resolution/60):5;
resampledScaleFactors = interp1(curveTimes, scaleFactors, resampledCurveTimes, 'cubic');
resampledScaleFactors = [zeros(size(resampledScaleFactors)) resampledScaleFactors];

%concentration = conv(inputSignal, resampledScaleFactors, 'same') * 0.37;
concentration = conv(inputSignal, resampledScaleFactors, 'same');

figure;
stem(inputTime(inputSignal~=0), inputSignal(inputSignal~=0)); datetick
hold on
plot(inputTime, concentration, 'r'); datetick;
title('Cumulative insulin concentration')
Posted in Data-betes, Diabetes, Fodder for Techno-weenies, MATLAB | 4 Comments

Motor Error


In March I got a new pump, since my older Minimed Paradigm 522 was very out of warranty. The differences between the 522 and the 523 are slight and barely noteworthy, but I would miss them if they went away.

Unfortunately, this new pump also came with some problems. “What kind?” you ask. “Motor errors,” I reply. Take a look at my pump’s own diagnostics—as parsed by the little app I’m writing—if you don’t believe me:

>> displayAllEvents(timelineAll, 'major alarms')
15-Apr-2013 17:29:31 - Alarm - No Delivery (4)
15-Apr-2013 17:30:17 - Alarm - No Delivery (4)
19-Apr-2013 09:19:53 - Alarm - Motor Error (43)
19-Apr-2013 11:48:37 - Alarm - No Delivery (4)
19-Apr-2013 11:49:23 - Alarm - No Delivery (4)
19-Apr-2013 11:50:27 - Alarm - No Delivery (4)
25-Apr-2013 18:20:45 - Alarm - No Delivery (4)
25-Apr-2013 18:22:18 - Alarm - No Delivery (4)
25-Apr-2013 18:24:22 - Alarm - No Delivery (4)
06-May-2013 07:27:35 - Alarm - Device Alarm (55)
09-May-2013 17:21:01 - Alarm - No Delivery (4)
09-May-2013 17:22:39 - Alarm - No Delivery (4)
09-May-2013 17:25:15 - Alarm - No Delivery (4)
17-May-2013 06:59:19 - Alarm - No Delivery (4)
17-May-2013 07:00:00 - Alarm - No Delivery (4)
17-May-2013 07:01:52 - Alarm - No Delivery (4)
17-May-2013 07:03:45 - Alarm - No Delivery (4)
18-May-2013 08:49:24 - Alarm - Motor Error (43)
24-May-2013 07:15:58 - Alarm - No Delivery (4)
24-May-2013 07:17:54 - Alarm - No Delivery (4)
24-May-2013 08:29:27 - Alarm - No Delivery (4)
27-May-2013 17:40:46 - Alarm - No Delivery (4)
27-May-2013 17:41:29 - Alarm - No Delivery (4)
07-Jun-2013 12:11:21 - Alarm - Motor Error (43)
10-Jun-2013 08:23:11 - Alarm - Motor Error (43)

The “No Delivery” alarms were mostly my fault. (Running a reservoir to completely empty will lead to that . . . along with the possibility of high BGs, so I don’t recommend it. I’m trying to pay more attention to how long it’s been since the previous “Low Reservoir” notice.) Those four “Motor Error (43)” messages, however, are definitely a problem with the pump and always appeared in the middle of a bolus.

Minimed’s customer service is great, and they delivered a new pump to me next day. The “next day” happened to be a Saturday, and the UPS man arrived mid-morning shortly after I got back from the track, where I had run ridiculously fast 30-second repeats—like 4:20/mile fast—in my last speed workout during the taper before this weekend’s 70.3. (Sorry, I’m getting distracted.) Sadly, technology will fail, but I’m glad that the manufacturers realize that these devices keep us living and go to extraordinary lengths to make things right.

Tomorrow, after transferring all of my settings into 523 #2, I’m sending 523 #1 back to the mothership. Godspeed little pump. May your refurbished motor be error-free in the future.

Posted in Data-betes, Diabetes | 2 Comments

Pharmacokinetics

Now on this evening’s reading list: Bioavailability and bioeffectiveness of subcutaneous human insulin and two of its analogs—LysB28ProB29-human insulin and AspB10LysB28ProB29-human insulin—assessed in a conscious pig model. (“LysB28ProB29,” or insulin lispro, is better known as Humalog.) Along with the “Pharmacokinetics” section of the Humalog FDA drug insert, it’s helping me better understand insulin absorption, metabolism, and elimination. My goal is to have a better model of “active insulin” than just insulin on board (IOB) and to look at how insulinized I am at different parts of the day.

The main question I hope to answer is whether having twice as much serum (i.e., blood) insulin concentration means twice as much BG lowering effect. I suspect it does, but as we all know, “Assumption, my dear Mitz, is the mother of all fuck-ups.” [IMDB]

Yesterday evening I estimated some of the information from one of the charts in the Humalog insert, put it into MATLAB, used one of our more awkwardly named functions (cumtrapz), and generated this table:


Those tiny numbers (hopefully) tonight will become a set of overlaid curves that show how much insulin is in my blood throughout the day. Yay, math!

Posted in Data-betes, Diabetes, Fodder for Techno-weenies | 2 Comments

Box Plot

Based on Sara‘s comment on yesterday’s post, I decided to use MATLAB’s boxplot function to show the statistical complexity in the data.


So what is this? The boxes show the 25th and 75th percentiles of the data, and the red line is the median (which is the middle value—not the average—in the data). The “whiskers” extend to the extremes of the statistically significant data, and the red “+” symbols are the outliers (which figure into the median and average but are statistically outside the normal distribution). I’ve added a couple of extras to the regular box plot; the first is a red-and-green dashed line that shows the average of all readings, while the curve with the “x” markers shows the average of each bin.

What does this say to me? Most of the medians are below the daily average, which means that most of the time my BG is pretty good, but I have a lot of “outlier” highs that I should work on. Also, the time right around lunch is the low time of my day, while the late afternoon (from about 3:00-6:00PM) tends to be my highest. I seem to be most consistent—statistically speaking—in the evenings.


What next? While I was walking off a hypo during today’s long run, I started thinking about how to extract “interesting” things from the data I’ve aggregated. I need to figure out how to programmatically request to “show me all of the data five hours before a long run in the afternoon” or “show me what happened on days that I exercised after bolusing two to three hours before starting.” I can think of “good” ways that are quite complicated, but I need to consider whether there’s a way to do some natural-language processing so that I can actually write something “human” instead of forcing people/myself to chain lots of conditionals and requests together. (Of course, the complicated way might be the first step.)

Figuring that out is going to take a while. In the meantime, I need to get to work on adding the currently unrecorded data to the mix and figuring out how to display just a day-or-so of data.

More soon!

Posted in Data-betes, Diabetes, Fodder for Techno-weenies | 3 Comments

A “Typical” Day’s Blood Sugars

I always wondered what an “average” day’s blood glucose looked like. Now I know.

Posted in Data-betes, Diabetes, MATLAB | 2 Comments

Diabetes Flight Data Recorder

Lisa and I took a quick trip to Iowa over the weekend for our college class reunion. I took advantage of the time in airports and airplanes to work on the diabetes app. Because I’m using MATLAB—which I know very well and which makes programming complicated tasks very easy—I was able to get a lot done. In my mind, development of version 1 of this app has five phases:

  1. Import data from CareLink and .fit files into MATLAB. — DONE!
  2. Create a data structure (“the timeline”) that can hold all of this data and import the CareLink data into it, taking care to prevent repetition when importing data that’s already present. — DONE!
  3. Import exercise data from .fit files into the timeline.
  4. Make a MATLAB GUI to enter other events that aren’t currently captured by any device, and put these events into the timeline.
  5. Create some MATLAB tools to visualize the data and search for patterns in it.

That seems like a reasonable first version. It will have the tools necessary to aggregate data from various sources and do something useful with it. My main goal when starting this project was to create something that can help me improve my BG self-management by revealing trends and adding context. This should make that possible. Later I would like to make it more portable, but I’m not sure how easy (or even how) to integrate this MATLAB-based processing and I/O with a mobile device. I have some ideas that involve iCloud. A first step in the next version will likely involve an iOS app to gather the “self-reporting” data, but even that is a ways down the road.

In the meantime here’s what I can currently do. This isn’t how I imagine working with the data in the future, but it shows a bit of what it is possible to do with a very little bit of work.

>> fname = 'CareLink-Export-2013-03-30-to-2013-05-01.csv';
>> importCarelink(fname, 'database.mat')
>> timeline = load('database.mat')

timeline = 

        alarmEvents: {1221x3 cell}
        basalEvents: {480x3 cell}
           bgEvents: {821x3 cell}
        bolusEvents: {1282x6 cell}
        calibEvents: {1300x3 cell}
     sensorBGEvents: {35586x4 cell}
    setChangeEvents: {184x5 cell}
      suspendEvents: {41x3 cell}
    tempBasalEvents: {108x5 cell}
       wizardEvents: {1160x8 cell}
          uploadIDs: {9x2 cell}

>> wizardEvents = timeline.wizardEvents;
>> wizardEvents(end-20:end,:)

ans = 

    [7.3538e+05]    [     4]    [40]    [  0]    [     0]    [     4]    [     0]    '10777573309'
    [7.3538e+05]    [0.8000]    [ 8]    [  0]    [     0]    [0.8000]    [     0]    '10777573301'
    [7.3538e+05]    [7.5000]    [75]    [127]    [0.5000]    [7.5000]    [1.3000]    '10777573290'
    [7.3538e+05]    [     4]    [40]    [  0]    [     0]    [     4]    [     0]    '10777573282'
    [7.3538e+05]    [8.5000]    [75]    [120]    [0.4000]    [8.3000]    [0.2000]    '10777573267'
    [7.3538e+05]    [4.4000]    [40]    [ 99]    [     0]    [4.4000]    [4.1000]    '10777573259'
    [7.3538e+05]    [0.5000]    [ 0]    [138]    [0.5000]    [     0]    [     0]    '10777573241'
    [7.3538e+05]    [     6]    [60]    [103]    [     0]    [     6]    [0.4000]    '10777573237'
    [7.3538e+05]    [2.5000]    [25]    [228]    [1.9000]    [2.5000]    [     3]    '10777573230'
    [7.3538e+05]    [7.5000]    [75]    [238]    [2.7000]    [7.5000]    [2.7000]    '10777573221'
    [7.3538e+05]    [5.2000]    [ 0]    [361]    [5.2000]    [     0]    [     0]    '10777573205'
    [7.3538e+05]    [6.6000]    [60]    [361]    [5.2000]    [6.6000]    [5.5000]    '10777573200'
    [7.3538e+05]    [     0]    [ 0]    [182]    [1.6000]    [     0]    [7.2000]    '10777573186'
    [7.3538e+05]    [0.9000]    [ 0]    [313]    [3.8000]    [     0]    [2.9000]    '10777573177'
    [7.3538e+05]    [3.5000]    [ 0]    [390]    [5.4000]    [     0]    [1.9000]    '10777573168'
    [7.3538e+05]    [0.6000]    [ 0]    [257]    [2.4000]    [     0]    [1.8000]    '10777573156'
    [7.3538e+05]    [3.4000]    [ 0]    [330]    [3.5000]    [     0]    [0.1000]    '10777573143'
    [7.3538e+05]    [     6]    [60]    [256]    [2.4000]    [     6]    [3.5000]    '10777573133'
    [7.3538e+05]    [8.5000]    [85]    [126]    [0.5000]    [8.5000]    [0.5000]    '10777573122'
    [7.3538e+05]    [     6]    [50]    [153]    [     1]    [     5]    [     0]    '10777573115'
    [7.3538e+05]    [7.2000]    [65]    [151]    [     1]    [7.2000]    [2.4000]    '10777573108'

I can’t remember what those wizard event columns mean, but it’s basically all of the data from the bolus wizard. (Updated: The columns are time in MATLAB datenum values, bolused insulin units, grams of carb, BG in mg/dL, correction calculation, food calculation, active insulin, and CareLink unique upload ID.) Let me distract you with a picture of CGM sensor data, smoothed over two hours.

>> sensorBGEvents = timeline.sensorBGEvents;
>> dates2013 = [sensorBGEvents{:,1}] > datenum(2013,1,1);
>> sensorBGEvents(~dates2013,:) = [];
>> figure; plot([sensorBGEvents{:,1}], medfilt2([sensorBGEvents{:,2}], [1 100])); datetick

Posted in Data-betes, Diabetes, Fodder for Techno-weenies, MATLAB | 4 Comments

Siri, Tell Me about the Ultimate Diabetes Device


Diabetes Blog Week is technically over, but I still want to write about one of the topics: my dream diabetes device.

I — In the past I’ve written about wanting an application that integrates all my current diabetes paraphernalia, my Carelink account, and my mobile phone iPod. The goal was to have total diabetes awareness by tagging “interesting” events so that I can go back to the historical record the next time that thing occurs. “When I was sick how much extra insulin did I need to give?” “When I ate Indian food, what was an appropriate amount of insulin and how did I deliver it?” “What basal rates and carb amounts worked well for a triathlon?” Ask one of these questions, and see the BG values, bolus wizard details, and CGM traces for all of the events tagged with those keywords. It wouldn’t be a perfect solution to preventing all lows and highs, but it would surely be better than my own faulty memory.

I actually started writing the application and got all of the data into a MacOS application, but I got frustrated that I wasn’t going to be able to easily get the data from my computer onto my mobile device. So, as usual, I set it aside and got distracted by something else. That was a couple years ago. Since then iCloud came along and makes sharing this kind of data between devices much easier. Maybe someday—after I win the PowerBall lottery, perhaps—when I have limitless time and ambition, I will pick it back up. Or (better yet) I’ll become a venture capitalist whose first project is to fund the development of such an app. That way I can travel the world while other people do most of the coding for me. I’ll show up for design reviews to give insightful commentary and gather information for my TED talks.

II — Recently I’ve started working on another diabetes data project. Now that I have a newer Mac, I can run MATLAB again. Yay! It occurred to me, after reading a coworker’s at-work blog about telling stories with MATLAB, that it should be possible to integrate a lot of the disparate sources of data into one application (MATLAB) and try to reconstruct a day with diabetes and try to figure out a partial model for some of the stuff that currently requires a lot of trial and error. It’s not a perfect solution, but it’s a start.

The thing that makes this all possible is the fact that so many of the devices I use every day record and export data. My cycling GPS and Garmin running watch tell when I exercise, for how long, and at what intensity. My CGM records my blood sugar patterns, while my BG meters record the ground truth. My insulin pump tracks my basal insulin usage and all of my bolus wizard details, along with a host of other details. There’s a lot of data there that I can potentially synthesize and display in one view. And, because it’s MATLAB, I can define every last little thing about how I want the information displayed, what details I want to filter out, and what I want to try to highlight or search for.

III — But even with all of this data there are missing parts of the picture. Diabetes is a difficult disease to manage, in large part, because it’s integrated with almost every other part of life. Unfortunately, daily life is messy. There’s a lot of it that just isn’t easily tracked by devices—well, not yet. I’ve toyed with the idea of getting a FitBit device to keep track of some additional things, such as overall activity and sleep, but that still leaves a lot of things untracked, especially food: food that I don’t bolus for, such as glucose tablets, food during exercise, “just in case” snacks, the things that seem too small to worry about, etc. And then there’s swimming, stress, pain, illness, hydration, weight, and so on. I wish there were a way to keep track of all of that. (At least for a few days or a couple weeks while trying to figure out appropriate baselines or when changing my training load. Paying attention to all of that data every day could be a bit overwhelming.)

So I asked one of my bildr/maker-type friends if there were good hardware or software solutions for keeping track of any of this stuff, especially the food-related bits. There are hundred (if not thousands) of nutrition apps, but all of them I’ve seen are much more heavyweight than I want. Don’t make me select something that says which food I ate in order to give me all of the nutrition info or calorie count when all I really want to record is “At 11:25AM (give or take) I ate 15 grams of carbs that I didn’t bolus for.” The best that we could come up with at the time is a small notepad and pen to record stuff before transferring it manually into whatever computerized, MATLAB-based system that holds all of the other diabetes events.

Thinking about it on a bike ride a couple days later, it seems like it should be possible to have a little nanny app that pops up a few times a day asking questions. How is everything going? What time did you wake up this morning? How much sleep did you get? Feeling stressed? Eaten anything you didn’t bolus for in the last day that we haven’t already talked about? Do any swimming or yard work? How active have you been this afternoon? Any pain? Illness? Have you been drinking water?

Just a few judgment-free yes/no questions and easy-to-answer questions involving time and quantity, and voilà! instant context. I could probably make an iOS app to do that in a weekend (if I didn’t mind it looking crappy). But really that’s all of the data that my devices don’t give me now that I want to capture. Oh, and it should have a one-touch switch that turns it off so that I’m not bothered during the 95% of the year that I don’t want to keep track of all that stuff.

IV — As an aside, wouldn’t it be awesome if someday there were a Siri-like interface for diabetes?

“Hey, Siri. Remind what I did those times that I had barbecue at the office and everything went pretty well?”

“You estimated you ate 100 grams of carbs. You delivered ten units of insulin in a dual-wave pattern with two-thirds up-front and the remaining third over an hour. Here’s what your CGM trace looked like for the next six hours.”

“Thanks, Siri. I love you.”

“Hey, let’s keep things professional. I’m not that kind of robot.”

“Sorry, girl.”

“It’s cool.”

V — But all of this “Total Diabetes Awareness” and data fusion and mindfulness/memory apps got me thinking that the ideal diabetes device system is one that wraps all of this up. It automatically keeps track of activity and food and active insulin and BG/CGM values and all of the other emotional intangibles.

But then I thought, keeping track of all that data in order to make better insulin dosing decisions is 20th century thinking. What I really want is a system that automatically regulates BG levels using two hormones, one that lowers blood glucose (via insulin) and one that raises it (via glucagon). Then the system can reach homeostasis all on its own.

Of course, an artificial pancreas that integrates everything together in a closed loop system needs believable inputs. BG meters and (especially) CGM sensors need to be much more accurate so that the system is given the right data to make the right decisions. It’s a bad thing when my CGM says I’m 40 mg/dL (2.2 mmol/L) when I’m really 140 (7.8) or, worse, vice versa. So obviously, an artificial pancreas that’s actually implanted and uses a semi-permeable membrane that lets more insulin seep out when it’s needed is the way to go.

And that’s when I realized the basic truth of diabetes technology: The ultimate diabetes device is a new pancreas.

Posted in Data-betes, Diabetes, Diabetes Blog Week, Fodder for Techno-weenies, Life Lessons | 1 Comment

Diabetes Math

After getting basal rates that I believe, I’m up to the part of my on-going “Let’s finally figure out the right pump settings!” project where I check my bolus amounts. I have long suspected that I am over-insulinized in the morning, since I frequently need a snack between 10AM and noon to prevent a hypo. Now that I know my basal rates are correct—I can plank pretty well if I don’t eat—the fiery finger of blame points at my bolus ratios.

Last week, after my awesome endocrinologist “ooh-ed and ahh-ed” over my much improved A1c, I asked her my burning question about active insulin (a.k.a., insulin on board or IOB). “When I’m bolus stacking, when do I consider active insulin and when don’t I?” I frequently eat multiple times during any given five hour period, which means that I have multiple doses of insulin working on their respective meals. I’ve noticed that sometimes I have to take that insulin into account, since its “long tail” will continue to lower my blood glucose for a bit longer. Other times, if I subtract out that IOB, I see high blood sugars later because that insulin was still needed for the previous meal/snack. What to do?

Her advice to me (and this supposes that my pump’s “active insulin” setting is correct) was to subtract out the active insulin if the bolus was three or more hours ago, since digestion should have finished by that point. This is when I’m already near my BG target and have IOB.

(Since I’m often back into the lower part of the “happy” range 2-3 hours after a bolus and/or I didn’t see much of a rise at all, this is probably another indicator that I’ve been taking in too much insulin. That and the fact that bolusing frequently comprised more than 70% of my total daily dose, which is higher than the 40-60% that most recommend. As a result I was eating a lot of “defensive” carbs to prevent lows, which seems to be leading to highs later in the day.)

I had been trying less aggressive bolus ratios over the weekend with some success, but acting on hunches and suspicions is bad form, so today I decided to be a bit more rigorous. Armed with my endo’s advice, a measuring cup, notebook, and pen, I set out to figure out what my bolus ratios need to be. Here is the data through lunch:

05:03 - 164 -       - Wake up... yawn.
05:45 -     -       - Swim 1000 yards in 20 minutes. Disconnected for 35 minutes.
06:21 - 121 - 2.9 u - Granola bar (24g) = 2.6u + 0.3u correction (using 1:9 ratio)
07:34 - 149 - 6.5 u - Cereal, milk, eggs, sausage (64g) = 7.1u (but I know this is too much)
10:18 - 104 -       - There was a bit of walking around in the previous hour
11:15 - 104 - 1.0 u - 1/2 donut from the box next to the printer (19g) = 2.3u - 1.3u IOB
12:00 - 120 - 8.3 u - Sandwich (35g), Yogurt (18g), Apple (~20g) = 75g = 8.3 (using a 1:9)

This morning looks pretty successful. Let’s try to reverse engineer a possibly correct bolus ratio. I ate 24+64=88 grams of carbohydrates for breakfast, and delivered 9.4 units of insulin. That yields, let’s see here, 1 unit for 9.4 grams, or about 1:9. But we know that’s too much from past experience (including this morning).

The 9.4 units of total insulin includes whatever insulin was needed to make up for the 35 minutes that I was disconnected from my pump while swimming and a correction of 0.3 units, which may or may not be the same. Let’s run the numbers again a few different ways.

Not taking correction into account: (24 + 64 g) / (2.9 + 6.5 units) = 9.4 g/unit

Just using the correction: (24 + 64 g) / (2.9 + 6.5 – 0.3 units) = 9.7 g/unit

Using the time off pump: (24 + 64 g) / (2.9 + 6.5 – 0.9*(35/60) units) = 9.9 g/unit — 0.9 units/hour is my basal rate at that time in the morning.

What’s the lesson here? What ratio should I use? 9.4? 9.7? 9.9? Since my pump only works in whole units for the ratio, it’s a choice between 1:9, 1:10, or carrying a calculator/MATLAB everywhere with me. (The pump version one generation after mine does allow fractional ratios.) The 1:9 ratio is clearly too aggressive given what’s been happening to me, so I’m going for 1:10, which has a certain easiness to it, too.

Let’s see what tomorrow brings.

Posted in Data-betes, Diabetes, Life Lessons | 4 Comments