-
Notifications
You must be signed in to change notification settings - Fork 4
/
harvest_pure_to_ricgraph.py
1791 lines (1615 loc) · 88.3 KB
/
harvest_pure_to_ricgraph.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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
# ########################################################################
#
# Ricgraph - Research in context graph
#
# ########################################################################
#
# MIT License
#
# Copyright (c) 2023 Rik D.T. Janssen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
# ########################################################################
#
# This file contains example code for Ricgraph.
#
# With this code, you can harvest persons, organizations and research outputs from Pure,
# using both the READ API as well as the CRUD API. You don't need to specify this,
# the script will know.
# I would recommend to use the READ API, since the CRUD API is in development and does not have
# filters on e.g. active persons yet. Neither does it allow harvesting of research outputs
# for one year only, so you might hit memory bounds if you harvest every research output
# for all years with the CRUD API.
#
# In Pure, organizations are hierarchical. That means, an organization has a parent org,
# which has a parent org, up until a root org.
# At the end of this script, a person (i.e. its person-root node) will be connected to
# all of these hierarchical orgs.
#
# You have to set some parameters in ricgraph.ini.
# Also, you can set a number of parameters in the code following the "import" statements below.
#
# Original version Rik D.T. Janssen, December 2022.
# Updated Rik D.T. Janssen, April, October, November 2023.
#
# ########################################################################
#
# Usage
# harvest_pure_to_ricgraph.py [options]
#
# Options:
# --empty_ricgraph <yes|no>
# 'yes': Ricgraph will be emptied before harvesting.
# 'no': Ricgraph will not be emptied before harvesting.
# If this option is not present, the script will prompt the user
# what to do.
# --organization <organization abbreviation>
# Harvest data from organization <organization abbreviation>.
# The organization abbreviations are specified in the Ricgraph ini
# file.
# If this option is not present, the script will prompt the user
# what to do.
# --harvest_projects <yes|no>
# 'yes': projects will be harvested.
# 'no' (or any other answer): projects will not be harvested.
# If this option is not present, projects will not be harvested,
# the script will not prompt the user.
#
# ########################################################################
import os.path
import sys
import re
import pandas
import numpy
from typing import Union
import configparser
import requests
import pathlib
import ricgraph as rcg
# ######################################################
# General parameters for harvesting from Pure.
# Documentation Pure API: PURE_URL/ws/api/524/api-docs/index.html
# ######################################################
# Pure can be harvested according to the READ or CRUD API.
global PURE_API_VERSION
PURE_READ_API_VERSION = 'ws/api/524'
PURE_CRUD_API_VERSION = 'ws/api'
PURE_CHUNKSIZE = 500
PURE_HEADERS = {'Accept': 'application/json'
# The following will be read in __main__
# 'api-key': PURE_API_KEY
}
global PURE_URL
global HARVEST_SOURCE
global HARVEST_PROJECTS
global resout_uuid_or_doi
# ######################################################
# Parameters for harvesting persons from Pure
# ######################################################
# Pure can be harvested according to the READ or CRUD API.
global PURE_PERSONS_ENDPOINT
PURE_READ_PERSONS_ENDPOINT = 'persons'
PURE_CRUD_PERSONS_ENDPOINT = 'persons/search'
PURE_PERSONS_HARVEST_FROM_FILE = False
# PURE_PERSONS_HARVEST_FROM_FILE = True
PURE_PERSONS_HARVEST_FILENAME = 'pure_persons_harvest.json'
PURE_PERSONS_DATA_FILENAME = 'pure_persons_data.csv'
PURE_PERSONS_MAX_RECS_TO_HARVEST = 0 # 0 = all records
# The current version of the Pure CRUD API does not have these filters yet.
PURE_PERSONS_FIELDS = {'fields': ['uuid',
'name.*',
'ids.*',
'staffOrganisationAssociations.period.*',
'staffOrganisationAssociations.organisationalUnit.*',
'orcid'
]
# See remark below.
# 'employmentStatus': 'ACTIVE'
}
# For the Pure READ API.
# We harvest all persons from Pure, whether they are active or not. We do this,
# because persons not active might have contributed to a research output.
# But we only add these persons if their endDate is within
# PURE_PERSONS_INCLUDE_YEARS_BEFORE years before the lowest value in PURE_RESOUT_YEARS.
# Otherwise, we may end up with far too many persons.
#
# Sept 2024: In 2023 I thought not to add the organization of such a person
# because it seemed very probably outdated.
# But it appears that some organizations use an endDate in the future (instead
# of no endDate) for persons employed.
# So we do need to add the organization of these persons.
PURE_PERSONS_INCLUDE_YEARS_BEFORE = 5
# For the Pure CRUD API we use this value, because we cannot filter research
# outputs on years.
PURE_PERSONS_LOWEST_YEAR = 2010
# ######################################################
# Parameters for harvesting organizations from Pure
# ######################################################
# Pure can be harvested according to the READ or CRUD API.
global PURE_ORGANIZATIONS_ENDPOINT
PURE_READ_ORGANIZATIONS_ENDPOINT = 'organisational-units'
PURE_CRUD_ORGANIZATIONS_ENDPOINT = 'organizations/search'
PURE_ORGANIZATIONS_HARVEST_FROM_FILE = False
# PURE_ORGANIZATIONS_HARVEST_FROM_FILE = True
PURE_ORGANIZATIONS_HARVEST_FILENAME = 'pure_organizations_harvest.json'
PURE_ORGANIZATIONS_DATA_FILENAME = 'pure_organizations_data.csv'
PURE_ORGANIZATIONS_MAX_RECS_TO_HARVEST = 0 # 0 = all records
# The current version of the Pure CRUD API does not have these filters yet.
PURE_ORGANIZATIONS_FIELDS = {'fields': ['uuid',
'period.*',
'name.*',
'type.*',
'ids.*',
'parents.*'
]
}
# ######################################################
# Parameters for harvesting research outputs from Pure
# ######################################################
# Pure can be harvested according to the READ or CRUD API.
global PURE_RESOUT_ENDPOINT
PURE_READ_RESOUT_ENDPOINT = 'research-outputs'
PURE_CRUD_RESOUT_ENDPOINT = 'research-outputs/search'
PURE_RESOUT_HARVEST_FROM_FILE = False
# PURE_RESOUT_HARVEST_FROM_FILE = True
PURE_RESOUT_HARVEST_FILENAME = 'pure_resout_harvest.json'
PURE_RESOUT_DATA_FILENAME = 'pure_resout_data.csv'
global PURE_RESOUT_YEARS
# The Pure READ API allows to specify years to harvest.
# PURE_READ_RESOUT_YEARS = ['2021']
PURE_READ_RESOUT_YEARS = ['2021', '2022', '2023', '2024']
# The Pure CRUD API does not allow this. This might cause memory problems.
# You might want to set PURE_RESOUT_MAX_RECS_TO_HARVEST.
PURE_CRUD_RESOUT_YEARS = ['all']
# For Pure READ API: this number is the max recs to harvest per year, not total
# For Pure CRUD API: this number is the max recs to harvest total.
PURE_RESOUT_MAX_RECS_TO_HARVEST = 0 # 0 = all records
global PURE_RESOUT_FIELDS
# The current version of the Pure CRUD API does not have these filters yet.
PURE_READ_RESOUT_FIELDS = {'fields': ['uuid',
'title.*',
'confidential',
'type.*',
'workflow.*',
'publicationStatuses.*',
'personAssociations.*',
'electronicVersions.*'
]
}
PURE_CRUD_RESOUT_FIELDS = {'orderings': ['publicationYear'],
'orderBy': 'descending'
}
# ######################################################
# Parameters for harvesting projects from Pure
# ######################################################
# Pure can be harvested according to the READ or CRUD API.
# However, for projects we only harvest them using the READ API.
global PURE_PROJECTS_ENDPOINT
PURE_READ_PROJECTS_ENDPOINT = 'projects'
# PURE_CRUD_PROJECTS_ENDPOINT = 'projects/search'
PURE_PROJECTS_HARVEST_FROM_FILE = False
# PURE_PROJECTS_HARVEST_FROM_FILE = True
PURE_PROJECTS_HARVEST_FILENAME = 'pure_projects_harvest.json'
PURE_PROJECTS_DATA_FILENAME = 'pure_projects_data.csv'
PURE_PROJECTS_MAX_RECS_TO_HARVEST = 0 # 0 = all records
# The current version of the Pure CRUD API does not have these filters yet.
PURE_PROJECTS_FIELDS = {'fields': ['uuid',
'period.*',
'confidential',
'title.*',
'status.*',
'visibility.*',
'workflow.*',
'descriptions.*',
'ids.*',
'participants.person.uuid.*',
'participants.organisationalUnits.uuid.*',
# 'managingOrganisationalUnit.*', # We use the organization of the participant.
# 'organizationalUnits.*', # We use the organization of the participant.
# 'collaborators.*', # These are other organizations, skip.
'relatedResearchOutputs.uuid.*',
'relatedResearchOutputs.type.*',
'relatedProjects.project.uuid.*',
# 'relatedDataSets.*', # Datasets are supposed to be in research outputs.
# 'relatedActivities.*',
# 'relatedPrizes.*',
# 'relatedPressMedia.*',
]
}
# ######################################################
# Mapping from Pure research output types to Ricgraph research output types.
# ######################################################
ROTYPE_PREFIX_PURE = '/dk/atira/pure/researchoutput/researchoutputtypes/'
ROTYPE_MAPPING_PURE = {
ROTYPE_PREFIX_PURE + 'bookanthology/anthology': rcg.ROTYPE_BOOK,
ROTYPE_PREFIX_PURE + 'bookanthology/book': rcg.ROTYPE_BOOK,
ROTYPE_PREFIX_PURE + 'bookanthology/commissioned': rcg.ROTYPE_BOOK,
ROTYPE_PREFIX_PURE + 'bookanthology/inaugural': rcg.ROTYPE_BOOK,
ROTYPE_PREFIX_PURE + 'bookanthology/registered_report': rcg.ROTYPE_REGISTERED_REPORT,
ROTYPE_PREFIX_PURE + 'bookanthology/valedictory': rcg.ROTYPE_BOOK,
ROTYPE_PREFIX_PURE + 'contributiontobookanthology/case_note': rcg.ROTYPE_MEMORANDUM,
ROTYPE_PREFIX_PURE + 'contributiontobookanthology/chapter': rcg.ROTYPE_BOOKCHAPTER,
ROTYPE_PREFIX_PURE + 'contributiontobookanthology/commissioned': rcg.ROTYPE_BOOKCHAPTER,
ROTYPE_PREFIX_PURE + 'contributiontobookanthology/conference': rcg.ROTYPE_BOOKCHAPTER,
ROTYPE_PREFIX_PURE + 'contributiontobookanthology/entry': rcg.ROTYPE_ENTRY,
ROTYPE_PREFIX_PURE + 'contributiontobookanthology/foreword': rcg.ROTYPE_ABSTRACT,
ROTYPE_PREFIX_PURE + 'contributiontoconference/abstract': rcg.ROTYPE_ABSTRACT,
ROTYPE_PREFIX_PURE + 'contributiontoconference/other': rcg.ROTYPE_CONFERENCE_ARTICLE,
ROTYPE_PREFIX_PURE + 'contributiontoconference/paper': rcg.ROTYPE_CONFERENCE_ARTICLE,
ROTYPE_PREFIX_PURE + 'contributiontoconference/poster': rcg.ROTYPE_POSTER,
ROTYPE_PREFIX_PURE + 'contributiontojournal/abstract': rcg.ROTYPE_ABSTRACT,
ROTYPE_PREFIX_PURE + 'contributiontojournal/article': rcg.ROTYPE_JOURNAL_ARTICLE,
ROTYPE_PREFIX_PURE + 'contributiontojournal/book': rcg.ROTYPE_BOOK,
ROTYPE_PREFIX_PURE + 'contributiontojournal/case_note': rcg.ROTYPE_MEMORANDUM,
ROTYPE_PREFIX_PURE + 'contributiontojournal/comment': rcg.ROTYPE_MEMORANDUM,
ROTYPE_PREFIX_PURE + 'contributiontojournal/conferencearticle': rcg.ROTYPE_CONFERENCE_ARTICLE,
ROTYPE_PREFIX_PURE + 'contributiontojournal/editorial': rcg.ROTYPE_EDITORIAL,
ROTYPE_PREFIX_PURE + 'contributiontojournal/erratum': rcg.ROTYPE_MEMORANDUM,
ROTYPE_PREFIX_PURE + 'contributiontojournal/letter': rcg.ROTYPE_LETTER,
ROTYPE_PREFIX_PURE + 'contributiontojournal/scientific': rcg.ROTYPE_JOURNAL_ARTICLE,
ROTYPE_PREFIX_PURE + 'contributiontojournal/shortsurvey': rcg.ROTYPE_JOURNAL_ARTICLE,
ROTYPE_PREFIX_PURE + 'contributiontojournal/special': rcg.ROTYPE_JOURNAL_ARTICLE,
ROTYPE_PREFIX_PURE + 'contributiontojournal/systematicreview': rcg.ROTYPE_REVIEW,
ROTYPE_PREFIX_PURE + 'memorandum/academicmemorandum': rcg.ROTYPE_MEMORANDUM,
ROTYPE_PREFIX_PURE + 'methoddescription': rcg.ROTYPE_METHOD_DESCRIPTION,
ROTYPE_PREFIX_PURE + 'nontextual/database': rcg.ROTYPE_DATASET,
ROTYPE_PREFIX_PURE + 'nontextual/design': rcg.ROTYPE_DESIGN,
ROTYPE_PREFIX_PURE + 'nontextual/digitalorvisualproducts': rcg.ROTYPE_DIGITAL_VISUAL_PRODUCT,
ROTYPE_PREFIX_PURE + 'nontextual/exhibition': rcg.ROTYPE_EXHIBITION_PERFORMANCE,
ROTYPE_PREFIX_PURE + 'nontextual/performance': rcg.ROTYPE_EXHIBITION_PERFORMANCE,
ROTYPE_PREFIX_PURE + 'nontextual/software': rcg.ROTYPE_SOFTWARE,
ROTYPE_PREFIX_PURE + 'nontextual/web': rcg.ROTYPE_WEBSITE,
ROTYPE_PREFIX_PURE + 'othercontribution/other': rcg.ROTYPE_OTHER_CONTRIBUTION,
ROTYPE_PREFIX_PURE + 'patent/patent': rcg.ROTYPE_PATENT,
ROTYPE_PREFIX_PURE + 'thesis/doc1': rcg.ROTYPE_PHDTHESIS,
ROTYPE_PREFIX_PURE + 'thesis/doc2': rcg.ROTYPE_PHDTHESIS,
ROTYPE_PREFIX_PURE + 'thesis/doc3': rcg.ROTYPE_PHDTHESIS,
ROTYPE_PREFIX_PURE + 'thesis/doc4': rcg.ROTYPE_PHDTHESIS,
ROTYPE_PREFIX_PURE + 'workingpaper/discussionpaper': rcg.ROTYPE_PREPRINT,
ROTYPE_PREFIX_PURE + 'workingpaper/preprint': rcg.ROTYPE_PREPRINT,
ROTYPE_PREFIX_PURE + 'workingpaper/workingpaper': rcg.ROTYPE_PREPRINT
}
# ######################################################
# Utility functions related to harvesting of Pure
# ######################################################
def create_pure_url(name: str, value: str) -> str:
"""Create a URL to refer to the source of a node.
:param name: an identifier name, e.g. PURE_UUID_PERS, PURE_UUID_ORG, etc.
:param value: the value.
:return: a URL.
"""
if name == '' or value == '':
return ''
if name == 'PURE_UUID_PERS':
return PURE_URL + '/en/persons/' + value
elif name == 'PURE_UUID_ORG':
return PURE_URL + '/en/organisations/' + value
elif name == 'PURE_UUID_RESOUT':
return PURE_URL + '/en/publications/' + value
elif name == 'PURE_UUID_PROJECT':
return PURE_URL + '/en/projects/' + value
else:
return ''
def create_urlmain(type_id: str, doi_value: str, uuid_value: str) -> str:
"""A helper function for parsed_resout_to_ricgraph()"""
if type_id == 'DOI':
return rcg.create_well_known_url(name=type_id,
value=doi_value)
elif type_id == 'PURE_UUID_RESOUT':
return create_pure_url(name=type_id,
value=uuid_value)
else:
# Should not happen
print('create_urlmain(): error')
return ''
def create_urlother(type_id: str, uuid_value: str) -> str:
"""A helper function for parsed_resout_to_ricgraph()"""
if type_id == 'DOI':
return create_pure_url(name='PURE_UUID_RESOUT',
value=uuid_value)
else:
return ''
def rewrite_pure_doi(doi: str) -> str:
"""Rewrite the DOI obtained from Pure.
They are written in various different ways, so they need to be rewritten.
:param doi: DOI to rewrite.
:return: Result of rewriting.
"""
doi = doi.lower()
# '|' in regex is "or"
# 'flags=re.IGNORECASE' not necessary, everything is lowercase already
doi = re.sub(pattern=r'https|http', repl='', string=doi)
doi = re.sub(pattern=r'doi.org', repl='', string=doi)
doi = re.sub(pattern=r'doi', repl='', string=doi)
# Remove any /, : or space at the beginning
doi = re.sub(pattern=r'^[/: ]*', repl='', string=doi)
doi = re.sub(pattern=r'.proxy.uu.nl/', repl='', string=doi)
return doi
def find_organization_name(uuid: str, organization_names: dict):
"""Find the full organization name which belongs to an organization with a certain UUID.
:param uuid: the UUID.
:param organization_names: the dict with organization names.
:return: the full organization name.
"""
if uuid in organization_names:
return str(organization_names[uuid])
else:
return 'Organization name not found for UUID ' + uuid + '.'
# ######################################################
# Parsing
# ######################################################
def parse_pure_persons(harvest: list) -> pandas.DataFrame:
"""Parse the harvested persons from Pure.
:param harvest: the harvest.
:return: the harvested persons in a DataFrame.
"""
if PURE_API_VERSION == PURE_READ_API_VERSION:
# We use the Pure READ API.
lowest_resout_year = int(min(PURE_RESOUT_YEARS)) - PURE_PERSONS_INCLUDE_YEARS_BEFORE
else:
lowest_resout_year = PURE_PERSONS_LOWEST_YEAR
# parse_chunk_final: things we want to put in the DataFrame parse_result with
# harvested persons to be returned.
parse_chunk_final = []
parse_result = pandas.DataFrame()
print('There are ' + str(len(harvest)) + ' person records ('
+ rcg.timestamp() + '), parsing record: 0 ', end='')
count = 0
for harvest_item in harvest:
# parse_chunk: things of this loop we might want to put in the DataFrame with
# harvested persons to be returned. If so, we add them to parse_chunk_final.
# If not they will not end up in the harvested persons.
parse_chunk = []
count += 1
if count % 1000 == 0:
print(count, ' ', end='', flush=True)
if count % 10000 == 0:
print('(' + rcg.timestamp() + ')\n', end='', flush=True)
if 'uuid' not in harvest_item:
# There must be an uuid, otherwise skip
continue
if 'name' in harvest_item:
if 'lastName' in harvest_item['name']:
parse_line = {'PURE_UUID_PERS': str(harvest_item['uuid']),
'FULL_NAME': harvest_item['name']['lastName']}
if 'firstName' in harvest_item['name']:
parse_line['FULL_NAME'] += ', ' + harvest_item['name']['firstName']
parse_chunk.append(parse_line)
if 'orcid' in harvest_item:
parse_line = {'PURE_UUID_PERS': str(harvest_item['uuid']),
'ORCID': str(harvest_item['orcid'])}
parse_chunk.append(parse_line)
if 'ids' in harvest_item:
# Field in Pure READ API.
for identities in harvest_item['ids']:
if 'value' in identities and 'type' in identities:
value_identifier = str(identities['value']['value'])
name_identifier = str(identities['type']['term']['text'][0]['value'])
parse_line = {'PURE_UUID_PERS': str(harvest_item['uuid']),
name_identifier: value_identifier}
parse_chunk.append(parse_line)
if 'identifiers' in harvest_item:
# Field in Pure CRUD API.
for identities in harvest_item['identifiers']:
if 'id' in identities and 'type' in identities:
value_identifier = str(identities['id'])
name_identifier = str(identities['type']['term']['en_GB'])
parse_line = {'PURE_UUID_PERS': str(harvest_item['uuid']),
name_identifier: value_identifier}
parse_chunk.append(parse_line)
label = ''
if 'staffOrganisationAssociations' in harvest_item:
# Field in Pure READ API.
label = 'staffOrganisationAssociations'
elif 'staffOrganizationAssociations' in harvest_item:
# Field in Pure CRUD API.
label = 'staffOrganizationAssociations'
if label != '':
for stafforg in harvest_item[label]:
if 'period' in stafforg:
if 'endDate' in stafforg['period'] and stafforg['period']['endDate'] != '':
# Only consider persons of current organizations, that is an organization
# where endData is not existing or empty. If not, then skip.
end_year = int(stafforg['period']['endDate'][:4])
if end_year < lowest_resout_year:
continue
# else:
# # In 2023:
# # Put in the DataFrame with harvested persons to be returned.
# # We do not add its organization because it is very probably outdated.
# # No need to check if it is already there, it that is the case it will
# # be filtered out from the dataframe below.
# #
# # Sept 2024: In 2023 I thought not to add the organization of such a person
# # because it seemed very probably outdated.
# # But it appears that some organizations use an endDate in the future (instead
# # of no endDate) for persons employed.
# # So we do need to add the organization of these persons.
# # So I commented this 'else'.
# parse_chunk_final.extend(parse_chunk)
# continue
else:
# If there is no period skip
continue
if 'organisationalUnit' in stafforg:
# Field in Pure READ API.
orgunit = stafforg['organisationalUnit']
if 'type' in orgunit:
pure_org_uri = str(orgunit['type']['uri'])
if pure_org_uri[-3] == 'r':
# Skip research organizations (with an 'r' in the uri, like ..../r05)
continue
elif 'organization' in stafforg:
# Field in Pure CRUD API.
orgunit = stafforg['organization']
# We don't have the 'type' in Pure CRUD API.
else:
continue
parse_line = {'PURE_UUID_PERS': str(harvest_item['uuid']),
'PURE_UUID_ORG': str(orgunit['uuid'])}
parse_chunk.append(parse_line)
# Put in the DataFrame with harvested persons to be returned.
parse_chunk_final.extend(parse_chunk)
print(count, '(' + rcg.timestamp() + ')\n', end='', flush=True)
parse_chunk_df = pandas.DataFrame(parse_chunk_final)
parse_result = pandas.concat([parse_result, parse_chunk_df], ignore_index=True)
# dropna(how='all'): drop row if all row values contain NaN
parse_result.dropna(axis=0, how='all', inplace=True)
parse_result.drop_duplicates(keep='first', inplace=True, ignore_index=True)
if 'Scopus Author ID' in parse_result.columns:
parse_result.rename(columns={'Scopus Author ID': 'SCOPUS_AUTHOR_ID'}, inplace=True)
if 'Digital author ID' in parse_result.columns:
parse_result.rename(columns={'Digital author ID': 'DIGITAL_AUTHOR_ID'}, inplace=True)
if 'Researcher ID' in parse_result.columns:
parse_result.rename(columns={'Researcher ID': 'RESEARCHER_ID'}, inplace=True)
if 'Employee ID' in parse_result.columns:
parse_result.rename(columns={'Employee ID': 'EMPLOYEE_ID'}, inplace=True)
if 'PURE_UUID_ORG' not in parse_result.columns \
and PURE_API_VERSION == PURE_CRUD_API_VERSION:
print('\nPure is harvested using the Pure CRUD API.')
print('Persons found are not members of any organization.')
print('This is probably caused by field "staffOrganizationAssociations" not present in')
print('the CRUD API export for "persons".')
print('Please ask your Pure administrator to export this field. Exiting.')
exit(1)
return parse_result
def parse_pure_organizations(harvest: list) -> pandas.DataFrame:
"""Parse the harvested organizations from Pure.
:param harvest: the harvest.
:return: the harvested organizations in a DataFrame.
"""
global organization
parse_result = pandas.DataFrame()
parse_chunk = [] # list of dictionaries
organization_names = {}
print('There are ' + str(len(harvest)) + ' organization records ('
+ rcg.timestamp() + '), parsing record: 0 ', end='')
count = 0
for harvest_item in harvest:
count += 1
if count % 1000 == 0:
print(count, ' ', end='', flush=True)
if count % 10000 == 0:
print('(' + rcg.timestamp() + ')\n', end='', flush=True)
if 'uuid' not in harvest_item:
# There must be an uuid, otherwise skip
continue
label = ''
if 'period' in harvest_item:
# Field in Pure READ API.
label = 'period'
elif 'lifecycle' in harvest_item:
# Field in Pure CRUD API.
label = 'lifecycle'
if label != '':
if 'endDate' in harvest_item[label] and harvest_item[label]['endDate'] != '':
# Only consider current organizations, that is an organization
# where endDate is not existing or empty. If not, then skip.
continue
else:
# If there is no period or lifecycle skip
continue
if 'type' in harvest_item:
pure_org_uri = str(harvest_item['type']['uri'])
if pure_org_uri[-3] == 'r':
# Skip research organizations (with an 'r' in the uri, like ..../r05)
continue
else:
# If there is no type skip
continue
if 'name' not in harvest_item:
# If there is no name skip
continue
# Skip the organization ids. There are only a few, and it
# seems to complicated to implement for now (we will need
# something like 'organization-root' aka 'person-root').
# if 'ids' in harvest_item:
# for identities in harvest_item['ids']:
# if 'value' in identities and 'type' in identities:
# value_identifier = str(identities['value']['value'])
# name_identifier = str(identities['type']['term']['text'][0]['value'])
# parse_line = {}
# parse_line['UUID'] = str(harvest_item['uuid'])
# parse_line[name_identifier] = value_identifier
# parse_chunk.append(parse_line)
if 'parents' in harvest_item:
for parentsorg in harvest_item['parents']:
if 'uuid' not in parentsorg:
# There must be an uuid, otherwise skip
continue
# Note: 'parents' does not have a 'period', so we don't need to do something.
# Note: 'type' and 'name' must exist, otherwise we wouldn't have gotten here.
if 'type' in parentsorg:
# Field in Pure READ API.
pure_parentsorg_uri = str(parentsorg['type']['uri'])
if pure_parentsorg_uri[-3] == 'r':
# Skip research organizations (with an 'r' in the uri, like ..../r05)
continue
org_type_name = str(harvest_item['type']['term']['text'][0]['value'])
org_name = str(harvest_item['name']['text'][0]['value'])
elif 'systemName' in parentsorg:
# Field in Pure CRUD API.
org_type_name = str(harvest_item['type']['term']['en_GB'])
org_name = str(harvest_item['name']['en_GB'])
else:
continue
parse_line = {'PURE_UUID_ORG': str(harvest_item['uuid']),
'ORG_TYPE_NAME': org_type_name,
'ORG_NAME': org_name,
'FULL_ORG_NAME': organization + ' ' + org_type_name + ': ' + org_name,
'PARENT_UUID': str(parentsorg['uuid'])}
parse_chunk.append(parse_line)
organization_names[parse_line['PURE_UUID_ORG']] = parse_line['FULL_ORG_NAME']
else:
# Assume it is the top level organization since it doesn't have a parent.
# Note: 'type' and 'name' must exist, otherwise we wouldn't have gotten here.
if PURE_API_VERSION == PURE_READ_API_VERSION:
# We are in Pure READ API.
org_type_name = str(harvest_item['type']['term']['text'][0]['value'])
org_name = str(harvest_item['name']['text'][0]['value'])
else:
# We are in Pure CRUD API.
org_type_name = str(harvest_item['type']['term']['en_GB'])
org_name = str(harvest_item['name']['en_GB'])
# Only necessary to add the top level organization to the dict with organization names.
organization_names[str(harvest_item['uuid'])] = org_type_name + ': ' + org_name
print(count, '(' + rcg.timestamp() + ')\n', end='', flush=True)
parse_chunk_df = pandas.DataFrame(parse_chunk)
parse_result = pandas.concat([parse_result, parse_chunk_df], ignore_index=True)
parse_result['FULL_PARENT_NAME'] = (
parse_result[['PARENT_UUID']].apply(lambda row:
find_organization_name(uuid=row['PARENT_UUID'],
organization_names=organization_names),
axis=1))
# dropna(how='all'): drop row if all row values contain NaN
parse_result.dropna(axis=0, how='all', inplace=True)
parse_result.drop_duplicates(keep='first', inplace=True, ignore_index=True)
return parse_result
def parse_pure_resout(harvest: list) -> pandas.DataFrame:
"""Parse the harvested research outputs from Pure.
:param harvest: the harvest.
:return: the harvested research outputs in a DataFrame.
"""
global organization
parse_result = pandas.DataFrame()
parse_chunk = [] # list of dictionaries
print('There are ' + str(len(harvest)) + ' research output records ('
+ rcg.timestamp() + '), parsing record: 0 ', end='')
count = 0
for harvest_item in harvest:
count += 1
if count % 1000 == 0:
print(count, ' ', end='', flush=True)
if count % 10000 == 0:
print('(' + rcg.timestamp() + ')\n', end='', flush=True)
if 'uuid' not in harvest_item:
# There must be an uuid, otherwise skip
continue
if 'title' not in harvest_item:
# There must be a title, otherwise skip
continue
if 'confidential' in harvest_item:
if harvest_item['confidential']:
# Skip the confidential ones
continue
if 'type' not in harvest_item:
# There must be a type of this resout, otherwise skip
continue
if 'workflow' in harvest_item:
if 'workflowStep' in harvest_item['workflow']:
# Field in Pure READ API.
if harvest_item['workflow']['workflowStep'] != 'validated' \
and harvest_item['workflow']['workflowStep'] != 'approved':
# Only 'validated' or 'approved' resouts.
continue
if 'step' in harvest_item['workflow']:
# Field in Pure CRUD API.
if harvest_item['workflow']['step'] != 'validated' \
and harvest_item['workflow']['step'] != 'approved':
# Only 'validated' or 'approved' resouts.
continue
else:
# Skip if no workflow
continue
publication_year = ''
if 'publicationStatuses' in harvest_item:
# We need a current status.
published_found = False
for pub_item in harvest_item['publicationStatuses']:
if pub_item['current']:
if 'publicationDate' in pub_item:
if 'year' in pub_item['publicationDate']:
publication_year = pub_item['publicationDate']['year']
if 'publicationStatus' in pub_item:
if pathlib.PurePath(pub_item['publicationStatus']['uri']).name == 'published':
published_found = True
break
if not published_found:
continue
else:
# Skip if no publicationStatuses
continue
doi = ''
if 'electronicVersions' in harvest_item:
for elecversions in harvest_item['electronicVersions']:
# Take the last doi found for a resout
if 'doi' in elecversions:
doi = str(elecversions['doi'])
doi = rewrite_pure_doi(doi=doi)
label = ''
if 'personAssociations' in harvest_item:
# Field in Pure READ API.
label = 'personAssociations'
elif 'contributors' in harvest_item:
# Field in Pure CRUD API.
label = 'contributors'
if label != '':
for persons in harvest_item[label]:
author_name = ''
if 'person' in persons: # internal person
if 'uuid' not in persons['person']:
# There must be an uuid, otherwise skip
continue
author_uuid = str(persons['person']['uuid'])
# Don't set 'author_name', it is not necessary.
elif 'externalPerson' in persons: # external person
if 'uuid' not in persons['externalPerson']:
# There must be an uuid, otherwise skip
continue
author_uuid = str(persons['externalPerson']['uuid'])
if 'name' in persons['externalPerson'] \
and 'text' in persons['externalPerson']['name'] \
and 'value' in persons['externalPerson']['name']['text'][0]:
author_name = persons['externalPerson']['name']['text'][0]['value']
author_name += ' (' + organization + ' external person)'
elif 'authorCollaboration' in persons: # author collaboration
if 'uuid' not in persons['authorCollaboration']:
# There must be an uuid, otherwise skip
continue
author_uuid = str(persons['authorCollaboration']['uuid'])
if 'name' in persons['authorCollaboration'] \
and 'text' in persons['authorCollaboration']['name'] \
and 'value' in persons['authorCollaboration']['name']['text'][0]:
author_name = persons['authorCollaboration']['name']['text'][0]['value']
author_name += ' (' + organization + ' author collaboration)'
else:
# If we get here you might want to add another "elif" above with
# the missing personAssociation. Sometimes there is none, then it is ok.
# Do not print a warning message, most of the time it is an external person
# without any identifier.
# print('\nparse_pure_resout(): Warning: Unknown personAssociation/contributor for publication '
# + str(harvest_item['uuid']))
continue
parse_line = {'RESOUT_UUID': str(harvest_item['uuid']),
'DOI': doi,
'TITLE': str(harvest_item['title']['value']),
'YEAR': str(publication_year),
'TYPE': rcg.lookup_resout_type(research_output_type=str(harvest_item['type']['uri']),
research_output_mapping=ROTYPE_MAPPING_PURE),
'AUTHOR_UUID': author_uuid,
'FULL_NAME': author_name}
parse_chunk.append(parse_line)
print(count, '(' + rcg.timestamp() + ')\n', end='', flush=True)
if len(parse_chunk) == 0 \
and PURE_API_VERSION == PURE_CRUD_API_VERSION:
print('\nPure is harvested using the Pure CRUD API.')
print('No research outputs were found.')
print('This is probably caused by one or more of the following fields not present in')
print('the CRUD API export for "research outputs":')
print('"workflow", "publicationStatuses" and/or "contributors".')
print('Please ask your Pure administrator to export these fields. Exiting.')
exit(1)
parse_chunk_df = pandas.DataFrame(parse_chunk)
parse_result = pandas.concat([parse_result, parse_chunk_df], ignore_index=True)
# dropna(how='all'): drop row if all row values contain NaN
parse_result.dropna(axis=0, how='all', inplace=True)
parse_result.drop_duplicates(keep='first', inplace=True, ignore_index=True)
return parse_result
def parse_pure_projects(harvest: list) -> pandas.DataFrame:
"""Parse the harvested projects from Pure.
:param harvest: the harvest.
:return: the harvested persons in a DataFrame.
"""
global resout_uuid_or_doi
global organization
parse_result = pandas.DataFrame()
parse_chunk = [] # list of dictionaries
print('There are ' + str(len(harvest)) + ' project records ('
+ rcg.timestamp() + '), parsing record: 0 ', end='')
count = 0
for harvest_item in harvest:
count += 1
if count % 1000 == 0:
print(count, ' ', end='', flush=True)
if count % 10000 == 0:
print('(' + rcg.timestamp() + ')\n', end='', flush=True)
if 'uuid' in harvest_item:
uuid = str(harvest_item['uuid'])
else:
# There must be an uuid, otherwise skip.
continue
if 'confidential' in harvest_item \
and harvest_item['confidential']:
# It may not be confidential.
continue
if 'title' in harvest_item:
title = str(harvest_item['title']['text'][0]['value'])
else:
# There must be a title, otherwise skip.
continue
if 'visibility' in harvest_item:
if 'key' in harvest_item['visibility'] \
and harvest_item['visibility']['key'] != 'FREE':
# TODO: Hack for Utrecht University Pure. Their projects have visibility
# 'BACKEND'. This will change sometime in the future and then this
# hack should be removed. Date of the hack: November 11, 2023.
# It should be like this:
# #### start
# It must be public, otherwise skip.
# continue
# #### end
# But with the hack it is:
if organization != 'UU':
# It must be public, otherwise skip.
continue
else:
# It must be explicitly declared to be public, otherwise skip.
continue
if 'period' in harvest_item:
if 'startDate' in harvest_item['period']:
start_date = str(harvest_item['period']['startDate'])[0:10]
period = 'started: ' + start_date + ', '
else:
period = 'not started, '
if 'endDate' in harvest_item['period']:
end_date = str(harvest_item['period']['endDate'])[0:10]
period += 'ended: ' + end_date
else:
period += 'not ended'
title += ' (' + period + ')'
if 'status' in harvest_item:
title += ' (' + str(harvest_item['status']['key'].lower()) + ')'
# For now, we don't care about the 'workflow' status.
# One could say: "There are no ids, so do not harvest". However, for
# now we don't use 'ids' as 'value' field, so for now we _do_ harvest.
if 'ids' in harvest_item:
name = ''
value = ''
if 'value' in harvest_item['ids'][0]:
value = str(harvest_item['ids'][0]['value']['value'])
if 'type' in harvest_item['ids'][0] \
and 'uri' in harvest_item['ids'][0]['type']:
name = str(pathlib.PurePath(harvest_item['ids'][0]['type']['uri']).name)
if name == '' or value == '':
continue
title = '[' + name + ': ' + value + '] ' + title
# else:
# continue
if 'participants' in harvest_item:
for participant in harvest_item['participants']:
if 'person' in participant \
and 'uuid' in participant['person']:
participant_uuid = str(participant['person']['uuid'])
else:
continue
if 'organisationalUnits' in participant \
and 'uuid' in participant['organisationalUnits'][0]:
participant_org = str(participant['organisationalUnits'][0]['uuid'])
else:
continue
parse_line = {'PURE_UUID_PROJECT': uuid,
'PURE_UUID_PROJECT_URL': create_pure_url(name='PURE_UUID_PROJECT',
value=uuid),
'PURE_PROJECT_TITLE': title,
'PURE_PROJECT_PARTICIPANT_UUID': participant_uuid,
'PURE_PROJECT_PARTICIPANT_ORG': participant_org}
parse_chunk.append(parse_line)
if 'relatedResearchOutputs' in harvest_item:
for resout in harvest_item['relatedResearchOutputs']:
if 'uuid' in resout:
resout_uuid = str(resout['uuid'])
else:
continue
if 'type' in resout \
and 'uri' in resout['type']:
resout_category = rcg.lookup_resout_type(research_output_type=str(resout['type']['uri']),
research_output_mapping=ROTYPE_MAPPING_PURE)
else:
continue
resout_name = 'PURE_UUID_RESOUT'
resout_value = resout_uuid
if resout_uuid_or_doi != {} \
and resout_uuid in resout_uuid_or_doi:
resout_value = resout_uuid_or_doi[resout_uuid]
if not numpy.isnan(resout_value):
if '/' in resout_value:
resout_name = 'DOI'
else:
resout_name = 'PURE_UUID_RESOUT'
parse_line = {'PURE_UUID_PROJECT': uuid,
'PURE_UUID_PROJECT_URL': create_pure_url(name='PURE_UUID_PROJECT',
value=uuid),
'PURE_PROJECT_TITLE': title,
'PURE_PROJECT_RESOUT_NAME': resout_name,
'PURE_PROJECT_RESOUT_CATEGORY': resout_category,
'PURE_PROJECT_RESOUT_VALUE': resout_value}
parse_chunk.append(parse_line)
if 'relatedProjects' in harvest_item:
for related_project in harvest_item['relatedProjects']:
if 'project' in related_project \
and 'uuid' in related_project['project']:
related_project_uuid = str(related_project['project']['uuid'])
else:
continue
parse_line = {'PURE_UUID_PROJECT': uuid,
'PURE_UUID_PROJECT_URL': create_pure_url(name='PURE_UUID_PROJECT',
value=uuid),
'PURE_PROJECT_TITLE': title,
'PURE_PROJECT_RELATEDPROJECT_UUID': related_project_uuid}
parse_chunk.append(parse_line)
print(count, '(' + rcg.timestamp() + ')\n', end='', flush=True)
parse_chunk_df = pandas.DataFrame(parse_chunk)
parse_result = pandas.concat([parse_result, parse_chunk_df], ignore_index=True)
# dropna(how='all'): drop row if all row values contain NaN
parse_result.dropna(axis=0, how='all', inplace=True)
parse_result.drop_duplicates(keep='first', inplace=True, ignore_index=True)
return parse_result
# ######################################################
# Harvesting and parsing
# ######################################################
def harvest_and_parse_pure_data(mode: str, endpoint: str,
headers: dict, body: dict,
harvest_filename: str) -> Union[pandas.DataFrame, None]:
"""Harvest and parse data from Pure.
:param mode: 'persons', 'organizations' or 'research outputs', to indicate what to harvest.
:param endpoint: endpoint Pure.
:param headers: headers for Pure.
:param body: the body of a POST request, or '' for a GET request.
:param harvest_filename: filename to write harvest results to.
:return: the DataFrame harvested, or None if nothing harvested.
"""
if mode != 'persons' \
and mode != 'organizations' \
and mode != 'research outputs' \
and mode != 'projects':
print('harvest_and_parse_pure_data(): unknown mode ' + mode + '.')
return None
if mode == 'persons':
max_recs_to_harvest = PURE_PERSONS_MAX_RECS_TO_HARVEST
elif mode == 'organizations':
max_recs_to_harvest = PURE_ORGANIZATIONS_MAX_RECS_TO_HARVEST
elif mode == 'research outputs':