Skip to content

Instantly share code, notes, and snippets.

@oneryalcin
Created April 2, 2020 00:47
Show Gist options
  • Save oneryalcin/688133f0961d93c1e5e9cef9365b2b72 to your computer and use it in GitHub Desktop.
Save oneryalcin/688133f0961d93c1e5e9cef9365b2b72 to your computer and use it in GitHub Desktop.
Covid testing
import random
from collections import Counter
class Person:
def __init__(self, issick):
self.issick = issick
def __repr__(self):
if self.issick:
return f'Sick'
return f'Healthy'
class Population:
"""
Define a population with sickness prevalence
"""
def __init__(self, prevalence, size):
self.prevalence = prevalence
self.size = size
def __repr__(self):
return f'Average # Covid19 patients per million is {1000000 * self.prevalence}'
def generate(self):
"""
Population (of size) of `Person`s some with sickness (prevalence)
"""
for _ in range(self.size):
if self.prevalence > random.random():
yield Person(issick=True)
else:
yield Person(issick=False)
class CovidTest:
def __init__(self, true_positive=0.99, true_negative=0.99):
self.true_positive = true_positive
self.true_negative = true_negative
def test_person(self, person):
"""
Test a single person against Covid19
"""
if person.issick:
if random.random() < self.true_positive:
return "True Positive"
return "False Negative"
else:
if random.random() < self.true_negative:
return "True Negative"
return "False Positive"
def test_population(self, population):
"""
Test a population of people (Population object) against Covid19
"""
test_results = []
for person in population.generate():
result = self.test_person(person)
test_results.append(result)
return Counter(test_results)
@staticmethod
def likelihood(ispositive, population_test):
"""
If you are tested positive, what is the probability that you are actually sick.
or vice versa
Args:
ispositive (bool): True if your test result is positive
population_test (collections.Counter): Population test results
"""
TN = population_test['True Negative']
FN = population_test['False Negative']
TP = population_test['True Positive']
FP = population_test['False Positive']
if ispositive:
return f'Likelihood of you are indeed positive is {100 * TP/(FP + TP):.3f}%'
return f'Likelihood of you are indeed negative is {100 * TN/(FN + TN):.3f}%'
@oneryalcin
Copy link
Author

This is a simple simulation of showing how reliable is a finger Covid 19 test for mass

UK = Population(prevalence=0.0002, size=1000000)
covid_test = CovidTest(true_positive=0.98, true_negative=0.98)

pop_test = covid_test.test_population(UK)

>>print(pop_test)
Counter({'True Negative': 979451,
         'False Positive': 20343,
         'True Positive': 203,
         'False Negative': 3})

What is the likelyhood that I'm indeed positive if my test result is positive

covid_test.likelihood(ispositive=True, population_test=pop_test)
>>'Likelihood of you are indeed positive is 0.988%'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment