-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAOP-Wiki_XML_to_RDF_conversion.py
More file actions
2281 lines (1768 loc) · 106 KB
/
AOP-Wiki_XML_to_RDF_conversion.py
File metadata and controls
2281 lines (1768 loc) · 106 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
# # <b>AOP-Wiki XML conversion to RDF</b>
# Author: Marvin Martens
#
# The [AOP-Wiki](https://aopwiki.org/) is the central repository for qualitative descriptions of AOPs, and releases its database every three months in XML format. This Jupyter notebook makes the conversion of the AOP-Wiki XML into RDF with Turtle (ttl) syntax.
#
# It downloads and parses the AOP-Wiki XML file with the ElementTree XML API Python library, and stores all its components in nested dictionaries for the all subjects which form the basis of the existing AOP-Wiki, being the AOPs, KEs, KERs, stressors, chemicals, taxonomy, cell-terms, organ-terms, and the KE components, which comprise of Biological Processes (BPs), Biological Objects (BOs) and Biological Actions (BAs). During the filling of those dictionaries, semantic annotations are being added for the subjects, the relationship (predicate) to their property (object), and for the properties themselves when meant to represent an identifier or ontology term.
#
# <img src="Overview AOP-Wiki RDF.svg" style="width: 650px;">
# ## <b>Step #1: imports and configuration</b>
# First, all required Python libraries are imported and configuration variables are set.
# --- Standard Library Imports ---
import sys
import os
import re
import time
import stat
import gzip
import shutil
import datetime
import logging
from xml.etree.ElementTree import parse
import urllib.request
# --- Third-Party Libraries ---
import requests
import pandas as pd
# --- Configuration ---
# URLs and endpoints
BRIDGEDB_URL = 'https://webservice.bridgedb.org/Human/' # Alternative: 'http://localhost:8183/Human/'
AOPWIKI_XML_URL = 'https://aopwiki.org/downloads/aop-wiki-xml.gz'
PROMAPPING_URL = 'https://proconsortium.org/download/current/promapping.txt'
# File paths and settings
DATA_DIR = 'data/'
MAX_RETRIES = 3
REQUEST_TIMEOUT = 30
# --- Constants / Compiled Patterns ---
TAG_RE = re.compile(r'<[^>]+>')
# Pre-compile frequently used patterns for performance
HTML_TAG_PATTERN = re.compile(r'<[^>]+>') # For HTML tag removal (used 1000+ times)
# --- Setup Logging ---
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(),
logging.FileHandler('aop_conversion.log')
]
)
logger = logging.getLogger(__name__)
# --- Helper Functions ---
def safe_get_text(element, default=''):
"""Safely extract text from XML element, returning default if None."""
if element is not None and element.text is not None:
return element.text.strip()
return default
def clean_html_tags(text):
"""Remove HTML tags from text."""
if text:
return HTML_TAG_PATTERN.sub('', text)
return text
def download_with_retry(url, filename, max_retries=MAX_RETRIES):
"""Download file with retry logic."""
for attempt in range(max_retries):
try:
logger.info(f"Downloading {url} (attempt {attempt + 1}/{max_retries})")
response = requests.get(url, verify=False, timeout=REQUEST_TIMEOUT)
response.raise_for_status()
with open(filename, 'wb') as f:
f.write(response.content)
logger.info(f"Successfully downloaded {filename}")
return True
except requests.RequestException as e:
logger.warning(f"Download attempt {attempt + 1} failed: {e}")
if attempt == max_retries - 1:
logger.error(f"Failed to download {url} after {max_retries} attempts")
raise
time.sleep(2 ** attempt) # Exponential backoff
return False
# --- Performance Optimization Helper Functions ---
# Removed regex-based gene mapping functions - using simple string containment instead
def convert_lists_to_sets_for_lookup(dict_of_lists):
"""Convert dictionary of lists to sets for O(1) membership testing."""
return {key: set(values) for key, values in dict_of_lists.items()}
def convert_sets_to_lists_for_output(dict_of_sets):
"""Convert dictionary of sets back to lists for consistent output format."""
return {key: list(values) for key, values in dict_of_sets.items()}
def map_genes_in_text_simple(text, genedict1, hgnc_list, genedict2=None):
"""
Enhanced two-stage gene mapping algorithm with false positive filtering.
Stage 1: Screen with genedict1 (basic gene names)
Stage 2: Match with genedict2 (punctuation-delimited variants) with precision filters
Stage 3: Apply false positive filters to eliminate problematic matches
Returns list of found HGNC IDs and updates the global hgnc_list.
"""
import time
import re
if not text or not genedict1:
return []
found_genes = []
# Add timing for performance monitoring
start_time = time.time()
genes_checked = 0
# False positive filter patterns
# Roman numerals (I, II, III, IV, V, etc.) - common in scientific text
roman_numeral_pattern = re.compile(r'\b[IVX]+\b')
# Single letter aliases that are too ambiguous
single_letter_aliases = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}
def is_false_positive(gene_symbol, matched_alias, matched_text_context):
"""Filter out known false positive patterns"""
# Filter 1: Single letter aliases (too ambiguous)
if matched_alias.strip() in single_letter_aliases:
return True, f"single letter alias '{matched_alias.strip()}'"
# Filter 2: Roman numerals (often match complex numbering in scientific text)
if roman_numeral_pattern.fullmatch(matched_alias.strip()):
return True, f"Roman numeral '{matched_alias.strip()}'"
# Filter 3: Short ambiguous symbols in parentheses or brackets
stripped = matched_alias.strip()
if len(stripped) <= 2 and any(char in matched_text_context for char in '()[]{}'):
return True, f"short symbol '{stripped}' in parentheses/brackets context"
# Filter 4: Gene-specific false positive patterns
if gene_symbol == 'IV' and ('Complex I' in matched_text_context or '(I–V)' in matched_text_context):
return True, "IV gene matching complex numbering"
if gene_symbol == 'GCNT2' and matched_alias.strip() == 'II' and ('(I–V)' in matched_text_context or 'complexes' in matched_text_context.lower()):
return True, "GCNT2 alias 'II' matching complex numbering"
return False, None
# Two-stage algorithm with enhanced precision filtering
for gene_key in genedict1:
genes_checked += 1
# Stage 1: Screen with genedict1 (basic gene symbols/names)
a = 0 # Match original notebook variable naming
stage1_matched_alias = None
for item in genedict1[gene_key]:
if item in text:
a = 1
stage1_matched_alias = item
break
# Stage 2: If Stage 1 passes, use genedict2 for precise matching
if a == 1:
hgnc_id = 'hgnc:' + gene_key
# If genedict2 available, use it for precision (recommended)
if genedict2 and gene_key in genedict2:
# Use punctuation-delimited variants for precise matching
for item in genedict2[gene_key]:
if item in text and hgnc_id not in found_genes:
# Stage 3: False positive filtering
# Get context around the match for better filtering
match_index = text.find(item)
context_start = max(0, match_index - 50)
context_end = min(len(text), match_index + len(item) + 50)
context = text[context_start:context_end]
# Extract the actual matched alias (strip punctuation delimiters)
matched_alias = item.strip(' ()[],.') if len(item) >= 3 else item[1:-1] if len(item) == 3 else item
# Apply false positive filters
is_fp, fp_reason = is_false_positive(gene_key, matched_alias, context)
if is_fp:
logger.debug(f"Filtered false positive: {gene_key} (alias '{matched_alias}') - {fp_reason}")
break # Skip this gene entirely
# Valid match - add to results
found_genes.append(hgnc_id)
# Add to global list if not already present
if hgnc_id not in hgnc_list:
hgnc_list.append(hgnc_id)
break
else:
# Fallback to genedict1-only matching (less precise)
# Still apply basic false positive filtering
is_fp, fp_reason = is_false_positive(gene_key, stage1_matched_alias, text)
if not is_fp and hgnc_id not in found_genes:
found_genes.append(hgnc_id)
# Add to global list if not already present
if hgnc_id not in hgnc_list:
hgnc_list.append(hgnc_id)
elif is_fp:
logger.debug(f"Filtered false positive: {gene_key} (alias '{stage1_matched_alias}') - {fp_reason}")
# Log slow mappings for performance monitoring
elapsed = time.time() - start_time
precision_note = " (using enhanced precision filtering)" if genedict2 else " (genedict1 fallback)"
if elapsed > 1.0: # Log anything taking more than 1 second
logger.info(f"SLOW gene mapping: {elapsed:.2f}s, {genes_checked} genes, {len(found_genes)} genes found, text_len={len(text)}{precision_note}")
elif found_genes: # Log successful finds
logger.debug(f"Gene mapping: {elapsed:.2f}s, {len(found_genes)} genes found, text_len={len(text)}{precision_note}")
return found_genes
# --- Validation Functions ---
def validate_xml_structure(root, expected_namespace):
"""Validate basic XML structure."""
if root is None:
raise ValueError("XML root is None")
if root.tag != expected_namespace + 'data':
logger.warning(f"Unexpected root tag: {root.tag}")
# Check for required vendor-specific section
vendor_section = root.find(expected_namespace + 'vendor-specific')
if vendor_section is None:
raise ValueError("Missing vendor-specific section in XML")
logger.info("XML structure validation passed")
return True
def validate_entity_counts(refs):
"""Validate that we have reasonable entity counts."""
min_expected = {'AOP': 1, 'KE': 1, 'KER': 1, 'Stressor': 1}
for entity_type, min_count in min_expected.items():
actual_count = len(refs.get(entity_type, {}))
if actual_count < min_count:
logger.warning(f"Low count for {entity_type}: {actual_count} (expected >= {min_count})")
else:
logger.info(f"Entity count validation passed for {entity_type}: {actual_count}")
return True
def validate_required_fields(entity_dict, entity_type, required_fields):
"""Validate that required fields are present in entities."""
missing_fields = []
for entity_id, entity_data in entity_dict.items():
for field in required_fields:
if field not in entity_data or not entity_data[field]:
missing_fields.append(f"{entity_type} {entity_id} missing {field}")
if missing_fields:
logger.warning(f"Found {len(missing_fields)} missing required fields")
for missing in missing_fields[:5]: # Log first 5
logger.warning(missing)
if len(missing_fields) > 5:
logger.warning(f"... and {len(missing_fields) - 5} more")
else:
logger.info(f"Required field validation passed for {entity_type}")
return len(missing_fields) == 0
# This notebook includes the mapping of identifiers for chemicals and genes. To make this possible, the URL to the BridgeDb service is defined in the configuration section above.
# Use configuration variable
bridgedb = BRIDGEDB_URL
# ## <b>Step #2: Getting the AOP-Wiki XML</b>
# Download and extract the latest AOP-Wiki XML with proper error handling.
from datetime import date
today = date.today()
logger.info(f"Starting AOP-Wiki conversion for date: {today}")
# Download AOP-Wiki XML with retry logic
aopwikixmlfilename = f'aop-wiki-xml-{today}'
try:
download_with_retry(AOPWIKI_XML_URL, aopwikixmlfilename)
except requests.RequestException as e:
logger.error(f"Failed to download AOP-Wiki XML: {e}")
raise SystemExit(1)
# Ensure data directory exists
filepath = DATA_DIR
os.makedirs(filepath, exist_ok=True)
logger.info(f"Using data directory: {filepath}")
# Extract gzipped XML file
try:
with gzip.open(aopwikixmlfilename, 'rb') as f_in:
with open(filepath + aopwikixmlfilename, 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
logger.info(f"Successfully extracted XML to {filepath + aopwikixmlfilename}")
except (FileNotFoundError, gzip.BadGzipFile, IOError) as e:
logger.error(f"Failed to extract XML file: {e}")
raise SystemExit(1)
# Parse XML with validation
try:
tree = parse(filepath + aopwikixmlfilename)
root = tree.getroot()
if root is None or len(root) == 0:
raise ValueError("XML file appears to be empty or invalid")
logger.info(f'AOP-Wiki XML parsed successfully, contains {len(root)} entities')
except Exception as e:
logger.error(f"Failed to parse XML file: {e}")
raise SystemExit(1)
aopxml = '{http://www.aopkb.org/aop-xml}'
# Validate XML structure
try:
validate_xml_structure(root, aopxml)
except ValueError as e:
logger.error(f"XML structure validation failed: {e}")
raise SystemExit(1)
# ## <b>Step #3: extracting information from the XML</b>
# The next section extracts all information from the main 11 AOP-Wiki entities shown in Figure 1. These are stored in nested dictionaries, while using ontological annotations as keys for semantic mapping of the information. Note that the cell-terms and organ-terms are included in the KE block of code.
#
# First, all reference identifiers for AOPs, KEs, KERs and stressors need to be extracted.
refs = {'AOP': {}, 'KE': {}, 'KER': {}, 'Stressor': {}}
for ref in root.find(aopxml + 'vendor-specific').findall(aopxml + 'aop-reference'):
refs['AOP'][ref.get('id')] = ref.get('aop-wiki-id')
for ref in root.find(aopxml + 'vendor-specific').findall(aopxml + 'key-event-reference'):
refs['KE'][ref.get('id')] = ref.get('aop-wiki-id')
for ref in root.find(aopxml + 'vendor-specific').findall(aopxml + 'key-event-relationship-reference'):
refs['KER'][ref.get('id')] = ref.get('aop-wiki-id')
for ref in root.find(aopxml + 'vendor-specific').findall(aopxml + 'stressor-reference'):
refs['Stressor'][ref.get('id')] = ref.get('aop-wiki-id')
for item in refs:
logger.info(f'Found {len(refs[item])} identifiers for entity type: {item}')
# Validate entity counts
try:
validate_entity_counts(refs)
except Exception as e:
logger.error(f"Entity count validation failed: {e}")
# Don't exit here since this is just a validation warning
# ### Adverse Outcome Pathways
aopdict = {}
kedict = {}
for AOP in root.findall(aopxml + 'aop'):
aopdict[AOP.get('id')] = {}
aopdict[AOP.get('id')]['dc:identifier'] = 'aop:' + refs['AOP'][AOP.get('id')]
aopdict[AOP.get('id')]['rdfs:label'] = '"AOP ' + refs['AOP'][AOP.get('id')] + '"'
aopdict[AOP.get('id')]['foaf:page'] = '<https://identifiers.org/aop/' + refs['AOP'][AOP.get('id')] + '>'
aopdict[AOP.get('id')]['dc:title'] = '"' + AOP.find(aopxml + 'title').text + '"'
aopdict[AOP.get('id')]['dcterms:alternative'] = AOP.find(aopxml + 'short-name').text
aopdict[AOP.get('id')]['dc:description'] = []
if AOP.find(aopxml + 'background') is not None:
aopdict[AOP.get('id')]['dc:description'].append('"""' + HTML_TAG_PATTERN.sub('', AOP.find(aopxml + 'background').text) + '"""')
if AOP.find(aopxml + 'authors').text is not None:
aopdict[AOP.get('id')]['dc:creator'] = '"""' + HTML_TAG_PATTERN.sub('', AOP.find(aopxml + 'authors').text) + '"""'
if AOP.find(aopxml + 'abstract').text is not None:
aopdict[AOP.get('id')]['dcterms:abstract'] = '"""' + HTML_TAG_PATTERN.sub('', AOP.find(aopxml + 'abstract').text) + '"""'
if AOP.find(aopxml + 'status').find(aopxml + 'wiki-status') is not None:
aopdict[AOP.get('id')]['dcterms:accessRights'] = '"' + AOP.find(aopxml + 'status').find(aopxml + 'wiki-status').text + '"'
if AOP.find(aopxml + 'status').find(aopxml + 'oecd-status') is not None:
aopdict[AOP.get('id')]['oecd-status'] = '"' + AOP.find(aopxml + 'status').find(aopxml + 'oecd-status').text + '"'
if AOP.find(aopxml + 'status').find(aopxml + 'saaop-status') is not None:
aopdict[AOP.get('id')]['saaop-status'] = '"' + AOP.find(aopxml + 'status').find(aopxml + 'saaop-status').text + '"'
aopdict[AOP.get('id')]['oecd-project'] = AOP.find(aopxml + 'oecd-project').text
aopdict[AOP.get('id')]['dc:source'] = AOP.find(aopxml + 'source').text
aopdict[AOP.get('id')]['dcterms:created'] = AOP.find(aopxml + 'creation-timestamp').text
aopdict[AOP.get('id')]['dcterms:modified'] = AOP.find(aopxml + 'last-modification-timestamp').text
for appl in AOP.findall(aopxml + 'applicability'):
for sex in appl.findall(aopxml + 'sex'):
if 'pato:0000047' not in aopdict[AOP.get('id')]:
aopdict[AOP.get('id')]['pato:0000047'] = [[sex.find(aopxml + 'evidence').text, sex.find(aopxml + 'sex').text]]
else:
aopdict[AOP.get('id')]['pato:0000047'].append([sex.find(aopxml + 'evidence').text, sex.find(aopxml + 'sex').text])
for life in appl.findall(aopxml + 'life-stage'):
if 'aopo:LifeStageContext' not in aopdict[AOP.get('id')]:
aopdict[AOP.get('id')]['aopo:LifeStageContext'] = [[life.find(aopxml + 'evidence').text, life.find(aopxml + 'life-stage').text]]
else:
aopdict[AOP.get('id')]['aopo:LifeStageContext'].append([life.find(aopxml + 'evidence').text, life.find(aopxml + 'life-stage').text])
aopdict[AOP.get('id')]['aopo:has_key_event'] = {}
if AOP.find(aopxml + 'key-events') is not None:
for KE in AOP.find(aopxml + 'key-events').findall(aopxml + 'key-event'):
aopdict[AOP.get('id')]['aopo:has_key_event'][KE.get('key-event-id')] = {}
aopdict[AOP.get('id')]['aopo:has_key_event'][KE.get('key-event-id')]['dc:identifier'] = 'aop.events:' + refs['KE'][KE.get('key-event-id')]
aopdict[AOP.get('id')]['aopo:has_key_event_relationship'] = {}
if AOP.find(aopxml + 'key-event-relationships') is not None:
for KER in AOP.find(aopxml + 'key-event-relationships').findall(aopxml + 'relationship'):
aopdict[AOP.get('id')]['aopo:has_key_event_relationship'][KER.get('id')] = {}
aopdict[AOP.get('id')]['aopo:has_key_event_relationship'][KER.get('id')]['dc:identifier'] = 'aop.relationships:' + refs['KER'][KER.get('id')]
aopdict[AOP.get('id')]['aopo:has_key_event_relationship'][KER.get('id')]['adjacency'] = KER.find(aopxml + 'adjacency').text
aopdict[AOP.get('id')]['aopo:has_key_event_relationship'][KER.get('id')]['quantitative-understanding-value'] = KER.find(aopxml + 'quantitative-understanding-value').text
aopdict[AOP.get('id')]['aopo:has_key_event_relationship'][KER.get('id')]['aopo:has_evidence'] = KER.find(aopxml + 'evidence').text
aopdict[AOP.get('id')]['aopo:has_molecular_initiating_event'] = {}
for MIE in AOP.findall(aopxml + 'molecular-initiating-event'):
aopdict[AOP.get('id')]['aopo:has_molecular_initiating_event'][MIE.get('key-event-id')] = {}
aopdict[AOP.get('id')]['aopo:has_molecular_initiating_event'][MIE.get('key-event-id')]['dc:identifier'] = 'aop.events:' + refs['KE'][MIE.get('key-event-id')]
aopdict[AOP.get('id')]['aopo:has_key_event'][MIE.get('key-event-id')] = {}
aopdict[AOP.get('id')]['aopo:has_key_event'][MIE.get('key-event-id')]['dc:identifier'] = 'aop.events:' + refs['KE'][MIE.get('key-event-id')]
if MIE.find(aopxml + 'evidence-supporting-chemical-initiation').text is not None:
kedict[MIE.get('key-event-id')] = {}
aopdict[AOP.get('id')]['dc:description'].append('"""' + HTML_TAG_PATTERN.sub('', MIE.find(aopxml + 'evidence-supporting-chemical-initiation').text) + '"""')
aopdict[AOP.get('id')]['aopo:has_adverse_outcome'] = {}
for AO in AOP.findall(aopxml + 'adverse-outcome'):
aopdict[AOP.get('id')]['aopo:has_adverse_outcome'][AO.get('key-event-id')] = {}
aopdict[AOP.get('id')]['aopo:has_adverse_outcome'][AO.get('key-event-id')]['dc:identifier'] = 'aop.events:' + refs['KE'][AO.get('key-event-id')]
aopdict[AOP.get('id')]['aopo:has_key_event'][AO.get('key-event-id')] = {}
aopdict[AOP.get('id')]['aopo:has_key_event'][AO.get('key-event-id')]['dc:identifier'] = 'aop.events:' + refs['KE'][AO.get('key-event-id')]
if AO.find(aopxml + 'examples').text is not None:
kedict[AO.get('key-event-id')] = {}
aopdict[AOP.get('id')]['dc:description'].append('"""' + HTML_TAG_PATTERN.sub('', AO.find(aopxml + 'examples').text) + '"""')
aopdict[AOP.get('id')]['nci:C54571'] = {}
if AOP.find(aopxml + 'aop-stressors') is not None:
for stressor in AOP.find(aopxml + 'aop-stressors').findall(aopxml + 'aop-stressor'):
aopdict[AOP.get('id')]['nci:C54571'][stressor.get('stressor-id')] = {}
aopdict[AOP.get('id')]['nci:C54571'][stressor.get('stressor-id')]['dc:identifier'] = 'aop.stressor:' + refs['Stressor'][stressor.get('stressor-id')]
aopdict[AOP.get('id')]['nci:C54571'][stressor.get('stressor-id')]['aopo:has_evidence'] = stressor.find(aopxml + 'evidence').text
if AOP.find(aopxml + 'overall-assessment').find(aopxml + 'description').text is not None:
aopdict[AOP.get('id')]['nci:C25217'] = '"""' + HTML_TAG_PATTERN.sub('', AOP.find(aopxml + 'overall-assessment').find(aopxml + 'description').text) + '"""'
if AOP.find(aopxml + 'overall-assessment').find(aopxml + 'key-event-essentiality-summary').text is not None:
aopdict[AOP.get('id')]['nci:C48192'] = '"""' + HTML_TAG_PATTERN.sub('', AOP.find(aopxml + 'overall-assessment').find(aopxml + 'key-event-essentiality-summary').text) + '"""'
if AOP.find(aopxml + 'overall-assessment').find(aopxml + 'applicability').text is not None:
aopdict[AOP.get('id')]['aopo:AopContext'] = '"""' + HTML_TAG_PATTERN.sub('', AOP.find(aopxml + 'overall-assessment').find(aopxml + 'applicability').text) + '"""'
if AOP.find(aopxml + 'overall-assessment').find(aopxml + 'weight-of-evidence-summary').text is not None:
aopdict[AOP.get('id')]['aopo:has_evidence'] = '"""' + HTML_TAG_PATTERN.sub('', AOP.find(aopxml + 'overall-assessment').find(aopxml + 'weight-of-evidence-summary').text) + '"""'
if AOP.find(aopxml + 'overall-assessment').find(aopxml + 'quantitative-considerations').text is not None:
aopdict[AOP.get('id')]['edam:operation_3799'] = '"""' + HTML_TAG_PATTERN.sub('', AOP.find(aopxml + 'overall-assessment').find(aopxml + 'quantitative-considerations').text) + '"""'
if AOP.find(aopxml + 'potential-applications').text is not None:
aopdict[AOP.get('id')]['nci:C25725'] = '"""' + HTML_TAG_PATTERN.sub('', AOP.find(aopxml + 'potential-applications').text) + '"""'
logger.info(f'Completed AOP parsing: {len(aopdict)} Adverse Outcome Pathways processed')
# Validate AOP required fields
try:
validate_required_fields(aopdict, 'AOP', ['dc:identifier', 'dc:title'])
except Exception as e:
logger.error(f"AOP required fields validation failed: {e}")
# Don't exit here since this is just a validation warning
# ### Chemicals
# For the chemicals in the AOP-Wiki, we added BridgeDb mappings for increased coverage of chemical databases for which we used the already present CAS identifers.
def map_chemicals_batch(cas_numbers, batch_size=100, bridgedb_url=None, timeout=REQUEST_TIMEOUT):
"""
Map multiple CAS numbers to chemical identifiers using BridgeDb batch API.
Args:
cas_numbers: List of CAS numbers to map
batch_size: Number of chemicals per batch request (default 100)
bridgedb_url: BridgeDb service URL (uses global bridgedb if None)
timeout: Request timeout in seconds
Returns:
Dictionary mapping CAS numbers to their identifier dictionaries
"""
if bridgedb_url is None:
bridgedb_url = bridgedb
batch_url = bridgedb_url.rstrip('/') + '/xrefsBatch/Ca'
results = {}
logger.info(f'Starting batch chemical mapping for {len(cas_numbers)} chemicals')
# Process in batches
for i in range(0, len(cas_numbers), batch_size):
batch = cas_numbers[i:i + batch_size]
batch_data = '\n'.join(batch)
batch_num = i//batch_size + 1
total_batches = (len(cas_numbers) + batch_size - 1)//batch_size
logger.info(f"Processing chemical batch {batch_num}/{total_batches} ({len(batch)} chemicals)")
try:
response = requests.post(
batch_url,
data=batch_data,
headers={'Content-Type': 'text/plain'},
timeout=timeout
)
response.raise_for_status()
# Parse batch response
batch_results = parse_batch_chemical_response(response.text)
results.update(batch_results)
except requests.RequestException as e:
logger.warning(f"Batch chemical mapping failed for batch {batch_num}: {e}")
# Fall back to individual requests for this batch
for cas in batch:
try:
individual_result = map_chemical_individual_fallback(cas, bridgedb_url, timeout)
if individual_result:
results[cas] = individual_result
except Exception as individual_error:
logger.warning(f"Individual chemical mapping fallback failed for {cas}: {individual_error}")
results[cas] = {}
logger.info(f'Completed batch chemical mapping: {len(results)} chemicals processed')
return results
def parse_batch_chemical_response(response_text):
"""
Parse BridgeDb batch chemical response into structured format.
Response format: "CAS_NUMBER\tCAS\tCs:id,Ch:id,Dr:id,Ce:id,..."
"""
results = {}
for line in response_text.strip().split('\n'):
if not line.strip():
continue
parts = line.split('\t')
if len(parts) < 3:
continue
cas_number = parts[0]
xrefs_str = parts[2]
if xrefs_str == 'N/A':
results[cas_number] = {}
continue
# Parse system codes
chemical_dict = {}
xrefs = xrefs_str.split(',')
for xref in xrefs:
if ':' not in xref:
continue
system_code, identifier = xref.split(':', 1)
# Map system codes to database names and chemical dictionary keys
# Reference: Complete BridgeDb system code mapping
if system_code == 'Ca': # CAS
# CAS is handled separately as dc:identifier, skip here
pass
elif system_code == 'Ce': # ChEBI
if 'cheminf:000407' not in chemical_dict:
chemical_dict['cheminf:000407'] = []
formatted_chebi = f"chebi:{identifier.split('CHEBI:')[-1]}"
chemical_dict['cheminf:000407'].append(formatted_chebi)
elif system_code == 'Cs': # ChemSpider
if 'cheminf:000405' not in chemical_dict:
chemical_dict['cheminf:000405'] = []
chemical_dict['cheminf:000405'].append(f"chemspider:{identifier}")
elif system_code == 'Cl': # ChEMBL compound
if 'cheminf:000412' not in chemical_dict:
chemical_dict['cheminf:000412'] = []
chemical_dict['cheminf:000412'].append(f"chembl.compound:{identifier}")
elif system_code == 'Dr': # DrugBank
if 'cheminf:000406' not in chemical_dict:
chemical_dict['cheminf:000406'] = []
chemical_dict['cheminf:000406'].append(f"drugbank:{identifier}")
elif system_code == 'Ch': # HMDB
if 'cheminf:000408' not in chemical_dict:
chemical_dict['cheminf:000408'] = []
chemical_dict['cheminf:000408'].append(f"hmdb:{identifier}")
elif system_code == 'Gpl': # Guide to Pharmacology Ligand ID (IUPHAR)
# Could add support if needed - not in original mapping
pass
elif system_code == 'Ik': # InChIKey
# InChIKey is handled separately from XML, skip here
pass
elif system_code == 'Ck': # KEGG Compound
if 'cheminf:000409' not in chemical_dict:
chemical_dict['cheminf:000409'] = []
chemical_dict['cheminf:000409'].append(f"kegg.compound:{identifier}")
elif system_code == 'Kd': # KEGG Drug
if 'cheminf:000409' not in chemical_dict:
chemical_dict['cheminf:000409'] = []
chemical_dict['cheminf:000409'].append(f"kegg.compound:{identifier}")
elif system_code == 'Kl': # KEGG Glycan
# Could add support if needed - not in original mapping
pass
elif system_code == 'Lm': # LIPID MAPS
if 'cheminf:000564' not in chemical_dict:
chemical_dict['cheminf:000564'] = []
chemical_dict['cheminf:000564'].append(f"lipidmaps:{identifier}")
elif system_code == 'Lb': # LipidBank
# Could add support if needed - not in original mapping
pass
elif system_code == 'Pgd': # PharmGKB Drug
# Could add support if needed - not in original mapping
pass
elif system_code == 'Cpc': # PubChem Compound
if 'cheminf:000140' not in chemical_dict:
chemical_dict['cheminf:000140'] = []
chemical_dict['cheminf:000140'].append(f"pubchem.compound:{identifier}")
elif system_code == 'Cps': # PubChem Substance
# Could add support if needed - not in original mapping
pass
elif system_code == 'Sl': # SwissLipids
# Could add support if needed - not in original mapping
pass
elif system_code == 'Td': # TTD Drug
# Could add support if needed - not in original mapping
pass
elif system_code == 'Wd': # Wikidata
if 'cheminf:000567' not in chemical_dict:
chemical_dict['cheminf:000567'] = []
chemical_dict['cheminf:000567'].append(f"wikidata:{identifier}")
elif system_code == 'Wi': # Wikipedia
# Could add support if needed - not in original mapping
pass
results[cas_number] = chemical_dict
return results
def map_chemical_individual_fallback(cas_number, bridgedb_url, timeout):
"""
Fall back to individual chemical mapping (original approach).
"""
individual_url = bridgedb_url.rstrip('/') + f'/xrefs/Ca/{cas_number}'
try:
response = requests.get(individual_url, timeout=timeout)
response.raise_for_status()
chemical_dict = {}
for line in response.text.split('\n'):
if not line.strip():
continue
parts = line.split('\t')
if len(parts) == 2:
identifier, database = parts
# Map database names to chemical dictionary keys (original format)
if database == 'Chemspider':
if 'cheminf:000405' not in chemical_dict:
chemical_dict['cheminf:000405'] = []
chemical_dict['cheminf:000405'].append(f"chemspider:{identifier}")
elif database == 'HMDB':
if 'cheminf:000408' not in chemical_dict:
chemical_dict['cheminf:000408'] = []
chemical_dict['cheminf:000408'].append(f"hmdb:{identifier}")
elif database == 'DrugBank':
if 'cheminf:000406' not in chemical_dict:
chemical_dict['cheminf:000406'] = []
chemical_dict['cheminf:000406'].append(f"drugbank:{identifier}")
elif database == 'ChEBI':
if 'cheminf:000407' not in chemical_dict:
chemical_dict['cheminf:000407'] = []
formatted_chebi = f"chebi:{identifier.split('CHEBI:')[-1]}"
chemical_dict['cheminf:000407'].append(formatted_chebi)
elif database == 'ChEMBL compound':
if 'cheminf:000412' not in chemical_dict:
chemical_dict['cheminf:000412'] = []
chemical_dict['cheminf:000412'].append(f"chembl.compound:{identifier}")
elif database == 'Wikidata':
if 'cheminf:000567' not in chemical_dict:
chemical_dict['cheminf:000567'] = []
chemical_dict['cheminf:000567'].append(f"wikidata:{identifier}")
elif database == 'PubChem-compound':
if 'cheminf:000140' not in chemical_dict:
chemical_dict['cheminf:000140'] = []
chemical_dict['cheminf:000140'].append(f"pubchem.compound:{identifier}")
elif database == 'KEGG Compound':
if 'cheminf:000409' not in chemical_dict:
chemical_dict['cheminf:000409'] = []
chemical_dict['cheminf:000409'].append(f"kegg.compound:{identifier}")
elif database == 'LIPID MAPS':
if 'cheminf:000564' not in chemical_dict:
chemical_dict['cheminf:000564'] = []
chemical_dict['cheminf:000564'].append(f"lipidmaps:{identifier}")
return chemical_dict
except requests.RequestException as e:
logger.warning(f"Individual chemical mapping failed for {cas_number}: {e}")
return {}
chedict = {}
listofchebi = []
listofchemspider = []
listofwikidata = []
listofchembl = []
listofdrugbank = []
listofpubchem = []
listoflipidmaps = []
listofhmdb = []
listofkegg = []
listofcas = []
listofinchikey = []
listofcomptox = []
# First pass: collect all chemical information and CAS numbers for batch processing
chemicals_to_map = [] # List of (chemical_id, cas_number) for batch mapping
cas_to_chemical_id = {} # Map CAS number back to chemical ID(s)
for che in root.findall(aopxml + 'chemical'):
chedict[che.get('id')] = {}
if che.find(aopxml + 'casrn') is not None:
if 'NOCAS' not in che.find(aopxml + 'casrn').text: # all NOCAS ids are taken out, so no issues as subjects
cas_number = che.find(aopxml + 'casrn').text
chedict[che.get('id')]['dc:identifier'] = 'cas:' + cas_number
listofcas.append('cas:' + cas_number)
chedict[che.get('id')]['cheminf:000446'] = '"' + cas_number + '"'
# Collect for batch processing
chemicals_to_map.append((che.get('id'), cas_number))
if cas_number not in cas_to_chemical_id:
cas_to_chemical_id[cas_number] = []
cas_to_chemical_id[cas_number].append(che.get('id'))
else:
chedict[che.get('id')]['dc:identifier'] = '"' + che.find(aopxml + 'casrn').text + '"'
# Batch BridgeDb chemical mapping (major performance improvement)
if chemicals_to_map:
logger.info(f"Starting batch chemical mapping for {len(chemicals_to_map)} chemicals with CAS numbers")
cas_numbers_list = [cas for _, cas in chemicals_to_map]
batch_results = map_chemicals_batch(cas_numbers_list)
# Apply batch results to chemical dictionaries
for cas_number, chemical_mappings in batch_results.items():
if cas_number in cas_to_chemical_id:
for chemical_id in cas_to_chemical_id[cas_number]:
# Apply all mapped identifiers to this chemical
for db_key, identifiers in chemical_mappings.items():
if identifiers: # Only add if there are identifiers
chedict[chemical_id][db_key] = identifiers.copy()
# Update global lists for deduplication (matching original behavior)
for identifier in identifiers:
if db_key == 'cheminf:000407' and identifier not in listofchebi: # ChEBI
listofchebi.append(identifier)
elif db_key == 'cheminf:000405' and identifier not in listofchemspider: # Chemspider
listofchemspider.append(identifier)
elif db_key == 'cheminf:000567' and identifier not in listofwikidata: # Wikidata
listofwikidata.append(identifier)
elif db_key == 'cheminf:000412' and identifier not in listofchembl: # ChEMBL
listofchembl.append(identifier)
elif db_key == 'cheminf:000140' and identifier not in listofpubchem: # PubChem
listofpubchem.append(identifier)
elif db_key == 'cheminf:000406' and identifier not in listofdrugbank: # DrugBank
listofdrugbank.append(identifier)
elif db_key == 'cheminf:000409' and identifier not in listofkegg: # KEGG
listofkegg.append(identifier)
elif db_key == 'cheminf:000564' and identifier not in listoflipidmaps: # LIPID MAPS
listoflipidmaps.append(identifier)
elif db_key == 'cheminf:000408' and identifier not in listofhmdb: # HMDB
listofhmdb.append(identifier)
# Continue with other chemical properties (InChI keys, names, etc.)
for che in root.findall(aopxml + 'chemical'):
if che.find(aopxml + 'jchem-inchi-key') is not None:
chedict[che.get('id')]['cheminf:000059'] = 'inchikey:' + str(che.find(aopxml + 'jchem-inchi-key').text)
listofinchikey.append('inchikey:' + str(che.find(aopxml + 'jchem-inchi-key').text))
if che.find(aopxml + 'preferred-name') is not None:
chedict[che.get('id')]['dc:title'] = '"' + che.find(aopxml + 'preferred-name').text + '"'
if che.find(aopxml + 'dsstox-id') is not None:
chedict[che.get('id')]['cheminf:000568'] = 'comptox:' + che.find(aopxml + 'dsstox-id').text
listofcomptox.append('comptox:' + che.find(aopxml + 'dsstox-id').text)
if che.find(aopxml + 'synonyms') is not None:
chedict[che.get('id')]['dcterms:alternative'] = []
for synonym in che.find(aopxml + 'synonyms').findall(aopxml + 'synonym'):
chedict[che.get('id')]['dcterms:alternative'].append(synonym.text[:-1])
logger.info(f'Completed chemical parsing: {len(chedict)} chemicals processed')
# ### Stressors
strdict = {}
for stressor in root.findall(aopxml + 'stressor'):
strdict[stressor.get('id')] = {}
strdict[stressor.get('id')]['dc:identifier'] = 'aop.stressor:' + refs['Stressor'][stressor.get('id')]
strdict[stressor.get('id')]['rdfs:label'] = '"Stressor ' + refs['Stressor'][stressor.get('id')] + '"'
strdict[stressor.get('id')]['foaf:page'] = '<https://identifiers.org/aop.stressor/' + refs['Stressor'][stressor.get('id')] + '>'
strdict[stressor.get('id')]['dc:title'] = '"' + stressor.find(aopxml + 'name').text + '"'
if stressor.find(aopxml + 'description').text is not None:
strdict[stressor.get('id')]['dc:description'] = '"""' + HTML_TAG_PATTERN.sub('', stressor.find(aopxml + 'description').text) + '"""'
strdict[stressor.get('id')]['dcterms:created'] = stressor.find(aopxml + 'creation-timestamp').text
strdict[stressor.get('id')]['dcterms:modified'] = stressor.find(aopxml + 'last-modification-timestamp').text
strdict[stressor.get('id')]['aopo:has_chemical_entity'] = []
strdict[stressor.get('id')]['linktochemical'] = []
if stressor.find(aopxml + 'chemicals') is not None:
for chemical in stressor.find(aopxml + 'chemicals').findall(aopxml + 'chemical-initiator'):
strdict[stressor.get('id')]['aopo:has_chemical_entity'].append('"' + chemical.get('user-term') + '"')
strdict[stressor.get('id')]['linktochemical'].append(chemical.get('chemical-id'))
logger.info(f'Completed stressor parsing: {len(strdict)} stressors processed')
# ### Taxonomy
taxdict = {}
for tax in root.findall(aopxml + 'taxonomy'):
taxdict[tax.get('id')] = {}
taxdict[tax.get('id')]['dc:source'] = tax.find(aopxml + 'source').text
taxdict[tax.get('id')]['dc:title'] = tax.find(aopxml + 'name').text
if taxdict[tax.get('id')]['dc:source'] == 'NCBI':
taxdict[tax.get('id')]['dc:identifier'] = 'ncbitaxon:' + tax.find(aopxml + 'source-id').text
elif taxdict[tax.get('id')]['dc:source'] is not None:
taxdict[tax.get('id')]['dc:identifier'] = '"' + tax.find(aopxml + 'source-id').text + '"'
else:
taxdict[tax.get('id')]['dc:identifier'] = '"' + tax.find(aopxml + 'source-id').text + '"'
logger.info(f'Taxonomy parsing completed: {len(taxdict)} taxonomies processed')
# ### AOP Taxonomy (Second Pass)
# Parse AOP taxonomy after taxdict is available
for AOP in root.findall(aopxml + 'aop'):
for appl in AOP.findall(aopxml + 'applicability'):
for tax in appl.findall(aopxml + 'taxonomy'):
if 'ncbitaxon:131567' not in aopdict[AOP.get('id')]:
if 'dc:identifier' in taxdict[tax.get('taxonomy-id')]:
aopdict[AOP.get('id')]['ncbitaxon:131567'] = [[tax.get('taxonomy-id'), tax.find(aopxml + 'evidence').text, taxdict[tax.get('taxonomy-id')]['dc:identifier'], taxdict[tax.get('taxonomy-id')]['dc:source'], taxdict[tax.get('taxonomy-id')]['dc:title']]]
else:
if 'dc:identifier' in taxdict[tax.get('taxonomy-id')]:
aopdict[AOP.get('id')]['ncbitaxon:131567'].append([tax.get('taxonomy-id'), tax.find(aopxml + 'evidence').text, taxdict[tax.get('taxonomy-id')]['dc:identifier'], taxdict[tax.get('taxonomy-id')]['dc:source'], taxdict[tax.get('taxonomy-id')]['dc:title']])
logger.info(f'AOP taxonomy second pass completed')
# ### Key Event Components
# Which comprise of the Biological Actions, Biological Processes, Biological Objects.
bioactdict = {None: {}}
bioactdict[None]['dc:identifier'] = None
bioactdict[None]['dc:source'] = None
bioactdict[None]['dc:title'] = None
for bioact in root.findall(aopxml + 'biological-action'):
bioactdict[bioact.get('id')] = {}
bioactdict[bioact.get('id')]['dc:source'] = '"' + bioact.find(aopxml + 'source').text + '"'
bioactdict[bioact.get('id')]['dc:title'] = '"' + bioact.find(aopxml + 'name').text + '"'
bioactdict[bioact.get('id')]['dc:identifier'] = '"' + bioact.find(aopxml + 'name').text + '"'
logger.info(f'Biological Activity parsing completed: {len(bioactdict)} annotations processed')
# Initialize bioprodict with default values
bioprodict = {
None: {
'dc:identifier': None,
'dc:source': None,
'dc:title': None
}
}
# Mapping of source prefixes to their respective formats
source_prefix_map = {
'"GO"': ('go:', 3),
'"MI"': ('mi:', 0),
'"MP"': ('mp:', 3),
'"MESH"': ('mesh:', 0),
'"HP"': ('hp:', 3),
'"PCO"': ('pco:', 4),
'"NBO"': ('nbo:', 4),
'"VT"': ('vt:', 3),
'"RBO"': ('rbo:', 4),
'"NCI"': ('nci:', 4),
'"IDO"': ('ido:', 4),
}
# Loop through biological processes and populate bioprodict
for biopro in root.findall(aopxml + 'biological-process'):
biopro_id = biopro.get('id')
bioprodict[biopro_id] = {}
# Extract values
source = f'"{biopro.find(aopxml + "source").text}"'
name = f'"{biopro.find(aopxml + "name").text}"'
source_id = biopro.find(aopxml + 'source-id').text
# Populate source and title
bioprodict[biopro_id]['dc:source'] = source
bioprodict[biopro_id]['dc:title'] = name
# Handle identifier based on source prefix
if source in source_prefix_map:
prefix, offset = source_prefix_map[source]
identifier = prefix + source_id[offset:]
bioprodict[biopro_id]['dc:identifier'] = identifier
else:
# Default case for unhandled sources
bioprodict[biopro_id]['dc:identifier'] = source_id
logger.info(f'Biological Process parsing completed: {len(bioprodict)} annotations processed')
# Initialize bioobjdict with default values
bioobjdict = {
None: {
'dc:identifier': None,
'dc:source': None,
'dc:title': None
}
}
objectstoskip = []
prolist = []
# Mapping of source prefixes to their respective formats
source_prefix_map = {
'"PR"': ('pr:', 3),
'"CL"': ('cl:', 3),
'"MESH"': ('mesh:', 0),
'"GO"': ('go:', 3),
'"UBERON"': ('uberon:', 7),
'"CHEBI"': ('chebio:', 6),
'"MP"': ('mp:', 3),
'"FMA"': ('fma:', 4),
'"PCO"': ('pco:', 4),
}
# Loop through biological objects and populate bioobjdict
for bioobj in root.findall(aopxml + 'biological-object'):
bioobj_id = bioobj.get('id')
bioobjdict[bioobj_id] = {}
# Extract values
source = f'"{bioobj.find(aopxml + "source").text}"'
name = f'"{bioobj.find(aopxml + "name").text}"'
source_id = bioobj.find(aopxml + 'source-id').text
# Populate source and title
bioobjdict[bioobj_id]['dc:source'] = source
bioobjdict[bioobj_id]['dc:title'] = name
# Handle identifier based on source prefix
if source in source_prefix_map:
prefix, offset = source_prefix_map[source]
identifier = prefix + source_id[offset:]
bioobjdict[bioobj_id]['dc:identifier'] = identifier
# Add to prolist if PR
if source == '"PR"':
prolist.append(identifier)