-
Notifications
You must be signed in to change notification settings - Fork 4
/
cooccurrence.py
69 lines (56 loc) · 2.7 KB
/
cooccurrence.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
import itertools
import scipy.stats
import pandas
def read_pmids_tsv(path, key, min_articles = 1):
term_to_pmids = dict()
pmids_df = pandas.read_table(path, compression='gzip')
pmids_df = pmids_df[pmids_df.n_articles >= min_articles]
for i, row in pmids_df.iterrows():
term = row[key]
pmids = row.pubmed_ids.split('|')
term_to_pmids[term] = set(pmids)
pmids_df.drop('pubmed_ids', axis=1, inplace=True)
return pmids_df, term_to_pmids
def score_pmid_cooccurrence(term0_to_pmids, term1_to_pmids, term0_name='term_0', term1_name='term_1', verbose=True):
"""
Find pubmed cooccurrence between topics of two classes.
term0_to_pmids -- a dictionary that returns the pubmed_ids for each term of class 0
term0_to_pmids -- a dictionary that returns the pubmed_ids for each term of class 1
"""
all_pmids0 = set.union(*term0_to_pmids.values())
all_pmids1 = set.union(*term1_to_pmids.values())
pmids_in_both = all_pmids0 & all_pmids1
total_pmids = len(pmids_in_both)
if verbose:
print('Total articles containing a {}: {}'.format(term0_name, len(all_pmids0)))
print('Total articles containing a {}: {}'.format(term1_name, len(all_pmids1)))
print('Total articles containing both a {} and {}: {}'.format(term0_name, term1_name, total_pmids))
term0_to_pmids = term0_to_pmids.copy()
term1_to_pmids = term1_to_pmids.copy()
for d in term0_to_pmids, term1_to_pmids:
for key, value in list(d.items()):
d[key] = value & pmids_in_both
if not d[key]:
del d[key]
if verbose:
print('\nAfter removing terms without any cooccurences:')
print('+ {} {}s remain'.format(len(term0_to_pmids), term0_name))
print('+ {} {}s remain'.format(len(term1_to_pmids), term1_name))
rows = list()
for term0, term1 in itertools.product(term0_to_pmids, term1_to_pmids):
pmids0 = term0_to_pmids[term0]
pmids1 = term1_to_pmids[term1]
a = len(pmids0 & pmids1)
b = len(pmids0) - a
c = len(pmids1) - a
d = total_pmids - len(pmids0 | pmids1)
contingency_table = [[a, b], [c, d]]
expected = len(pmids0) * len(pmids1) / total_pmids
enrichment = a / expected
oddsratio, pvalue = scipy.stats.fisher_exact(contingency_table, alternative='greater')
rows.append([term0, term1, a, expected, enrichment, oddsratio, pvalue])
columns = [term0_name, term1_name, 'cooccurrence', 'expected', 'enrichment', 'odds_ratio', 'p_fisher']
df = pandas.DataFrame(rows, columns=columns)
if verbose:
print('\nCooccurrence scores calculated for {} {} -- {} pairs'.format(len(df), term0_name, term1_name))
return df