-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapp.py
More file actions
2279 lines (1927 loc) · 95.9 KB
/
app.py
File metadata and controls
2279 lines (1927 loc) · 95.9 KB
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
import streamlit as st
import requests
import urllib.parse
import xml.etree.ElementTree as ET
import pandas as pd
import numpy as np
import math
import datetime
import time
import re
import os
import io
import matplotlib.pyplot as plt
import seaborn as sns
import plotly.express as px
import plotly.graph_objects as go
from collections import OrderedDict
from wordcloud import WordCloud
import nltk
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from io import BytesIO
import logging
from openpyxl.styles import Alignment, Font, PatternFill, Border, Side
from openpyxl.utils import get_column_letter
from openpyxl.workbook import Workbook
def build_query_terms(field, text, use_and=True):
"""
Convert a string into PubMed search terms split by whitespace.
E.g., 'breast cancer' → '"breast"[field] AND "cancer"[field]'
"""
words = text.strip().split()
operator = " AND " if use_and else " OR "
return operator.join([f'"{word}"[{field}]' for word in words])
# Configure logging to file instead of displaying on screen
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
filename='pubmed_app.log',
filemode='a')
logger = logging.getLogger('pubmed_app')
# Suppress warnings in streamlit
# st.set_option('deprecation.showPyplotGlobalUse', False)
# Download necessary NLTK data silently without user-visible warnings
try:
nltk.download('punkt', quiet=True)
nltk.download('stopwords', quiet=True)
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
NLTK_AVAILABLE = True
logger.info("NLTK resources loaded successfully")
except Exception as e:
NLTK_AVAILABLE = False
logger.error(f"NLTK error: {str(e)}")
# Set Streamlit page configuration
st.set_page_config(
page_title="PubMed Research Analyzer",
page_icon="📊",
layout="wide",
initial_sidebar_state="expanded"
)
# App title and styling
st.markdown("""
<style>
.main-header {
font-size: 2.5rem;
color: #1E88E5;
text-align: center;
margin-bottom: 1rem;
}
.subheader {
font-size: 1.5rem;
color: #0D47A1;
margin-top: 2rem;
margin-bottom: 1rem;
}
.section-header {
font-size: 1.25rem;
color: #1565C0;
margin-top: 1.5rem;
margin-bottom: 0.75rem;
}
.insight-box {
background-color: #1A237E;
color: white;
border-radius: 5px;
padding: 1rem;
margin-bottom: 1rem;
}
.text-centered {
text-align: center;
}
.footer {
text-align: center;
margin-top: 3rem;
padding-top: 1rem;
border-top: 1px solid #1565C0;
color: #BBDEFB;
}
.stTabs [data-baseweb="tab-list"] {
gap: 24px;
}
.stTabs [data-baseweb="tab"] {
height: 50px;
white-space: pre-wrap;
background-color: #0D47A1;
color: white;
border-radius: 4px 4px 0px 0px;
gap: 1px;
padding-top: 10px;
padding-bottom: 10px;
}
.stTabs [aria-selected="true"] {
background-color: #1976D2;
color: white;
}
/* Main background and text color */
.stApp {
background-color: #121212;
color: #FFFFFF;
}
/* Make download buttons stand out */
.stDownloadButton button {
background-color: #1976D2 !important;
color: white !important;
font-weight: bold !important;
border: 1px solid #1565C0 !important;
padding: 10px 20px !important;
}
.stDownloadButton button:hover {
background-color: #1565C0 !important;
border-color: #0D47A1 !important;
}
/* Style dataframes for dark mode */
.stDataFrame {
background-color: #212121;
}
/* Style form elements */
[data-testid="stForm"] {
border-color: #424242 !important;
background-color: #212121;
padding: 20px;
}
/* Sidebar styling */
[data-testid="stSidebar"] {
background-color: #1A1A1A;
}
/* Hide streamlit warnings/errors */
[data-testid="stSidebar"] [data-testid="stException"] {
display: none;
}
div[data-testid="stStatusWidget"] {
display: none;
}
</style>
<h1 class="main-header">PubMed Research Analyzer</h1>
<p class="text-centered">Extract, analyze, and download PubMed articles before and after FDA approval.</p>
""", unsafe_allow_html=True)
# ------------------ PubMed Retrieval Functions ------------------
DB = 'pubmed'
BASEURL_SRCH = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi'
BASEURL_FTCH = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi'
BATCH_NUM = 1000 # records per batch
def mkquery(base_url, params):
"""Build a URL with proper URL encoding."""
query = '&'.join([f'{key}={urllib.parse.quote(str(value))}' for key, value in params.items()])
return f"{base_url}?{query}"
def getXmlFromURL(base_url, params):
"""Return the XML ElementTree for a given URL built from parameters."""
url = mkquery(base_url, params)
response = requests.get(url)
return ET.fromstring(response.text)
def getTextFromNode(root, path, default=""):
"""Safely extract text from an XML node specified by an XPath."""
node = root.find(path)
return node.text.strip() if node is not None and node.text is not None else default
def parse_month(month_str):
"""
Convert month string to numeric month value (1-12).
Handles numeric strings, full month names, and abbreviations.
"""
if not month_str:
return "1" # Default to January if no month
# If already numeric
if month_str.isdigit():
month_num = int(month_str)
if 1 <= month_num <= 12:
return str(month_num)
# If it's a text month name
month_str = month_str.strip().lower()
month_map = {
'jan': '1', 'january': '1',
'feb': '2', 'february': '2',
'mar': '3', 'march': '3',
'apr': '4', 'april': '4',
'may': '5',
'jun': '6', 'june': '6',
'jul': '7', 'july': '7',
'aug': '8', 'august': '8',
'sep': '9', 'september': '9', 'sept': '9',
'oct': '10', 'october': '10',
'nov': '11', 'november': '11',
'dec': '12', 'december': '12'
}
for abbr, num in month_map.items():
if month_str.startswith(abbr):
return num
# If we couldn't determine the month, default to January
return "1"
# ------------------ Processing Each Article ------------------
def process_article(article):
"""
Given an XML element for a PubMed article, extract basic information and author details
with full publication date precision. Also extracts DOI and creates article link.
"""
record = OrderedDict()
record["PMID"] = getTextFromNode(article, "./MedlineCitation/PMID", "")
record["JournalTitle"] = getTextFromNode(article, "./MedlineCitation/Article/Journal/Title", "")
record["ArticleTitle"] = getTextFromNode(article, "./MedlineCitation/Article/ArticleTitle", "")
# Extract DOI
doi = ""
# Try to get DOI from first ArticleId with DOI type
article_ids = article.findall(".//ArticleId")
for article_id in article_ids:
if article_id.get("IdType") == "doi" and article_id.text:
doi = article_id.text.strip()
break
# If not found, try getting DOI from ELocation element
if not doi:
elocation_ids = article.findall(".//ELocationID")
for eloc in elocation_ids:
if eloc.get("EIdType") == "doi" and eloc.text:
doi = eloc.text.strip()
break
record["DOI"] = doi
# Create article link
pmid = record["PMID"]
if pmid:
record["ArticleLink"] = f"https://pubmed.ncbi.nlm.nih.gov/{pmid}/"
else:
record["ArticleLink"] = ""
# Extract full publication date information - first try ArticleDate
pub_year = getTextFromNode(article, "./MedlineCitation/Article/ArticleDate/Year", "")
pub_month = getTextFromNode(article, "./MedlineCitation/Article/ArticleDate/Month", "")
pub_day = getTextFromNode(article, "./MedlineCitation/Article/ArticleDate/Day", "")
# If ArticleDate is not available, try JournalIssue/PubDate
if not pub_year:
pub_year = getTextFromNode(article, "./MedlineCitation/Article/Journal/JournalIssue/PubDate/Year", "")
pub_month = getTextFromNode(article, "./MedlineCitation/Article/Journal/JournalIssue/PubDate/Month", "")
pub_day = getTextFromNode(article, "./MedlineCitation/Article/Journal/JournalIssue/PubDate/Day", "")
# If still no month, try MedlineDate which might contain a string like "2014 Mar-Apr"
if not pub_month:
medline_date = getTextFromNode(article, "./MedlineCitation/Article/Journal/JournalIssue/PubDate/MedlineDate", "")
if medline_date:
# Try to extract year and month from strings like "2014 Mar-Apr" or "2023 Jan"
parts = medline_date.split()
if len(parts) >= 2 and parts[0].isdigit():
pub_year = parts[0]
month_part = parts[1].split('-')[0] # Take first month if range
pub_month = parse_month(month_part)
# If year is missing or invalid, try to extract from other fields
if not pub_year:
pub_date = getTextFromNode(article, "./MedlineCitation/Article/Journal/JournalIssue/PubDate/MedlineDate", "")
if pub_date:
# Try to extract just the year from any date string
year_match = re.search(r'\b(19|20)\d{2}\b', pub_date)
if year_match:
pub_year = year_match.group(0)
# Clean and convert months to standardized format
pub_month = parse_month(pub_month)
# Default day to 1 if not available
if not pub_day or not pub_day.isdigit():
pub_day = "1"
# Store full date components
record["PublicationYear"] = pub_year
record["PublicationMonth"] = pub_month
record["PublicationDay"] = pub_day
# Create a full date string in format "YYYY-MM-DD"
try:
year = int(pub_year) if pub_year else 0
month = int(pub_month) if pub_month else 1
day = int(pub_day) if pub_day else 1
if year > 0:
# Ensure valid month (1-12)
month = max(1, min(12, month))
# Ensure valid day (1-31 depending on month)
max_days = [31, 29 if (year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)) else 28,
31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
day = max(1, min(max_days[month-1], day))
# Format the date
record["PublicationDate"] = f"{year:04d}-{month:02d}-{day:02d}"
else:
record["PublicationDate"] = ""
except (ValueError, TypeError):
# If any conversion fails, store empty string
record["PublicationDate"] = ""
abstracts = article.findall("./MedlineCitation/Article/Abstract/AbstractText")
if abstracts:
record["Abstract"] = " ".join([a.text.strip() for a in abstracts if a.text])
else:
record["Abstract"] = ""
authors = article.findall("./MedlineCitation/Article/AuthorList/Author")
author_count = 1
for auth in authors:
name = ""
collective = auth.find("CollectiveName")
if collective is not None and collective.text:
name = collective.text.strip()
else:
fore = auth.find("ForeName")
last = auth.find("LastName")
if fore is not None and last is not None:
name = f"{fore.text.strip()} {last.text.strip()}"
elif fore is not None:
name = fore.text.strip()
elif last is not None:
name = last.text.strip()
aff_elem = auth.find("./AffiliationInfo/Affiliation")
affiliation = aff_elem.text.strip() if (aff_elem is not None and aff_elem.text) else ""
record[f"Author{author_count}"] = name
record[f"Affiliation{author_count}"] = affiliation
author_count += 1
# If no authors found, don't skip this article - just assign empty values
if author_count == 1: # No authors were added
record["Author1"] = ""
record["Affiliation1"] = ""
return record
def fetch_pubmed_articles(query, batch_size=BATCH_NUM, limit=None, progress_callback=None):
"""
Use ESearch and EFetch to retrieve PubMed articles matching a query.
Returns a list of OrderedDict records (one per article), each processed by process_article().
Optional limit parameter to restrict the number of articles processed.
"""
params = {"db": DB, "term": query, "usehistory": "y", "retmax": 0}
root = getXmlFromURL(BASEURL_SRCH, params)
count = int(getTextFromNode(root, "./Count", "0"))
if count == 0:
return []
# If limit is specified, adjust count
if limit and limit < count:
count = limit
query_key = getTextFromNode(root, "./QueryKey", "")
webenv = getTextFromNode(root, "./WebEnv", "")
records = []
iterCount = math.ceil(count / batch_size)
for i in range(iterCount):
params_fetch = {
"db": DB,
"query_key": query_key,
"WebEnv": webenv,
"retstart": i * batch_size,
"retmax": batch_size,
"retmode": "xml"
}
# For the last batch with a limit, adjust retmax
if limit and (i+1) * batch_size > limit:
params_fetch["retmax"] = limit - i * batch_size
root_fetch = getXmlFromURL(BASEURL_FTCH, params_fetch)
for art in root_fetch.findall(".//PubmedArticle"):
record = process_article(art)
records.append(record)
# Check if we've reached the limit
if limit and len(records) >= limit:
break
# If we've reached the limit, break out of the loop
if limit and len(records) >= limit:
break
# Update progress
if progress_callback:
progress_callback((i + 1) / iterCount)
time.sleep(0.34) # Respect rate limits
return records
# ------------------ Data Verification Functions ------------------
def check_date_range(df, dataset_type, start_date, end_date):
"""
Check if dates are within the expected range using full publication date.
Handles different precision levels with appropriate rounding.
For imprecise dates:
- Year only: For "before" category, use Dec 31; for "after", use Jan 1
- Year-month: For "before" category, use last day of month; for "after", use first day
Returns the count of invalid dates found.
"""
invalid_count = 0
rows_to_drop = []
# Month name to number mapping (both full names and abbreviations)
month_map = {
'jan': 1, 'january': 1,
'feb': 2, 'february': 2,
'mar': 3, 'march': 3,
'apr': 4, 'april': 4,
'may': 5,
'jun': 6, 'june': 6,
'jul': 7, 'july': 7,
'aug': 8, 'august': 8,
'sep': 9, 'september': 9, 'sept': 9,
'oct': 10, 'october': 10,
'nov': 11, 'november': 11,
'dec': 12, 'december': 12
}
for idx, row in df.iterrows():
# First try to use the PublicationDate field if available
if not pd.isna(row.get('PublicationDate', None)) and row.get('PublicationDate', '') != '':
try:
# Try to parse the date
pub_date = datetime.datetime.strptime(row['PublicationDate'], "%Y-%m-%d")
# Check if date is outside the expected range
if dataset_type == "before" and (pub_date < start_date or pub_date > end_date):
rows_to_drop.append(idx)
invalid_count += 1
elif dataset_type == "after" and (pub_date < start_date):
rows_to_drop.append(idx)
invalid_count += 1
continue # Skip to next record if we've processed this one
except (ValueError, TypeError):
# If parsing fails, continue to component-based processing
pass
# If PublicationDate doesn't exist or couldn't be parsed, try component-based approach
pub_year = row.get("PublicationYear", "")
pub_month = row.get("PublicationMonth", "")
pub_day = row.get("PublicationDay", "")
if pub_year and str(pub_year).isdigit():
year = int(pub_year)
# Different handling based on available precision
if pub_month and str(pub_month).isdigit():
month = int(pub_month)
if pub_day and str(pub_day).isdigit():
# Full date precision
day = int(pub_day)
try:
pub_date = datetime.datetime(year, month, day)
except ValueError:
# Invalid date (e.g., Feb 30) - use month-level precision
if dataset_type == "before":
# Get the last day of the month
if month == 12:
last_day = 31
else:
try:
next_month = datetime.datetime(year, month+1, 1)
last_day = (next_month - datetime.timedelta(days=1)).day
except ValueError:
last_day = 28 # Default to a safe value
pub_date = datetime.datetime(year, month, last_day)
else: # "after"
pub_date = datetime.datetime(year, month, 1)
else:
# Year-month precision - use last day or first day
if dataset_type == "before":
# Get the last day of the month
if month == 12:
last_day = 31
else:
try:
next_month = datetime.datetime(year, month+1, 1)
last_day = (next_month - datetime.timedelta(days=1)).day
except ValueError:
# Invalid month, default to day 1
last_day = 1
try:
pub_date = datetime.datetime(year, month, last_day)
except ValueError:
# If invalid date, default to Jan 1
pub_date = datetime.datetime(year, 1, 1)
else: # "after"
try:
pub_date = datetime.datetime(year, month, 1)
except ValueError:
# Invalid month, default to Jan 1
pub_date = datetime.datetime(year, 1, 1)
else:
# Year-only precision - use Dec 31 or Jan 1
if dataset_type == "before":
pub_date = datetime.datetime(year, 12, 31)
else: # "after"
pub_date = datetime.datetime(year, 1, 1)
# Check if date is outside the expected range
if dataset_type == "before" and (pub_date < start_date or pub_date > end_date):
rows_to_drop.append(idx)
invalid_count += 1
elif dataset_type == "after" and (pub_date < start_date):
rows_to_drop.append(idx)
invalid_count += 1
# Drop rows with invalid dates
if rows_to_drop:
df.drop(rows_to_drop, inplace=True)
return invalid_count
def find_max_author_column(df):
"""Find the maximum author column that has non-empty values, returns at least 1"""
max_author = 0
author_pattern = re.compile(r"^Author(\d+)$")
# For each row, find the highest author number with data
for _, row in df.iterrows():
row_max = 0
for col in df.columns:
match = author_pattern.match(col)
if match:
author_num = int(match.group(1))
# Check if this specific cell has content
if pd.notna(row[col]) and row[col] != '':
if author_num > row_max:
row_max = author_num
# Update the overall max if this row has a higher number
if row_max > max_author:
max_author = row_max
# Always return at least 1 to ensure we have Author1 column
return max(1, max_author)
def trim_author_columns(df, max_author):
"""Trim excess author columns beyond the maximum needed"""
columns_to_keep = []
author_pattern = re.compile(r"^Author(\d+)$")
affiliation_pattern = re.compile(r"^Affiliation(\d+)$")
profile_pattern = re.compile(r"^Profile(\d+)$")
# Add all non-author/affiliation columns
for col in df.columns:
if (not author_pattern.match(col) and
not affiliation_pattern.match(col) and
not profile_pattern.match(col)):
columns_to_keep.append(col)
# Add author/affiliation columns up to max_author
for i in range(1, max_author + 1):
author_col = f"Author{i}"
if author_col in df.columns:
columns_to_keep.append(author_col)
affiliation_col = f"Affiliation{i}"
if affiliation_col in df.columns:
columns_to_keep.append(affiliation_col)
profile_col = f"Profile{i}"
if profile_col in df.columns:
columns_to_keep.append(profile_col)
# Return the dataframe with only the needed columns
return df[columns_to_keep]
def process_dataset(df, dataset_type, start_date, end_date):
"""Process a dataset to check dates and trim author columns"""
original_row_count = len(df)
original_column_count = len(df.columns)
# Make a copy to avoid SettingWithCopyWarning
df = df.copy()
# 1. Check and filter by date if within range
invalid_date_count = check_date_range(df, dataset_type, start_date, end_date)
# 2. Trim excess author columns
max_author_column = find_max_author_column(df)
df = trim_author_columns(df, max_author_column)
return df, {
"original_rows": original_row_count,
"original_columns": original_column_count,
"final_rows": len(df),
"final_columns": len(df.columns),
"invalid_dates": invalid_date_count,
"max_author": max_author_column,
"columns_removed": original_column_count - len(df.columns)
}
def verify_dates_and_recategorize(records_before, records_after, fda_date):
"""
Double-check dates and move articles to the correct category, with improved handling
for different date precision levels.
For imprecise dates:
- Year only: For "before" category, use Dec 31 of the year; for "after", use Jan 1
- Year-month: For "before" category, use last day of month; for "after", use first day
Returns verified before/after records lists and counts of moved articles.
"""
verified_before = []
verified_after = []
moved_to_before = 0
moved_to_after = 0
# Process "before" records
for record in records_before:
# First try to use the PublicationDate field if available
if record.get("PublicationDate", ""):
try:
pub_date = datetime.datetime.strptime(record["PublicationDate"], "%Y-%m-%d")
if pub_date > fda_date:
verified_after.append(record)
moved_to_after += 1
else:
verified_before.append(record)
continue # Skip to next record
except (ValueError, TypeError):
# If parsing fails, continue to component-based processing
pass
# Component-based approach for imprecise dates
pub_year = record.get("PublicationYear", "")
pub_month = record.get("PublicationMonth", "")
pub_day = record.get("PublicationDay", "")
if pub_year and str(pub_year).isdigit():
year = int(pub_year)
# Different handling based on available precision
if pub_month and str(pub_month).isdigit():
month = int(pub_month)
if pub_day and str(pub_day).isdigit():
# Full date precision
day = int(pub_day)
try:
pub_date = datetime.datetime(year, month, day)
except ValueError:
# For "before" records with invalid dates, use conservative approach
# Treat as Dec 31 of the year (maximizing chance it belongs in "before")
pub_date = datetime.datetime(year, 12, 31)
else:
# Year-month precision - for "before" records, use last day of month
try:
if month == 12:
last_day = 31
else:
next_month = datetime.datetime(year, month+1, 1)
last_day = (next_month - datetime.timedelta(days=1)).day
pub_date = datetime.datetime(year, month, last_day)
except ValueError:
# Invalid month, default to Dec 31
pub_date = datetime.datetime(year, 12, 31)
else:
# Year-only precision - for "before" records, use Dec 31
pub_date = datetime.datetime(year, 12, 31)
# Check against FDA date
if pub_date > fda_date:
verified_after.append(record)
moved_to_after += 1
else:
verified_before.append(record)
else:
# If no parseable year, keep in original category
verified_before.append(record)
# Process "after" records
for record in records_after:
# First try to use the PublicationDate field if available
if record.get("PublicationDate", ""):
try:
pub_date = datetime.datetime.strptime(record["PublicationDate"], "%Y-%m-%d")
if pub_date <= fda_date:
verified_before.append(record)
moved_to_before += 1
else:
verified_after.append(record)
continue # Skip to next record
except (ValueError, TypeError):
# If parsing fails, continue to component-based processing
pass
# Component-based approach for imprecise dates
pub_year = record.get("PublicationYear", "")
pub_month = record.get("PublicationMonth", "")
pub_day = record.get("PublicationDay", "")
if pub_year and str(pub_year).isdigit():
year = int(pub_year)
# Different handling based on available precision
if pub_month and str(pub_month).isdigit():
month = int(pub_month)
if pub_day and str(pub_day).isdigit():
# Full date precision
day = int(pub_day)
try:
pub_date = datetime.datetime(year, month, day)
except ValueError:
# For "after" records with invalid dates, use conservative approach
# Treat as Jan 1 of the year (maximizing chance it belongs in "after")
pub_date = datetime.datetime(year, 1, 1)
else:
# Year-month precision - for "after" records, use first day of month
try:
pub_date = datetime.datetime(year, month, 1)
except ValueError:
# Invalid month, default to Jan 1
pub_date = datetime.datetime(year, 1, 1)
else:
# Year-only precision - for "after" records, use Jan 1
pub_date = datetime.datetime(year, 1, 1)
# Check against FDA date
if pub_date <= fda_date:
verified_before.append(record)
moved_to_before += 1
else:
verified_after.append(record)
else:
# If no parseable year, keep in original category
verified_after.append(record)
return verified_before, verified_after, moved_to_before, moved_to_after
def deduplicate_records(records_before, records_after):
# First deduplicate within each dataset
before_pmids = {}
after_pmids = {}
# Deduplicate within before dataset
for record in records_before:
pmid = record.get("PMID", "")
if pmid and pmid not in before_pmids:
before_pmids[pmid] = record
# Deduplicate within after dataset
for record in records_after:
pmid = record.get("PMID", "")
if pmid and pmid not in after_pmids:
after_pmids[pmid] = record
# Convert to lists
unique_before = list(before_pmids.values())
unique_after = list(after_pmids.values())
# Now deduplicate between datasets
# Before records take precedence
pmid_seen = set(before_pmids.keys())
# Filter after dataset to remove any PMIDs already in before dataset
final_after = [record for record in unique_after if record.get("PMID", "") not in pmid_seen]
return unique_before, final_after
# ------------------ Data Analysis Functions ------------------
def create_top_journals_chart(df):
"""Create a bar chart of top journals by publication count"""
if len(df) == 0 or 'JournalTitle' not in df.columns:
return None
journal_counts = df['JournalTitle'].value_counts().reset_index()
journal_counts.columns = ['Journal', 'Count']
# Get top 10 journals or all if less than 10
top_n = min(10, len(journal_counts))
top_journals = journal_counts.head(top_n)
# Create horizontal bar chart
fig = px.bar(
top_journals,
y='Journal',
x='Count',
orientation='h',
title=f'Top {top_n} Journals by Publication Count',
height=400,
color='Count',
color_continuous_scale=px.colors.sequential.Blues
)
fig.update_layout(
xaxis_title='Number of Publications',
yaxis_title='Journal',
yaxis={'categoryorder':'total ascending'},
template="plotly_dark",
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(30,30,30,1)'
)
return fig
def create_yearly_trend_chart(df):
"""Create a line chart showing publication trends over years"""
if len(df) == 0 or 'PublicationYear' not in df.columns:
return None
# Convert publication year to numeric and create year count
df_year = df.copy()
df_year['PublicationYear'] = pd.to_numeric(df_year['PublicationYear'], errors='coerce')
df_year = df_year.dropna(subset=['PublicationYear'])
if len(df_year) == 0:
return None
# Round to integer years
df_year['PublicationYear'] = df_year['PublicationYear'].astype(int)
# Count by year
year_counts = df_year['PublicationYear'].value_counts().reset_index()
year_counts.columns = ['Year', 'Count']
year_counts = year_counts.sort_values('Year')
# Create line chart
fig = px.line(
year_counts,
x='Year',
y='Count',
markers=True,
title='Publication Trend by Year',
height=400
)
fig.update_layout(
xaxis_title='Publication Year',
yaxis_title='Number of Publications',
template="plotly_dark",
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(30,30,30,1)'
)
return fig
def create_monthly_trend_chart(df):
"""Create a line chart showing publication trends by month"""
if len(df) == 0 or 'PublicationYear' not in df.columns or 'PublicationMonth' not in df.columns:
return None
# Convert publication year and month to numeric values
df_date = df.copy()
df_date['PublicationYear'] = pd.to_numeric(df_date['PublicationYear'], errors='coerce')
df_date['PublicationMonth'] = pd.to_numeric(df_date['PublicationMonth'], errors='coerce')
# Drop rows with missing year or month
df_date = df_date.dropna(subset=['PublicationYear', 'PublicationMonth'])
if len(df_date) == 0:
return None
# Create date strings in format "YYYY-MM" for sorting
df_date['YearMonth'] = df_date.apply(
lambda row: f"{int(row['PublicationYear']):04d}-{int(row['PublicationMonth']):02d}",
axis=1
)
# Count by year-month
date_counts = df_date['YearMonth'].value_counts().reset_index()
date_counts.columns = ['YearMonth', 'Count']
date_counts = date_counts.sort_values('YearMonth')
# Create line chart
fig = px.line(
date_counts,
x='YearMonth',
y='Count',
markers=True,
title='Publication Trend by Month',
height=400
)
fig.update_layout(
xaxis_title='Publication Month',
yaxis_title='Number of Publications',
xaxis={'type': 'category'}, # Treat as categorical to show all months
template="plotly_dark",
paper_bgcolor='rgba(0,0,0,0)',
plot_bgcolor='rgba(30,30,30,1)'
)
# Rotate x-axis labels for better readability
fig.update_xaxes(tickangle=45)
return fig
def create_author_collaboration_network(df, top_n=20):
"""Create a simple author collaboration network visualization"""
if len(df) == 0:
return None
# Get all author columns
author_cols = [col for col in df.columns if col.startswith('Author') and col != 'Author']
if not author_cols:
return None
# Collect all authors - skip empty or 'Anonymous' authors
all_authors = []
for _, row in df.iterrows():
paper_authors = [row[col] for col in author_cols if pd.notna(row[col]) and row[col] != '' and row[col].lower() != 'anonymous']
if len(paper_authors) > 1: # Only consider papers with multiple authors
all_authors.extend(paper_authors)
# If no authors were found, return None
if not all_authors:
return None
# Count author occurrences
author_counts = pd.Series(all_authors).value_counts()
# If there are no authors or too few unique authors, return None
if len(author_counts) < 3:
return None
# Get top authors
top_authors = author_counts.head(top_n).index.tolist()
# Create edges between co-authors
edges = []
for _, row in df.iterrows():
paper_authors = [row[col] for col in author_cols if pd.notna(row[col]) and row[col] != '' and row[col] in top_authors]
for i in range(len(paper_authors)):
for j in range(i+1, len(paper_authors)):
edges.append((paper_authors[i], paper_authors[j]))
# Count edge occurrences
edge_counts = pd.Series(edges).value_counts().reset_index()
if len(edge_counts) == 0:
return None
edge_counts.columns = ['pairs', 'weight']
edge_counts[['source', 'target']] = pd.DataFrame(edge_counts['pairs'].tolist(), index=edge_counts.index)
# Create nodes dataframe with author frequencies
nodes = pd.DataFrame({
'name': top_authors,
'size': [author_counts[author] for author in top_authors]
})
# Create network visualization using Plotly
node_x = []
node_y = []
node_text = []
node_size = []
# Simple circular layout for nodes
for i, (_, row) in enumerate(nodes.iterrows()):
angle = 2 * math.pi * i / len(nodes)
x = math.cos(angle)