[5b4ecd]: / gap-replay / pubmed / upsample.py

Download this file

698 lines (598 with data), 28.3 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
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),
os.path.pardir)))
import argparse
import json
import time
import numpy as np
from tqdm import tqdm
from datetime import datetime, timedelta
from collections import defaultdict
import matplotlib.pyplot as plt
import seaborn as sns
from pubmed.approved_journals import APPROVED_JOURNALS
FILTER_CONSTANT = -1000000
PUBLICATION_TYPE_FACTORS = {
"Guideline": {
"filter": 1,
"upsample": 1
},
"Practice Guideline": {
"filter": 1,
"upsample": 1
},
"Patient Education Handout": {
"filter": 1,
"upsample": 1
},
"Meta-Analysis": {
"filter": 1,
"upsample": 1
},
"Systematic Review": {
"filter": 1,
"upsample": 0.8
},
"Clinical Trial, Phase IV": {
"filter": 1,
"upsample": 0.8
},
"Clinical Trial, Phase III": {
"filter": 1,
"upsample": 0.6
},
"Clinical Trial, Phase II": {
"filter": 1,
"upsample": 0.4
},
"Clinical Trial, Phase I": {
"filter": 1,
"upsample": 0.2
},
"Randomized Controlled Trial": {
"filter": 1,
"upsample": 0.5
},
"Review": {
"filter": 1,
"upsample": 0.5
},
"Observational Study": {
"filter": 1,
"upsample": 0.5
},
"Comparative Study": {
"filter": 1,
"upsample": 0.5
},
"Clinical Study": {
"filter": 1,
"upsample": 0.4
},
"Observational Study, Veterinary":
{
"filter": 0,
"upsample": FILTER_CONSTANT
},
"Case Reports": {
"filter": 0,
"upsample": 0
},
"Editorial": {
"filter": 0,
"upsample": 0.1
},
"Letter": {
"filter": 0,
"upsample": 0.1
},
"Comment": {
"filter": 0,
"upsample": 0.1
},
"Retracted Publication": {
"filter": 0,
"upsample": FILTER_CONSTANT
},
"Retraction of Publication": {
"filter": 0,
"upsample": FILTER_CONSTANT
},
"Preprint": {
"filter": 0,
"upsample": FILTER_CONSTANT
},
}
MESH_FACTORS = {
"Animals": {
"filter": 0,
"upsample": FILTER_CONSTANT
},
}
MESH_FACTORS = defaultdict(lambda: {"filter": 1, "upsample": 0}, MESH_FACTORS)
CURRENT_DATE = datetime.strptime("2023-07-15", "%Y-%m-%d") # date of scraping
FIRST_CUTOFF_DATE = CURRENT_DATE - timedelta(days=365*5.5)
SECOND_CUTOFF_DATE = CURRENT_DATE - timedelta(days=365*10)
DATE_FACTORS = {
"new": {
"filter": 1,
"upsample": 1
},
"middle": {
"filter": 1,
"upsample": 0.2
},
"old": {
"filter": 0,
"upsample": 0
}
}
CITATION_FACTORS = {
"top": { # top 25% of citations
"filter": 1,
"upsample": 1
},
"middle": { # middle 50% of citations
"filter": 1,
"upsample": 0.5
},
"bottom": { # bottom 25% of citations
"filter": 0,
"upsample": 0
}
}
JOURNAL_FACTORS = {
"approved": {
"filter": 1,
"upsample": 1
},
"non-approved": {
"filter": 0,
"upsample": 0
}
}
def include_decision(article, citation_thresholds):
"""
DEPRECATED: this was used for the old "Quality FILTER" scheme, which is now partially included in
the "Quality UPSAMPLING" options.
"""
# Whether the article has at least one publication type that is covered in our list
publication_covered = 0
for publicationtype in article["publicationtype"]:
if publicationtype in PUBLICATION_TYPE_FACTORS:
publication_covered = 1
if PUBLICATION_TYPE_FACTORS[publicationtype]["filter"] == 0:
include_decision.filtered_from_publication_type += 1
return False
if publication_covered == 0:
include_decision.filtered_from_publication_notcovered += 1
return False
for mesh in article["mesh"]:
if MESH_FACTORS[mesh]["filter"] == 0:
include_decision.filtered_from_mesh += 1
return False
try:
if datetime.strptime(article["publicationDate"], "%Y-%m-%d") < SECOND_CUTOFF_DATE:
if DATE_FACTORS["old"]["filter"] == 0:
include_decision.filtered_from_date += 1
return False
elif datetime.strptime(article["publicationDate"], "%Y-%m-%d") < FIRST_CUTOFF_DATE:
if DATE_FACTORS["middle"]["filter"] == 0:
include_decision.filtered_from_date += 1
return False
else:
if DATE_FACTORS["new"]["filter"] == 0:
include_decision.filtered_from_date += 1
return False
publication_age = (CURRENT_DATE - datetime.strptime(article["publicationDate"], "%Y-%m-%d")).days // 365 + 1
n_citations_normalized = article["citationCount"] / publication_age
if n_citations_normalized <= citation_thresholds["bottom25"]:
if CITATION_FACTORS["bottom"]["filter"] == 0:
include_decision.filtered_from_citation += 1
return False
elif n_citations_normalized <= citation_thresholds["top25"]:
if CITATION_FACTORS["middle"]["filter"] == 0:
include_decision.filtered_from_citation += 1
return False
else:
if CITATION_FACTORS["top"]["filter"] == 0:
include_decision.filtered_from_citation += 1
return False
except TypeError: # publicationDate is None (i.e. missing metadata)
include_decision.filtered_from_nometadata += 1
return False
translation = {ord(ch): '' for ch in ":,.-"}
if article["venue"].lower().translate(translation) in APPROVED_JOURNALS:
if JOURNAL_FACTORS["approved"]["filter"] == 0:
include_decision.filtered_from_journal += 1
return False
else:
if JOURNAL_FACTORS["non-approved"]["filter"] == 0:
include_decision.filtered_from_journal += 1
return False
return True
include_decision.filtered_from_nometadata = 0
include_decision.filtered_from_publication_type = 0
include_decision.filtered_from_publication_notcovered = 0
include_decision.filtered_from_mesh = 0
include_decision.filtered_from_date = 0
include_decision.filtered_from_citation = 0
include_decision.filtered_from_journal = 0
def compute_factor(article, citation_thresholds):
"""
Tweak this function and the dictionaries at the top of the file
to change the UPSAMPLING OPTION.
"""
factor = 0
no_publication_type = True
for publicationtype in article["publicationtype"]:
if publicationtype in PUBLICATION_TYPE_FACTORS:
no_publication_type = False
factor += PUBLICATION_TYPE_FACTORS[publicationtype]["upsample"]
for mesh in article["mesh"]:
factor += MESH_FACTORS[mesh]["upsample"]
translation = {ord(ch): '' for ch in ":,.-"}
if article["venue"].lower().translate(translation) in APPROVED_JOURNALS:
factor += JOURNAL_FACTORS["approved"]["upsample"]
else:
factor += JOURNAL_FACTORS["non-approved"]["upsample"]
# if article["uptodate_reference"]:
# factor += 1
# if article["cochrane_reference"]:
# factor += 1
try:
# Only add date factor for SELECTED articles
if factor > 0:
if datetime.strptime(article["publicationDate"], "%Y-%m-%d") < SECOND_CUTOFF_DATE:
# if no_publication_type:
# return FILTER_CONSTANT
factor += DATE_FACTORS["old"]["upsample"]
elif datetime.strptime(article["publicationDate"], "%Y-%m-%d") < FIRST_CUTOFF_DATE:
# if no_publication_type:
# return FILTER_CONSTANT
factor += DATE_FACTORS["middle"]["upsample"]
else:
factor += DATE_FACTORS["new"]["upsample"]
publication_age = (CURRENT_DATE - datetime.strptime(article["publicationDate"], "%Y-%m-%d")).days // 365 + 1
n_citations_normalized = article["citationCount"] / publication_age
if n_citations_normalized <= citation_thresholds["bottom25"]:
# if no_publication_type:
# return FILTER_CONSTANT
factor += CITATION_FACTORS["bottom"]["upsample"]
elif n_citations_normalized <= citation_thresholds["top25"]:
# if no_publication_type:
# return FILTER_CONSTANT
factor += CITATION_FACTORS["middle"]["upsample"]
else:
factor += CITATION_FACTORS["top"]["upsample"]
except TypeError: # if the publicationDate is None (i.e. missing metadata)
return FILTER_CONSTANT
return factor
def filter(source_path, output_dir, citation_thresholds):
"""
Filter the articles according to the quality thresholds.
DEPRECATED: this corresponded to the old "Quality FILTER" scheme, which is now partially included in
the "Quality UPSAMPLING" options.
"""
with open(source_path, 'r') as f_in, open(output_dir + "filtered.jsonl", 'w') as f_out:
errors = 0
for i, line in tqdm(enumerate(f_in), total=4700000, desc="Filtering..."):
record = json.loads(line)
try:
if include_decision(record, citation_thresholds):
f_out.write(line)
except KeyError:
errors += 1
continue
print(f"Errors: {errors}")
total_articles = 899631
remaining_articles = total_articles
print(f"Number of articles before filtering: {remaining_articles}")
print(F"Number of articles with metadata: {remaining_articles - errors - include_decision.filtered_from_nometadata} (removed {errors+include_decision.filtered_from_nometadata}, {(errors+include_decision.filtered_from_nometadata) / remaining_articles * 100:.2f}% of remaining)")
remaining_articles -= (errors + include_decision.filtered_from_nometadata)
print(f"Number of articles after filtering from publication type (removing Case Reports, Editorials, Comments, Letters, Redacted and preprints): {remaining_articles-include_decision.filtered_from_publication_type} (filtered {include_decision.filtered_from_publication_type}, {include_decision.filtered_from_publication_type / remaining_articles * 100:.2f}% of remaining)")
remaining_articles -= include_decision.filtered_from_publication_type
print(f"Number of articles after filtering from publication not covered: {remaining_articles-include_decision.filtered_from_publication_notcovered} (filtered {include_decision.filtered_from_publication_notcovered}, {include_decision.filtered_from_publication_notcovered / remaining_articles * 100:.2f}% of remaining)")
remaining_articles -= include_decision.filtered_from_publication_notcovered
print(f"Number of articles after filtering from mesh (removing Animals): {remaining_articles-include_decision.filtered_from_mesh} (filtered {include_decision.filtered_from_mesh}, {include_decision.filtered_from_mesh / remaining_articles * 100:.2f}% of remaining)")
remaining_articles -= include_decision.filtered_from_mesh
print(f"Number of articles after filtering from date: {remaining_articles-include_decision.filtered_from_date} (filtered {include_decision.filtered_from_date}, {include_decision.filtered_from_date / remaining_articles * 100:.2f}% of remaining)")
remaining_articles -= include_decision.filtered_from_date
print(f"Number of articles after filtering from citation: {remaining_articles-include_decision.filtered_from_citation} (filtered {include_decision.filtered_from_citation}, {include_decision.filtered_from_citation / remaining_articles * 100:.2f}% of remaining)")
remaining_articles -= include_decision.filtered_from_citation
print(f"Number of articles after filtering from journal: {remaining_articles-include_decision.filtered_from_journal} (filtered {include_decision.filtered_from_journal}, {include_decision.filtered_from_journal / remaining_articles * 100:.2f}% of remaining)")
remaining_articles -= include_decision.filtered_from_journal
print(f"Final number of articles after filtering: {remaining_articles} ({remaining_articles / total_articles * 100:.2f}% of original)")
def upsample(source_path, output_dir, citation_thresholds, upfold, test_size=0.03):
"""
Upsample the articles according to the quality thresholds. First computes all the factors, then converts them to probabilities
and sample with replacement according to these probabilities.
"""
np.random.seed(42)
## Step 1: Compute factors for each article, filter out the articles with factor 0 (i.e. the ones explicitly filtered out, such as animal studies)
## and split the remaining ones into a train and test set
train_path = output_dir + "train.jsonl"
test_path = output_dir + "test.jsonl"
with open(source_path, 'r') as f_in, open(train_path, 'w') as f_train, open(test_path, 'w') as f_test:
factors = []
errors = 0
n_train = 0
n_test = 0
n_filtered = 0
for line in tqdm(f_in, total=4700000, desc="Computing UpSampling factors..."):
record = json.loads(line)
try:
factor = compute_factor(record, citation_thresholds)
except (KeyError, TypeError):
errors += 1
factor = FILTER_CONSTANT
if factor >= 0:
if np.random.rand() < test_size:
f_test.write(line)
n_test += 1
else:
f_train.write(line)
n_train += 1
factors.append(factor)
else:
n_filtered += 1
n_total = n_train + n_test + n_filtered
with open(output_dir + "log.txt", 'a') as f_out:
f_out.write(f"Errors: {errors}\n")
f_out.write(f"Number of articles (with metadata) before filtering: {n_total}\n")
f_out.write(f"Number of articles after filtering: {n_total - n_filtered} ({(n_total - n_filtered) / n_total * 100:.2f}% of all)\n")
remaining = n_total - n_filtered
f_out.write(f"Number of articles in train set: {n_train} ({n_train / remaining * 100:.2f}% of after filtering)\n")
f_out.write(f"Number of articles in test set: {n_test} ({n_test / remaining * 100:.2f}% of after filtering)\n\n")
factors = np.array(factors)
## Step 2: Convert factors to counts, and save the counts in a file
counts = method1(factors, upfold) # change here the UPSAMPLING METHOD
save_counts(counts, train_path, output_dir)
def method1(factors, upfold):
counts = 1 + factors * upfold
for i in tqdm(range(len(counts)), desc="Converting factors to counts"):
if np.random.rand() < counts[i] - int(counts[i]):
counts[i] = int(counts[i]) + 1
else:
counts[i] = int(counts[i])
return counts
def method2(factors, upfold):
counts = factors * upfold
for i in tqdm(range(len(counts)), desc="Converting factors to counts"):
if np.random.rand() < counts[i] - int(counts[i]):
counts[i] = int(counts[i]) + 1
else:
counts[i] = int(counts[i])
return counts
def method3(factors, upfold, clamp=5):
counts = np.exp(factors) * upfold
for i in tqdm(range(len(counts)), desc="Converting factors to counts"):
if np.random.rand() < counts[i] - int(counts[i]):
counts[i] = min(int(counts[i]) + 1, clamp)
else:
counts[i] = min(int(counts[i]), clamp)
return counts
def save_counts(counts, train_path, output_dir):
# print in log file
log_path = output_dir + "log.txt"
with open(log_path, 'a') as f_out:
f_out.write("Statistics about counts:\n")
f_out.write(f"Mean: {np.mean(counts)}\n")
f_out.write(f"Std: {np.std(counts)}\n")
f_out.write(f"Min: {np.min(counts)}\n")
f_out.write(f"Max: {np.max(counts)}\n")
f_out.write(f"10th percentile: {np.quantile(counts, 0.10)}\n")
f_out.write(f"25th percentile: {np.quantile(counts, 0.25)}\n")
f_out.write(f"Median: {np.median(counts)}\n")
f_out.write(f"75th percentile: {np.quantile(counts, 0.75)}\n")
f_out.write(f"90th percentile: {np.quantile(counts, 0.9)}\n")
f_out.write(f"95th percentile: {np.quantile(counts, 0.95)}\n")
f_out.write(f"99th percentile: {np.quantile(counts, 0.99)}\n")
f_out.write("\n\n")
# create plots of distribution
plt.figure(figsize=(10, 5))
sns.histplot(counts)
plt.xlabel("Counts")
plt.ylabel("Frequency")
plt.tight_layout()
plt.savefig(output_dir + "count_distribution.png")
plt.figure(figsize=(10, 5))
sns.histplot(counts, log_scale=(False, True))
plt.xlabel("Counts")
plt.ylabel("Frequency")
plt.tight_layout()
plt.savefig(output_dir + "count_distribution_log.png")
with open(train_path, 'r') as f_in, open(output_dir + "train_upsampled.jsonl", 'w') as f_out:
for i, line in tqdm(enumerate(f_in), total=len(counts), desc="Writing output..."):
for _ in range(int(counts[i])):
f_out.write(line)
def compute_statistics(file_dir, log_dir, citation_thresholds):
articles_per_publicationtype = defaultdict(int)
articles_per_datecategory = defaultdict(int)
articles_per_citationscategory = defaultdict(int)
articles_approvedjournals = 0
# articles_uptodate_refs = 0
# articles_cochrane_refs = 0
narticles = 0
translation = {ord(ch): '' for ch in ":,.-"}
with open(file_dir, 'r') as f_in:
for i, line in tqdm(enumerate(f_in), total=4700000, desc="Computing statistics..."):
article = json.loads(line)
try:
covered = 0
for publicationtype in article["publicationtype"]:
if publicationtype in PUBLICATION_TYPE_FACTORS:
covered = 1
articles_per_publicationtype[publicationtype] += 1
if covered == 0:
articles_per_publicationtype["other"] += 1
narticles += 1
if datetime.strptime(article["publicationDate"], "%Y-%m-%d") < SECOND_CUTOFF_DATE:
articles_per_datecategory["old"] += 1
elif datetime.strptime(article["publicationDate"], "%Y-%m-%d") < FIRST_CUTOFF_DATE:
articles_per_datecategory["middle"] += 1
else:
articles_per_datecategory["new"] += 1
publication_age = (CURRENT_DATE - datetime.strptime(article["publicationDate"], "%Y-%m-%d")).days // 365 + 1
n_citations_normalized = article["citationCount"] / publication_age
if n_citations_normalized <= citation_thresholds["bottom25"]:
articles_per_citationscategory["bottom25"] += 1
elif n_citations_normalized <= citation_thresholds["top25"]:
articles_per_citationscategory["middle50"] += 1
else:
articles_per_citationscategory["top25"] += 1
if article["venue"].lower().translate(translation) in APPROVED_JOURNALS:
articles_approvedjournals += 1
# if article["uptodate_reference"]:
# articles_uptodate_refs += 1
# if article["cochrane_reference"]:
# articles_cochrane_refs += 1
except:
continue
with open(log_dir, 'a') as f_out:
f_out.write("Statistics about articles:\n")
f_out.write(f"Number of articles: {narticles}\n")
for k, v in sorted(articles_per_publicationtype.items(), key=lambda item: item[0]):
f_out.write(f"Number of articles with publication type {k}: {v} ({v/narticles*100:.2f}%)\n")
f_out.write("----------------------------\n")
f_out.write(f"Number of articles with date < 5.5 years {articles_per_datecategory['new']} ({articles_per_datecategory['new']/narticles*100:.2f}%)\n")
f_out.write(f"Number of articles with date between 5.5 and 10 years {articles_per_datecategory['middle']} ({articles_per_datecategory['middle']/narticles*100:.2f}%)\n")
f_out.write(f"Number of articles with date > 10 years {articles_per_datecategory['old']} ({articles_per_datecategory['old']/narticles*100:.2f}%)\n")
f_out.write("----------------------------\n")
f_out.write(f"Number of articles with citation count in top 25%: {articles_per_citationscategory['top25']} ({articles_per_citationscategory['top25']/narticles*100:.2f}%)\n")
f_out.write(f"Number of articles with citation count in middle 50%: {articles_per_citationscategory['middle50']} ({articles_per_citationscategory['middle50']/narticles*100:.2f}%)\n")
f_out.write(f"Number of articles with citation count in bottom 25%: {articles_per_citationscategory['bottom25']} ({articles_per_citationscategory['bottom25']/narticles*100:.2f}%)\n")
f_out.write("----------------------------\n")
f_out.write(f"Number of articles in approved journals: {articles_approvedjournals} ({articles_approvedjournals/narticles*100:.2f}%)\n")
f_out.write(f"Number of articles not in approved journals: {narticles - articles_approvedjournals} ({(narticles - articles_approvedjournals)/narticles*100:.2f}%)\n")
f_out.write("----------------------------\n")
# f_out.write(f"Number of articles with UpToDate references: {articles_uptodate_refs} ({articles_uptodate_refs/narticles*100:.2f}%)\n")
# f_out.write(f"Number of articles without UpToDate references: {narticles - articles_uptodate_refs} ({(narticles - articles_uptodate_refs)/narticles*100:.2f}%)\n")
# f_out.write("----------------------------\n")
# f_out.write(f"Number of articles with Cochrane references: {articles_cochrane_refs} ({articles_cochrane_refs/narticles*100:.2f}%)\n")
# f_out.write(f"Number of articles without Cochrane references: {narticles - articles_cochrane_refs} ({(narticles - articles_cochrane_refs)/narticles*100:.2f}%)\n")
def compute_citation_thresholds(source_path, output_path):
"""
Find the number of citations corresponding to the top 25%, middle 50%, and bottom 25% of citations.
"""
with open(source_path, 'r') as f_in:
citation_counts = []
for i, line in tqdm(enumerate(f_in), total=4700000, desc="Counting citation quantiles..."):
record = json.loads(line)
try:
publication_age = (CURRENT_DATE - datetime.strptime(record["publicationDate"], "%Y-%m-%d")).days // 365 + 1
n_citations_normalized = record["citationCount"] / publication_age
except: # if the publicationDate is None or missing
continue
citation_counts += [n_citations_normalized]
citation_counts = np.array(citation_counts)
top_threshold = np.quantile(citation_counts, 0.75)
middle_threshold = np.quantile(citation_counts, 0.5)
bottom_threshold = np.quantile(citation_counts, 0.25)
with open(output_path, 'w') as f_out:
json.dump({
"top25": top_threshold,
"middle50": middle_threshold,
"bottom25": bottom_threshold
}, f_out, indent=4)
f_out.write("\n")
def compute_publication_types(source_path, save_path):
with open(source_path, 'r') as f_in:
publication_types = {}
for i, line in tqdm(enumerate(f_in), total=4700000, desc="Counting publication types..."):
record = json.loads(line)
try:
for publicationtype in record["publicationtype"]:
if publicationtype not in publication_types:
publication_types[publicationtype] = 0
publication_types[publicationtype] += 1
except:
continue
# sort by value
publication_types = {k: v for k, v in sorted(publication_types.items(), key=lambda item: item[1], reverse=True)}
with open(save_path, 'w') as f_out:
json.dump(publication_types, f_out, indent=4)
def count_venues(source_path, save_path):
with open(source_path, 'r') as f_in:
venue_counts = {}
for i, line in tqdm(enumerate(f_in), total=4700000, desc="Counting venues..."):
record = json.loads(line)
try:
if record["venue"] not in venue_counts:
venue_counts[record["venue"]] = 0
venue_counts[record["venue"]] += 1
except:
continue
# sort by value
venue_counts = {k: v for k, v in sorted(venue_counts.items(), key=lambda item: item[1], reverse=True)}
with open(save_path, 'w') as f_out:
json.dump(venue_counts, f_out, indent=4)
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"--input_path",
type=str,
required=True,
help="PubMedCentral file, enriched of MeSH tags and Publication Types and pre-processed (after running both augment and process).")
parser.add_argument(
"--output_dir",
type=str,
required=True,
help="Output directory.")
parser.add_argument(
"--citation_thresholds",
type=str,
required=True,
help="JSON file containing the thresholds for the citation count. If not present, they will be computed from the input file.")
parser.add_argument(
"--upfold_number",
type=int,
default=1,
help="Number by which all factors are multiplied.")
parser.add_argument(
"--mode",
choices={"filter", "upsample"},
required=True
)
args = parser.parse_args()
print(args)
if not os.path.exists(args.output_dir):
os.makedirs(args.output_dir)
else:
print("Output directory already exists. Do you really want to continue and replace all existing files? (y/n)...")
choice = input().lower()
if choice != "y":
print("Exiting...")
sys.exit()
# remove all files in output directory
for filename in os.listdir(args.output_dir):
os.remove(args.output_dir + filename)
if not os.path.exists(args.citation_thresholds):
print("Computing citation thresholds...")
compute_citation_thresholds(args.input_path, args.citation_thresholds)
with open(args.citation_thresholds, 'r') as f_in:
citation_thresholds = json.load(f_in)
# create log file
log_path = args.output_dir + "log.txt"
with open(log_path, 'w') as f_out:
f_out.write(f"Date: {datetime.now()}\n")
f_out.write(f"Input path: {args.input_path}\n")
f_out.write(f"Output directory: {args.output_dir}\n")
f_out.write(f"Citation thresholds: {args.citation_thresholds}\n")
f_out.write(f"Upfold number: {args.upfold_number}\n")
f_out.write(f"Mode: {args.mode}\n")
f_out.write("\n\n")
if args.mode == "filter":
filter(args.input_path, args.output_dir, citation_thresholds, verbose=1)
elif args.mode == "upsample":
upsample(args.input_path, args.output_dir, citation_thresholds, upfold=args.upfold_number)
else:
raise NotImplementedError("Mode not implemented.")
with open(log_path, 'a') as f_out:
# f_out.write("--------------------------PRE-UPSAMPLING STATISTICS--------------------------\n")
# compute_statistics(args.input_path, log_path,citation_thresholds)
# f_out.write("--------------------------POST-UPSAMPLING STATISTICS--------------------------\n")
compute_statistics(args.output_dir + "train_upsampled.jsonl", log_path, citation_thresholds)
if __name__ == "__main__":
main()