<?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 davidkdryan on Medium]]></title>
        <description><![CDATA[Stories by davidkdryan on Medium]]></description>
        <link>https://medium.com/@davidkdryan?source=rss-f200e4e174b6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*6lqZGkkCvpkfaLrlhzoUjA.jpeg</url>
            <title>Stories by davidkdryan on Medium</title>
            <link>https://medium.com/@davidkdryan?source=rss-f200e4e174b6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:34:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@davidkdryan/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[Web-Scraping for Healthcare Data: How to Pull Data From the Internet?]]></title>
            <link>https://medium.com/swlh/web-scraping-for-healthcare-data-how-to-pull-data-from-the-internet-a4353697491?source=rss-f200e4e174b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4353697491</guid>
            <category><![CDATA[web-scraping]]></category>
            <category><![CDATA[biomedical-informatics]]></category>
            <category><![CDATA[health-technology]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[davidkdryan]]></dc:creator>
            <pubDate>Mon, 18 Jan 2021 13:07:01 GMT</pubDate>
            <atom:updated>2021-01-20T00:02:43.193Z</atom:updated>
            <content:encoded><![CDATA[<h4>Dr David Ryan</h4><p>Health data comes in all shapes and sizes. Web-scraping represents an efficient tool to obtain data from hard-to-reach places.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dl0F36mQqB_LNtA_dKd3ug.jpeg" /><figcaption>Image credit: <a href="https://unsplash.com/photos/iar-afB0QQw">https://unsplash.com/photos/iar-afB0QQw</a></figcaption></figure><h4><strong>Scraping the barrel for every byte of information</strong></h4><p>In today’s world, the ability to obtain large amount of clean data efficiently is a key skill.</p><p>One of the most important methods for obtaining data on a large scale is to web-scrape. This refers to the automatic extraction of targeted information from a website. It is essentially a hide-and-seek exercise. We build a programme or “bot” that searches the back end of websites and harvests this information in a format that we can manipulate into our dataset.</p><p>This has been applied in many fields. For example, we can develop a bot that pulls the stock prices for a certain date, pulls the average daily temperature or the average number of commuters on the London Underground. Web-scraping unlocks huge potential for us to add more features to our data and rapidly build up richer datasets.</p><blockquote>Simply put, web-scraping enables us to expand our datasets using search queries on the internet</blockquote><p>Applied to Medicine, there is a huge potential to expand datasets. For example, we can obtain data relating to genetic variants online or enrich datasets with medication side-effects.</p><p><strong>A non-technical introduction</strong></p><p>As an example, this notebook will demonstrate web-scraping using the python selenium package. I will demonstrate this using the following use-case:</p><p>Develop code that takes electronic prescribing data (from the US open-source National Health and Nutrition Examination Survey) and returns the drug details from the NHS website.</p><p><strong>The code: Prescribed Medication</strong></p><p>As always, we start with importing our libraries:</p><pre>#import library<br>import pandas as pd <br>import numpy as np<br>#!pip install selenium<br>from selenium import webdriver</pre><p>Next we import the data set (available at: <a href="https://www.kaggle.com/dkryan/webscraping">https://www.kaggle.com/dkryan/webscraping/)</a>. This is a list of medication prescribed for each individual in the National Health and Nutrition Examination Survey. This is a publicly-available, cross-sectional health database, studying the health and nutritional status of a representative sample of the US population.</p><pre>#import drug chart<br>df = pd.read_csv(‘drug_chart.csv’)</pre><p>Note the prescriptions are imported as a string, whereas it is easier to deal with a list of prescriptions for each individual patient.</p><pre>#prescription list formation <br>def prescription_list(row): </pre><pre>    &quot;&quot;&quot; This function returns a list of all the prescription       medication an individual is prescribed&quot;&quot;&quot;</pre><pre>    if row[&#39;Prescriptions&#39;] is np.nan: <br>        return(np.nan)<br>    else: <br>        drugs = row[&#39;Prescriptions&#39;].split(&quot;, &quot;)<br>        <br>        drugs_list = []<br>        <br>        for i in drugs: <br>                drugs_list.append(i)      <br>           <br>        return(drugs_list)        <br>    <br>df[&#39;prescription_list&#39;] = df.apply(prescription_list, axis=1)</pre><pre>#display<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bdgo-XrDX52mmpbT89Q_Vw.png" /><figcaption>National Health and Nutritional Examination Survey prescribed medication lists</figcaption></figure><p>Selenium is a web-scraping library in python that works by setting up an automated google chrome page. We can then programatically control this to do our searching for us. We instantiate this using the function:</p><pre>driver = webdriver.Chrome(&quot;/usr/local/bin/chromedriver&quot;)</pre><p>We can then get driver to search a specific page. Here it is searching the NHS page on metformin (a common anti-diabetic medication).</p><pre>driver.get(&quot;https://www.nhs.uk/medicines/metformin/&quot;)</pre><p>If you now go to the chrome page that was opened by selenium, you can see that it has opened up the metformin page. Select the information on the page that you want to extract, right click and copy export path. This copies the link to the relevant HTML code, meaning that you can then access that specific part of the website. This is the scraping in web-scraping.</p><p>For example, I want to return all the drug information from the NHS website for metformin. This information is found under the pathway:</p><pre>&quot;&quot;&quot;//*[<a href="http://twitter.com/id">@id</a>=”about-metformin”]/div&quot;&quot;&quot;</pre><p>Therefore, we can return this using:</p><pre>#scrape <br>metformin = driver.find_element_by_xpath(&quot;&quot;&quot;//*[<a href="http://twitter.com/id">@id</a>=&quot;about-metformin&quot;]/div&quot;&quot;&quot;)<br>metformin.text</pre><pre>&quot;Metformin is a medicine used to treat type 2 diabetes, and to help prevent type 2 diabetes if you&#39;re at high risk of developing it.\nMetformin is used when treating polycystic ovary syndrome (PCOS), although it&#39;s not officially approved for PCOS.\nType 2 diabetes is an illness where the body does not make enough insulin, or the insulin that it makes does not work properly. This can cause high blood sugar levels (hyperglycaemia).\nPCOS is a condition that affects how the ovaries work.\nMetformin lowers your blood sugar levels by improving the way your body handles insulin.\nIt&#39;s usually prescribed for diabetes when diet and exercise alone have not been enough to control your blood sugar levels.\nFor women with PCOS, metformin lowers insulin and blood sugar levels, and can also stimulate ovulation.\nMetformin is available on prescription as tablets and as a liquid that you drink.&quot;</pre><p>We can then use regex and other manipulations (e.g replace functions) to tidy up the returned text.</p><pre>metformin.text.replace(&quot;\n&quot;, &quot; &quot;)</pre><p>Now we can use this understanding to pull multiple sections from the NHS website. This nhs_details function returns the drug details for all the prescribed medication in the dataset.</p><p>It is important to note that Selenium makes the assumption that all page structures are the same. Therefore, the find_element_by_xpath can throw a glitch if the website HTML make-up changes. To address this, I have several different options for finding the drug information using several try and except clauses. This was discovered through trial and error and learning the basic structure of the HTML behind the NHS website.</p><pre>def nhs_details(drug): <br>    <br>    drug = drug.lower()<br>    try: <br>        driver.get(f&quot;<a href="https://www.nhs.uk/medicines/%7Bdrug%7D/">https://www.nhs.uk/medicines/{drug}/</a>&quot;)<br>        section_1 = driver.find_element_by_xpath(f&quot;&quot;&quot;//*[<a href="http://twitter.com/id">@id</a>=&quot;about-{drug}&quot;]/div&quot;&quot;&quot;)<br>        section_1_text = section_1.text.replace(&quot;\n&quot;, &quot; &quot;)<br>        section_2 = driver.find_element_by_xpath(&quot;&quot;&quot;//*[<a href="http://twitter.com/id">@id</a>=&quot;key-facts&quot;]/div&quot;&quot;&quot;)<br>        section_2_text = section_2.text.replace(&quot;\n&quot;, &quot; &quot;)<br>        try: <br>            section_3 = driver.find_element_by_xpath(f&quot;&quot;&quot;//*[<a href="http://twitter.com/id">@id</a>=&quot;who-can-and-cannot-take-{drug}&quot;]/div&quot;&quot;&quot;)<br>            section_3_text = section_3.text.replace(&quot;\n&quot;, &quot; &quot;)<br>        except: <br>            section_3 = driver.find_element_by_xpath(f&quot;&quot;&quot;//*[<a href="http://twitter.com/id">@id</a>=&quot;who-can-and-cant-take-{drug}&quot;]/div&quot;&quot;&quot;)<br>            section_3_text = section_3.text.replace(&quot;\n&quot;, &quot; &quot;)<br>   <br>        return(section_1_text, section_2_text, section_3_text)<br>        <br>    except: <br>        driver.get(f&quot;<a href="https://www.nhs.uk/medicines/%7Bdrug%7D-for-adults/">https://www.nhs.uk/medicines/{drug}-for-adults/</a>&quot;)<br>        section_1 = driver.find_element_by_xpath(f&quot;&quot;&quot;//*[<a href="http://twitter.com/id">@id</a>=&quot;about-{drug}-for-adults&quot;]/div&quot;&quot;&quot;)<br>        section_1_text = section_1.text.replace(&quot;\n&quot;, &quot; &quot;)<br>        section_2 = driver.find_element_by_xpath(&quot;&quot;&quot;//*[<a href="http://twitter.com/id">@id</a>=&quot;key-facts&quot;]/div&quot;&quot;&quot;)<br>        section_2_text = section_2.text.replace(&quot;\n&quot;, &quot; &quot;)<br>        section_3 = driver.find_element_by_xpath(f&quot;&quot;&quot;//*[<a href="http://twitter.com/id">@id</a>=&quot;who-can-and-cannot-take-{drug}&quot;]/div&quot;&quot;&quot;)<br>        section_3_text = section_3.text.replace(&quot;\n&quot;, &quot; &quot;)<br>   <br>    <br>        return(section_1_text, section_2_text, section_3_text)</pre><p>Some key parts of this code:</p><ul><li>.lower() standardises the input the the webdriver</li><li>f-strings enable us to insert any drug we want into the URL</li><li>The find_element_by_xpath method returns the data of interest from the html as a json object.</li><li>This is then converted to text and cleaned to remove escape characters</li></ul><pre>nhs_details(&#39;SITAGLIPTIN&#39;)</pre><pre>(&#39;Sitagliptin is a medicine used to treat type 2 diabetes. Type 2 diabetes is an illness where the body does not make enough insulin, or the insulin that it makes does not work properly. This can cause high blood sugar levels (hyperglycaemia). Sitagliptin is prescribed for people who still have high blood sugar, even though they have a sensible diet and exercise regularly. Sitagliptin is only available on prescription. It comes as tablets that you swallow. It also comes as tablets containing a mixture of sitagliptin and metformin. Metformin is another drug used to treat diabetes.&#39;,<br> &quot;Sitagliptin works by increasing the amount of insulin that your body makes. Insulin is the hormone that controls sugar levels in your blood. You take sitagliptin once a day. The most common side effect of sitagliptin is headaches. This medicine does not usually make you put on weight. Sitagliptin is also called by the brand name Januvia. When combined with metformin it&#39;s called Janumet.&quot;,<br> &quot;Sitagliptin can be taken by adults (aged 18 years and older). Sitagliptin is not suitable for some people. To make sure it&#39;s safe for you, tell your doctor if you: have had an allergic reaction to sitagliptin or any other medicines in the past have problems with your pancreas have gallstones or very high levels of triglycerides (a type of fat) in your blood are a heavy drinker or dependent on alcohol have (or have previously had) any problems with your kidneys are pregnant or breastfeeding, or trying to get pregnant This medicine is not used to treat type 1 diabetes (when your body does not produce insulin).&quot;)</pre><p>Now let’s build a function that returns the NHS website advice for all the drugs a patient is prescribed in the annonymised NHANES extract.</p><pre>#build a function that returns information for all medication prescribed <br>def drug_information(patient_number): <br>    &quot;&quot;&quot;webscrapes NHS website and returns drug information&quot;&quot;&quot;</pre><pre>drugs = df.loc[patient_number][&#39;prescription_list&#39;]<br>    print(drugs)<br>        <br>    for drug in drugs: <br>            print(&#39;\nPrescription medication:&#39;, drug)<br>            print(&#39;\nAccessing NHS drug information&#39;)<br>            <br>            try: <br>                print(nhs_details(drug))<br>                <br>            except: <br>                print(&#39;No NHS details available&#39;)</pre><pre>drug_information(0)</pre><pre>[&#39;AMLODIPINE&#39;, &#39;LOSARTAN&#39;, &#39;SIMVASTATIN&#39;]<br><br>Prescription medication: AMLODIPINE<br><br>Accessing NHS drug information<br>(&#39;Amlodipine is a medicine used to treat high blood pressure (hypertension). If you have high blood pressure, taking amlodipine helps prevent future heart disease, heart attacks and strokes. Amlodipine is also used to prevent chest pain caused by heart disease (angina). This medicine is only available on prescription. It comes as tablets or as a liquid to swallow.&#39;, &quot;Amlodipine lowers your blood pressure and makes it easier for your heart to pump blood around your body. It&#39;s usual to take amlodipine once a day. You can take it at any time of day, but try to make sure it&#39;s around the same time each day. The most common side effects include headache, flushing, feeling tired and swollen ankles. These usually improve after a few days. Amlodipine can be called amlodipine besilate, amlodipine maleate or amlodipine mesilate. This is because the medicine contains another chemical to make it easier for your body to take up and use it. It doesn&#39;t matter what your amlodipine is called. They all work as well as each other. Amlodipine is also called by the brand names Istin and Amlostin.&quot;, &quot;Amlodipine can be taken by adults and children aged 6 years and over. Amlodipine is not suitable for some people. To make sure amlodipine is safe for you, tell your doctor if you: have had an allergic reaction to amlodipine or any other medicines in the past are trying to get pregnant, are already pregnant or you&#39;re breastfeeding have liver or kidney disease have heart failure or you have recently had a heart attack&quot;)<br><br>Prescription medication: LOSARTAN<br><br>Accessing NHS drug information<br>(&quot;Losartan is a medicine widely used to treat high blood pressure and heart failure, and to protect your kidneys if you have both kidney disease and diabetes. Losartan helps to prevent future strokes, heart attacks and kidney problems. It also improves your survival if you&#39;re taking it for heart failure or after a heart attack. This medicine is only available on prescription. It comes as tablets.&quot;, &quot;Losartan lowers your blood pressure and makes it easier for your heart to pump blood around your body. It&#39;s often used as a second-choice treatment if you had to stop taking another blood pressure-lowering medicine because it gave you a dry, irritating cough. If you have diarrhoea and vomiting from a stomach bug or illness while taking losartan, tell your doctor. You may need to stop taking it until you feel better. The main side effects of losartan are dizziness and fatigue, but they&#39;re usually mild and shortlived. Losartan is not normally recommended in pregnancy or while breastfeeding. Talk to your doctor if you&#39;re trying to get pregnant, you&#39;re already pregnant or you&#39;re breastfeeding. Losartan is also called by the brand name Cozaar.&quot;, &quot;Losartan can be taken by adults aged 18 years and over. Children aged 6 years and older can take it, but only to treat high blood pressure. Your doctor may prescribe losartan if you&#39;ve tried taking similar blood pressure-lowering medicines such as ramipril and lisinopril in the past, but had to stop taking them because of side effects such as a dry, irritating cough. Losartan isn&#39;t suitable for some people. To make sure losartan is safe for you, tell your doctor if you: have had an allergic reaction to losartan or other medicines in the past have diabetes have heart, liver or kidney problems recently had a kidney transplant have had diarrhoea or vomiting have been on a low salt diet have low blood pressure are trying to get pregnant, are already pregnant or you are breastfeeding&quot;)<br><br>Prescription medication: SIMVASTATIN<br><br>Accessing NHS drug information<br>(&quot;Simvastatin belongs to a group of medicines called statins. It&#39;s used to lower cholesterol if you&#39;ve been diagnosed with high blood cholesterol. It&#39;s also taken to prevent heart disease, including heart attacks and strokes. Your doctor may prescribe simvastatin if you have a family history of heart disease, or a long-term health condition such as rheumatoid arthritis, or type 1 or type 2 diabetes. The medicine is available on prescription as tablets. You can also buy a low-strength 10mg tablet from a pharmacy.&quot;, &quot;Simvastatin seems to be a very safe medicine. It&#39;s unusual to have any side effects. Keep taking simvastatin even if you feel well, as you will still be getting the benefits. Most people with high cholesterol don&#39;t have any symptoms. Do not take simvastatin if you&#39;re pregnant, trying to get pregnant or breastfeeding. Do not drink grapefruit juice while you&#39;re taking simvastatin. It doesn&#39;t mix well with this medicine. Simvastatin is also called Zocor and Simvador.&quot;, &quot;Simvastatin can be taken by adults and children over the age of 10 years. Simvastatin isn&#39;t suitable for some people. Tell your doctor if you: have had an allergic reaction to simvastatin or any other medicines in the past have liver or kidney problems are trying to get pregnant, think you might be pregnant, you&#39;re already pregnant, or you&#39;re breastfeeding have severe lung disease regularly drink large amounts of alcohol have an underactive thyroid have, or have had, a muscle disorder (including fibromyalgia)&quot;)</pre><p>So that’s all folks! This post described how to build a basic web-scraping tool to download drug data from the NHS website. I’ve used this template in other situations as well, including finding the chromosome location for 49K genetic variants (single nucleotide polymorphisms). Web-scraping is a pretty nice tool to have available when data is tricky to obtain in clean and user-friendly formats.</p><p>Read the docs on selenium: <a href="https://selenium-python.readthedocs.io/">https://selenium-python.readthedocs.io/</a></p><p>Kaggle data: <a href="https://www.kaggle.com/dkryan/webscraping">https://www.kaggle.com/dkryan/webscraping</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4353697491" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/web-scraping-for-healthcare-data-how-to-pull-data-from-the-internet-a4353697491">Web-Scraping for Healthcare Data: How to Pull Data From the Internet?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All is fair in Medicine and Technology: How to avoid interventional generated inequality in health…]]></title>
            <link>https://davidkdryan.medium.com/all-is-fair-in-medicine-and-technology-how-to-avoid-interventional-generated-inequality-in-health-67bd7b8fe7a0?source=rss-f200e4e174b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/67bd7b8fe7a0</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[health]]></category>
            <category><![CDATA[medtech]]></category>
            <category><![CDATA[inequality]]></category>
            <category><![CDATA[biomedical-informatics]]></category>
            <dc:creator><![CDATA[davidkdryan]]></dc:creator>
            <pubDate>Fri, 02 Oct 2020 01:16:25 GMT</pubDate>
            <atom:updated>2020-10-02T21:49:11.814Z</atom:updated>
            <content:encoded><![CDATA[<h3>All is fair in Medicine and Technology: interventional generated inequality in health technology</h3><h4>Dr David Ryan</h4><p>It is a truth universally acknowledged that technology is rapidly altering, augmenting and ameliorating many aspects of our lives and the field of medicine is no exception. Moore’s law is a testament to the speed of technological advancement, stating that computer processing power doubles every two years. Despite the growing pace of the technological revolution and increasing use of IT in healthcare settings, consideration of wider societal and ethical implications are still lagging.</p><h4>Interventional generated inequality</h4><p>One area of particular concern is the prospect that new technologies in healthcare can shift the scales of equality and further exacerbate existing inequalities. This concept is termed interventional generated inequality and refers to the process where interventions, such as the development of phone applications for better self-management of chronic disease or novel sensors for diabetes, disproportionately benefit people who are already engaged with their health. These patients tend to have higher health literacy and come from higher socio-economic groups with greater means to access and adopt to technology earlier. As a result, the developments of healthcare technologies may not even permeate to the people who need it most.</p><h4>Unequal societies create unequal technology</h4><p>Interventional generated inequality can also stem from the training of models on data originating from a deeply unequal world. Large cohorts and databases can oftentimes be victims of self-selection, where people who opt into such research studies are white, educated and engaged patients. For example, the UK Biobank, a major contributor to global knowledge on the influence of genetic and environmental factors on disease, contains data on 500,000 people. This cohort is largely white (95%) and less deprived than the average UK population. The knowledge we gain from such databases and the models we train on this data are based on biased foundations, skewing our knowledge discovery and generalisability of our models. And this tends to be a phenomenon that is seen in many databases around the world.</p><p>There have been several striking examples of racial and gender discrimination in technology when applied to other areas of life. Last year, Apple developed an algorithm to determine credit limits that systematically discriminated against women. For some couples, the male partner received a credit rating twenty times higher than the female partner, despite all other factors (including credit rating) being equal! Despite the fact that gender was not a directly included as a feature in this model, it is possible that a confounding factor in the training data set could have led to a biased model. Perhaps, men were more likely to take out more low-risk, low-value loans more frequently compared to women, who may make more high-value and higher-risk loans (such as mortgages). Gender would then become an indirect proxy for loan risk.</p><p>More recently, we witnessed the A-level grading algorithm disproportionately downgrading pupils from disadvantaged backgrounds. And while we should be rightly angry about this unjust model and the impact this had on teenagers educational opportunities, our anger needs to be directed firstly at the world that created such data. Perhaps there is a role for interrogating this black box model to see where exactly disadvantaged students were downgraded. In this way, we could use the model to better understand and target investment in education and try to right the wrongs of our unequal world.</p><p>If we are not careful, considerate and cautious in our development of health technology, it won’t be long until we have a high-profile case of biased medical models doing harm to our patients.</p><h4>Mind the intervention generated gap</h4><p>To promote inclusive access to healthcare technology, innovators should conduct an equality impact assessment as part of any research or development proposal. It is vital that datasets are assessed for diversity. For example, in medical imaging, this will include having representative images from people of all skin colours. In large databases, this may involve over-recruiting and targeting of difficult-to-reach segments of the population (as was done in the National Health and Nutrition Examination Study in the US). Ideally, I would like to see an equality assessment being made compulsory as part of reporting guidelines for health technology research papers.</p><p>Patient and public involvement have a key role to play in equality assessments and it is imperative that researchers communicate, and if possible, collaborate with patients to understand and reduce barriers to adoption of technology. Medical innovation should not be developed in an isolated black box, rather, the development of medical technology needs to be democratised and made more open to the public. This would improve the technology we develop, empower a wider audience to engage with advancements in medicine and minimise any potential for technology to widen the equality gap.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67bd7b8fe7a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Quantify Social Distancing? Mining Google Maps Location History]]></title>
            <link>https://davidkdryan.medium.com/how-to-quantify-social-distancing-mining-google-maps-location-history-8673e8094e24?source=rss-f200e4e174b6------2</link>
            <guid isPermaLink="false">https://medium.com/p/8673e8094e24</guid>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[social-distance]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[davidkdryan]]></dc:creator>
            <pubDate>Sun, 10 May 2020 17:26:14 GMT</pubDate>
            <atom:updated>2020-05-10T17:26:14.999Z</atom:updated>
            <content:encoded><![CDATA[<p>As a Junior Doctor working in a busy London Hospital, I am very grateful to everybody who is staying home and minding each other.</p><p>Flattening the curve and social distancing have become the new buzz words and they have very much helped reduce the stress on our hospitals and have saved many lives.</p><p>Google have published COVID-19 mobility reports that quantify, on a macro level, just how much our world has changed. For example, it showed that Londoners were transiting through transport hubs 64% less than pre-covid times and were at workplaces 48% less than pre-lockdown days.</p><p>However, this does not capture the unprecedented change and sacrifice that individuals have made in their everyday lives. As a project (and/or distraction and/or way to relax after a day on the wards) to develop my coding skills, I used Google maps location history to quantify how much my own mobility patterns have changed.</p><p>Move over banana bread and Tiger King! This might also be a nice quarantine project for people to geek out on. It provides a purposeful way to learn python and see how much we are contributing to social distancing and flattening curves through changes we are making in our own lives.</p><h3><strong>The data source</strong></h3><p>Google records a phone’s location (longitude and latitude) approximately once every minute, linking these to known locations (semantic location data) and predictions for methods of transport . It is incredible how much data Google can have on an individual if the location history setting is turned on. I had mine turned on for my first few years at University and I can now put together my entire life from first-year at medical school like a jigsaw.</p><p>It is obvious to see why companies such as Google, Facebook and Apple have the potential to play pivotal roles in contact tracing with such granular data on most people in our society.</p><blockquote>Big brother is watching you (and has been for a while). But is it now time for big brother to grow up and start to look out for us? Isn’t this what a big brother does?</blockquote><p>In fact, covid-19 is rapidly pushing forward pubic debates about the involvement of tech and AI in medicine. This can only be a good thing.</p><p>For people who are concerned about companies collecting such data, you can review, adjust or turn off location records here: <a href="https://support.google.com/accounts/answer/3467281?hl=en">https://support.google.com/accounts/answer/3467281?hl=en</a></p><p>Your personal data is available for download at Google Takeout: <a href="https://takeout.google.com/settings/takeout">https://takeout.google.com/settings/takeout</a></p><p>I did not have any contemporary data available for myself so I used my previously collected data from 2013. I chose a date from exam-season as surrogate for the covid-19 data and used a post-exam season day as a proxy for pre-covid data. Studying for med school exams was as good a practice at social distancing and quarantine as you’ll get! I’m hoping this will simulate some social distancing and isolation behaviours in my data.</p><p>The data presented here is just for example and is a way of showing how we can code our way around Google location data. I have also transformed my data to be located in Paris as a way of making my movement history anonymous. Que la vie est belle!</p><h3><strong>The problem space</strong></h3><p>There are many different ways to approach quantifying and describing our mobility. My approach to this problem space was to consider heatmaps, time spent at home, maximum distance from home and the area enclosed by the points on the map as a metric of social mobility. This is an approximation as human interaction depends on much more than geographical location, but also population density and how bustling a particular place is.</p><h3><strong>The code</strong></h3><p>Full kaggle notebook and dataset is available here: <br><a href="https://www.kaggle.com/dkryan/social-distancing-with-google-maps-data">https://www.kaggle.com/dkryan/social-distancing-with-google-maps-data</a></p><p>I coded using python, converting the json file into a pandas dataframe and then using the gmaps library to create maps. Distances between geo-locations was calculated using the haversine formula for two points on a sphere.</p><h3><strong>The results:</strong></h3><h4>Home sweet home</h4><blockquote>Home is where the heart is. But in this instance, home is the modal geo-location between the hours of 3am and 8am.</blockquote><p>I build a function that returns the modal value for geo-locations overnight and then built an exclusion zone of 0.5km around this geo-location to represent home. This is to encompass small variations in geo-locations (Google’s longitude and latitude data has 7 decimal points!) associated with moving within a house or garden.</p><pre>def sleep_location(df):<br>    <br>    <em>&quot;&quot;&quot;This finds the most common location between the hours of <br>    3am and 8am. If this has no value, most common location for     <br>    the day is chosen&quot;&quot;&quot;</em><br>    <br>    date = str((df.iloc[0][&#39;Datetime&#39;]).date())<br>    night_start = date + &#39; 03:00:00&#39;<br>    night_end = date  + &#39; 08:00:00&#39;<br>    datetime.datetime.strptime(night_start, &#39;%Y-%m-<strong>%d</strong> %H:%M:%S&#39;) <br>    datetime.datetime.strptime(night_end, &#39;%Y-%m-<strong>%d</strong> %H:%M:%S&#39;) <br>    <br>    sleeping_df = df[(df[&#39;Datetime&#39;] &gt; night_start) &amp; (df[&#39;Datetime&#39;] &lt; night_end)]<br>    <br>    sleeping_geo_tuple = sleeping_df[&#39;geo_tuple&#39;].mode()<br>    most_common_geo_tuple = df[&#39;geo_tuple&#39;].mode()<br>    <br>    if <strong>not</strong> any(sleeping_geo_tuple):<br>        sleeping_geo_tuple = most_common_geo_tuple<br><br>        <br>    else: <br>        sleeping_geo_tuple = sleeping_geo_tuple <br>        <br><br>    return(sleeping_geo_tuple)</pre><p>I then used the following function to build the exclusion zone:</p><pre>def exclusion_zone(row, radius, lat, long): <br>    <em>&quot;&quot;&quot;returns home if within radius of lat and long</em><br><em>       returns away if outside given radius of lat and long. </em><br><em>       employs haversine formula&quot;&quot;&quot;</em><br>    <br>    radius = radius <br>    sleeping_geo_location = (lat, long)<br>    lat1 = sleeping_geo_location[0]<br>    lon1 = sleeping_geo_location[1]<br>    lat2 = row[&#39;Lat&#39;]<br>    lon2 = row[&#39;Long&#39;]<br>    <br>    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])<br>    <br>    <em># haversine formula </em><br>    dlon = lon2 - lon1 <br>    dlat = lat2 - lat1 <br>    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2<br>    c = 2 * asin(sqrt(a)) <br>    r = 6371 <em># Radius of earth in kilometers. Use 3956 for miles</em><br>    a = c*r<br><br>    if a &lt;= radius:<br>        return(&#39;Home&#39;)<br>    else:<br>        return(&#39;Away&#39;)</pre><p>To calculate time in one location, I used a for-loop that would have a running clock for whenever I was at a home location. This adds time in a cumulative fashion, adding time to a running total if the following ping is from the same location. If the ping has moved geo-location, the time is not added. This method is robust as it allows for multiple excursions to and from the house or location of interest.</p><pre><em>#set time at zero </em><br>time_at_home = datetime.timedelta(seconds=0)<br><br><em>#for loop to iterate through the dataframe </em><br>for i <strong>in</strong> range(0, pre_covid.shape[0]): <br>    <br>    row = i <br>    next_row = i + 1 <br>    <br>    <em>#if I am at the last row - skip </em><br>    if row == (pre_covid.shape[0]-1): <br>        pass <br>    <br>    else:<br>        <br>        <em>#if I am at home </em><br>        if &#39;Home&#39; <strong>in</strong> pre_covid.iloc[row][&#39;Home_Away&#39;]: <br>        <br>            <em>#and my next row says that I am still at home by the next ping </em><br>            if &#39;Home&#39; <strong>in</strong> pre_covid.iloc[next_row][&#39;Home_Away&#39;]: <br>                <br>                <em>#find the difference in times </em><br>                duration = pre_covid.iloc[next_row][&#39;Datetime&#39;] - pre_covid.iloc[row][&#39;Datetime&#39;]<br>                <br>                <em>#add this time to the time_at_home timer</em><br>                time_at_home += duration<br>            <br>            else: <br>                pass</pre><p>This method showed that using my simulated data, I spent approximately 3 hours and 20 minutes extra at home coming up to exams.</p><h4>Distance from home</h4><p>In terms of distance-from-home, my maximum distance from home was greater after exams compared to before exams. As expected, my maximum distance after exams finished was 2.2km compared to 1.4km when I was studying. It is no coincidence that the University library was also located 1.4km from my flat.</p><pre>def distance_from_home(row, lat, long): <br>    <em>&quot;&quot;&quot;returns distance from home in km&quot;&quot;&quot;</em><br><br>    sleeping_geo_location = (lat, long)<br>    lat1 = sleeping_geo_location[0]<br>    lon1 = sleeping_geo_location[1]<br>    lat2 = row[&#39;Lat&#39;]<br>    lon2 = row[&#39;Long&#39;]<br>    <br>    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])<br>    <br>    <em># haversine formula </em><br>    dlon = lon2 - lon1 <br>    dlat = lat2 - lat1 <br>    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2<br>    c = 2 * asin(sqrt(a)) <br>    r = 6371 <em># Radius of earth in kilometers. Use 3956 for miles</em><br>    a = c*r<br><br>    return(a)</pre><p>Plotting distances from home, we can see in finer detail mobility patterns. For example, this graph shows I was out-and-about in town during the early hours of the pre-covid day and that I was going further from home during pre-covid times.</p><p>Vertical lines on this graph represent time when I was in one place for a prolonged period of time. The orange dots (post-covid day) have much more vertical lines in the middle of the day suggesting that I was remaining in one place for longer compared to pre-covid times. The blue dots (pre-covid times) have a more horizontal orientation — suggesting that I was wondering around town at varying distances from home throughout the day.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*r-JzJ_ChhwT8SN5rKYkRZA.png" /><figcaption>Scatter plot showing the distance from home (km) at various times in the day for pre-covid and post-covid times.</figcaption></figure><h4>Visualising my movements using heatmaps</h4><p>Heatmaps for these 2 days show that I remained close to my flat before exams whereas after exams, I spent less time in my flat as my hotspot was located within another area of the city.</p><pre><em>#pre_covid</em><br>gmaps.configure(api_key=&#39;api&#39;) <em>#insert own api here </em><br>    <br>start_coordinates = (48.84954515968211, 2.3391025994419903) <em>#start co-ordinates are for where the map should be centred</em><br><br>fig = gmaps.figure(center=start_coordinates, zoom_level=14)<br>    <br><em># Adding a marker layer for home co-ordinates </em><br>home = [(48.84954515968211, 2.3391025994419903)]<br>marker_layer = gmaps.marker_layer(home)<br>fig.add_layer(marker_layer)<br><br><br><em># Adding a heatmap layer to the map</em><br>heatmap_layer = gmaps.heatmap_layer(pre_covid[[&#39;Lat&#39;, &#39;Long&#39;]], point_radius=10, dissipating=False)<br>fig.add_layer(heatmap_layer)<br><br>fig</pre><p>Here we can see the heatmap for before exams…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zbeDs6bK6uj7lyTc8sH-Dw.png" /><figcaption>Before exams …. concentrated, hotspot around my flat. I was a study hermit! Red pin indicates where I lived at the time in transposed co-ordinates. Quel dommage, I have sadly not lived in Paris.</figcaption></figure><p>And after exams, the hot spot has moved away from my flat …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j_NTDukYTJepKyix8-XG7A.png" /><figcaption>Here we can see the heatmap for after exams. Note that the hotspot has gone away from the home pin.</figcaption></figure><p>These heatmaps depict how movements can change given different circumstances. It is likely that an even more striking pattern would be seen for covid-19 changes in mobility.</p><h4>Area enclosed by co-ordinates</h4><p>The area enclosed by the co-ordinates also reduced slightly for the pre-exam (i.e. covid-19 simulated day). This was measured using the Shoelace equation for measuring the area within a polygon. However, the issue with this metric is that it is without tangible units. It showed that the area reduced from 2.3972774215508252e-05 to 7.80074333306402e-06!</p><pre>#area of a polygon using shoelace formula </pre><pre>def PolyArea(df):<br>    <br>    x=df[&#39;Long&#39;]<br>    y=df[&#39;Lat&#39;]<br>    return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))</pre><h4>Other frequented locations</h4><p>We can also investigate other locations that we frequent throughout the day. This might be useful for showing up other locations where we spent time such as workplaces or coffee shops. To do this, I did a simple value count for all the geo-locations outside of the home region. This showed that for the covid-simulation day, I had 154 pings from another single location outside of my flat (yes, you guessed it right, it was the library!). For the pre-covid simulation day, the maximum pings from one location outside of my flat was 43. This again reflects my increased mobility on these days. I was spending less time in more frequent places.</p><p>Using the cumulative method to count the time spent within a 0.2km radius of the library, I could calculate that I spent 2 hours and 30 minutes within the library complex on a revision day (slack, I know!). However, the difference between my first and last ping within the library complex was 3 hours and 20 minutes. This suggests that there is 50 minutes when I was wandering around the library talking to friends, gettting coffee or generally not sitting at my desk. Google is unveiling that I wasted 25% of my time not at my desk in the library!</p><p>This finding also shows the benefit of doing a cumulative count approach to time-in-a-single-location. It allows for excursions from a location. The greater the cumulative time in one location suggests the better the social distancing and isolation — particularly if one is at home. However, a metric of social bustle would be needed to validate such an approach if we were to use this for pure assessment of our social distancing.</p><h3><strong>Key Insights and Take Home Messages</strong></h3><ul><li>It is very easy to start accessing and using our own personal data to gain insights into our lives. Some of these insights can be banal but it is undeniably eye-opening (if not a little scary) to see the inferences these companies can make about our lives with some old school coding. These insights can range from the sublime (such as time spent at home in a pandemic) to the ridiculous (the percentage of time I spent procrastinating at the library coming up to my first year exams).</li><li>Possible metrics to explore mobility include mean and maximum distance from home, cumulative time within a home zone, area enclosed by co-ordinates or heatmaps. Social distancing is not simply about location but is also highly influenced by population density, traffic volumes and social busyness. Including such data would be critical before making a richer assessment of changes in mobility pattern. Furthermore, google has semantic location data available and incorporating this into data analysis could aid quantification and grading of social distancing.</li><li>Between these two simulation days (pre-exam and post-exam), there is a modest reduction in my mobility for the days in question. I would assume that my movements have become even more limited as a result of social distancing and quarantine advice.</li><li>Google aims to send a ping from phones every minute. However, this data suggests that there can be times with limited coverage of geo-locations. This could be due to poor-signal, low battery or use of other applications. This is more likely to occur when we are out-and-about. This missing data would need to be addressed and accounted for, particularly as it is most prominent during times when the user is out in public. Missing data could be a major issue in a system that is trying to identify people who may be at risk of contracting covid-19 based on being in a similar location to a person who is infected with the virus!</li><li>This project looks at mobility patterns for 2 days. It would be interesting to plot these patterns over several different days to see what trends happen over time.</li></ul><p>Full dataset and data is available here:</p><p><a href="https://www.kaggle.com/dkryan/social-distancing-with-google-maps-data">https://www.kaggle.com/dkryan/social-distancing-with-google-maps-data</a></p><p>Would appreciate any thoughts, ideas or suggestions on this!</p><p>Stay safe. Stay at home.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8673e8094e24" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>