Array3022 commited on
Commit
d62ad66
·
0 Parent(s):

2024-02-14 Release Updates

Browse files
.devcontainer/devcontainer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:06beaca5feb5e2c110677a1d907d4a914d136c7a13cbc1335efdd556b3225079
3
+ size 1187
.gitattributes ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ *.json filter=lfs diff=lfs merge=lfs -text
2
+ *.pkl.bz2 filter=lfs diff=lfs merge=lfs -text
3
+ *.mp4 filter=lfs diff=lfs merge=lfs -text
.vscode/settings.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc82b5393cad6eac5b74380d8834f45ace4c2d3022fa81c8ae83705a8667f69a
3
+ size 475
01_Introduction.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+
3
+ st.set_page_config(page_title='The PubMed Topic Modeling Toolkit')
4
+
5
+ # Introduction
6
+ st.title('The PubMed Topic Modeling Toolkit')
7
+ st.caption('By [Brice Bowrey](https://bowrey.info)')
8
+ st.caption('Developed with support from the NLM Michael E. DeBakey Fellowship in the History of Medicine.')
9
+ st.caption('''\nThis is a stable release of a project that may see continued development.
10
+ If you have suggestions, advice, or an interest in collaborating/contributing, please contact me at bowrey[at]umd.edu.''')
11
+
12
+ st.header('Introduction & Tutorial Video')
13
+
14
+ st.markdown('''This short video will provide an introduction to this site.
15
+ If you'd like to learn more about topic modeling or the inner workings of the software,
16
+ read the brief descriptions below. If you'd like to run the application locally to make changes
17
+ or get better performance, please see the information in the `README.md` file in the Hugging Face Files tab.''')
18
+
19
+ with open('PubmedTM_Tutorial_1440p.mp4', 'rb') as video:
20
+ video_bytes = video.read()
21
+ st.video(video_bytes)
22
+
23
+ # About Topic Modeling
24
+ st.header('About Topic Modeling')
25
+
26
+ st.subheader('Vocabulary')
27
+ st.markdown('''**Corpus**: a set of documents or texts. In this tool, the corpus consists of a approximately 300,000 abstracts related to biomedical technology. These abstracts were published between 1950 and 2000 and retried from the PubMed index.
28
+
29
+ **Topic**: a cluster of related documents, as defined by the model.
30
+
31
+ **Model**: the computational engine that produces topics and information about the documents inside topics.
32
+
33
+ **Cosine Similarity**: a measure of the similarity between two pieces of text that is independent of the length of the texts. Possible values range between negative one (-1) and positive one (1). Two texts are more similar the closer the cosine similarity is to one (1). In this tool, cosine similarity is often presented to measure how closely returned results match a query.
34
+ ''')
35
+
36
+ st.subheader('Topic Modeling')
37
+ st.markdown('''Topic modeling uses statistics and machine learning to identify clusters of related
38
+ words and texts (e.g., text within the same “topic”) in a corpus. Topic modeling is mostly
39
+ “unsupervised,” which means that the researcher does not tell the algorithm how it
40
+ should label the data. While this technique leverages quantitative tools, there is still significant humanistic inquiry involved in
41
+ producing and interpreting the model. The algorithm identifies related texts,
42
+ but the user must determine how and why those texts are related. In other words,
43
+ the user has to determine what a topic is “about.”
44
+ ''')
45
+ st.markdown('''Because the meaning of a topic is a matter of interpretation, this tool
46
+ identifies topics using numbers, not names. When presented with a topic,
47
+ you will see a list of words that are most associated with that topic.
48
+ From those words and the documents linked to that topic, you can make your own
49
+ judgment about a topic's meaning. Keep in mind that some topics might just
50
+ be noise or outliers.
51
+ ''')
52
+ st.markdown('''For more detailed discussion of topic modeling in humanities and social science research, see:
53
+
54
+ * Mohr, John W., and Petko Bogdanov. “Introduction—Topic Models: What They Are and Why They Matter.” _Poetics_ 41, no. 6 (December 2013): 545–69. [https://doi.org/10.1016/j.poetic.2013.10.001](https://doi.org/10.1016/j.poetic.2013.10.001).
55
+
56
+ * Goldstone, Andrew, and Ted Underwood. “The Quiet Transformations of Literary Studies: What Thirteen Thousand Scholars Could Tell Us.” _New Literary History_ 45, no. 3 (2014): 359–84. [https://doi.org/10.1353/nlh.2014.0025](https://doi.org/10.1353/nlh.2014.0025).
57
+
58
+ * Hannigan T.R., Glaser V.L., Wang M.S., Jennings P.D., Haan R.F.J., Vakili K., Tchalian H., and Kaplan S. “Topic Modeling in Management Research: Rendering New Theory from Textual Data.” _Academy of Management Annals_ 13, no. 2 (2019): 586–632. [https://doi.org/10.5465/annals.2017.0099](https://doi.org/10.5465/annals.2017.0099).
59
+ ''')
60
+ st.markdown('''This tool was created using Top2Vec. This algorithm avoids the need
61
+ for significant pre-processing of the text. This was advantageous due to the difficulty
62
+ of using existing tools to clean and pre-process the unique and
63
+ discipline-specific jargon in the corpus. For more on Top2Vec, see:
64
+
65
+ * Angelov, Dimo. “Top2Vec: Distributed Representations of Topics,” August 19, 2020. [https://doi.org/10.48550/ARXIV.2008.09470](https://doi.org/10.48550/ARXIV.2008.09470).
66
+
67
+ * Egger, Roman, and Joanne Yu. “A Topic Modeling Comparison Between LDA, NMF, Top2Vec, and BERTopic to Demystify Twitter Posts.” _Frontiers in Sociology_ 7 (May 6, 2022): 886498. [https://doi.org/10.3389/fsoc.2022.886498](https://doi.org/10.3389/fsoc.2022.886498)
68
+ ''')
2024-02-14_22_19_09_reduced__model_medline0[test,mincount_250,topicmergedelta_0.15,ngram_True,ngramvocab_args_250_.4_80M_npmi_connector].json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f1c4c7f40220fac2edc20e62ace22ea502111d4cc2d3279aa925c8423f208d7
3
+ size 869721267
PubmedTM_Tutorial_1440p.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:65967427b9da1a3317a3de1fe3a12d4004002295f8ebbff38ea78c9c7150b635
3
+ size 50886721
README.md ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: The PubMed Topic Modeling Toolkit
3
+ emoji: ⚕ # STAFF OF AESCULAPIUS (U+2695)
4
+ colorFrom: gray
5
+ colorTo: gray
6
+ sdk: streamlit
7
+ sdk_version: 1.26.0
8
+ python_version: 3.11.4
9
+ app_file: 01_Introduction.py
10
+ pinned: false
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
14
+
15
+ ### Local Install
16
+
17
+ For optimal performance, run this application locally on a computer with a performant CPU and at least 16GB of RAM. Using Dev Containers within Visual Studio Code (VS Code) is the easiest way to run the application on locally. To get started, follow [this](https://code.visualstudio.com/docs/devcontainers/tutorial) tutorial until the "Check Installation" step.
18
+
19
+ Next, download all the files in this repository to your computer, preserving the file structure in the process. To my knowledge, Hugging Face does not provide a way to do this via the GUI other than downloading each file individually. If you are comfortable with the terminal, you can clone the repository using [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) and [Git-lfs](https://docs.github.com/en/repositories/working-with-files/managing-large-files/installing-git-large-file-storage?platform=windows).
20
+
21
+ Once you've downloaded the files, open the folder containing the files in VS Code. You should be prompted to reopen the folder in a container. If not, press F1, search for, then select the option "Dev Containers: Reopen in Container."
22
+
23
+ Wait for the container to build and install the requirements. This could take five to ten minutes depending on the internet connection and hardware. Once the container is ready, run the application by typing `streamlit run 01_Introduction.py` in the terminal at the bottom of VS Code. The application should open in your default browser automatically.
24
+
25
+ ### Troubleshooting
26
+
27
+ - If the container fails to build, look for a part of the error message that says `"bind": bind source path does not exist:` then delete the wayland-0 and wayland-0.lock files in the path specified by that portion of the error. On a default Ubuntu installation, the path is `/run/user/1000/wayland-0`. This advice is taken from [here](https://dev.to/crumdev/vscode-dev-container-failing-to-build-ap4).
28
+ - If the app starts to run in the Dev Container but spontaneously kills itself, increase the maximum RAM and SWAP allocations in the Docker Desktop application settings.
medline_0_df_nlp.pkl.bz2 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:14ab46560c6f85637776fb580d8724433918e5f75c9e9f05860303c9bbe039bc
3
+ size 195577628
pages/02_Explore_Topics.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ from top2vec import Top2Vec
4
+ from wordcloud import WordCloud
5
+
6
+ @st.cache_resource
7
+ def load_model():
8
+ name = '2024-02-14_22_19_09_reduced__model_medline0[test,mincount_250,topicmergedelta_0.15,ngram_True,ngramvocab_args_250_.4_80M_npmi_connector].json'
9
+ with open(name, 'rb') as f:
10
+ return Top2Vec.load(f)
11
+
12
+ @st.cache_data
13
+ def load_data():
14
+ df = pd.read_pickle('medline_0_df_nlp.pkl.bz2', compression='bz2')
15
+ return df
16
+
17
+ # Notification of loading
18
+ start_container = st.empty()
19
+ if 'first' not in st.session_state:
20
+ st.session_state['first'] = True
21
+
22
+ if st.session_state['first'] == True:
23
+ start_container.text('Loading model and data... This may take two to three minutes on the initial run.')
24
+ st.session_state['first'] = False
25
+
26
+ # Load the model and data
27
+ model = load_model()
28
+ df = load_data()
29
+
30
+ # Remove loading notification
31
+ start_container.empty()
32
+
33
+ # User interface
34
+ with st.sidebar.form('Explore Topics', clear_on_submit=False):
35
+ st.write('Input a search term(s) separated by a space and receive the topics that are most semantically similar.')
36
+ txt_et = st.text_area('Keyword(s) or Phrase(s)')
37
+ num_et = st.number_input('Number of topics to return',
38
+ min_value=1,
39
+ max_value=model.get_num_topics(reduced=True), # Number of topics in the reduced model
40
+ value=10) # Default value is 10
41
+ submitted_et = st.form_submit_button("Submit")
42
+ if submitted_et:
43
+ txt_et_list = txt_et.split()
44
+ topic_words, word_scores, topic_scores, topic_nums = model.search_topics(txt_et_list, num_topics=num_et, reduced=True)
45
+ for i, topic in enumerate(topic_nums):
46
+ st.subheader('Topic Number: ' + str(topic))
47
+ st.write('Search Cosine Similarity: ' + str(topic_scores[i]))
48
+ st.write('Topic Words:', ', '.join(topic_words[i][:10]))
49
+
50
+ # Top documents for each topic
51
+ with st.expander('Top Documents in Topic'):
52
+ _, document_ids = model.search_documents_by_topic(topic_num=topic, reduced=True, num_docs=10)
53
+ for id in document_ids:
54
+ st.markdown(f'[{df.at[id, "TI"]}](https://pubmed.ncbi.nlm.nih.gov/{df.at[id, "PMID"]})')
55
+
56
+
57
+ # Wordcloud
58
+ new_dict = {}
59
+ for ii, words in enumerate(topic_words[i]):
60
+ new_dict[words] = word_scores[i][ii]
61
+ st.image(WordCloud(width=850, height=250,
62
+ background_color='white',
63
+ prefer_horizontal=0.7).generate_from_frequencies(new_dict).to_image())
pages/03_Explore_Documents.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ from top2vec import Top2Vec
4
+
5
+
6
+ # def append_dict(data):
7
+ # # Create df with author info
8
+ # author_df = pd.DataFrame(columns=['Name', 'Affiliation'])
9
+ # for i, item in enumerate(data):
10
+ # author_df.at[i, 'Name'] = item['name']
11
+ # if item['affiliation'] is not None:
12
+ # author_df.at[i, 'Affiliation'] = item['affiliation']
13
+ # else:
14
+ # author_df.at[i, 'Affiliation'] = ''
15
+
16
+ # # Find longest affiliation string
17
+ # max_affiliation = 0
18
+ # for item in author_df['Affiliation']:
19
+ # if len(item) > max_affiliation:
20
+ # max_affiliation = len(item)
21
+
22
+ # # Add space to affiliation strings to match longest string
23
+ # for i, item in enumerate(author_df['Affiliation']):
24
+ # author_df.at[i, 'Affiliation'] = item + ' ' * (max_affiliation - len(item))
25
+
26
+ # # Change index to start at 1
27
+ # author_df.index = author_df.index + 1
28
+
29
+ # return author_df
30
+
31
+
32
+ @st.cache_resource
33
+ def load_model():
34
+ name = '2024-02-14_22_19_09_reduced__model_medline0[test,mincount_250,topicmergedelta_0.15,ngram_True,ngramvocab_args_250_.4_80M_npmi_connector].json'
35
+ with open(name, 'rb') as f:
36
+ return Top2Vec.load(f)
37
+
38
+ @st.cache_data
39
+ def load_data():
40
+ df = pd.read_pickle('medline_0_df_nlp.pkl.bz2', compression='bz2')
41
+ return df
42
+
43
+ # Notification of loading
44
+ start_container = st.empty()
45
+ if 'first' not in st.session_state:
46
+ st.session_state['first'] = True
47
+
48
+ if st.session_state['first'] == True:
49
+ start_container.text('Loading model and data... This may take two to three minutes on the initial run.')
50
+ st.session_state['first'] = False
51
+
52
+ # Load the model and data
53
+ model = load_model()
54
+ df = load_data()
55
+
56
+ # Remove loading notification
57
+ start_container.empty()
58
+
59
+ # User interface
60
+ with st.sidebar.form('Explore Documents', clear_on_submit=False):
61
+ st.write('Input a search term(s) separated by a space and receive the documents that are most semantical similar.')
62
+ txt_ed = st.text_area('Keyword(s) or Phrase(s)')
63
+ num_ed = st.number_input('Number of documents to return',
64
+ min_value=1,
65
+ max_value=50,
66
+ value=10) # Default value is 10
67
+ submitted_ed = st.form_submit_button("Submit")
68
+ if submitted_ed:
69
+ txt_ed_list = txt_ed.split()
70
+ doc_scores, doc_ids = model.search_documents_by_keywords(txt_ed_list, num_docs=num_ed)
71
+ for i, doc in enumerate(doc_ids):
72
+ st.header(f'{df.at[doc, "TI"]}')
73
+ with st.expander('See more'):
74
+ # st.write('Authors:', f'{df.at[doc, "AU"]}')
75
+ st.write('Authors:', ','.join(df.at[doc, "AU"]).replace(',', ', '))
76
+ # st.dataframe(append_dict(df.iat[doc, 5]))
77
+ st.write('Year:', f'{df.at[doc, "DP"]}')
78
+ st.markdown(f'PMUID: [{df.at[doc, "PMID"]}](https://pubmed.ncbi.nlm.nih.gov/{df.at[doc, "PMID"]})')
79
+ st.write('Journal:', f'*{df.at[doc, "JT"]}*')
80
+ st.write('Journal Location:', f'{df.at[doc, "PL"]}')
81
+ st.write('Cosine Similarity:', str(doc_scores[i]))
82
+ st.write('Abstract:', f'{df.at[doc,"AB"]}')
83
+ st.write('Keywords:', '|'.join(df.at[doc, "MH"]).replace('|', ' | '))
pages/04_Topic_Prevalence.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import datetime
4
+ from top2vec import Top2Vec
5
+ from matplotlib import pyplot as plt
6
+
7
+ st.set_page_config(layout='wide')
8
+
9
+ def create_frequency_dataframe(dataframe, default, specific, year_start=1976, year_stop=2000):
10
+ '''Produces a dataframe with the number of articles in each topic in a each year.
11
+
12
+ Parameters
13
+ dataframe: Pandas dataframe containing the articles, abstracts, and dates.
14
+ default: String indicating which topics to include in the dataframe. Selected by user.
15
+ specific: String of additional topic numbers to include in the dataframe. Selected by user. Added to default.
16
+ year_start: Integer indicating the first year to include in the dataframe. Selected by user.
17
+ year_stop: Integer indicating the last year to include in the dataframe. Selected by user.
18
+
19
+ Returns
20
+ date_df: Pandas dataframe with the number of articles in each topic in a each year.
21
+ topic_columns: List of topic numbers included in the dataframe.
22
+ '''
23
+ topic_sizes, topic_nums = model.get_topic_sizes(reduced=True)
24
+ topic_columns = []
25
+ if default == 'Top 5':
26
+ topic_columns = topic_nums[:5]
27
+ elif default == 'Top 10':
28
+ topic_columns = topic_nums[:10]
29
+ elif default == 'Bottom 5':
30
+ topic_columns = topic_nums[-5:]
31
+ elif default == 'Bottom 10':
32
+ topic_columns = topic_nums[-10:]
33
+
34
+ topic_columns= list(topic_columns) + [int(i) for i in specific.split() if len(i) > 0] # Break input text into list of ints then merge lists
35
+
36
+ # Format df for number of articles in each topic in a given year
37
+ date_df = pd.DataFrame(index=range(year_start, year_stop + 1), columns=topic_columns)
38
+ for col in date_df.columns:
39
+ date_df[col].values[:] = 0 # Covert values from null to 0
40
+
41
+ #Year/index num correspondence
42
+ # index_dict = {}
43
+ # for i, year in enumerate(date_df.index.values):
44
+ # index_dict[year] = i
45
+
46
+ # Get doc_ids for each requested topic
47
+ for topic in topic_columns:
48
+ _, document_ids = model.search_documents_by_topic(topic_num=topic, reduced=True, num_docs=topic_sizes[topic]) # Works because topic number corresponds to its order in the topic size list
49
+ for id in document_ids:
50
+ if dataframe.at[id, 'DP'] >= datetime.date(year_start,1,1).year and dataframe.at[id, 'DP'] < datetime.date(year_stop + 1,1,1).year:
51
+ date_df.at[dataframe.at[id, 'DP'], topic] += 1
52
+
53
+ return date_df, topic_columns
54
+
55
+ def create_prevalence_dataframe(date_df):
56
+ date_df = date_df.join(date_df.apply(sum, axis=1).reindex_like(date_df.index.to_series()).rename('Sums')) # Sum the total number of articles in each year
57
+ # Find the percentage of total number of articles represented by each topic in each year
58
+ for i, row in zip(date_df.index.values, date_df['Sums']):
59
+ if row != 0:
60
+ date_df.loc[i, :] = (date_df.loc[i, :] / date_df.loc[i, 'Sums']) * 100
61
+ date_df = date_df.drop(columns='Sums')
62
+ return date_df
63
+
64
+ def create_plot(date_df, ylabel, title):
65
+ fig, ax = plt.subplots(figsize=(10, 5))
66
+ for topic in date_df.columns:
67
+ ax.plot(date_df.index.values, date_df.loc[:, topic].values, label=f'Topic {topic}')
68
+ ax.xaxis.set_major_locator(plt.MaxNLocator(integer=True)) # Only show whole numbers on x-axis
69
+ ax.set_xlabel('Year')
70
+ ax.set_ylabel(ylabel)
71
+ ax.set_title(title)
72
+ ax.legend(bbox_to_anchor=(1, 1))
73
+ ax.grid(True)
74
+ return fig
75
+
76
+ @st.cache_resource
77
+ def load_model():
78
+ name = '2024-02-14_22_19_09_reduced__model_medline0[test,mincount_250,topicmergedelta_0.15,ngram_True,ngramvocab_args_250_.4_80M_npmi_connector].json'
79
+ with open(name, 'rb') as f:
80
+ return Top2Vec.load(f)
81
+
82
+ @st.cache_data
83
+ def load_data():
84
+ df = pd.read_pickle('medline_0_df_nlp.pkl.bz2', compression='bz2')
85
+ return df
86
+
87
+ # Notification of loading
88
+ start_container = st.empty()
89
+ if 'first' not in st.session_state:
90
+ st.session_state['first'] = True
91
+
92
+ if st.session_state['first'] == True:
93
+ start_container.text('Loading model and data... This may take two to three minutes on the initial run.')
94
+ st.session_state['first'] = False
95
+
96
+ # Load the model and data
97
+ model = load_model()
98
+ df = load_data()
99
+
100
+ # Remove loading notification
101
+ start_container.empty()
102
+
103
+ # User Interface
104
+ with st.sidebar.form('Topic Prevalence', clear_on_submit=False):
105
+ default = st.radio('Default Topics', ['Top 5', 'Top 10', 'Bottom 5', 'Bottom 10', 'None'])
106
+ specific = st.text_input('Topic Numbers', help='''Enter a series of topic numbers to graph.
107
+ The numbers should be separated by a space.
108
+ Topic numbers are assigned in order of decreasing frequency across the corpus.
109
+ In other words, Topic 0 is the most frequent topic, Topic 1 is the second most frequent, etc.''')
110
+ year_start_tp, year_stop_tp = st.slider('Year Range',
111
+ min_value=1975,
112
+ max_value=2000,
113
+ value=[1975, 2000])
114
+ submitted_ed = st.form_submit_button("Submit")
115
+
116
+ st.markdown('### Glossary')
117
+ st.markdown('**Proportion of Articles:** The percentage of the total number of articles displayed that was in a given topic.')
118
+ st.markdown('**Topic Frequency**: The number of articles in a given topic.')
119
+
120
+ if submitted_ed:
121
+ frequency_df, topics = create_frequency_dataframe(dataframe = df,
122
+ default = default,
123
+ specific = specific,
124
+ year_start = year_start_tp,
125
+ year_stop = year_stop_tp)
126
+ frequency_plot = create_plot(frequency_df, 'Number of Articles in Topic', 'Topic Frequency by Year')
127
+ prevalence_df = create_prevalence_dataframe(frequency_df)
128
+ prevalence_plot = create_plot(prevalence_df, ylabel='Percent of all Articles (%)', title='Proportion of Articles in Topics by Year')
129
+
130
+ # Display data
131
+ col1, col2 = st.columns([3, 1])
132
+
133
+ with col1:
134
+ st.header('Proportion of Articles in Topics by Year - Graph')
135
+ st.pyplot(prevalence_plot)
136
+ st.divider()
137
+
138
+ st.header('Proportion of Articles in Topics by Year - Table')
139
+ st.dataframe(prevalence_df.T)
140
+ st.divider()
141
+
142
+ st.header('Topic Frequency by Year - Graph')
143
+ st.pyplot(frequency_plot)
144
+ st.divider()
145
+
146
+ st.header('Topic Frequency by Year - Table')
147
+ st.dataframe(frequency_df.T)
148
+ st.divider()
149
+
150
+ with col2:
151
+ st.header('Topic Information')
152
+ topic_words, _, topic_nums = model.get_topics(reduced=True)
153
+ for topic in topics:
154
+ st.write(f'Topic {topic}:', ', '.join(topic_words[topic][:10]))
155
+ st.divider()
pages/05_Text_Analysis.py ADDED
@@ -0,0 +1,626 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ from matplotlib import pyplot as plt
4
+ import stanza
5
+ from stanza import DownloadMethod
6
+
7
+ # Load data
8
+ @st.cache_data
9
+ def load_data():
10
+ df = pd.read_pickle('medline_0_df_nlp.pkl.bz2', compression='bz2')
11
+ return df
12
+
13
+ # Notification of loading
14
+ start_container = st.empty()
15
+ if 'first' not in st.session_state:
16
+ st.session_state['first'] = True
17
+
18
+ if st.session_state['first'] == True:
19
+ start_container.text('Loading model and data... This may take two to three minutes on the initial run.')
20
+ st.session_state['first'] = False
21
+
22
+ # Load the model and data
23
+ df = load_data()
24
+
25
+ # Remove loading notification
26
+ start_container.empty()
27
+
28
+ @st.cache_resource
29
+ def load_nlp():
30
+ # Download and initialize a genia pipeline with an anatem NER model
31
+ nlp = stanza.Pipeline('en', package='genia', processors=['tokenize', 'pos', 'lemma'],
32
+ use_gpu=True, ner_batch_size=128, tokenize_batch_size=128,
33
+ download_method=DownloadMethod.REUSE_RESOURCES, logging_level='WARN')
34
+ return nlp
35
+
36
+ ###### Helper Functions ######
37
+ def filter_by_year(data, year_start, year_end):
38
+
39
+ if year_start == None and year_end == None:
40
+ return data
41
+ elif year_start == None:
42
+ return data[data['DP'] <= year_end]
43
+ elif year_end == None:
44
+ return data[data['DP'] >= year_start]
45
+
46
+ else:
47
+ return data.loc[(data['DP'] >= year_start) & (data['DP'] <= year_end)]
48
+
49
+ def filter_tuples_by_entity_type(data, entity_type):
50
+ '''Filters out tuples in the NER column based on the specified entity type.'''
51
+
52
+ if entity_type == 'ALL': # Return all data
53
+ return data
54
+
55
+ data['NER'] = data['NER'].apply(lambda ner_list: [tup for tup in ner_list if tup[1] == entity_type]) # Return only tuples with the specified entity type
56
+
57
+ return data
58
+
59
+ def filter_by_country(data, country):
60
+ data = data[data['PL'] == country]
61
+ return data
62
+
63
+ def group_entity_by_year(data):
64
+
65
+ data_explode = data.explode('NER')
66
+ data_explode['NER'] = data_explode['NER'].apply(lambda x: x[0] if not type(x)==float else None) # Return none if the entity is NaN (which is seen as a float)
67
+ data_explode = data_explode.dropna(subset=['NER']) # Drop rows with None as the entity
68
+
69
+ records = zip(data_explode['DP'], data_explode['NER'])
70
+
71
+ entitiesDict = {} # {NER: [{year: count}, total_count]
72
+
73
+ for yr, name in records:
74
+ if name not in entitiesDict:
75
+ entitiesDict[name] = [{}, 0]
76
+ entityDict = entitiesDict[name][0]
77
+ if yr not in entityDict:
78
+ entityDict[yr] = 0
79
+ entityDict[yr] += 1
80
+ entitiesDict[name][1] += 1
81
+
82
+ return entitiesDict
83
+
84
+ def group_journal_by_year(data):
85
+ # records = []
86
+ # for idx, row in data.iterrows():
87
+ # year = row['DP']
88
+ # journal_title = row['JT']
89
+ # journal_id = row['JID']
90
+ # records.append((year, journal_id, journal_title))
91
+
92
+ records = zip(data['DP'], data['JID'], data['JT'])
93
+ journalsDict = {} # {JID: [{DP: count}, total_count, JT]
94
+
95
+ for yr, jid, title in records:
96
+ if jid not in journalsDict:
97
+ journalsDict[jid] = [{}, 0, title]
98
+ journalDict = journalsDict[jid][0]
99
+ if yr not in journalDict:
100
+ journalDict[yr] = 0
101
+ journalDict[yr] += 1
102
+ journalsDict[jid][1] += 1
103
+
104
+ return journalsDict
105
+
106
+ def group_mesh_by_year(data):
107
+ data_explode = data.explode('MH')
108
+ data_explode = data_explode.dropna(subset=['MH']) # Drop rows with NaN as the entity
109
+ records = zip(data_explode['DP'], data_explode['MH'])
110
+
111
+ meshesDict = {}
112
+ for yr, word in records:
113
+ # Add mesh term if it does not exist in the dictionary
114
+ if word not in meshesDict:
115
+ meshesDict[word] = [{}, 0] # Create new entry prepared for the year count. {word: [{year: count}, total_count]}
116
+
117
+ # Update the year count
118
+ single_meshDict = meshesDict[word][0] # Access the subdictionary in each entry
119
+
120
+ if yr not in single_meshDict:
121
+ single_meshDict[yr] = 0
122
+ single_meshDict[yr] += 1
123
+ meshesDict[word][1] += 1 # Update the total count
124
+
125
+ return meshesDict
126
+
127
+ # def find_occurrence(list, target): # Finds the index of the first occurrence of an element in a list which contains tuples
128
+ # index = 0
129
+ # for element in list:
130
+ # if element[0] == target:
131
+ # return index
132
+ # index += 1
133
+
134
+ ###### Collocation Functions ######
135
+ def find_collocation(word, texts, n):
136
+ # Could work on allowing user to enter list of words.
137
+ # Could remove small strings (e.g. "'s") from ngrams.
138
+ # 'America' and 'American' are different words, but 'America' and 'Americans' lemmatize to different words, which is somewhat unexpected behavior to me.
139
+ '''
140
+ Finds neighboring words/n-grams of given word in text.
141
+
142
+ Parameters:
143
+ word (str): Word to find n-grams of.
144
+ texts (list): List of strings to search for n-grams.
145
+ n (int): Number of words to include in n-gram.
146
+
147
+ Returns:
148
+ (dict): Dictionary of n-grams with word as key and count as value.
149
+ '''
150
+ # Find n-grams and create dictionary of n-grams
151
+ ngrams = {}
152
+ for text in texts:
153
+ if word in text:
154
+ i = text.index(word)
155
+ for j in range(1, n+1): # Get required number of words before and after word based on n-gram count specified
156
+ if i-j >= 0:
157
+ if text[i-j] in ngrams:
158
+ ngrams[text[i-j]] += 1
159
+ else:
160
+ ngrams[text[i-j]] = 1
161
+ try:
162
+ if text[i+j] in ngrams:
163
+ ngrams[text[i+j]] += 1
164
+ else:
165
+ ngrams[text[i+j]] = 1
166
+ except IndexError:
167
+ pass
168
+ return dict(sorted(ngrams.items(), key=lambda x:x[1], reverse=True))
169
+
170
+ # def create_plot(dictionary, word, number_of_items=10):
171
+ # '''Creates a bar chart of the frequency of the items in the dictionary'''
172
+
173
+ # fig, ax = plt.subplots()
174
+ # ax.bar(x=list(dictionary.keys())[:number_of_items], height=list(dictionary.values())[:number_of_items], align='center')
175
+ # # ax.set_xticklabels(labels=list(dictionary.keys())[:number_of_items], rotation=45)
176
+ # ax.tick_params(axis='x', rotation=45) # Rotates x-axis labels
177
+ # ax.set_xlabel('Words')
178
+ # ax.set_ylabel('Frequency')
179
+ # ax.set_title('Frequency of Words Surrounding ' + '"' + word + '"')
180
+ # return fig
181
+
182
+ def run_collocation(word, degree, dataframe=df, number_of_items=10):
183
+ nlp = load_nlp()
184
+
185
+ # Lemmatize input word
186
+ process_word = nlp(word)
187
+ lemma = process_word.sentences[0].words[0].lemma
188
+
189
+ # Find ngrams
190
+ ngrams = find_collocation(word=lemma, texts=dataframe['lemma_AB'], n=degree)
191
+
192
+ # Plot ngrams
193
+ fig, ax = plt.subplots()
194
+ ax.bar(x=list(ngrams.keys())[:number_of_items], height=list(ngrams.values())[:number_of_items], align='center')
195
+ # ax.set_xticklabels(labels=list(dictionary.keys())[:number_of_items], rotation=45)
196
+ ax.tick_params(axis='x', rotation=45) # Rotates x-axis labels
197
+ ax.set_xlabel('Words')
198
+ ax.set_ylabel('Frequency')
199
+ ax.set_title('Frequency of Words Surrounding ' + '"' + word + '"')
200
+ return fig
201
+ # return create_plot(ngrams, word)
202
+
203
+ ###### Journal Analytics Functions ######
204
+ def jid_frequency(data=df, year_start=1975, year_end=2000, n=15):
205
+ '''
206
+ Returns the frequency of the top n most common journal IDs in a given year range.
207
+ '''
208
+ jid_dict = {}
209
+ added = set() # List used to keep track of all of the items which have already been added to the jid_dict
210
+
211
+ dates = data['DP'].tolist()
212
+ jid = data['JID'].tolist()
213
+ index = 0
214
+ for item in jid:
215
+ if dates[index] >= year_start and dates[index] <= year_end:
216
+ if item in added: # jid is already in the dictionary
217
+ jid_dict[item] += 1
218
+ else:
219
+ jid_dict[item] = 1
220
+ added.add(item)
221
+ index += 1
222
+
223
+ # display(jid_dict) # Used for testing and debugging
224
+ jid_df = pd.DataFrame.from_dict(jid_dict, orient='index', columns=['Frequency'])
225
+ jid_df.sort_values(by=['Frequency'], inplace=True, ascending=False)
226
+ jid_df = jid_df.head(n)
227
+
228
+ # Create matplotlib figure from dataframe
229
+ fig, ax = plt.subplots()
230
+ ax.barh(y=jid_df.index, width=jid_df['Frequency'], align='center')
231
+ ax.bar_label(ax.containers[0], fmt='%d', label_type='edge')
232
+ ax.set_xlim(right=jid_df['Frequency'].max() + jid_df['Frequency'].max()*0.08) # Prevents labels from overlapping with border in most cases; increase the number if needed
233
+ ax.set_title('Top {} Most Common JID\'s of Publications'.format(n))
234
+ ax.set_xlabel('Number of publications')
235
+ ax.set_ylabel('Journal NlmId/JID')
236
+ return fig
237
+ # jid_df.plot(kind='barh', figsize=(10, 10),
238
+ # title='Top {} Most Common JID\'s of Publications'.format(n),
239
+ # legend=True,
240
+ # xlabel='Number of publications',
241
+ # ylabel='Journal NlmId/JID',
242
+ # )
243
+ # # display(jid_df)
244
+ # return(jid_df)
245
+
246
+ def jid_frequency_by_year(data=df, year_start=1975, year_end=2000, n=15):
247
+ '''
248
+ Creates a line graph showing the frequency at which the most common n JIDs appear in the dataset for each year in given year range.
249
+
250
+ Parameters
251
+ data: the medline dataframe
252
+ n: int. The number of journals to display.
253
+ year_start: int. The start of the year range to display. Years for each data point are taken from the 'DP' column.
254
+ year_end: int. The end of the year range to display. Can be the same as year_start.
255
+
256
+ Returns
257
+ Matplotib figure object.
258
+ '''
259
+
260
+ filtered_by_year = filter_by_year(data, year_start, year_end)
261
+ journalsDict = group_journal_by_year(filtered_by_year)
262
+ sortedJournals = sorted(journalsDict.items(), key = lambda x: x[1][1], reverse = True)
263
+ topJournals = sortedJournals[0:n]
264
+
265
+ df = pd.DataFrame()
266
+
267
+ # Convert the dictionary to a Series and assign it to a new column in the DataFrame
268
+ for jid, data in topJournals:
269
+ yearly_data = data[0]
270
+ # title = data[2]
271
+ df[jid] = pd.Series(yearly_data)
272
+
273
+ # Fill NaN values with 0, in case some entities don't have data for all years
274
+ df = df.fillna(0)
275
+
276
+ # Debug
277
+ # display(df)
278
+
279
+ # Create a figure and axes
280
+ fig, ax = plt.subplots()
281
+
282
+ # Plot the data on the axes objects
283
+ for column in df.columns:
284
+ x, y = zip(*sorted(zip(df.index, df[column].values))) # Must sort the data before plotting it; https://stackoverflow.com/questions/37414916/matplotlib-plotting-in-wrong-order
285
+ ax.plot(x, y, marker='o', label=column)
286
+ # ax.plot(df.index, df[column].values)
287
+
288
+ # Set plot details
289
+ ax.set_title("Journal Frequencies by Year")
290
+ ax.set_xlabel("Year")
291
+ ax.set_ylabel("Frequency")
292
+ ax.grid(True)
293
+ ax.legend()
294
+
295
+ # ax.set_xticks([tick for tick in ax.get_xticks() if tick.is_integer()])
296
+ # ax.set_yticks([tick for tick in ax.get_yticks() if tick.is_integer()])
297
+
298
+ return fig
299
+
300
+ def pl_frequency(data=df, year_start=1975, year_end=2000, n=15):
301
+ '''
302
+ Returns the frequency of the top n most common places of publication in a given year range.
303
+ '''
304
+ pl_dict = {}
305
+ added = set() # List used to keep track of all of the items which have already been added to the ner_dict
306
+
307
+ dates = data['DP'].tolist()
308
+ pl = data['PL'].tolist()
309
+ # display(pl)
310
+ index = 0
311
+ for item in pl:
312
+ if dates[index] >= year_start and dates[index] <= year_end:
313
+ if item in added: # pl is already in the dictionary
314
+ pl_dict[item] += 1
315
+ else:
316
+ pl_dict[item] = 1
317
+ added.add(item)
318
+ index += 1
319
+
320
+ #display(pl_dict) # Used for testing and debugging
321
+ pl_df = pd.DataFrame.from_dict(
322
+ pl_dict, orient='index', columns=['Frequency'])
323
+ pl_df.sort_values(by=['Frequency'], inplace=True, ascending=False)
324
+ pl_df = pl_df.head(n)
325
+
326
+ # Create matplotlib figure from dataframe
327
+ fig, ax = plt.subplots()
328
+ ax.barh(y=pl_df.index, width=pl_df['Frequency'], align='center')
329
+ ax.bar_label(ax.containers[0], fmt='%d', label_type='edge')
330
+ ax.set_xlim(right=pl_df['Frequency'].max() + pl_df['Frequency'].max()*0.10) # Prevents labels from overlapping with border in most cases; increase the number if needed
331
+ ax.set_title('Top {} Most Common Places of Publications'.format(n))
332
+ ax.set_xlabel('Number of publications')
333
+ ax.set_ylabel('Journal NlmId/JID')
334
+ return fig
335
+
336
+ ###### Named Biological Entities Functions ######
337
+ def ner_frequency(data=df, n=15, entity_toggle='ALL', year_start=1975, year_end=2000):
338
+ """
339
+ Displays the frequency of the top n most common named entities in a graph.
340
+
341
+ Parameters
342
+ data: the medline dataframe (or a subset of it)
343
+ n: int. The number of entities to display.
344
+ entity_toggle: str. The type of entity to display. This info is stored in the tuples in the 'ner' column.
345
+ Options are 'ALL', 'ANATOMY', 'DISEASE'. If 'ALL', displays all entities.
346
+ year_start: int. The start of the year range to display.
347
+ year_end: int. The end of the year range to display. Can be the same as year_start.
348
+
349
+ """
350
+
351
+ # Function can be slow. Could be improved by using group_entity_by_year() then counting the number of times each year appears.
352
+ ner_dict = {}
353
+ added = set() # List used to keep track of all of the items which have already been added to the ner_dict
354
+
355
+ dates = data['DP'].tolist()
356
+ ner = data['NER'].tolist()
357
+
358
+ index = 0
359
+ for item in ner:
360
+ if dates[index] >= year_start and dates[index] <= year_end:
361
+ for tup in item:
362
+ if entity_toggle == 'ALL' or entity_toggle == tup[1]:
363
+ ner = tup[0]
364
+ if ner in added: # ner is already in the dictionary
365
+ ner_dict[ner] += 1
366
+ else:
367
+ ner_dict[ner] = 1
368
+ added.add(ner)
369
+ index += 1
370
+
371
+ # display(ner_dict) # Used for testing and debugging
372
+ ner_df = pd.DataFrame.from_dict(
373
+ ner_dict, orient='index', columns=['Frequency'])
374
+ ner_df.sort_values(by=['Frequency'], inplace=True, ascending=False)
375
+ ner_df = ner_df.head(n)
376
+
377
+ fig, ax = plt.subplots()
378
+ ax.barh(y=ner_df.index, width=ner_df['Frequency'], align='center')
379
+ ax.bar_label(ax.containers[0], fmt='%d', label_type='edge')
380
+ ax.set_xlim(right=ner_df['Frequency'].max() + ner_df['Frequency'].max()*0.08) # Prevents labels from overlapping with border in most cases; increase the number if needed
381
+ if entity_toggle == 'ALL':
382
+ ax.set_title('Top {} Most Common Named Biological Entities'.format(n))
383
+ else:
384
+ ax.set_title('Top {} Most Common Named {} Entities'.format(n, entity_toggle.lower().capitalize()))
385
+ ax.set_xlabel('Number of publications')
386
+ ax.set_ylabel('Journal NlmId/JID')
387
+ return fig
388
+
389
+ def ner_frequency_by_year(data=df, n=15, entity_toggle='ALL', year_start=1975, year_end=2000) :
390
+ """
391
+ Creates a line graph showing the frequency at which the most common n entities appear in the dataset for each year in given year range.
392
+ In other words, X axis = year, Y axis = frequency, and each line represents a different entity.
393
+
394
+ Parameters
395
+ data: the medline dataframe
396
+ n: int. The number of entities to display.
397
+ entity_toggle: str. The type of entity to display. This info is stored in the tuples in the 'NER' column.
398
+ Options are 'ALL', 'ANATOMY', 'DISEASE'. If 'ALL', displays all entities.
399
+ year_start: int. The start of the year range to display. Years for each data point are taken from the 'DP' column.
400
+ year_end: int. The end of the year range to display. Can be the same as year_start.
401
+
402
+ Returns
403
+ Matplotib figure object.
404
+ """
405
+
406
+ filtered_by_year = filter_by_year(data, year_start, year_end)
407
+ filtered_by_entity = filter_tuples_by_entity_type(filtered_by_year, entity_toggle)
408
+ entitiesDict = group_entity_by_year(filtered_by_entity)
409
+ sortedEntities = sorted(entitiesDict.items(), key = lambda x: x[1][1], reverse = True)
410
+ topEntities = sortedEntities[0:n]
411
+
412
+ df = pd.DataFrame()
413
+
414
+ print(topEntities)
415
+ for entity, data in topEntities:
416
+ # Convert the dictionary to a Series and assign it to a new column in the DataFrame
417
+ yearly_data = data[0]
418
+ df[entity] = pd.Series(yearly_data)
419
+
420
+ # Fill NaN values with 0, in case some entities don't have data for all years
421
+ df = df.fillna(0)
422
+
423
+ print(df)
424
+
425
+ fig, ax = plt.subplots()
426
+
427
+ # Plot the data on the axes object
428
+ for column in df.columns:
429
+ x, y = zip(*sorted(zip(df.index, df[column].values))) # Must sort the data before plotting it; https://stackoverflow.com/questions/37414916/matplotlib-plotting-in-wrong-order
430
+ ax.plot(x, y, marker='o', label=column)
431
+
432
+ # Set plot details
433
+ ax.set_title("Entity Frequencies by Year")
434
+ ax.set_xlabel("Year")
435
+ ax.set_ylabel("Frequency")
436
+ ax.grid(True)
437
+ ax.legend(loc='upper left')
438
+
439
+ return fig
440
+
441
+ ###### MeSH Terms Functions ######
442
+ def mh_frequency(country, globally=False, data=df, year_start=1975, year_end=2000, n=15):
443
+ '''
444
+ Returns the frequency of the top n most common MeSH terms in a given year range.
445
+ '''
446
+
447
+ mh_dict = {}
448
+ added = set() # List used to keep track of all of the items which have already been added to the mh_dict
449
+
450
+ if globally:
451
+ pass
452
+ else:
453
+ data = filter_by_country(data, country)
454
+
455
+ dates = data['DP'].tolist()
456
+ mh = data['MH'].tolist()
457
+ index = 0
458
+ for item in mh:
459
+ if dates[index] >= year_start and dates[index] <= year_end:
460
+ for i in item:
461
+ if i in added: # mh is already in the dictionary
462
+ mh_dict[i] += 1
463
+ else:
464
+ mh_dict[i] = 1
465
+ added.add(i)
466
+ index += 1
467
+
468
+ #display(mh_dict) # Used for testing and debugging
469
+ mh_df = pd.DataFrame.from_dict(
470
+ mh_dict, orient='index', columns=['Frequency'])
471
+ mh_df.sort_values(by=['Frequency'], inplace=True, ascending=False)
472
+ mh_df = mh_df.head(n)
473
+
474
+ fig, ax = plt.subplots()
475
+ ax.barh(y=mh_df.index, width=mh_df['Frequency'], align='center')
476
+ ax.bar_label(ax.containers[0], fmt='%d', label_type='edge')
477
+ ax.set_xlim(right=mh_df['Frequency'].max() + mh_df['Frequency'].max()*0.08) # Prevents labels from overlapping with border in most cases; increase the number if needed
478
+ if globally:
479
+ ax.set_title('Top {} Most Common MeSH Terms Globally'.format(n))
480
+ else:
481
+ ax.set_title('Top {} Most Common MeSH Terms in {}'.format(n, country))
482
+ ax.set_xlabel('Number of occurrences')
483
+ ax.set_ylabel('Term')
484
+ return fig
485
+
486
+ # mh_df.plot(kind='barh', figsize=(10, 10), title='Top ' +
487
+ # str(n) + ' Most Common Places of Publication', legend=False)
488
+ # #display(mh_df)
489
+ # return(mh_df)
490
+
491
+ def mh_time_series(country, globally=False, data=df, year_start=1975, year_end=2000, n=15):
492
+ """
493
+ Creates a matplotlib line plot showing the frequency of the top n most common MeSH topics in a given country (or globally) for each year in a given range.
494
+
495
+ The MH column contains MeSH terms (controlled library of words used to categorize articles).
496
+ The PL column contains publication locations.
497
+
498
+ Parameters
499
+ country: str. The country to display.
500
+ n: int. The number of MESH topics to display.
501
+ year_start: int. The start of the year range to display. Years for each data point are taken from the 'DP' column.
502
+ year_end: int. The end of the year range to display. Can be the same as year_start.
503
+
504
+ Returns
505
+ Matplotib figure object.
506
+
507
+ # Stores the data in a dictionary with this format:
508
+ pl_mh_dict = {} # {year: {(pl, mh): (count)}} Storing the pl is redundant, but I'd like to keep it for now in case of future changes
509
+ """
510
+ filtered_by_year = filter_by_year(data, year_start, year_end)
511
+
512
+ ### TODO: Check if this is fixed
513
+ if globally:
514
+ filtered_by_country = filtered_by_year
515
+ else:
516
+ filtered_by_country = filter_by_country(filtered_by_year, country)
517
+
518
+ meshesDict = group_mesh_by_year(filtered_by_country)
519
+ sortedMeshes = sorted(meshesDict.items(), key = lambda x: x[1][1], reverse = True)
520
+ topMeshes = sortedMeshes[0:n]
521
+
522
+
523
+ df = pd.DataFrame()
524
+ for mesh, data in topMeshes:
525
+ # Convert the dictionary to a Series and assign it to a new column in the DataFrame
526
+ yearly_data = data[0]
527
+
528
+ df[mesh] = pd.Series(yearly_data)
529
+
530
+ # Fill NaN values with 0, in case some entities don't have data for all years
531
+ df = df.fillna(0)
532
+
533
+ fig, ax = plt.subplots()
534
+
535
+ # Plot the data on the axes object
536
+ for column in df.columns:
537
+ x, y = zip(*sorted(zip(df.index, df[column].values)))
538
+ ax.plot(x, y, marker='o', label=column)
539
+ # ax.plot(df.index, df[column], marker='o', label=column)
540
+
541
+ # Set plot details
542
+ if globally:
543
+ ax.set_title("MeSH Topic Frequencies by Year Globally")
544
+ else:
545
+ ax.set_title("MeSH Topic Frequencies by Year in " + country)
546
+ ax.set_xlabel("Year")
547
+ ax.set_ylabel("Frequency")
548
+ ax.grid(True)
549
+ ax.legend()
550
+
551
+ return fig
552
+
553
+ ###### User Interface ######
554
+ with st.sidebar:
555
+
556
+ with st.expander('Word Collocation'):
557
+ with st.form(key='collocation_form'):
558
+ word = st.text_input(label='Enter a word to see the most common surrounding words',
559
+ placeholder='Enter a keyword')
560
+ degree = st.selectbox('Select the number of adjacent words', [1, 2, 3],
561
+ help='''If you select 1, the output will include words immediately before and after the keyword.
562
+ If you select 2, the output will include words two words before and after the keyword, etc.''')
563
+ # Could also provide an option to override the lemmatization here
564
+ submit_collocation = st.form_submit_button('Submit')
565
+
566
+ with st.expander('Journal Analytics'):
567
+ with st.form(key='journal_form'):
568
+ year_start_journal, year_end_journal = st.slider(label='Select a year range', min_value=1975, max_value=2000, value=(1975, 2000), step=1)
569
+ n_journal = st.number_input(label='Enter the number of journals to display', min_value=5, max_value=25, value=10, step=1)
570
+ submit_journal = st.form_submit_button('Submit')
571
+
572
+ with st.expander('Named Biological Entities'):
573
+ with st.form(key='nbe_form'):
574
+ entity = st.selectbox('Select an entity type', ['ALL', 'ANATOMY', 'DISEASE'],
575
+ help='''The natural language processing model that extracts these entities categorizes them as either a disease or an anatomical term. This is an artifact of the corpus that trained the model.''')
576
+ n_nbe = st.number_input(label='Enter the number of entities to display', min_value=5, max_value=25, value=10, step=1)
577
+ year_start_nbe, year_end_nbe = st.slider(label='Select a year range', min_value=1975, max_value=2000, value=(1975, 2000), step=1)
578
+
579
+ submit_nbe = st.form_submit_button('Submit')
580
+
581
+ with st.expander('MeSH Terms'):
582
+ with st.form(key='mesh_form'):
583
+ year_start_mesh, year_end_mesh = st.slider(label='Select a year range', min_value=1975, max_value=2000, value=(1975, 2000), step=1)
584
+ n_mesh = st.number_input(label='Enter the number of MeSH terms to display', min_value=5, max_value=25, value=10, step=1)
585
+ country_mesh = st.selectbox(label='Select a country to view the data related to that location',
586
+ help='The names shown here are drawn directly from data attached to the articles.',
587
+ options=sorted(df['PL'].unique().tolist()))
588
+ submit_mesh = st.form_submit_button('Submit')
589
+
590
+ if submit_collocation:
591
+ st.subheader('Collocation')
592
+ st.markdown('This program attempts to find the stem (or root form) of the word you enter and compare it against the database. This can lead to surprising results.')
593
+ collocation_plot = run_collocation(word, degree=degree, number_of_items=10)
594
+ st.pyplot(collocation_plot)
595
+
596
+ elif submit_journal:
597
+ st.subheader('Journal Frequency')
598
+ st.markdown('The NLM lists the names of journals associated with these identifiers [here](https://ftp.ncbi.nih.gov/pubmed/J_Medline.txt).')
599
+ st.pyplot(jid_frequency(year_start=year_start_journal, year_end=year_end_journal, n=n_journal))
600
+ st.pyplot(jid_frequency_by_year(year_start=year_start_journal, year_end=year_end_journal, n=n_journal))
601
+ st.divider()
602
+
603
+ st.subheader('Place of Publication Frequency')
604
+ st.markdown('Note that the place of publication is derived from the location of the journal, not the location of the author(s).')
605
+ st.pyplot(pl_frequency(year_start=year_start_journal, year_end=year_end_journal, n=n_journal))
606
+
607
+ elif submit_nbe:
608
+ st.subheader('Named Biological Entities')
609
+ st.markdown('This program uses a natural language processing model to extract named biological entities from the abstracts in the database. The model categorizes these entities as either a disease or an anatomical term. This is an artifact of the corpus that trained the model.')
610
+ st.pyplot(ner_frequency(n=n_nbe, entity_toggle=entity, year_start=year_start_nbe, year_end=year_end_nbe))
611
+ st.pyplot(ner_frequency_by_year(n=n_nbe, entity_toggle=entity, year_start=year_start_nbe, year_end=year_end_nbe))
612
+ # st.pyplot(run_colocation('cancer'))
613
+
614
+ elif submit_mesh:
615
+ st.header('MeSH Term Data')
616
+ st.markdown('MeSH (Medical Subject Headings) is the NLM controlled vocabulary thesaurus used for indexing articles. For more information, visit the [MeSH homepage](https://www.nlm.nih.gov/mesh/meshhome.html).')
617
+
618
+ st.subheader('MeSH Terms by Country')
619
+ st.pyplot(mh_frequency(country=country_mesh, globally=False, data=df, year_start=year_start_mesh, year_end=year_end_mesh, n=n_mesh))
620
+ st.pyplot(mh_time_series(country=country_mesh, globally=False, data=df, year_start=year_start_mesh, year_end=year_end_mesh, n=n_mesh))
621
+
622
+ st.divider()
623
+
624
+ st.subheader('Mesh Terms Globally')
625
+ st.pyplot(mh_frequency(country=None, globally=True, data=df, year_start=year_start_mesh, year_end=year_end_mesh, n=n_mesh))
626
+ st.pyplot(mh_time_series(country=None, globally=True, data=df, year_start=year_start_mesh, year_end=year_end_mesh, n=n_mesh))
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ streamlit==1.26.0
2
+ pandas==2.1.0
3
+ matplotlib==3.7.2
4
+ top2vec[indexing]==1.0.34
5
+ wordcloud==1.9.2
6
+ stanza==1.5.0 # Stanza is only used for a small bit of text processing on user input, but it pulls in alot of additonal dependencies. It could be replaced with a lighter library or removed entirely.
7
+ numpy==1.24.3