Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

calculate and add coverage info, change format #30

Merged
merged 1 commit into from
Jun 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 123 additions & 53 deletions functions/Untitled.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"cells": [
{
"cell_type": "code",
"execution_count": 2,
"execution_count": 1,
"metadata": {},
"outputs": [
{
Expand Down Expand Up @@ -414,7 +414,7 @@
},
{
"cell_type": "code",
"execution_count": 3,
"execution_count": 2,
"metadata": {},
"outputs": [
{
Expand Down Expand Up @@ -445,7 +445,7 @@
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 3,
"metadata": {
"scrolled": true
},
Expand All @@ -463,7 +463,7 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 4,
"metadata": {},
"outputs": [
{
Expand All @@ -480,7 +480,7 @@
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": 5,
"metadata": {},
"outputs": [
{
Expand Down Expand Up @@ -928,7 +928,7 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 6,
"metadata": {},
"outputs": [
{
Expand Down Expand Up @@ -1183,7 +1183,7 @@
"[3142 rows x 9 columns]"
]
},
"execution_count": 7,
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
Expand All @@ -1194,7 +1194,7 @@
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
Expand All @@ -1214,12 +1214,12 @@
"date2 = []\n",
"k = 0\n",
"while True:\n",
" d = datetime.today() - timedelta(days=i)\n",
" date2.append(d+timedelta(days=7))\n",
" d = (datetime.today() - timedelta(days=i)).date()\n",
" i += 1\n",
" if cached_dir is not None:\n",
" cached_fname = oj(cached_dir, f'preds_{d.month}_{d.day}_cached.pkl')\n",
" if os.path.exists(cached_fname):\n",
" date2.append(d+timedelta(days=7))\n",
" add_predictions_7day(pd.read_pickle(cached_fname),df_tab)\n",
" else:\n",
" k += 1\n",
Expand All @@ -1229,7 +1229,7 @@
},
{
"cell_type": "code",
"execution_count": 25,
"execution_count": 65,
"metadata": {
"scrolled": true
},
Expand All @@ -1240,7 +1240,7 @@
"'test.html'"
]
},
"execution_count": 25,
"execution_count": 65,
"metadata": {},
"output_type": "execute_result"
}
Expand All @@ -1249,17 +1249,36 @@
"row = df_tab.iloc[0]\n",
"state,county,FIPS = row['State'],row['County']+\" County\",row['countyFIPS']\n",
"newdates = date1\n",
"fig = make_subplots(rows=1, cols=2, specs=[[{\"secondary_y\": True},{\"secondary_y\": True}]],subplot_titles=(\"Time series with 7 day prediction\",\"Time series with historical prediction\"))\n",
"fig = make_subplots(rows=1, cols=2, specs=[[{\"secondary_y\": True},{\"secondary_y\": True}]],\n",
" subplot_titles=(\"Time series with 7 day prediction\",\n",
" \"Time series with historical prediction(7 day)\"))\n",
"traces = []\n",
"keys_curves=['deaths','cases']\n",
"credstr ='rgb(179,0,10)'\n",
"cbluestr = 'rgb(42,100,244)'\n",
"fill_strings = ['rgba(179,0,10,0.4)','rgba(42,100,244,0.4)']\n",
"color_strings = [credstr, cbluestr]\n",
"\n",
"\n",
"red = '179,74,71'\n",
"blue = '83,137,190'\n",
"credstr ='rgb(' + red + ')'\n",
"cbluestr = 'rgb(' + blue + ')'\n",
"fill_strings = ['rgba(' + red + ',0.4)','rgba(' + blue + ',0.4)']\n",
"color_strings=[credstr,cbluestr]\n",
"\n",
"def make_traces(fig, row, pre, date1, date2, r, c, show_lengend,keys_curves=['deaths','cases']):\n",
"def cal_coverage(row,date1,date2,keys = ['deaths', 'cases']):\n",
" def cal(key, key_inv):\n",
" dic_real = {}\n",
" dic_pre = {}\n",
" for i in range(len(date1)):\n",
" dic_real[date1[i]] = row[key][i]\n",
" for i in range(len(date2)):\n",
" dic_pre[date2[i]] = row[key_inv][i]\n",
" hit = miss = 0\n",
" for d in dic_pre.keys():\n",
" if d in dic_real:\n",
" if dic_real[d] >= round(dic_pre[d][0],0) and dic_real[d] <= round(dic_pre[d][1],0):\n",
" hit += 1\n",
" else:\n",
" miss += 1\n",
" return (hit/(hit+miss))\n",
" return [cal(key, 'pred_7day_' + key +'_interval') for key in keys]\n",
"def make_traces(fig, row, pre, date1, date2, r, c, width,show_lengend,keys_curves=['deaths','cases']):\n",
" for j, key_curve in enumerate(keys_curves):\n",
" curve = row[key_curve]\n",
" traces = []\n",
Expand All @@ -1268,7 +1287,7 @@
" showlegend=show_lengend,\n",
" visible=True, #key == key0,# False, #key == key0,\n",
" name=key_curve,\n",
" line=dict(color=color_strings[j], width=4)) )\n",
" line=dict(color=color_strings[j], width=width)) )\n",
" low = np.hstack((curve[-1],[x[0] for x in row[pre+key_curve+'_interval']]))\n",
" up = np.hstack((curve[-1],[x[1] for x in row[pre+key_curve+'_interval']]))\n",
" if pre == 'pred_7day_':\n",
Expand All @@ -1279,20 +1298,20 @@
" showlegend= False,\n",
" x = date2,\n",
" y = up,\n",
" marker = dict(size=0),\n",
" line=dict(dash ='solid',color=fill_strings[j], width=0)))\n",
" traces.append(go.Scatter(x= date2,\n",
" y=row[pre+key_curve],\n",
" name = key_curve +' prediction',\n",
" showlegend= show_lengend,\n",
" visible=True,\n",
" mode = 'lines',\n",
" line=dict(dash ='dash',color=color_strings[j], width=4),\n",
" line=dict(dash ='dash',color=color_strings[j], width=width),\n",
" fillcolor = fill_strings[j],\n",
" fill ='tonexty'))\n",
" traces.append(go.Scatter(\n",
" name = 'Lower Bound',\n",
" visible = True,\n",
" showlegend= False,\n",
" marker = dict(size=0),\n",
" x = date2,\n",
" y = low,\n",
" fill ='tonexty',\n",
Expand All @@ -1301,61 +1320,112 @@
" for trace in traces:\n",
" fig.add_trace(trace, secondary_y=key_curve==\"deaths\", row=r,col=c)\n",
" return fig\n",
"fig = make_traces(fig, row,'pred_7day_',date1,date2,1,2,False)\n",
"fig = make_traces(fig, row,'pred_7day_',date1,date2,1,2,3,False)\n",
"newdates = [date1[-1] + timedelta(days =i) for i in range(0,8)]\n",
"fig = make_traces(fig, row,'pred_',date1,newdates,1,1,True) \n",
"fig = make_traces(fig, row,'pred_',date1,newdates,1,1,4,True) \n",
"for i in fig['layout']['annotations']:\n",
" i['font'] = dict(size=15,color='white') \n",
"\n",
"deaths_cov,cases_cov = cal_coverage(row,date1,date2)\n",
"# Update the margins to add a title and see graph x-labels.\n",
"fig.layout.margin.update({'t':150, 'b':120})\n",
" \n",
"fig.layout.update(\n",
" title ={'text':state+' '+county+ '<br>' + 'FIPS:'+row['countyFIPS'], 'y':0.92,\n",
" 'x':0.03, \n",
" 'yanchor': 'top'},\n",
" width=1200,\n",
" height=700,\n",
" font=dict(\n",
" size=12))\n",
"fig.update_layout(legend=dict(x=0.9, y=1.3))\n",
" title = dict(text = county+', '+state+ '<br>' + 'FIPS:'+row['countyFIPS'], \n",
" y = 0.92,\n",
" x = 0.03, \n",
" yanchor = 'top'),\n",
" width=1200,height=700,\n",
" font=dict(size=12),\n",
" legend=dict(x=0.5, y=1.2),\n",
" legend_orientation=\"h\"\n",
" )\n",
"fig.add_annotation(dict(font=dict(color=\"white\",size=11),\n",
" x=0.8,\n",
" y=0.9,\n",
" showarrow=False,\n",
" text='Cases Prediction coverage: '+str(round(cases_cov, 2))+'<br>'\n",
" ' Deaths Prediction coverage: '+str(round(deaths_cov, 2)),\n",
" textangle=0,\n",
" xref=\"paper\",\n",
" yref=\"paper\"\n",
" ))\n",
"fig.add_annotation(dict(font=dict(color=\"white\",size=12),\n",
" x=0.9,\n",
" y=1.3,\n",
" showarrow=False,\n",
" text='Modebar '+u'\\u2191',\n",
" textangle=0,\n",
" xref=\"paper\",\n",
" yref=\"paper\"\n",
" ))\n",
"## Set plot1 axes properties\n",
"y1 = max([x[1] for x in row['pred_cases_interval']])\n",
"y2 = max([x[1] for x in row['pred_deaths_interval']])\n",
"fig.update_xaxes(title_text=\"Date\",range=[datetime(2020, 3, 25), newdates[-1]],domain = [0,0.41],row=1, col=1)\n",
"fig.update_yaxes(title_text=\"Cases\", color='rgb(42,130,244)',rangemode = 'tozero',\n",
" dtick = y1/5,range=[0,y1], domain=[0,0.95],row=1, col=1) \n",
"fig.update_yaxes(title_text=\"Deaths\",rangemode = 'tozero',color='rgb(255,50,50)',\n",
" dtick = y2*1.3/5, range=[0,y2*1.3], secondary_y=True, row=1,col=1)\n",
"fig.update_xaxes(title_text=\"Date\",range=[datetime(2020, 3, 24), newdates[-1]],domain = [0,0.41],row=1, col=1)\n",
"fig.update_yaxes(title_text=\"Cases\", color=cbluestr,rangemode = 'tozero',\n",
" dtick = (y1-y11)/5,range=[y11,y1], domain=[0,0.95],row=1, col=1) \n",
"fig.update_yaxes(title_text=\"Deaths\",showgrid=False,rangemode = 'tozero',color=credstr,\n",
" dtick = (y2*1.3-y22)/5, range=[y22,y2*1.3], secondary_y=True, row=1,col=1)\n",
" ## Set plot2 axes properties\n",
"y1 = max([x[1] for x in row['pred_7day_cases_interval'][7:]])\n",
"y11 = min([x[0] for x in row['pred_7day_cases_interval'][7:]])\n",
"y2 = max([x[1] for x in row['pred_7day_deaths_interval'][7:]])\n",
"y22 = min([x[0] for x in row['pred_7day_deaths_interval'][7:]])\n",
"fig.update_xaxes(title_text=\"Date\",range=[date2[-1], date2[7]],domain = [0.59,1], row=1, col=2)\n",
"fig.update_yaxes(title_text=\"Cases\", color='rgb(42,130,244)',rangemode = 'tozero',\n",
" dtick = (y1-y11)/5,range=[y11,y1],domain=[0,0.95], row=1, col=2)\n",
"fig.update_yaxes(title_text=\"Deaths\",showgrid=False,rangemode = 'tozero',color='rgb(255,50,50)',\n",
" dtick = (y2*1.5-y22)/5, range=[y22,y2*1.5], secondary_y=True, row=1,col=2)\n",
"fig.update_yaxes(title_text=\"Cases\", color=cbluestr,rangemode = 'tozero',\n",
" dtick = (y1-y11)/5,range=[y11,y1], domain=[0,0.95],row=1, col=2) \n",
"fig.update_yaxes(title_text=\"Deaths\",rangemode = 'tozero',color=credstr,\n",
" dtick = (y2-y22)*1.3/5, showgrid=False,range=[y22,y2*1.3], secondary_y=True, row=1,col=2)\n",
"fig.layout.template = 'plotly_dark'\n",
"plotly.offline.plot(fig, filename='test.html', auto_open=True)"
]
},
{
"cell_type": "code",
"execution_count": 30,
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(len(date2))\n",
"len(row['pred_7day_cases_interval'])"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2020-06-20 21:39:59.601047\n"
"ename": "ValueError",
"evalue": "Unknown format code 'd' for object of type 'float'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-18-f18988ccf924>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0;34mf'{10.324335:03d}'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mValueError\u001b[0m: Unknown format code 'd' for object of type 'float'"
]
}
],
"source": [
"print(date2[7])"
"f'{10.324335:03d}'"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'↑'"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"u'\\u2191'"
]
},
{
Expand Down
10 changes: 5 additions & 5 deletions functions/test.html

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions functions/update_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,12 @@ def add_predictions_7day(data,df):
date2 = []
k = 0
while True:
d = datetime.today() - timedelta(days=i)
date2.append(d+timedelta(days=7))
d = (datetime.today() - timedelta(days=i)).date()
i += 1
if cached_dir is not None:
cached_fname = oj(cached_dir, f'preds_{d.month}_{d.day}_cached.pkl')
if os.path.exists(cached_fname):
date2.append(d+timedelta(days=7))
add_predictions_7day(pd.read_pickle(cached_fname),df_tab)
else:
k += 1
Expand Down
Loading