main.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. import csv
  2. import os
  3. import sys
  4. import matplotlib.pyplot as plt
  5. import requests
  6. import data
  7. _URLS = {
  8. 'cases': 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv',
  9. 'deaths': 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Deaths.csv',
  10. }
  11. _DATES_START_AT = 4
  12. _REGIONS = [
  13. ('Sweden', ['Sweden']),
  14. ('Ireland', ['Ireland']),
  15. ('Iran', ['Iran']),
  16. ('Italy', ['Italy']),
  17. ('NY', ['US, New York']),
  18. ('Europe', ['Italy', 'Sweden', 'Ireland']),
  19. ]
  20. _MARKERS = ['o', 'x', 'D']
  21. _MIN_COUNT = 10
  22. def write_fig(url_label, regions_label, regions, dates, region_data, start_date_idx, scale, normalize):
  23. title = '%s-%s' % (url_label, scale)
  24. if normalize:
  25. title += '-normalized'
  26. plt.figure()
  27. fig, ax = plt.subplots()
  28. plt.yscale(scale)
  29. min_value = 10**10
  30. max_value = None
  31. for region, series, marker in zip(regions, region_data, _MARKERS):
  32. series = series[start_date_idx:]
  33. if normalize:
  34. if region not in data.POPULATIONS:
  35. print 'Cannot normalize data for %s: population data is not available. Aborting.' % region
  36. return
  37. series = [x / data.POPULATIONS[region] for x in series]
  38. ax.plot(series, marker=marker)
  39. max_value = max(max_value, max(series))
  40. min_value = min(min_value, min([x for x in series if x > 0]))
  41. xlabels = dates[start_date_idx:]
  42. if len(xlabels) > 7:
  43. for i, date in enumerate(xlabels):
  44. if i != len(xlabels) -1 and i % (len(xlabels) / 5) != 0:
  45. xlabels[i] = ''
  46. plt.xticks(range(len(xlabels)), xlabels)
  47. plt.title('%s-%s' % (regions_label, title))
  48. if scale == 'log' and normalize:
  49. yticks = [10**exp for exp in range(-10, 0) if min_value / 3 < 10 ** exp < max_value * 3]
  50. ylabels = ['%f' % (x*100) for x in yticks]
  51. ylabels = ['0' + x.strip('0') + '%' for x in ylabels]
  52. plt.yticks(yticks, ylabels)
  53. if len(regions) > 1:
  54. ax.legend(regions)
  55. ax.grid()
  56. fig.savefig('figs/%s/%s.png' % (regions_label, title))
  57. plt.close()
  58. def run(url_label, regions_label, regions, dates, region_data):
  59. start_date_idx = None
  60. for i, (series, region) in enumerate(zip(region_data, regions)):
  61. for j, count in enumerate(series):
  62. if count >= _MIN_COUNT:
  63. if start_date_idx is None:
  64. start_date_idx = j-1 if j else j
  65. else:
  66. start_date_idx = min(start_date_idx, j-1 if j else j)
  67. if start_date_idx is None:
  68. print 'No data for %s-%s; aborting' % (url_label, regions_label)
  69. return
  70. if not os.path.isdir('figs'):
  71. os.mkdir('figs')
  72. if not os.path.isdir('figs/%s' % regions_label):
  73. os.mkdir('figs/%s' % regions_label)
  74. for scale in ['linear', 'log']:
  75. for normalize in [True, False]:
  76. write_fig(url_label, regions_label, regions, dates, region_data, start_date_idx, scale, normalize)
  77. def load(url):
  78. raw = requests.get(url).content
  79. dates = None
  80. counts = {}
  81. reader = csv.reader(raw.splitlines(), delimiter=',', quotechar='"')
  82. for row in reader:
  83. if dates is None:
  84. dates = row[_DATES_START_AT:]
  85. continue
  86. region = '%s, %s' % (row[1], row[0]) if row[0] else row[1]
  87. counts[region] = [float(x) for x in row[_DATES_START_AT:]]
  88. dates = ['%s/%s' % tuple(d.split('/')[:2]) for d in dates]
  89. return dates, counts
  90. def print_regions(counts):
  91. for region in sorted(counts.keys()):
  92. print region
  93. if __name__ == "__main__":
  94. for url_label, url in _URLS.items():
  95. dates, counts = load(url)
  96. for region_label, regions in _REGIONS:
  97. regions_data = [counts[region] for region in regions]
  98. run(url_label, region_label, regions, dates, regions_data)