-
Notifications
You must be signed in to change notification settings - Fork 0
/
rejanalysis.py
1734 lines (1214 loc) · 55.4 KB
/
rejanalysis.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import mailbox
import email.utils
# In[2]:
import pandas as pd
import numpy as np
import datetime
import plotly.express as px
# In[3]:
mbox = mailbox.mbox('Rej.mbox')
mbox2 = mailbox.mbox('rej2.mbox')
# # Email Processing
# In[4]:
import mailbox
import bs4
def get_html_text(html):
try:
return bs4.BeautifulSoup(html, "html5lib").body.get_text(' ', strip=True)
except AttributeError: # message contents empty
return None
class GmailMboxMessage():
def __init__(self, email_data):
if not isinstance(email_data, mailbox.mboxMessage):
raise TypeError('Variable must be type mailbox.mboxMessage')
self.email_data = email_data
self.labels= self.date= self.efrom= self.eto= self.subject= self.text=None
def parse_email(self):
email_labels = self.email_data['X-Gmail-Labels']
email_date = self.email_data['Date']
email_from = self.email_data['From']
email_to = self.email_data['To']
email_subject = self.email_data['Subject']
email_text = self.read_email_payload()
self.labels=email_labels
self.date=email_date
self.efrom=email_from
self.eto=email_to
self.subject=email_subject
self.text=email_text
def read_email_payload(self):
email_payload = self.email_data.get_payload()
if self.email_data.is_multipart():
email_messages = list(self._get_email_messages(email_payload))
else:
email_messages = [email_payload]
return [self._read_email_text(msg) for msg in email_messages]
def _get_email_messages(self, email_payload):
for msg in email_payload:
if isinstance(msg, (list,tuple)):
for submsg in self._get_email_messages(msg):
yield submsg
elif msg.is_multipart():
for submsg in self._get_email_messages(msg.get_payload()):
yield submsg
else:
yield msg
def _read_email_text(self, msg):
content_type = 'NA' if isinstance(msg, str) else msg.get_content_type()
encoding = 'NA' if isinstance(msg, str) else msg.get('Content-Transfer-Encoding', 'NA')
if 'text/plain' in content_type and 'base64' not in encoding:
msg_text = msg.get_payload()
elif 'text/html' in content_type and 'base64' not in encoding:
msg_text = get_html_text(msg.get_payload())
elif content_type == 'NA':
msg_text = get_html_text(msg)
else:
msg_text = None
return (content_type, encoding, msg_text)
# In[5]:
emails=[]
num_entries = len(mbox)
for idx, email_obj in enumerate(mbox):
email_data = GmailMboxMessage(email_obj)
email_data.parse_email()
emails.append(email_data)
# print('Parsing email {0} of {1}'.format(idx, num_entries))
# In[6]:
num_entries = len(mbox2)
for idx, email_obj in enumerate(mbox2):
email_data = GmailMboxMessage(email_obj)
email_data.parse_email()
emails.append(email_data)
# print('Parsing email {0} of {1}'.format(idx, num_entries))
# In[7]:
# construct the dataframe
email_df= pd.DataFrame()
for e in emails:
email_df=email_df.append([{'date':e.date,'from':e.efrom,'to':e.eto,'subject':e.subject,'text':e.text}])
# In[8]:
from pytz import timezone
# In[9]:
from dateutil.parser import parse
from datetime import datetime as dt
# In[10]:
email_df['date_n']=pd.to_datetime(email_df.date)
# In[11]:
email_df['date_es']=email_df['date_n'].apply(lambda x: x.astimezone(timezone('US/Eastern')))
# In[ ]:
# In[ ]:
# In[12]:
email_df['weekdays']=email_df.date_es.apply(lambda x: dt.strftime(x, "%A"))
# In[13]:
email_df['hour']=email_df.date_es.apply(
lambda x: dt.strftime(x, "%I %p")
)
# In[ ]:
# In[14]:
day_list = [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
]
# In[ ]:
# # Text Mining
# In[15]:
import re, string
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
import nltk
from nltk.corpus import stopwords
nltk.download('stopwords')
stop = list(stopwords.words('english'))
stop.extend(['yukun','yukun yang','yang','data','scientist'])
def extract_text(text_list):
tags=[component[0] for component in text_list]
real_content=None
if 'text/html' in tags:
ind=[component[0] for component in text_list].index('text/html')
real_content=text_list[ind][-1]
if real_content=='None':
real_content=None
elif 'text/plain' in tags:
ind=[component[0] for component in text_list].index('text/plain')
real_content=text_list[ind][-1]
elif 'NA' in tags:
ind=[component[0] for component in text_list].index('NA')
real_content=text_list[ind][-1]
if (real_content is not None):
if len(real_content)>10000:
real_content=None
return real_content
def clean_text(text):
if text is not None:
text=re.sub('=\n', '', text)
text=re.sub('\S*@\S*\s?', '', text)
text=' '.join(word.strip(string.punctuation) for word in text.split())
text=re.sub(r'((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z]){2,6}([a-zA-Z0-9\.\&\/\?\:@\-_=#])*', '', text, flags=re.MULTILINE)
# text=re.sub(r'\..*\..* ?', '', text, flags=re.MULTILINE)
text=re.sub(r"\d+", "", text)
text=re.sub(r"={1}.{2}", "", text)
text=text.replace('size','').replace('text size', '').replace('adjust','').replace('td','')
return text
else:
return None
# In[16]:
email_df['extracted']=email_df.text.apply(extract_text)
email_df['cleaned']=email_df.extracted.apply(clean_text)
# In[17]:
def important_words(metric, ranks):
import nltk
from nltk.corpus import stopwords
nltk.download('stopwords')
# stop = list(stopwords.words('english'))
# stop.extend(['yukun','yukun yang','yang','data','scientist'])
if metric=='tf':
vectorizer= CountVectorizer(ngram_range=(1,3),stop_words=stop)
vectors = vectorizer.fit_transform(email_df.dropna().cleaned.to_list())
elif metric=='tfidf':
vectorizer = TfidfVectorizer(ngram_range=(1,3),stop_words=stop)
# tf_vectorizer= CountVectorizer(ngram_range=(1,3),stop_words=stop)
vectors = vectorizer.fit_transform(email_df.dropna().cleaned.to_list())
#making df
rankings=pd.DataFrame(vectors.todense().tolist(), columns=vectorizer.get_feature_names()).sum().reset_index().rename(columns={'index':'word',0:'value'})
# if rankings.value.dtype !='int':
rankings['value']=rankings['value'].round(2)
#making distinguish
rankings['type']=None
for ind, row in rankings.iterrows():
num=len(row['word'].split())
if num==1:
rankings.loc[ind,'type']='unigram'
elif num==2:
rankings.loc[ind,'type']='bigram'
elif num==3:
rankings.loc[ind,'type']='trigram'
return rankings.sort_values('value', ascending=False).head(ranks)
def make_important_graphs(df):
bar=px.bar(df, y='value', x='word', text='value', color='type', template='seaborn', title='Important Terms Bar Chart')
bar.update_layout(xaxis_categoryorder = 'total descending')
tree=px.treemap(df,path=['type','word'],values='value', template='seaborn', title='Important Terms Tree Map')
return bar,tree
# In[18]:
import nltk
from nltk.collocations import *
from collections import Counter
def collo(metric):
bigram_measures = nltk.collocations.BigramAssocMeasures()
# trigram_measures = nltk.collocations.TrigramAssocMeasures()
text=' '.join(i for i in email_df.dropna().cleaned.to_list())
words=[word for word in text.lower().split() if word not in stop]
# change this to read in your data
finder = BigramCollocationFinder.from_words(words)
# only bigrams that appear 3+ times
finder.apply_freq_filter(3)
# return the 10 n-grams with the highest PMI
# finder.nbest(bigram_measures.pmi, 15)
# finder.nbest(bigram_measures.likelihood_ratio, 15)
if metric=='pmi':
coli=finder.score_ngrams(bigram_measures.pmi)
elif metric=='chisquare':
coli=finder.score_ngrams(bigram_measures.chi_sq)
elif metric=='likelihood_ratio':
coli=finder.score_ngrams(bigram_measures.likelihood_ratio)
return coli
def make_circos(test_co):
colors=['#fff1d6','#c9a03d','#02b1a0','#848484','#cfcfcf','#a2e8eb','#ecd1fc',"#f0b3c5","#c4e5d6","#d7f2fd",'#feb408',
'#f09654','#ee6f37','#6da393','#007890','#e8c8ee','#ffa3a3','#f6e777']
colors.extend(colors)
top20=test_co[:10]
workcounter=Counter()
for i in top20:
workcounter.update(i[0])
ideogram=[]
for tu in workcounter.most_common():
ideogram.append({'id':tu[0], 'label':tu[0], 'color':colors.pop(), 'len':tu[-1]})
ribbons=[]
for co in top20:
ribbons.append({'color':'#9ecaf6',
'source':{'id':co[0][0],'start':0,'end':1},
'target':{'id':co[0][-1],'start':0,'end':1}})
return dashbio.Circos(
id='circos',
layout=ideogram,
size=600,
selectEvent={'hover': "hover", 'click': "click", 2: "both"},
# eventDatum={"0": "hover", "1": "click", "2": "both"},
config= {'ticks': {'display': False},'labels':{'size': 10,'position': 'center'}},
tracks=[{
'type': 'CHORDS',
'data': ribbons,
'selectEvent':{"0": "hover", "1": "click", "2": "both"},
'tooltipContent': {
'source': 'source',
'sourceID': 'id',
'target': 'target',
'targetID': 'id',
'targetEnd': 'end'
}
}
]
)
# In[19]:
import gensim
import spacy
def sent_to_words(sentences):
for sentence in sentences:
yield(gensim.utils.simple_preprocess(str(sentence), deacc=True))
def remove_stopwords(texts):
new_docs=[]
for doc in texts:
new_docs.append([word for word in doc if word not in stop])
return new_docs
def make_bigrams(texts):
return [bigram_mod[doc] for doc in texts]
def make_trigrams(texts):
return [trigram_mod[bigram_mod[doc]] for doc in texts]
def lemmatization(texts, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV']):
"""https://spacy.io/api/annotation"""
texts_out = []
for sent in texts:
doc = nlp(" ".join(sent))
texts_out.append([token.lemma_ for token in doc if token.pos_ in allowed_postags])
return texts_out
# In[ ]:
# In[ ]:
# In[20]:
data=email_df[email_df.cleaned.notna()].cleaned.values.tolist()
# In[21]:
data_words = list(sent_to_words(data))
# In[22]:
bigram = gensim.models.Phrases(data_words, min_count=5, threshold=100) # higher threshold fewer phrases.
trigram = gensim.models.Phrases(bigram[data_words], threshold=100)
bigram_mod = gensim.models.phrases.Phraser(bigram)
trigram_mod = gensim.models.phrases.Phraser(trigram)
# In[23]:
# Remove Stop Words
data_words_nostops = remove_stopwords(data_words)
# Form Bigrams
data_words_bigrams = make_bigrams(data_words_nostops)
# In[24]:
nlp = spacy.load('en', disable=['parser', 'ner'])
# Do lemmatization keeping only noun, adj, vb, adv
data_lemmatized = lemmatization(data_words_bigrams, allowed_postags=['NOUN', 'ADJ', 'VERB', 'ADV'])
# print(data_lemmatized[:1])
# In[25]:
import gensim
import gensim.corpora as corpora
from gensim.utils import simple_preprocess
from gensim.models import CoherenceModel
# Create Dictionary
id2word = corpora.Dictionary(data_lemmatized)
# Create Corpus
texts = data_lemmatized
# Term Document Frequency
corpus = [id2word.doc2bow(text) for text in texts]
# View
# print(corpus[:1])
# In[26]:
def compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=3):
"""
Compute c_v coherence for various number of topics
Parameters:
----------
dictionary : Gensim dictionary
corpus : Gensim corpus
texts : List of input texts
limit : Max num of topics
Returns:
-------
model_list : List of LDA topic models
coherence_values : Coherence values corresponding to the LDA model with respective number of topics
"""
coherence_values = []
model_list = []
for num_topics in range(start, limit, step):
model = gensim.models.ldamodel.LdaModel(corpus=corpus, num_topics=num_topics, id2word=id2word,random_state=2020)
model_list.append(model)
coherencemodel = CoherenceModel(model=model, texts=texts, dictionary=dictionary, coherence='c_v')
coherence_values.append(coherencemodel.get_coherence())
return model_list, coherence_values
# In[27]:
model_list, coherence_values = compute_coherence_values(dictionary=id2word, corpus=corpus, texts=data_lemmatized, start=2, limit=40, step=2)
# In[28]:
x=range(2,40,2)
# In[29]:
choose_k=pd.DataFrame({'# of Topics':x,'coherence':coherence_values})
# In[ ]:
# In[30]:
def format_topics_sentences(ldamodel=None, corpus=corpus, texts=data):
# Init output
sent_topics_df = pd.DataFrame()
# Get main topic in each document
for i, row_list in enumerate(ldamodel[corpus]):
row = row_list[0] if ldamodel.per_word_topics else row_list
# print(row)
row = sorted(row, key=lambda x: (x[1]), reverse=True)
# Get the Dominant topic, Perc Contribution and Keywords for each document
for j, (topic_num, prop_topic) in enumerate(row):
if j == 0: # => dominant topic
wp = ldamodel.show_topic(topic_num)
topic_keywords = ", ".join([word for word, prop in wp])
sent_topics_df = sent_topics_df.append(pd.Series([int(topic_num), round(prop_topic,4), topic_keywords]), ignore_index=True)
else:
break
sent_topics_df.columns = ['Dominant_Topic', 'Perc_Contribution', 'Topic_Keywords']
# Add original text to the end of the output
contents = pd.Series(texts)
sent_topics_df = pd.concat([sent_topics_df, contents], axis=1)
return(sent_topics_df)
# df_topic_sents_keywords = format_topics_sentences(ldamodel=lda_model, corpus=corpus, texts=data_lemmatized)
# # Format
# df_dominant_topic = df_topic_sents_keywords.reset_index()
# df_dominant_topic.columns = ['Document_No', 'Dominant_Topic', 'Topic_Perc_Contrib', 'Keywords', 'Text']
# df_dominant_topic.head(10)
# In[ ]:
# # Define all functions for the app
# In[ ]:
# In[31]:
def intro():
"""
:return: A Div containing dashboard title & descriptions.
"""
return html.Div(
id="description-card",
children=[
html.H3("Rejection Email Analytics"),
# html.H3("Welcome to the Clinical Analytics Dashboard"),
html.Blockquote(
id="intro",
children=["Rejection hurts. Yes but yet, I've met nobody who has not been rejected.\
It is a part of life and instead of drowning in the sorrow and somberness of being rejected, we can make it fun and try to try to analyze it.",
]
),
html.Div(children=['👋 My name is ',
html.A("Yukun", href='#contact_info'),
", I graduated in this crazy time of the year and have collected 100 rejection emails from all kinds of employers during these 3 months.\
Here I am applying my Data Science skills in Interactive Data Viz, Temporal Point Process Modelling, and Text Mining to analyze these emails. Hope you enjoy it!😀"]),
html.Br(),
html.H4('Instructions'),
html.Div(children=[
html.P("This dashboard enables multiple ways for you to interact with the plots. Every plot can be zoomed and selected, along with hovering tooltips. Despite these basics, it also supports the following interactions:"),
html.Li(
'Subsetting the dataset by selecting the time range, the weekdays, and the hours.'),
html.Li('Showing specific data entries by clicking on the Heatmap.'),
html.Div('Other interaction options are detailed in the corresponding part')])
# html.Li(
# 'Change the Solver of the Temporal Process and the number of days to prdict.'),
# html.Li('Change the metric to rank the important terms, and the number of topics to model.')])
],
)
# In[32]:
def control_card():
return html.Div(
id="control-card",
children=[
html.Strong("Select Date Range"),
dcc.DatePickerRange(
id='my-date-picker-range',
min_date_allowed=email_df['date_es'].min().date(),
max_date_allowed=email_df['date_es'].max().date(),
initial_visible_month=dt(2020, 4, 5),
start_date=email_df['date_es'].min().date(),
end_date=email_df['date_es'].max().date()
),
html.Br(),
html.Br(),
html.Strong("Select the Day of a Week"),
dcc.Dropdown(
id='weekdays',
options=[{'label': day, 'value': day} for day in day_list],
value=day_list,
multi=True
# style=dict(
# # height='100%',
# display='block',
# verticalAlign="middle"
# )
),
html.Br(),
html.Br(),
html.Strong("Select Specific Hours"),
dcc.Checklist(
id='time',
options=[{'label': t, 'value': t}
for t in[datetime.time(i).strftime("%I %p") for i in range(24)]],
value=[datetime.time(i).strftime("%I %p") for i in range(24)],
labelStyle={'display': 'inline-block'}
),
],
)
# In[33]:
def filter_df(start,end,weekdays,time):
filtered_df = email_df.sort_values("date_es").set_index("date_es")[
start.astimezone(timezone('US/Eastern')):end.astimezone(timezone('US/Eastern'))
]
filtered_df= filtered_df[filtered_df.weekdays.isin(weekdays)]
filtered_df= filtered_df[filtered_df.hour.isin(time)]
return filtered_df.reset_index()
# In[34]:
def generate_paco(filtered):
filtered.loc[filtered.date_es.dt.weekday.isin([6,5]),'Is Weekend']=True
filtered['Is Weekend']=filtered['Is Weekend'].fillna(False)
filtered['Day Time']=((filtered.date_es.dt.hour % 24 + 4) // 4).map({1: 'Late Night',
2: 'Early Morning',
3: 'Morning',
4: 'Noon',
5: 'Evening',
6: 'Night'})
groupedby=filtered.groupby(['Is Weekend','weekdays','Day Time','hour'])['from'].count().reset_index()
new_df=pd.merge(left=filtered,right=groupedby, left_on=['Is Weekend','weekdays','Day Time','hour'],right_on=['Is Weekend','weekdays','Day Time','hour'])
fig=px.parallel_categories(data_frame=new_df,
dimensions=['Is Weekend','weekdays','Day Time','hour'],
color='from_y',
labels={'weekdays':'Day in the Week','hour':'Hour in the Day'},
color_continuous_scale=px.colors.sequential.dense)
fig.layout['coloraxis']['colorbar']['title']['text']='Count'
fig.update_layout({'height':600})
fig.layout.margin={'t':30, 'l':10, 'r':10,'b':20}
return fig
# In[35]:
# f=generate_paco(email_df)
# f.layout.margin=['t':30, 'l':10, 'r':10]
# In[36]:
def generate_patient_volume_heatmap(start, end, hm_click, reset, weekdays, time):
"""
:param: start: start date from selection.
:param: end: end date from selection.
:param: clinic: clinic from selection.
:param: hm_click: clickData from heatmap.
:param: admit_type: admission type from selection.
:param: reset (boolean): reset heatmap graph if True.
:return: Patient volume annotated heatmap.
"""
# filtered_df = df[
# (df["Clinic Name"] == clinic) & (df["Admit Source"].isin(admit_type))
# ]
filtered_df = email_df.sort_values("date_es").set_index("date_es")[
start.astimezone(timezone('US/Eastern')):end.astimezone(timezone('US/Eastern'))
]
filtered_df = filtered_df[filtered_df.weekdays.isin(weekdays)]
filtered_df = filtered_df[filtered_df.hour.isin(time)]
x_axis = [datetime.time(i).strftime("%I %p")
for i in range(24)] # 24hr time list
y_axis = day_list
hour_of_day = ""
weekday = ""
shapes = []
if hm_click is not None:
hour_of_day = hm_click["points"][0]["x"]
weekday = hm_click["points"][0]["y"]
# Add shapes
x0 = x_axis.index(hour_of_day) / 24
x1 = x0 + 1 / 24
y0 = y_axis.index(weekday) / 7
y1 = y0 + 1 / 7
shapes = [
dict(
type="rect",
xref="paper",
yref="paper",
x0=x0,
x1=x1,
y0=y0,
y1=y1,
line=dict(color="#ff6347"),
)
]
z = np.zeros((7, 24))
annotations = []
for ind_y, day in enumerate(y_axis):
filtered_day = filtered_df[filtered_df["weekdays"] == day]
for ind_x, x_val in enumerate(x_axis):
sum_of_record = len(filtered_day[filtered_day["hour"] == x_val])
z[ind_y][ind_x] = sum_of_record
annotation_dict = dict(
showarrow=False,
text="<b>" + str(sum_of_record) + "<b>",
xref="x",
yref="y",
x=x_val,
y=day,
font=dict(family="sans-serif"),
)
# Highlight annotation text by self-click
if x_val == hour_of_day and day == weekday:
if not reset:
annotation_dict.update(size=15, font=dict(color="#ff6347"))
annotations.append(annotation_dict)
hovertemplate = "<b> %{y} %{x} <br><br> %{z} Emails"
data = [
dict(
x=x_axis,
y=y_axis,
z=z,
type="heatmap",
name="",
hovertemplate=hovertemplate,
showscale=False,
colorscale=[[0, "#caf3ff"], [1, "#2c82ff"]],
)
]
layout = dict(
margin=dict(l=70, b=30, t=50, r=50),
modebar={"orientation": "v"},
font=dict(family="Open Sans"),
annotations=annotations,
shapes=shapes,
xaxis=dict(
side="top",
ticks="",
ticklen=2,
tickfont=dict(family="sans-serif"),
tickcolor="#ffffff",
),
yaxis=dict(
side="left", ticks="", tickfont=dict(family="sans-serif"), ticksuffix=" "
),
hovermode="closest",
showlegend=False,
)
return {"data": data, "layout": layout}
# In[37]:
def generate_hist(start,end, weekdays,time):
df=email_df.copy()
df['date_pure']=df.date_es.dt.date
df=df.sort_values("date_pure").set_index("date_pure")
df['selected']=False
# print(df)
# df.loc[~df.weekdays.isin(weekdays),'selected']=False
# df.loc[~df.hour.isin(time),'selected']=False
df.loc[pd.to_datetime(start).date():pd.to_datetime(end).date(),'selected']=True
df.loc[~df.weekdays.isin(weekdays),'selected']=False
df.loc[~df.hour.isin(time),'selected']=False
df=df.reset_index()
fig=px.histogram(df, "date_es", color='selected', marginal="rug", nbins=12,
height=400,
color_discrete_map={
True: "rgb(166,206,227)", False: "rgb(31,120,180)"
},
)
fig.update_layout(margin=dict(l=2, r=2, t=2, b=2), height=200)
fig.layout.xaxis.title.text=None
fig.layout.yaxis.title.text='Count'
# fig.layout.legend['orientation']='h'
# fig.update_layout(legend=dict(x=0.25, y=-0.25))
fig.data[0]['nbinsx']=20
return fig
# In[38]:
# fig=generate_hist('2020-03-15', '2020-06-15', day_list, ['12 PM'])
# fig.layout.xaxis.title.text=None
# fig.layout.margin.l=30
# fig.data
# In[39]:
from tick.hawkes import (SimuHawkes, HawkesKernelTimeFunc, HawkesKernelExp,
HawkesEM, SimuHawkesSumExpKernels, HawkesSumExpKern,HawkesExpKern)
from tick.plot import plot_point_process
import itertools
import plotly.tools as tls
def haweks(learner, pre_days):
test_time = (email_df.date_es.sort_values() -
email_df.date_es.min()).astype('timedelta64[h]')/24.0
timestamps = [test_time.to_numpy(dtype='double')]
best_score = -1e100
decay_candidates = np.logspace(0, 6, 20)
if learner == 'Exponential':
for i, decay in enumerate(decay_candidates):
hawkes_learner = HawkesExpKern(decay, verbose=False, max_iter=10000,
tol=1e-10)
# hawkes_learner = HawkesSumExpKern(decays=[6])
hawkes_learner.fit(timestamps)
hawkes_score = hawkes_learner.score()
if hawkes_score > best_score:
print('obtained {}\n with {}\n'.format(hawkes_score, decay))
best_hawkes = hawkes_learner
best_score = hawkes_score
elif learner == 'ExponentialSum':
decay_candidates = np.logspace(0, 3, 10)
for i, decays in enumerate(itertools.combinations(decay_candidates, 3)):
# Each time we test a different set of 3 decays.
decays = np.array(decays)
hawkes_learner = HawkesSumExpKern(decays, verbose=False, max_iter=10000,
tol=1e-10)
# hawkes_learner._prox_obj.positive = False
hawkes_learner.fit(timestamps)
hawkes_score = hawkes_learner.score()
if hawkes_score > best_score:
print('obtained {}\n with {}\n'.format(hawkes_score, decays))
best_hawkes = hawkes_learner
best_score = hawkes_score
simu = best_hawkes._corresponding_simu()
simu.seed=2020
simu.track_intensity(0.01)
simu.set_timestamps([test_time.to_numpy(dtype='double')])
simu.end_time = 100+pre_days
simu.simulate()
# process = plot_point_process(simu, plot_intensity=True)
plotly_fig = tls.mpl_to_plotly(plot_point_process(simu, plot_intensity=True))
return seperate(plotly_fig)
# In[40]:
import plotly.graph_objects as go
def seperate(f):
original_f= go.Figure(f)
cop_f= go.Figure(f)
new_color='rgba(63, 191, 63, 0.4)'
cop_f.data[0]['x']=tuple(filter(lambda x: x > 100, cop_f.data[0]['x']))
cop_f.data[0]['y']=cop_f.data[0]['y'][len(cop_f.data[0]['y'])-len(cop_f.data[0]['x']):]
cop_f.data[1]['x']=tuple(filter(lambda x: x > 100, cop_f.data[1]['x']))
cop_f.data[1]['y']=cop_f.data[1]['y'][len(cop_f.data[1]['y'])-len(cop_f.data[1]['x']):]