-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1893 lines (1759 loc) · 88.9 KB
/
index.js
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
/* Local Citation Network (GPL-3) */
/* by Tim Woelfle */
/* https://LocalCitationNetwork.github.io */
/* global fetch, localStorage, vis, Vue, Buefy */
'use strict'
const localCitationNetworkVersion = 1.25
/*
For now, old terminology is kept in-code because of back-compatibility with old saved graphs objects (localStorage & JSON)
"incomingSuggestions" are now "topReferences"
"outgoingSuggestions" are now "topCitations"
*/
const arrSum = arr => arr.reduce((a, b) => a + b, 0)
const arrAvg = arr => arrSum(arr) / arr.length
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze#examples
function deepFreeze (object) {
if (typeof object !== 'object') return object
for (const name of Reflect.ownKeys(object)) {
const value = object[name]
if ((value && typeof value === 'object') || typeof value === 'function') {
deepFreeze(value)
}
}
return Object.freeze(object)
}
/* Semantic Scholar API */
// https://api.semanticscholar.org/api-docs/graph#tag/paper
async function semanticScholarWrapper (ids, responseFunction, phase, retrieveAllReferences = false, retrieveAllCitations = false, getReferenceContexts = false) {
let responses = []
ids = ids.map(id => {
if (!id) return undefined
else if (!isNaN(id)) return 'pmid:' + id
else return id
})
let selectFields = 'title,venue,year,externalIds,abstract,referenceCount,citationCount,publicationTypes,publicationDate,journal'
// Use "references" / "citations" API endpoints instead of a a single query for each reference / citation for "Retrieve references / citations: All" (faster)
if ((phase === 'references' && retrieveAllReferences) || (phase === 'citations' && retrieveAllCitations)) {
let offset, response
// Cannot get author affiliations and external IDs (e.g. ORCID) on references / citations endpoints
selectFields += ',authors'
ids = ids.filter(Boolean)
vm.isLoadingTotal = ids.length
for (const i of Array(ids.length).keys()) {
const id = ids[i]
response = undefined
vm.isLoadingIndex = i
offset = 0
while (offset !== undefined) {
response = await semanticScholarPaper(id + '/' + phase + '?limit=1000&offset=' + offset + '&fields=' + selectFields, { headers: { 'x-api-key': vm.semanticScholarAPIKey } })
offset = response.next
response = response.data.map(x => x.citedPaper || x.citingPaper) // citedPaper for references, citingPaper for citations
// Semantic Scholar doesn't provide references & citations lists for citations & references endpoint
// That's why for S2: All Citations always only have one reference and All References only have one citation (the one that called them), which are merged in responseToArray during de-duplication
// response can be null in case of placeholders in id-list
if (phase === 'citations' && response) {
response = response.map(x => { x.references = [{ paperId: id }]; return x })
}
// This is not needed, as computed.referencedCiting only relies on references arrays
/* else { // must be (phase === 'references')
response = response.map(x => { x.citations = [{ paperId: id }]; return x })
} */
responses = responses.concat(response)
}
}
// Phase 'source' / 'input' / 'references' && !retrieveAllReferences (i.e. Top references only) / 'citations' && !retrieveAllCitations (i.e. Top Citations only)
} else {
// These fields cannot be retrieved on references / citations endpoints
selectFields += ',authors.externalIds,authors.name,authors.affiliations,references.paperId,tldr'
// Get citations ids for input articles (if not all citations are retrieved anyway)
if (['source', 'input'].includes(phase) && !retrieveAllCitations) selectFields += ',citations.paperId'
// Batch endpoint allows max. 500 ids at the same time
responses = await semanticScholarPaper('batch?fields=' + selectFields, { method: 'POST', headers: { 'x-api-key': vm.semanticScholarAPIKey }, body: JSON.stringify({ ids: ids.filter(Boolean) }) })
// Get referenceContexts for source
if (phase === 'source' && getReferenceContexts) {
const referenceContexts = await semanticScholarPaper(ids[0] + '/references?limit=1000&fields=paperId,contexts')
if (referenceContexts) responses[0].referenceContexts = referenceContexts
}
// Add placeholders for missing items from batch response
// ?. because empty batch API call (e.g. "Retrieve references: None") doesn't return array
responses = responses?.map((e, i) => (e === null) ? { title: 'Missing: ' + ids[i] + ' (id not found in S2)', placeholderForId: ids[i] } : e)
}
// Some S2 responses don't have S2 ids, remove them for now (except placeholders)
responses = responses.filter(response => response.paperId || response.placeholderForId)
vm.isLoadingTotal = 0
responseFunction(responses)
}
function semanticScholarPaper (suffix, init = undefined) {
return fetch('https://api.semanticscholar.org/graph/v1/paper/' + suffix, init).then(response => {
if (!response.ok) throw (response)
return response.json()
}).catch(async function (response) {
// "Too Many Requests" errors (status 429) are unfortunately sometimes sent with wrong CORS header and thus cannot be distinguished from generic network errors
if (response.status === 429 || typeof response.statusText !== 'string') {
if (response.status === 429) vm.errorMessage('Semantic Scholar (S2) reports too rapid requests. Waiting 2 minutes...')
else vm.errorMessage('Semantic Scholar (S2) not reachable, probably too rapid requests. Waiting 2 minutes...')
await new Promise(resolve => setTimeout(resolve, 120000))
return semanticScholarPaper(suffix, init)
}
const id = suffix.replace(/\?.*/, '')
vm.errorMessage('Error while processing data through Semantic Scholar API for ' + id + ': ' + response.statusText + ' (' + response.status + ')')
// Add placeholders for missing items with reason
return { title: 'Missing: ' + id + ' (' + response.statusText + ', ' + response.status + ')', placeholderForId: id }
})
}
function semanticScholarResponseToArticleArray (data) {
return data.filter(Boolean).map(article => {
const doi = article.externalIds?.DOI?.toUpperCase()
return {
id: article.paperId,
numberInSourceReferences: data.indexOf(article) + 1,
doi: doi,
type: article.publicationTypes,
title: article.title || '',
authors: (article.authors || []).map(author => {
const cutPoint = (author.name.lastIndexOf(',') !== -1) ? author.name.lastIndexOf(',') : author.name.lastIndexOf(' ')
return {
id: author.authorId,
orcid: author.externalIds?.ORCID,
url: author.url,
LN: author.name.substr(cutPoint + 1),
FN: author.name.substr(0, cutPoint),
affil: (author.affiliations || []).join(', ') || undefined
}
}),
year: article.year,
date: article.publicationDate,
journal: article.journal?.name || article.venue,
volume: article.journal?.volume?.trim(),
firstPage: article.journal?.pages?.split('-')?.[0]?.trim(),
lastPage: article.journal?.pages?.split('-')?.[1]?.trim(),
references: article.references?.map(x => x.paperId),
referencesCount: article.referenceCount,
citations: article.citations?.map(x => x.paperId).filter(Boolean),
citationsCount: article.citationCount,
abstract: article.abstract,
tldr: article.tldr?.text,
referenceContexts: article.referenceContexts && Object.fromEntries(article.referenceContexts.data.filter(x => x.citedPaper.paperId).map(x => [x.citedPaper.paperId, x.contexts]))
}
})
}
/* OpenAlex API */
// https://docs.openalex.org/about-the-data/work#the-work-object
async function openAlexWrapper (ids, responseFunction, phase, retrieveAllReferences = false, retrieveAllCitations = false) {
let responses = []
ids = ids.map(id => {
if (!id) return undefined
// OpenAlex usually formats ids as URLs (e.g. https://openalex.org/W2741809807 / https://doi.org/10.7717/peerj.4375 / https://pubmed.ncbi.nlm.nih.gov/29456894)
// Supported ids: https://docs.openalex.org/api-entities/works/work-object#id
else if (id.includes('https://')) return id
else if (id.toLowerCase().match(/doi:|mag:|openalex:|pmid:|pmcid:/)) return id.toLowerCase()
else if (id.includes('/')) return 'doi:' + id
else if (!isNaN(id)) return 'pmid:' + id
else return 'openalex:' + id
})
const selectFields = 'id,doi,title,authorships,publication_year,primary_location,biblio,referenced_works,cited_by_count,abstract_inverted_index,is_retracted,type,publication_date'
let id, cursor, response
// Use "filter" API endpoint instead of a a single query for each reference / citation for "Retrieve references / citations: All" (faster)
if ((phase === 'references' && retrieveAllReferences) || (phase === 'citations' && retrieveAllCitations)) {
// OpenAlex API allows OR combination of up to 50 IDs: https://docs.openalex.org/how-to-use-the-api/get-lists-of-entities/filter-entity-lists
const max = Math.ceil(ids.filter(Boolean).length / 50)
let idsString
vm.isLoadingTotal = max
for (const i of Array(max).keys()) {
idsString = ids.filter(Boolean).slice(i * 50, (i + 1) * 50).map(x => x.replace('openalex:', '')).join('|')
response = undefined
vm.isLoadingIndex = i
// Cursor paging allows getting all records (up to 200 per API call): https://docs.openalex.org/how-to-use-the-api/get-lists-of-entities/paging
cursor = '*'
while (cursor) {
response = await openAlexWorks('?select=' + selectFields + '&per-page=200&sort=referenced_works_count:desc&filter=' + ((phase === 'references') ? 'cited_by' : 'cites') + ':' + idsString + '&cursor=' + cursor)
cursor = response.meta.next_cursor
if (response.results?.length) responses = responses.concat(response.results)
}
}
// Phase 'source' / 'input' / 'references' && !retrieveAllReferences (i.e. Top references only) / 'citations' && !retrieveAllCitations (i.e. Top Citations only)
} else {
vm.isLoadingTotal = ids.length
for (const i of Array(ids.length).keys()) {
id = ids[i]
response = undefined
vm.isLoadingIndex = i
if (id) {
response = await openAlexWorks('/' + id.replace('openalex:', '') + '?select=' + selectFields)
// Get citations ids for input articles (if not all citations are retrieved anyway)
if (['source', 'input'].includes(phase) && response.id && !retrieveAllCitations) {
// Careful: Citation results are incomplete when a paper is cited by >200 (current per-page upper-limit of OA), use "API options => Retrieve citations => All" for completeness
const citations = await openAlexWorks('?select=id&per-page=200&sort=referenced_works_count:desc&filter=cites:' + response.id.replace('https://openalex.org/', ''))
if (citations) { response.citations = citations }
}
}
responses.push(response)
}
}
vm.isLoadingTotal = 0
responseFunction(responses)
}
function openAlexWorks (suffix) {
return fetch('https://api.openalex.org/works' + suffix + '&[email protected]').then(response => {
if (!response.ok) throw (response)
return response.json()
}).catch(async function (response) {
if (response.status === 429 || typeof response.statusText !== 'string') {
if (response.status === 429) vm.errorMessage('OpenAlex (OA) reports too rapid requests. Waiting 2 minutes...')
else vm.errorMessage('OpenAlex (OA) not reachable. Waiting 2 minutes...')
await new Promise(resolve => setTimeout(resolve, 120000))
return openAlexWorks(suffix)
}
const id = suffix.substr(1).replace(/\?.*/, '')
vm.errorMessage('Error while processing data through OpenAlex API for ' + id + ': ' + response.statusText + ' (' + response.status + ')')
// Add placeholders for missing items with reason
return { title: 'Missing: ' + id + ' (' + response.statusText + ', ' + response.status + ')', placeholderForId: id }
})
}
function openAlexResponseToArticleArray (data) {
return data.filter(Boolean).map(article => {
const doi = (article.doi) ? article.doi.replace('https://doi.org/', '').toUpperCase() : undefined
let journal = article.primary_location?.source?.display_name
if (article.primary_location?.source?.host_organization_name && !article.primary_location?.source?.title?.includes(article.primary_location.source?.host_organization_name)) { journal += ' (' + article.primary_location?.source?.host_organization_name + ')' }
return {
id: article.id?.replace('https://openalex.org/', ''),
numberInSourceReferences: data.indexOf(article) + 1,
doi: doi,
type: article.type,
title: article.title || '',
authors: (article.authorships || []).map(authorship => {
const display_name = authorship.author.display_name || ''
const cutPoint = (display_name.lastIndexOf(',') !== -1) ? display_name.lastIndexOf(',') : display_name.lastIndexOf(' ')
return {
id: authorship.author.id?.replace('https://openalex.org/', ''),
orcid: authorship.author.orcid?.replace('https://orcid.org/', ''),
LN: display_name.substr(cutPoint + 1),
FN: display_name.substr(0, cutPoint),
affil: (authorship.institutions || []).map(institution => institution.display_name + (institution.country_code ? ' (' + institution.country_code + ')' : '')).join(', ') || undefined
}
}),
year: article.publication_year,
date: article.publication_date,
journal: journal,
volume: article.biblio?.volume,
issue: article.biblio?.issue,
firstPage: article.biblio?.first_page,
lastPage: article.biblio?.last_page,
references: article.referenced_works?.map(x => x.replace('https://openalex.org/', '')),
referencesCount: article.referenced_works?.length,
citations: article.citations?.results.map(x => x.id.replace('https://openalex.org/', '')),
citationsCount: article.cited_by_count,
abstract: (article.abstract_inverted_index) ? revertAbstractFromInvertedIndex(article.abstract_inverted_index) : undefined,
isRetracted: article.is_retracted
}
})
}
function revertAbstractFromInvertedIndex (abstract_inverted_index) {
const abstract = []
Object.keys(abstract_inverted_index).forEach(word => abstract_inverted_index[word].forEach(i => { abstract[i] = word }))
return abstract.join(' ').replaceAll(' ', ' ').trim()
}
/* Crossref API */
// https://github.com/CrossRef/rest-api-doc#api-overview
async function crossrefWrapper (ids, responseFunction, phase) {
const responses = []
vm.isLoadingTotal = ids.length
for (const i of Array(ids.length).keys()) {
let response
vm.isLoadingIndex = i
if (ids[i]) response = await crossrefWorks(ids[i])
responses.push(response)
}
vm.isLoadingTotal = 0
responseFunction(responses)
}
function crossrefWorks (id) {
return fetch('https://api.crossref.org/works?filter=doi:' + id + '&select=DOI,title,author,issued,container-title,reference,is-referenced-by-count,abstract,type,&[email protected]').then(response => {
if (!response.ok) throw (response)
return response.json()
}).then(data => {
if (typeof data !== 'object' || !data.message || !data.message.items || !data.message.items[0]) throw ({ statusText: 'Empty response', status: 200 })
return (data.message.items[0])
}).catch(async function (response) {
if (response.status === 429 || typeof response.statusText !== 'string') {
if (response.status === 429) vm.errorMessage('Crossref reports too rapid requests. Waiting 2 minutes...')
else vm.errorMessage('Crossref not reachable. Waiting 2 minutes...')
await new Promise(resolve => setTimeout(resolve, 120000))
return crossrefWorks(id)
}
vm.errorMessage('Error while processing data through Crossref API for ' + id + ': ' + response.statusText + ' (' + response.status + ')')
// Add placeholders for missing items with reason
return { title: 'Missing: ' + id + ' (' + response.statusText + ', ' + response.status + ')', placeholderForId: id }
})
}
function crossrefResponseToArticleArray (data) {
return data.filter(Boolean).map(article => {
const doi = article.DOI?.toUpperCase()
function formatDate (year, month, day) {
// Create a new Date object with the provided year, month, and day
const date = new Date(year, month - 1, day)
// Get the individual components of the date
const formattedYear = date.getFullYear()
const formattedMonth = String(date.getMonth() + 1).padStart(2, '0')
const formattedDay = String(date.getDate()).padStart(2, '0')
// Return the formatted date in the YYYY-MM-DD format
return `${formattedYear}-${formattedMonth}-${formattedDay}`
}
return {
id: doi,
numberInSourceReferences: data.indexOf(article) + 1,
doi: doi,
type: article.type,
title: String(article.title), // most of the time title is an array with length=1, but I've also seen pure strings
authors: (article.author?.length) ? article.author.map(x => ({
orcid: x.ORCID,
LN: x.family || x.name,
FN: x.given,
affil: (x.affiliation?.length) ? x.affiliation.map(aff => aff.name).join(', ') : (typeof (x.affiliation) === 'string' ? x.affiliation : undefined)
})) : [{ LN: article.author || undefined }],
year: article.issued?.['date-parts']?.[0]?.[0],
date: (article.issued?.['date-parts']?.[0]?.[0]) ? formatDate(article.issued['date-parts'][0][0], article.issued['date-parts'][0][1], article.issued['date-parts'][0][2]) : undefined,
journal: String(article['container-title']),
// Crossref "references" array contains null positions for references it doesn't have DOIs for, thus preserving the original number of references
references: article.reference?.map(x => x.DOI?.toUpperCase()),
referencesCount: article.reference?.length,
citationsCount: article['is-referenced-by-count'],
abstract: article.abstract
}
})
}
/* OpenCitations API */
// https://opencitations.net/index/api/v1#/metadata/{dois}
async function openCitationsWrapper (ids, responseFunction, phase) {
const responses = []
vm.isLoadingTotal = ids.length
for (const i of Array(ids.length).keys()) {
let response
vm.isLoadingIndex = i
if (ids[i]) response = (await openCitationsMetadata(ids[i]))[0]
responses.push(response)
}
vm.isLoadingTotal = 0
responseFunction(responses)
}
function openCitationsMetadata (id) {
return fetch('https://opencitations.net/index/api/v1/metadata/' + id + '[email protected]').then(response => {
if (!response.ok) throw (response)
return response.json()
}).then(data => {
if (typeof data !== 'object' || !data.length) throw ({ statusText: 'Empty response', status: 200 })
return data
}).catch(async function (response) {
if ((response.status === 429 || typeof response.statusText !== 'string') && response.status !== 404) {
if (response.status === 429) vm.errorMessage('OpenCitations (OC) reports too rapid requests. Waiting 2 minutes...')
else vm.errorMessage('OpenCitations (OC) not reachable. Waiting 2 minutes...')
await new Promise(resolve => setTimeout(resolve, 120000))
return openCitationsMetadata(id)
}
vm.errorMessage('Error while processing data through OpenCitations API for ' + id + ': ' + response.statusText + ' (' + response.status + ')')
// Add placeholders for missing items with reason (OC always returns an array, which is why (await openCitationsMetadata(ids[i]))[0] is selected above)
return [{ title: 'Missing: ' + id + ' (' + response.statusText + ', ' + response.status + ')', placeholderForId: id }]
})
}
function openCitationsResponseToArticleArray (data) {
return data.filter(Boolean).map(article => {
const doi = article.doi?.toUpperCase()
return {
id: doi,
numberInSourceReferences: data.indexOf(article) + 1,
doi: doi,
title: String(article.title), // most of the time title is an array with length=1, but I've also seen pure strings
authors: article.author?.split('; ').map(x => ({ LN: x.split(', ')[0], FN: x.split(', ')[1] })) ?? [],
year: Number(article.year?.substr(0, 4)) || undefined,
date: article.year, // is apparerently sometimes date not only year
journal: article.source_title,
volume: article.volume,
issue: article.issue,
firstPage: article.page?.split('-')?.[0],
lastPage: article.page?.split('-')?.[1],
references: article.reference?.split('; ').map(x => x.toUpperCase()),
referencesCount: article.reference?.split('; ').length,
citations: article.citation?.split('; ').map(x => x.toUpperCase()),
citationsCount: Number(article.citation_count) || undefined
}
})
}
/* vis.js Reference graph */
// I've tried keeping citationNetwork in Vue's data, but it slowed things down a lot -- better keep it as global variable as network is not rendered through Vue anyway
let citationNetwork, authorNetwork
function htmlTitle (html) {
const container = document.createElement('div')
container.innerHTML = vm.formatTags(html)
return container
}
function initCitationNetwork (app, minDegreeIncomingSuggestions = 1, minDegreeOutgoingSuggestions = 1) {
// This line is necessary because of v-if="currentTabIndex !== undefined" in the main columns div, which apparently is evaluated after watch:currentTabIndex is called
if (!document.getElementById('citationNetwork')) return setTimeout(function () { app.init() }, 1)
// Only init network if it doesn't exist yet (or was previously reset == destroyed)
if (document.getElementById('citationNetwork').innerHTML !== '') return false
app.citationNetworkIsLoading = true
// Filter articles according to settings
// Articles must have year for hierarchical layout
const sourceId = app.currentGraph.source.id
const inputArticles = app.currentGraph.input
.filter(article => article.year)
.filter(article => (app.citationNetworkShowSource ? true : !article.isSource))
const incomingSuggestions = (app.currentGraph.incomingSuggestions ?? [])
// De-duplicate against inputArticles (only relevant when All References are retrieved)
.filter(article => !app.inputArticlesIds.includes(article.id))
.filter(article => article.year)
.filter(article => app.inDegree(article.id) + app.outDegree(article.id) >= minDegreeIncomingSuggestions)
.toSorted((a, b) => vm.sortInDegreeWrapper(a, b, false))
.slice(0, app.maxIncomingSuggestions)
const outgoingSuggestions = (app.currentGraph.outgoingSuggestions ?? [])
// De-duplicate against inputArticles and incomingSuggestions (only relevant when All References are retrieved)
.filter(article => !app.inputArticlesIds.includes(article.id) && !app.incomingSuggestionsIds.includes(article.id))
.filter(article => article.year)
.filter(article => app.inDegree(article.id) + app.outDegree(article.id) >= minDegreeOutgoingSuggestions)
.toSorted((a, b) => vm.sortOutDegreeWrapper(a, b, false))
.slice(0, app.maxOutgoingSuggestions)
// Create an array with edges
// Only keep connected articles (no singletons)
let articles = new Set()
// Edges from inputArticles
let edges = inputArticles.concat(incomingSuggestions).concat(outgoingSuggestions).map(article => app.referencedCiting.referenced[article.id]?.map(fromId => {
// Some input articles have been removed above (e.g. those without year, so double check here)
if (inputArticles.map(x => x.id).includes(fromId)) {
if (app.citationNetworkShowSource || fromId != sourceId) {
articles.add(article)
articles.add(inputArticles[inputArticles.map(x => x.id).indexOf(fromId)])
return { from: fromId, to: article.id }
}
}
}))
// Edges from incomingSuggestions and outgoingSuggestions to inputArticles
edges = edges.concat(incomingSuggestions.concat(outgoingSuggestions).map(article => app.referencedCiting.citing[article.id]?.map(toId => {
// Some input articles have been removed above (e.g. those without year, so double check here)
if (inputArticles.map(x => x.id).includes(toId)) {
if (app.citationNetworkShowSource || toId != sourceId) {
articles.add(article)
articles.add(inputArticles[inputArticles.map(x => x.id).indexOf(toId)])
return { from: article.id, to: toId }
}
}
})))
edges = edges.flat().filter(Boolean)
articles = Array.from(articles)
if (!articles.length) {
app.citationNetworkIsLoading = false
}
// Sort hierarchical levels by rank of year
const years = Array.from(new Set(articles.map(article => article?.year).sort()))
const nodes = articles.map(article => ({
id: article.id,
title: htmlTitle(app.authorStringShort(article.authors) + '. <a><em>' + article.title + '</em></a>. ' + article.journal + '. ' + article.year + '.<br>(Double click opens article: <a>' + String(app.articleLink(article)).substr(0, 28) + '...</a>)'),
level: years.indexOf(article.year),
group: article[app.citationNetworkNodeColor],
value: arrSum([['in', 'both'].includes(app.citationNetworkNodeSize) ? app.inDegree(article.id) : 0, ['out', 'both'].includes(app.citationNetworkNodeSize) ? app.outDegree(article.id) : 0]),
shape: (sourceId === article.id) ? 'diamond' : (app.inputArticlesIds.includes(article.id) ? 'dot' : (app.incomingSuggestionsIds.includes(article.id) ? 'triangle' : 'triangleDown')),
label: article.authors[0]?.LN + '\n' + article.year
}))
// Create network
const options = {
layout: {
hierarchical: {
direction: (app.currentGraph.citationNetworkTurned) ? 'LR' : 'DU',
levelSeparation: 40,
nodeSpacing: 10
}
},
nodes: {
font: {
strokeWidth: 3,
strokeColor: '#eeeeee'
},
scaling: {
min: 3,
max: 30,
label: {
enabled: true,
min: 10,
max: 30,
maxVisible: 300,
drawThreshold: 10
}
}
},
edges: {
color: {
color: 'rgba(0,0,0,0.05)',
highlight: 'rgba(0,0,0,0.8)'
},
arrows: {
to: {
enabled: true,
scaleFactor: 0.4
}
},
width: 0.8,
selectionWidth: 0.8,
smooth: false
},
interaction: {
hideEdgesOnDrag: true,
hideEdgesOnZoom: true,
keyboard: {
enabled: true,
bindToWindow: false,
autoFocus: false
}
},
physics: {
enabled: true,
hierarchicalRepulsion: {
nodeDistance: 80
}
},
configure: {
enabled: true,
container: document.getElementById('citationNetworkConfigure')
}
}
citationNetwork = new vis.Network(document.getElementById('citationNetwork'), { nodes: nodes, edges: edges }, options)
citationNetwork.on('click', networkOnClick)
citationNetwork.on('doubleClick', networkOnDoubleClick)
citationNetwork.stabilize(citationNetwork.body.nodeIndices.length)
citationNetwork.on('stabilizationIterationsDone', function (params) {
app.citationNetworkIsLoading = false
citationNetwork.setOptions({ physics: false })
citationNetwork.fit()
})
// Draw a white background behind canvas so that right-click "Open/Save Image" works properly
citationNetwork.on('beforeDrawing', function (ctx) {
// https://github.com/almende/vis/issues/2292#issuecomment-372044181
// save current translate/zoom
ctx.save()
// reset transform to identity
ctx.setTransform(1, 0, 0, 1, 0, 0)
// fill background with solid white
ctx.fillStyle = '#ffffff'
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height)
// restore old transform
ctx.restore()
})
function networkOnClick (params) {
let selectedNodeId
// Select corresponding row in table
if (params.nodes.length > 0) {
selectedNodeId = params.nodes[0]
// Input article node was clicked (circle)
if (app.inputArticlesIds.includes(selectedNodeId)) {
app.showArticlesTab = 'inputArticles'
app.selected = app.currentGraph.input[app.inputArticlesIds.indexOf(selectedNodeId)]
// Suggested article node was clicked (triangle)
} else if (app.incomingSuggestionsIds.includes(selectedNodeId)) {
app.showArticlesTab = 'topReferences'
app.selected = app.currentGraph.incomingSuggestions[app.incomingSuggestionsIds.indexOf(selectedNodeId)]
} else {
app.showArticlesTab = 'topCitations'
app.selected = app.currentGraph.outgoingSuggestions[app.outgoingSuggestionsIds.indexOf(selectedNodeId)]
}
// Don't select edges
} else {
app.selected = undefined
citationNetwork.setSelection({
nodes: [],
edges: []
})
}
}
function networkOnDoubleClick (params) {
// Open article in new tab
if (params.nodes.length > 0) {
window.open(app.articleLink(app.selected), '_blank')
} else {
citationNetwork.fit()
}
}
}
function initAuthorNetwork (app, minPublications = undefined) {
if (!document.getElementById('authorNetwork')) return false
// Only init network if it doesn't exist yet (or was previously reset == destroyed)
if (document.getElementById('authorNetwork').innerHTML !== '') return false
app.authorNetworkIsLoading = true
// Deep copy articles because otherwise sorting (and setting "x.id = ..." later) would overwrite currentGraph's articles
const articles = JSON.parse(JSON.stringify(app.currentGraph.input))
articles.sort((articleA, articleB) => (app.authorNetworkNodeColor === 'firstArticle') ? articleA.year - articleB.year : articleB.year - articleA.year)
// Used to be "x.id = x.id || x.name" but caused too many duplicates (at least on OA), double check in the future if this has been fixed
let allAuthors = articles.map(article => article.authors.map(x => { x.name = app.authorString([x]); x.id = x.name; return x }))
let authorIdGroups = allAuthors.map(authorGroup => authorGroup.map(author => author.id))
allAuthors = Object.fromEntries(allAuthors.flat().map(author => [author.id, author]))
// Count publications per author
const publicationsCount = {}
authorIdGroups.flat().forEach(authorId => {
publicationsCount[authorId] = (publicationsCount[authorId] || 0) + 1
})
let authorIdsWithMinPubs = []
const links = {}
if (!minPublications) {
// Default minPublications: Increase iteratively until <= 50 authors are shown
minPublications = 2
authorIdsWithMinPubs = Object.keys(publicationsCount).filter(authorId => publicationsCount[authorId] >= minPublications)
while (authorIdsWithMinPubs.length > 50) {
minPublications++
authorIdsWithMinPubs = Object.keys(publicationsCount).filter(authorId => publicationsCount[authorId] >= minPublications)
}
app.authorNetworkMinPublications = minPublications
} else {
authorIdsWithMinPubs = Object.keys(publicationsCount).filter(authorId => publicationsCount[authorId] >= minPublications)
}
if (!authorIdsWithMinPubs.length) {
app.authorNetworkIsLoading = false
}
authorIdGroups = authorIdGroups.map(group => group.filter(authorId => authorIdsWithMinPubs.includes(authorId)))
authorIdGroups.forEach(group => group.forEach(authorId1 => group.forEach(authorId2 => {
if (authorId1 === authorId2) return false
// Is there already a link for this pair? If so, make it stronger
if (links[authorId1]?.[authorId2]) return links[authorId1][authorId2]++
if (links[authorId2]?.[authorId1]) return links[authorId2][authorId1]++
// Create new link
if (!links[authorId1]) links[authorId1] = {}
links[authorId1][authorId2] = 1
})))
const edges = Object.keys(links).map(authorId1 => Object.keys(links[authorId1]).map(authorId2 => {
return { from: authorId1, to: authorId2, value: links[authorId1][authorId2], title: allAuthors[authorId1].name + ' & ' + allAuthors[authorId2].name + ' (' + links[authorId1][authorId2] / 2 + ' collaboration(s) among input & suggested articles)' }
})).flat(2)
const nodes = authorIdsWithMinPubs.map(authorId => {
const author = allAuthors[authorId]
const isSourceAuthor = app.authorString(app.currentGraph.source.authors).includes(author.name)
const inputArticlesAuthoredCount = app.currentGraph.input.filter(article => app.authorString(article.authors).includes(author.name)).length
const authorIdGroupIndex = authorIdGroups.map(group => group.includes(author.id)).indexOf(true)
return {
id: author.id,
title: htmlTitle(author.name + ': author of ' + inputArticlesAuthoredCount + ' input articles' + (isSourceAuthor ? ' (including source)' : '') + '.<br>' + (author.affil ? 'Affiliation(s): ' + author.affil + '<br>' : '') + ' Color by ' + ((app.authorNetworkNodeColor === 'firstArticle') ? 'first' : 'last') + ' article: ' + articles[authorIdGroupIndex].title + ' <br>(Double click opens author: <a>' + app.authorLink(author).substr(0, 28) + '...</a>)'),
group: authorIdGroupIndex,
label: ((app.authorNetworkFirstNames) ? (author.FN + ' ') : '') + author.LN,
value: publicationsCount[author.id],
mass: publicationsCount[author.id],
shape: (isSourceAuthor) ? 'diamond' : 'dot'
}
})
// create a network
const options = {
nodes: {
font: {
strokeWidth: 3,
strokeColor: '#eeeeee'
},
scaling: {
min: 10,
max: 30,
label: {
enabled: true,
min: 14,
max: 30,
maxVisible: 30,
drawThreshold: 8
}
}
},
edges: {
color: {
inherit: 'both'
},
smooth: false
},
physics: {
barnesHut: {
centralGravity: 10
},
maxVelocity: 20
},
interaction: {
multiselect: true,
hideEdgesOnDrag: true,
hideEdgesOnZoom: true,
keyboard: {
enabled: true,
bindToWindow: false,
autoFocus: false
}
},
configure: {
enabled: true,
container: document.getElementById('authorNetworkConfigure')
}
}
authorNetwork = new vis.Network(document.getElementById('authorNetwork'), { nodes: nodes, edges: edges }, options)
authorNetwork.on('click', networkOnClick)
authorNetwork.on('doubleClick', networkOnDoubleClick)
authorNetwork.stabilize(100)
authorNetwork.on('stabilizationIterationsDone', function (params) {
app.authorNetworkIsLoading = false
authorNetwork.setOptions({ physics: false })
authorNetwork.fit()
})
authorNetwork.on('beforeDrawing', function (ctx) {
// https://github.com/almende/vis/issues/2292#issuecomment-372044181
// save current translate/zoom
ctx.save()
// reset transform to identity
ctx.setTransform(1, 0, 0, 1, 0, 0)
// fill background with solid white
ctx.fillStyle = '#ffffff'
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height)
// restore old transform
ctx.restore()
})
function networkOnClick (params) {
app.filterColumn = 'authors'
// If no node is clicked...
if (!params.nodes.length) {
// Maybe an edge?
if (params.edges.length) {
const edge = authorNetwork.body.data.edges.get(params.edges[0])
params.nodes = [edge.from, edge.to]
app.filterString = '(?=.*' + allAuthors[edge.from].name + ')(?=.*' + allAuthors[edge.to].name + ')'
// Otherwise reset filterString
} else {
app.selected = undefined
app.filterString = undefined
}
// If just one node is selected perform simple filter for that author
} else if (params.nodes.length === 1) {
app.filterString = allAuthors[params.nodes[0]].name
// If more than one node are selected, perform "boolean and" in regular expression through lookaheads, which means order isn't important (see https://www.ocpsoft.org/tutorials/regular-expressions/and-in-regex/)
} else {
app.filterString = '(?=.*' + params.nodes.map(x => allAuthors[x].name).join(')(?=.*') + ')'
}
app.highlightNodes(params.nodes)
}
function networkOnDoubleClick (params) {
// Open author in new tab
if (params.nodes.length > 0) {
window.open(app.authorLink(allAuthors[params.nodes[0]]), '_blank')
} else {
authorNetwork.fit()
}
}
}
/* App logic */
Vue.use(Buefy)
const vm = new Vue({
el: '#app',
data: {
// Settings
API: 'OpenAlex', // Options: 'OpenAlex', 'Semantic Scholar', 'OpenCitations', 'Crossref'
semanticScholarAPIKey: '',
retrieveReferences: 10,
retrieveCitations: 10,
maxTabs: 5,
autosaveResults: false,
// Data
graphs: [],
newSourceId: undefined,
file: undefined,
listOfIds: undefined,
listName: undefined,
bookmarkletURL: undefined,
// UI
fullscreenTable: false,
fullscreenNetwork: false,
filterColumn: 'titleAbstract',
filterString: undefined,
selectedInputArticle: undefined,
selectedIncomingSuggestionsArticle: undefined,
selectedOutgoingSuggestionsArticle: undefined,
articlesPerPage: 20,
inputArticlesTablePage: 1,
topReferencesTablePage: 1,
topCitationsTablePage: 1,
currentTabIndex: undefined,
showArticlesTab: 'inputArticles',
showAuthorNetwork: 0,
isLoading: false,
isLoadingIndex: 0,
isLoadingTotal: 0,
citationNetworkIsLoading: undefined,
authorNetworkIsLoading: undefined,
showFAQ: false,
indexFAQ: 'about',
editListOfIds: false,
showCitationNetworkSettings: false,
showAuthorNetworkSettings: false,
showOptionsAPI: false
},
computed: {
editedListOfIds: {
get: function () { return (this.listOfIds || []).join('\n') },
set: function (x) { this.listOfIds = x.split('\n').map(x => x.replaceAll(/\s/g, '')) }
},
currentGraph: function () {
if (this.currentTabIndex === undefined) return {}
return this.graphs[this.currentTabIndex]
},
inputArticlesIds: function () {
return this.currentGraph.input.map(article => article.id)
},
incomingSuggestionsIds: function () {
return this.currentGraph.incomingSuggestions.map(article => article.id)
},
outgoingSuggestionsIds: function () {
return this.currentGraph.outgoingSuggestions.map(article => article.id)
},
inputArticlesFiltered: function () {
return this.filterArticles(this.currentGraph.input, true)
},
incomingSuggestionsFiltered: function () {
return this.filterArticles(this.currentGraph.incomingSuggestions ?? [])
},
outgoingSuggestionsFiltered: function () {
return this.filterArticles(this.currentGraph.outgoingSuggestions ?? [])
},
referencedCiting: function () {
const articles = this.currentGraph.input.concat(this.currentGraph.incomingSuggestions || []).concat(this.currentGraph.outgoingSuggestions || [])
const referencedCiting = this.computeInputArticlesRelationships(articles, this.inputArticlesIds)
let referenced = referencedCiting.inputArticlesA
const citing = referencedCiting.inputArticlesB
// Reduce referenced Object to items with key in articles.id
referenced = articles.map(x => x.id).filter(x => Object.keys(referenced).includes(x)).reduce((reducedReferenced, id) => { reducedReferenced[id] = referenced[id]; return reducedReferenced }, {})
return { referenced, citing }
},
selected: {
get: function () {
switch (this.showArticlesTab) {
case 'inputArticles': return this.selectedInputArticle
case 'topReferences': return this.selectedIncomingSuggestionsArticle
case 'topCitations': return this.selectedOutgoingSuggestionsArticle
}
},
set: function (x) {
switch (this.showArticlesTab) {
case 'inputArticles':
this.selectedInputArticle = x
if (x) this.inputArticlesTablePage = Math.ceil((this.$refs.inputArticlesTable.newData.indexOf(x) + 1) / vm.articlesPerPage)
break
case 'topReferences':
this.selectedIncomingSuggestionsArticle = x
if (x) this.topReferencesTablePage = Math.ceil((this.$refs.topReferencesTable.newData.indexOf(x) + 1) / vm.articlesPerPage)
break
case 'topCitations':
this.selectedOutgoingSuggestionsArticle = x
if (x) this.topCitationsTablePage = Math.ceil((this.$refs.topCitationsTable.newData.indexOf(x) + 1) / vm.articlesPerPage)
break
}
if (x && document.getElementById(x.id)) document.getElementById(x.id).scrollIntoView({ behavior: 'smooth', block: 'center' })
}
},
linkToShareAppendix: function () {
let appendix = '?API=' + encodeURIComponent(this.currentGraph.API)
if (this.currentGraph.source.id) {
appendix += '&source=' + (this.currentGraph.source.doi ? this.currentGraph.source.doi : this.currentGraph.source.id)
if (this.currentGraph.source.customListOfReferences) {
appendix += '&listOfIds=' + this.currentGraph.source.customListOfReferences.join(',')
}
if (this.currentGraph.bookmarkletURL) {
appendix += '&bookmarkletURL=' + this.currentGraph.bookmarkletURL
}
} else {
appendix += '&name=' + encodeURIComponent(this.currentGraph.tabLabel) + '&listOfIds=' + this.currentGraph.source.references.join(',')
}
return appendix
},
showNumberInSourceReferences: function () {
return this.currentGraph.API === 'Crossref' || (this.currentGraph.source.customListOfReferences !== undefined) || !this.currentGraph.source.id
},
// The following are settings and their default values
maxIncomingSuggestions: {
get: function () { return this.currentGraph.maxIncomingSuggestions ?? Math.min(10, this.currentGraph.incomingSuggestions?.length) },
set: function (x) { if (x >= 0 && x <= this.currentGraph.incomingSuggestions?.length) this.$set(this.currentGraph, 'maxIncomingSuggestions', Number(x)) }
},
maxOutgoingSuggestions: {
get: function () { return this.currentGraph.maxOutgoingSuggestions ?? Math.min(10, this.currentGraph.outgoingSuggestions?.length) },
set: function (x) { if (x >= 0 && x <= this.currentGraph.outgoingSuggestions?.length) this.$set(this.currentGraph, 'maxOutgoingSuggestions', Number(x)) }
},
minDegreeIncomingSuggestions: {
get: function () { return this.currentGraph.minDegreeIncomingSuggestions ?? 1 },
set: function (x) { this.$set(this.currentGraph, 'minDegreeIncomingSuggestions', Number(x)) }
},
minDegreeOutgoingSuggestions: {
get: function () { return this.currentGraph.minDegreeOutgoingSuggestions ?? 1 },
set: function (x) { this.$set(this.currentGraph, 'minDegreeOutgoingSuggestions', Number(x)) }
},
citationNetworkNodeColor: {
// Options: 'year', 'journal'
get: function () { return this.currentGraph.citationNetworkNodeColor ?? 'year' },
set: function (x) { this.$set(this.currentGraph, 'citationNetworkNodeColor', x) }
},
citationNetworkNodeSize: {
// Options: 'both', 'in', 'out
get: function () { return this.currentGraph.citationNetworkNodeSize ?? 'both' },
set: function (x) { this.$set(this.currentGraph, 'citationNetworkNodeSize', x) }
},
citationNetworkShowSource: {
get: function () { return this.currentGraph.citationNetworkShowSource ?? true },
set: function (x) { this.$set(this.currentGraph, 'citationNetworkShowSource', x) }
},
authorNetworkNodeColor: {
// Options: 'firstArticle', 'lastArticle'
get: function () { return this.currentGraph.authorNetworkNodeColor ?? 'firstArticle' },
set: function (x) { this.$set(this.currentGraph, 'authorNetworkNodeColor', x) }
},
authorNetworkFirstNames: {
get: function () { return this.currentGraph.authorNetworkFirstNames ?? false },
set: function (x) { this.$set(this.currentGraph, 'authorNetworkFirstNames', x) }
},
authorNetworkMinPublications: {
get: function () { return this.currentGraph.authorNetworkMinPublications },
set: function (x) { this.$set(this.currentGraph, 'authorNetworkMinPublications', x) }
},
// The following are for the estimation of the completeness of the data
completenessOriginalReferencesCount: function () {
return (this.currentGraph.source.customListOfReferences || this.currentGraph.source.references).length
},