<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sam Fox Royston on Medium]]></title>
        <description><![CDATA[Stories by Sam Fox Royston on Medium]]></description>
        <link>https://medium.com/@samfoxroyston?source=rss-8476bbbfdda9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-lAhM7KXNx7MfO_8uHqC2Q.jpeg</url>
            <title>Stories by Sam Fox Royston on Medium</title>
            <link>https://medium.com/@samfoxroyston?source=rss-8476bbbfdda9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 23:37:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samfoxroyston/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Perfect Insulin Dose]]></title>
            <link>https://medium.com/@samfoxroyston/the-perfect-insulin-dose-9448b2f8ea1d?source=rss-8476bbbfdda9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9448b2f8ea1d</guid>
            <category><![CDATA[healthtech]]></category>
            <category><![CDATA[health]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[type-1-diabetes]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Sam Fox Royston]]></dc:creator>
            <pubDate>Mon, 24 Apr 2023 18:17:29 GMT</pubDate>
            <atom:updated>2023-04-24T18:17:29.284Z</atom:updated>
            <content:encoded><![CDATA[<p>I started <a href="http://replica.health/">Replica Health</a> to interpret the explosion of metabolic data relevant to the treatment of type-1 diabetes and other metabolic disorders. The technical challenges in building the tools needed to search and process these metabolic data are varied and plentiful, and I’ll try to document some of them along the way. Today I will introduce some of the basics of T1D management, and deep dive into <strong><em>how to build the perfect insulin dose</em></strong>.</p><p><em>***This post describes experimental technology that is not FDA approved, and this particular dose-recommender may not make it into the first or later versions of the Replica app***</em></p><p>An egg sandwich is composed of egg, bread, cheese, as well as tater-tots and avocado if you get yours the way I do at a diner in Brooklyn. Typically, the diligent diabetic would estimate the total carbs in their sandwich via visual inspection and take a dose of fast-acting insulin on their insulin pump corresponding to the estimated grams of carbs divided by their “carb ratio”.</p><p>Carb ratio and insulin sensitivity are two metrics that tell a diabetic how much insulin to take in different situations; CR refers to the grams of carbohydrates that each unit of insulin “accounts for” while insulin sensitivity or ISF refers to the total amount your blood glucose is lowered by a single unit of insulin. These patient specific parameters are interesting in their own right and I will discuss the methods we use to infer them from data in another write-up.</p><p>In the case of the egg sandwich, the diabetic usually would make a single calculation using their carb ratio and the estimated grams to derive their dose. Let’s say Diana diabetic estimates the sandwich is 50g and their carb ratio is 14 g/IU, then she should take 3.57 units of insulin. Following this strategy if she ate a slice of cake that she estimated at 50g of carbs, she would do the exact same thing. Even to the layperson it should be obvious that egg sandwich does not equal cake. But how are they different?</p><h4>The Time Dimension for Carbs</h4><p>The sandwich and cake are different because the rate that the 50g of carbs break down into glucose and enter the blood stream is different in each case. Even if our sandwich and our cake are really both 50g of carbs, the temporal profile of their conversion into blood glucose is very different. The egg is protein, the avocado is fat and protein; both these elements delay the release of the 50g relative to the simple carbs in the cake and icing.</p><p>So, we would like a way to estimate this curve, given enough data about what happens when one eats this meal. T1D data allows us to do this in a way that is not possible with only CGM (continuous glucose monitor) data, because T1Ds often also have data about the concentration of the regulatory hormone for glucose metabolism, insulin, via their connected insulin pumps. With those two components one can infer the contribution of any exogenous sources of glucose.</p><p>Using both CGM and insulin pump data, we estimate the curve as the difference between blood glucose change modeled by insulin effect and actual blood glucose change. Pharma companies release the temporal dynamics of the insulins that they produce, otherwise known as pharmacokinetics, so we usually can find a closed form equation for <em>insulin-effect(t) </em>for each insulin brand.</p><p>Lets look at some real data from our platform. One reason Replica is special is because of how it helps you log metabolic events — we rely on geofencing and contextual data to predict when an event has likely happened — so without too much trouble I have an annotated list of every time I’ve eaten this egg sandwich in the past year. The carb release profile is estimated using data from those 26 examples. Here’s how it looks in our (upcoming) iOS app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CIT4CkD85v6b6X65TCz-Dw.png" /></figure><p>In the United States, offering dose suggestions requires a Class 2 certification from the FDA, so for now we are only releasing the automatic logging functionality and a great interface for making use of the carb release estimates (which is all you need to form an appropriate combo of doses). That said, with a carb release profile for a meal, it is possible to compute an <strong><em>optimal dose timing for that meal</em></strong>. The general recipe for doing this is fitting an insulin effect curve (in (mg/dl)/min) to the carb release curve (also converted to (mg/dl)/min). We tackled this as a sparse optimization problem, where the optimal combination of a small number of doses are selected to approximate the carb release curve. If there was no limit on the amount of doses given, i.e. they were sent directly to the pump, we would probably just cast this as a vanilla linear optimization problem, but if we are giving instructions to a human there is a benefit to limiting the number of doses recommended.</p><p>If you want to know the specifics of how we set up our optimization, keep reading, but if you want to jump ahead to some examples <a href="#e8bc">click here</a>.</p><h4>The Optimization Math</h4><p>In the compressed sensing literature, this application maps fairly neatly onto a technique called <a href="https://en.wikipedia.org/wiki/Sparse_dictionary_learning">Dictionary Learning or Sparse Coding</a>, where we assemble a “dictionary” of signals, or doses in our case, that we learn how to combine into a desired output (the expected carb release profile). For our dictionary we use an assemblage of hypothetical “unit doses” administered at different times.</p><p>Terminology:</p><p><strong>D — Dictionary : </strong>an<strong> <em>m</em></strong> by <strong><em>t</em></strong><em> </em>matrix where the rows are insulin effect curves of unit-doses (the effect curve resulting from a single unit), where <strong><em>m</em></strong> is the number of unit doses (differentiated by their start time), and <strong><em>t</em></strong><em> </em>is the time interval in minutes over which we are computing the combination of doses. Below is an example of what the dictionary could look like, where each line is a unit-dose initiated at a different time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*QecgqiEgE02Gr1WDirkvDw.png" /><figcaption>The x-axis is truncated here, but imagine these curves continuing further to the right.</figcaption></figure><p><strong><em>X — </em>dose combination : </strong>non-negative sparse<strong> </strong>solution vector of length <strong><em>m </em></strong>describing the timings (the indices of the non-zero entries) and magnitude (the entries themselves) of the optimal combination of doses.</p><p><strong><em>CRP — </em>Carb Release Profile : </strong>a vector of length <strong><em>t </em></strong>that describes our estimate of how a given event will contribute to blood glucose changes over a ~ 5hr time period after occurring. This is the data driven curve we are trying to fit to.</p><p><strong><em>λ — lambda </em>: </strong>a positive real number describing how much we care about the sparseness of our solution vector <strong><em>X </em></strong>. The higher we make <strong><em>λ, </em></strong>the fewer dose components we will have, and if it is zero we will have the typical linear optimization problem.</p><p>So the expression being optimized is the squared L2 distance between the sparse reconstruction (<strong>D<em>X</em></strong>) and the Carb Release Profile curve plus the L1-norm of the dose combination coefficients:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mpm1wAD5E9nldNNjTpsWpw.png" /></figure><p>Solving for <strong><em>X</em></strong> above, <strong><em>X </em></strong>gives the timing and amounts of bolus (impulse doses measured in units) doses for a given meal.</p><p>One of the cool things that the Replica app does is that it builds up a profile of a given meal type, like pizza for example. This carbohydrate release profile is a function that takes in a time inteval after ingestion of a meal and returns the expected change in blood glucose in the absence of insulin for that time interval. This is a unique temporal summary of a meal in terms of nutritional data because it relies on blood glucose data as well as insulin pump data. Other meal characterizations that only rely on blood glucose will have trouble separating the user-specific factors from the factors intrinsic to the meal.</p><p>So next time I eat pizza, I know the optimal dose determined from all the pizzas I’ve recorded eating:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*uqy0CPzaD8DB1vGmnW7StQ.png" /></figure><p>And from this the we provide a composition of doses that gives me this net insulin effect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*3nfPi9irOnASY4J3dWdSpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*OZbTEgufDOoXvSOzl9sMCg.png" /></figure><p>And here’s another example that operates on a shorter timescale — chocolate babka:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*IWnSAuTBUC8nCHB2PqVXFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*yNhcqxWrynvTy-yDXWouHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*b_k4eu7SEj3NbQoIm5ODcA.png" /></figure><p>Lastly, I’ll include the bagel, which holds just as bad or worse of a reputation than pizza among diabetics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*tu5FDzO-gfpNcUTF71LYKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*6CiHOlyMQJCvqGD2uWdjDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*kpDEYP6_h_6tWg1vRCYy-Q.png" /></figure><p>Bagel, Babka, and Pizza are three things that most type-1 diabetics should probably avoid, but with the perfect dose(s) at the perfect times, these meals don’t have to spell disaster for your blood sugar. In my own experience, I’ve used this dose sculpting technique to find exactly the insulin I need to keep my blood glucose flat post-pizza.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9448b2f8ea1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modeling the Spread of Covid-19]]></title>
            <link>https://medium.com/@samfoxroyston/modeling-the-spread-of-covid-19-a5b80bd9b245?source=rss-8476bbbfdda9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5b80bd9b245</guid>
            <category><![CDATA[pandemic]]></category>
            <category><![CDATA[epidemiology]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Sam Fox Royston]]></dc:creator>
            <pubDate>Sun, 15 Mar 2020 00:01:07 GMT</pubDate>
            <atom:updated>2020-03-15T00:01:07.151Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Model-based predictions about SARS-CoV-2 spread in the US</strong></p><p>In recent days, a critical mass of the public seems to have changed its viewpoint about widespread Covid-19 infections from one of possibility to inevitability. Most Americans are anxiously wondering what to expect over the next few weeks — this article is meant to provide a basis for forward looking predictions over the course of the pandemic in the US. I am NOT a trained epidemiologist but will apply epidemiological methods along with my expertise in computing and mathematical modeling to model the current spread within New York. It goes without saying that we should always defer to the epidemiologists and public health professionals. I will continue to add to this article over the next few days as new information becomes available.</p><p>We should each take seriously our own contribution to the spread of the disease — the end results for the country can vary widely based on how effectively we carry out social distancing. So far the results from Korea, Italy, and Iran are roughly in line with the second model presented here.</p><h3>Compartmental Models</h3><h4>SIR</h4><p>The <a href="https://en.wikipedia.org/wiki/Compartmental_models_in_epidemiology#The_SIR_model">SIR model </a>(<em>Susceptible, Infected, Recovered</em>), first described in 1927, is a baseline method for modeling viral spread. The idea of SIR models is to describe the evolution of the <em>susceptible, infected, and recovered </em>populations and their interactions over time. This is done via a system of differential equations <a href="#5dca">described in detail below</a>. We will refer to a few variables quite frequently, so its best to try to grasp these ahead of time:</p><p>𝛽 — The transmission rate (expected number people an infected individual will infect per time step)</p><p>𝛾 — the number of recoveries per time step, per capita. Correspondingly 1/𝛾 is the expected number of time steps (days) that a person remains infectious.</p><p>𝙍ₒ — pronounced “R-nought”, is distinct from the recovered population R (in SIR) and can be expressed as 𝙍ₒ = 𝛽 / 𝛾. 𝙍ₒ is known as the <em>epidemiological threshold</em> and defines whether the epidemic will experience exponential growth (𝙍ₒ &gt; 1), decay (𝙍ₒ &lt; 1) or remain endemic (𝙍ₒ = 1). Any disease with an 𝙍ₒ less than 1 is not worrisome because it will immediately begin to decline from its current levels.</p><h4>Basic <strong>SIR</strong> model applied to US Population (Worst Case)</h4><p>As of writing, the current confirmed cases in the US is around 1600. We will select 𝛽 so that each infected person is likely to infect 0.5 other people per day. Lets set 𝛾 =0.2 which translates to an average infection length of around 5 days; these are in line with <a href="https://www.sciencedirect.com/science/article/pii/S0140673620302609">reported values</a> and gives us an implied 𝙍ₒ of 2.5, which is within the realm of reported values. This naive model leads to dire predictions; unimpeded, the virus will spread among the majority of Americans.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*sRExJIKcpaj4U9_mj8vF_Q.png" /></figure><p>The numbers of a completely ignorant United States (populated by people unaware of the concept of viruses and contagion) are sobering. This is a reminder of how lucky we are to have the knowledge we do about viruses. In reality things will be quite different: the transmissibility rate will be directly affected by centralized government actions and mitigative steps taken by individuals. In the next model we take these factors into account to give a more realistic picture of how things might look.</p><h4>SIR model with evolving 𝛽</h4><p>Obviously our previous attempt is missing some key information; the way the public’s actions change in response to the progression of the pandemic.</p><p>We modify the SEIR (<em>Susceptable, Exposed, Infected, Recovered</em>) model described in <a href="https://www.ijidonline.com/action/showPdf?pii=S1201-9712%2820%2930117-X">this paper</a> which was used to interpret data from the original outbreak in Wuhan, China. In our model we will collapse governmental effects and individual effects into a single term, defining 𝛽 in terms of a reaction to reported deaths (a static percentage of the recovered population R). We also ignore the <em>Exposed s</em>tate for simplicity. Here we select a lower initial 𝙍ₒ of 2 and decay it exponentially according to the number deaths, assuming that individuals will take more drastic social distancing measures as more deaths are recorded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*10UtWWZoVahWZCuLkB6xXg.png" /></figure><p>One thing to remember is that if the number of cases are under-reported (we are assuming by 90% when fitting the model) then applying the 2% death rate may over-estimate deaths. I have chosen to apply 2% nonetheless since I would rather over-estimate deaths than under-estimate them; keep this in mind if the projected deaths seem like a high number — if you believe the CDC is only reporting 20% of cases for example, you should divide our model’s resulting death projection by 5. Other key takeaways from this model are when new cases are expected to peak and when total cases are expected to peak. I will not refer to the projections explicitly here since I will continue to update the figure and projections above over time.</p><p>As before, 𝙍ₒ = 𝛽/𝛾, but in this model a time-evolving 𝛽 is defined with</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*ebvsH03d2ffPAliHYY1DHQ.png" /></figure><p>where <em>k </em>is meant to capture the public and government’s (fear-based) response to deaths, and <em>R </em>is the recovered population (see below). One publication derived <em>k</em>= 1117.3 for the Spanish Flu outbreak of 1918, but it could be higher nowadays given the speed and effects of mass media and social media platforms; either way it is hard to interpret this variable and I stuck with the 1918 value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*OzWMVoXV2IjobeO3NOpHJw.png" /></figure><p>Compartmental models are very sensitive to changes in 𝛽, in this case vis-a-vis the public-motivation variable<em> k. </em>This observation is important because it captures our agency as citizens in this crisis. <em>If we avoid all unnecessary contact and take all precautions we can stop Covid-19 in it’s tracks.</em></p><h4>Mathematics of the SIR Model</h4><p>The canonical SIR model is the <a href="https://mathworld.wolfram.com/Kermack-McKendrickModel.html">Kermack-McKendrick</a> model. For our purposes it is most useful to represent it as a recurrence equation with time discretized by day. I’ll explain each term below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*mzM7kdjY1jPGYitgQUx38w.png" /></figure><p>The <strong>Susceptible Population</strong> at time step t+1 is the susceptible population at the previous time step less those who have been newly infected. The term for how many have been newly infected contains “𝛽” which is the expected number people an infected individual will infect per time step, and the I*S / N portion of the term represents all of the possible couplings of infected and susceptible people. For this reason, in this case beta should probably be on the order of j/total_population if you see one other person per day and j is the probability of transmission per interaction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*L3x6fCcayjymbvIwg5HrwQ.png" /></figure><p>The <strong>Infected Population</strong> at t+1 is the infected population at the previous time step plus the net number of new infected individuals, which is newly infected individuals (discussed above) minus the number of newly recovered individuals. Newly recovered individuals are specified with 𝛾 which is the recoveries per time step, per capita. Correspondingly 1/ 𝛾 is the expected length of infection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*UnVjCXAiyfpOXJjBoSHW-w.png" /></figure><p>The <strong>Recovered Population </strong>at t+1 is the previous recovered population plus the newly recovered individuals. Keep in mind that membership in R (recovered) makes no distinction between immunity or death. In these equations the total value (S + I + R) will always remain static.</p><p>We should prepare for continued exponential growth of reported cases in the next few weeks, and be on the lookout for a peak in the daily reported cases, which this model predicts on 3–30–2020. If new cases continue to grow exponentially past this date then we can expect progressively worse prognoses for the country.</p><p>These models are also very sensitive to the initial conditions. Therefore the model’s predictive ability is entirely based on our ability to guess these values. In this case I picked values that fit within reported results for 𝙍ₒ, while also fitting the model to the reported new cases from the CDC. An assumption I made with little concrete evidence is that only 10% of cases are being measured; given the reported difficulties setting up testing in the US as well as the fact that the majority of cases will resolve without treatment, this seemed reasonable.</p><p>Over the next weeks I will update these charts as new data become available from the CDC.</p><p>A great resource I found for exploring models like this is <a href="https://neherlab.org/covid19/">https://neherlab.org/covid19/</a> — there are many options in configuring these models and depending on the parameters they usually predicted peaking at further time scales than my models. These models are more sophisticated and worthy of consideration.</p><p>Coming soon — I’ll take a look at network science and agent based simulations for this problem…</p><h3>References</h3><p><a href="https://www.nytimes.com/interactive/2020/world/coronavirus-maps-italy-iran-korea.html?action=click&amp;module=Top%20Stories&amp;pgtype=Homepage">https://www.nytimes.com/interactive/2020/world/coronavirus-maps-italy-iran-korea.html</a></p><p><a href="https://www.ijidonline.com/article/S1201-9712(20)30117-X/fulltext#%20">https://www.ijidonline.com/article/S1201-9712(20)30117-X/fulltext#%20</a></p><ul><li><a href="https://www.sciencedirect.com/science/article/pii/S0140673620302609">Nowcasting and forecasting the potential domestic and international spread of the 2019-nCoV outbreak originating in Wuhan, China: a modelling study</a></li><li><a href="https://mathworld.wolfram.com/Kermack-McKendrickModel.html">Kermack-McKendrick Model</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5b80bd9b245" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>