فهرست منبع

initial commit

Martin 6 سال پیش
والد
کامیت
a57433a72e
6فایلهای تغییر یافته به همراه192 افزوده شده و 1 حذف شده
  1. 47 0
      .flake8
  2. 2 0
      .gitignore
  3. 1 1
      README.md
  4. 7 0
      data.py
  5. 132 0
      main.py
  6. 3 0
      requirements.txt

+ 47 - 0
.flake8

@@ -0,0 +1,47 @@
+[flake8]
+max-line-length = 120
+max-complexity = 10
+exclude =
+    # Other languages
+    *.js,
+    css,
+    js,
+
+    # Bytecode
+    *.pyc,
+
+    # Configuration files
+    .git,
+
+ignore =
+    # NDB instrospection support
+    # *Comparison to true should be 'if cond is true:' or 'if cond:'*
+    # https://lintlyci.github.io/Flake8Rules/rules/E712.html
+    # e.g.: User.query(User.verified == False)
+    E712,
+    # *Comparison to None should be 'if cond is not None:'*
+    # https://lintlyci.github.io/Flake8Rules/rules/E711.html
+    # e.g.: Shop.query(pdt.Shop.chain == None)
+    E711,
+
+    # *Line-break occurred before binary operator*
+    # https://lintlyci.github.io/Flake8Rules/rules/W503.html
+    # Because it is the opposite of PEP8 and will be reversed in the future
+    # e.g.:
+    #   is_amount_equal_to_immediately_after_amount = (
+    #       not is_amount_equal_to_prior_amount
+    #       and history
+    #       and insertion_idx < len(history)
+    #   )
+    W503,
+
+    # *Remove bad quotes from multiple lines string*
+    # https://github.com/zheller/flake8-quotes/blob/4dbc2e/flake8_quotes/__init__.py#L220
+    # SQL Queries are better written with 'bad quotes'(sic)
+    # e.g.:
+    #     stmt = """
+    #         UPDATE ShopSignups
+    #         SET first_device_shipment_date = %s
+    #         WHERE shop_id = %s AND first_device_shipment_date IS NULL
+    #     """
+    Q001,

+ 2 - 0
.gitignore

@@ -58,3 +58,5 @@ docs/_build/
 # PyBuilder
 target/
 
+
+figs/

+ 1 - 1
README.md

@@ -1,2 +1,2 @@
-# covid-analyzer
+# covid19-analyzer
 

+ 7 - 0
data.py

@@ -0,0 +1,7 @@
+POPULATIONS = {
+    'Ireland': 4.83 * 10**6,
+    'Sweden': 10.12 * 10**6,
+    'Iran': 81.16 * 10**6,
+    'Italy': 60.48 * 10**6,
+    'US, New York': 19.54 * 10**6,
+}

+ 132 - 0
main.py

@@ -0,0 +1,132 @@
+import csv
+import os
+import sys
+
+import matplotlib.pyplot as plt
+import requests
+
+import data
+
+_FNAME = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv'
+_DATES_START_AT = 4
+_REGIONS = [
+    ('Sweden', ['Sweden']),
+    ('Ireland', ['Ireland']),
+    ('Iran', ['Iran']),
+    ('Italy', ['Italy']),
+    ('NY', ['US, New York']),
+    ('Europe', ['Italy', 'Sweden', 'Ireland']),
+]
+_MARKERS = ['o', 'x', 'D']
+
+
+def write_fig(regions_label, regions, dates, region_data, start_date_idx, scale, normalize):
+    title = scale
+    if normalize:
+        title += '-normalized'
+    
+    plt.figure()
+    fig, ax = plt.subplots()
+    plt.yscale(scale)
+
+    min_value = 10**10
+    max_value = None
+
+    for region, series, marker in zip(regions, region_data, _MARKERS):
+        series = series[start_date_idx:]
+
+        if normalize:
+            if region not in data.POPULATIONS:
+                print 'Cannot normalize data for %s: population data is not available. Aborting.' % region
+                return
+            
+            series = [x / data.POPULATIONS[region] for x in series]
+
+        ax.plot(series, marker=marker)
+
+        max_value = max(max_value, max(series))
+        min_value = min(min_value, min([x for x in series if x > 0]))
+
+    xlabels = dates[start_date_idx:]
+    if len(xlabels) > 7:
+        for i, date in enumerate(xlabels):
+            if i != len(xlabels) -1 and i % (len(xlabels) / 5) != 0:
+                xlabels[i] = ''
+    plt.xticks(range(len(xlabels)), xlabels)
+    plt.title('%s-%s' % (regions_label, title))
+
+    if scale == 'log' and normalize:
+        yticks = [10**exp for exp in range(-10, 0) if min_value / 3 < 10 ** exp < max_value * 3]
+        
+        ylabels = ['%f' % (x*100) for x in yticks]
+        ylabels = ['0' + x.strip('0') + '%' for x in ylabels]
+
+        plt.yticks(yticks, ylabels)
+
+    if len(regions) > 1:
+        ax.legend(regions)
+
+    ax.grid()
+
+    fig.savefig('figs/%s/%s.png' % (regions_label, title))
+
+    plt.close()
+
+
+def run(regions_label, regions, dates, region_data):
+    start_date_idx = None
+    for i, (series, region) in enumerate(zip(region_data, regions)):
+        for j, count in enumerate(series):
+            if count >= 10:
+                if start_date_idx is None:
+                    start_date_idx = j-1 if j else j
+                else:
+                    start_date_idx = min(start_date_idx, j-1 if j else j)
+    
+    if start_date_idx is None:
+        print 'No data for %s; aborting' % label
+        return
+
+    if not os.path.isdir('figs'):
+        os.mkdir('figs')
+    if not os.path.isdir('figs/%s' % label):
+        os.mkdir('figs/%s' % label)
+
+    for scale in ['linear', 'log']:
+        for normalize in [True, False]:
+            write_fig(regions_label, regions, dates, region_data, start_date_idx, scale, normalize)
+
+
+def load():
+    raw = requests.get(_FNAME).content
+
+    dates = None
+
+    counts = {}
+
+    reader = csv.reader(raw.splitlines(), delimiter=',', quotechar='"')
+    for row in reader:
+        if dates is None:
+            dates = row[_DATES_START_AT:]
+            continue
+
+        region = '%s, %s' % (row[1], row[0]) if row[0] else row[1]
+
+        counts[region] = [float(x) for x in row[_DATES_START_AT:]]
+    
+    dates = ['%s/%s' % tuple(d.split('/')[:2]) for d in dates]
+
+    return dates, counts
+
+
+def print_regions(counts):
+    for region in sorted(counts.keys()):
+        print region
+
+
+if __name__ == "__main__":
+    dates, counts = load()
+
+    for label, regions in _REGIONS:
+        region_data = [counts[region] for region in regions]
+        run(label, regions, dates, region_data)

+ 3 - 0
requirements.txt

@@ -0,0 +1,3 @@
+requests
+matplotlib
+numpy