-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathutil.py
1504 lines (1294 loc) · 56.1 KB
/
util.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
"""Utility functions."""
import itertools as itt
import json
import logging as _logging
import os
import re
from collections import ChainMap, defaultdict
from dataclasses import dataclass, field
from functools import partial, reduce
from pathlib import Path
from string import punctuation
from typing import Any, DefaultDict, Dict, List, Optional, Set, TextIO, Tuple, Union
import curies
import numpy as np
import pandas as pd
import validators
import yaml
from curies import Converter
from deprecation import deprecated
from jsonschema import ValidationError
from linkml_runtime.linkml_model.types import Uriorcurie
from sssom_schema import Mapping as SSSOM_Mapping
from sssom_schema import MappingSet, slots
from .constants import (
COLUMN_INVERT_DICTIONARY,
COMMENT,
CONFIDENCE,
MAPPING_JUSTIFICATION,
MAPPING_SET_ID,
MAPPING_SET_SOURCE,
OBJECT_CATEGORY,
OBJECT_ID,
OBJECT_LABEL,
OBJECT_SOURCE,
OBO_HAS_DB_XREF,
OWL_DIFFERENT_FROM,
OWL_EQUIVALENT_CLASS,
PREDICATE_ID,
PREDICATE_INVERT_DICTIONARY,
PREDICATE_LIST,
PREDICATE_MODIFIER,
PREDICATE_MODIFIER_NOT,
RDFS_SUBCLASS_OF,
SCHEMA_YAML,
SEMAPV,
SKOS_BROAD_MATCH,
SKOS_CLOSE_MATCH,
SKOS_EXACT_MATCH,
SKOS_NARROW_MATCH,
SKOS_RELATED_MATCH,
SSSOM_SUPERCLASS_OF,
SSSOM_URI_PREFIX,
SUBJECT_CATEGORY,
SUBJECT_ID,
SUBJECT_LABEL,
SUBJECT_SOURCE,
UNKNOWN_IRI,
MetadataType,
_get_sssom_schema_object,
get_default_metadata,
)
from .context import (
SSSOM_BUILT_IN_PREFIXES,
ConverterHint,
_get_built_in_prefix_map,
ensure_converter,
get_converter,
)
from .sssom_document import MappingSetDocument
logging = _logging.getLogger(__name__)
SSSOM_DEFAULT_RDF_SERIALISATION = "turtle"
URI_SSSOM_MAPPINGS = f"{SSSOM_URI_PREFIX}mappings"
#: The 4 columns whose combination would be used as primary keys while merging/grouping
KEY_FEATURES = [SUBJECT_ID, PREDICATE_ID, OBJECT_ID, PREDICATE_MODIFIER]
TRIPLES_IDS = [SUBJECT_ID, PREDICATE_ID, OBJECT_ID]
@dataclass
class MappingSetDataFrame:
"""A collection of mappings represented as a DataFrame, together with additional metadata."""
df: pd.DataFrame
converter: Converter = field(default_factory=get_converter)
metadata: MetadataType = field(default_factory=get_default_metadata)
@property
def prefix_map(self):
"""Get a simple, bijective prefix map."""
return self.converter.bimap
@classmethod
def with_converter(
cls,
converter: Converter,
df: pd.DataFrame,
metadata: Optional[MetadataType] = None,
) -> "MappingSetDataFrame":
"""Instantiate with a converter instead of a vanilla prefix map."""
# TODO replace with regular instantiation
return cls(
df=df,
converter=converter,
metadata=metadata or get_default_metadata(),
)
@classmethod
def from_mappings(
cls,
mappings: List[SSSOM_Mapping],
*,
converter: ConverterHint = None,
metadata: Optional[MetadataType] = None,
) -> "MappingSetDataFrame":
"""Instantiate from a list of mappings, mapping set metadata, and an optional converter."""
# This combines multiple pieces of metadata in the following priority order:
# 1. The explicitly given metadata passed to from_mappings()
# 2. The default metadata (which includes a dummy license and mapping set URI)
chained_metadata = ChainMap(
metadata or {},
get_default_metadata(),
)
mapping_set = MappingSet(mappings=mappings, **chained_metadata)
return cls.from_mapping_set(mapping_set=mapping_set, converter=converter)
@classmethod
def from_mapping_set(
cls, mapping_set: MappingSet, *, converter: ConverterHint = None
) -> "MappingSetDataFrame":
"""Instantiate from a mapping set and an optional converter.
:param mapping_set: A mapping set
:param converter: A prefix map or pre-instantiated converter. If none given, uses a default
prefix map derived from the Bioregistry.
:returns: A mapping set dataframe
"""
doc = MappingSetDocument(converter=ensure_converter(converter), mapping_set=mapping_set)
return cls.from_mapping_set_document(doc)
@classmethod
def from_mapping_set_document(cls, doc: MappingSetDocument) -> "MappingSetDataFrame":
"""Instantiate from a mapping set document."""
if doc.mapping_set.mappings is None:
return cls(df=pd.DataFrame(), converter=doc.converter)
df = pd.DataFrame(get_dict_from_mapping(mapping) for mapping in doc.mapping_set.mappings)
meta = _extract_global_metadata(doc)
# remove columns where all values are blank.
df.replace("", np.nan, inplace=True)
df.dropna(axis=1, how="all", inplace=True) # remove columns with all row = 'None'-s.
slots_with_double_as_range = {
slot
for slot, slot_metadata in _get_sssom_schema_object().dict["slots"].items()
if slot_metadata["range"] == "double"
}
non_double_cols = df.loc[:, ~df.columns.isin(slots_with_double_as_range)]
non_double_cols = non_double_cols.replace(np.nan, "")
df[non_double_cols.columns] = non_double_cols
df = sort_df_rows_columns(df)
return cls.with_converter(df=df, converter=doc.converter, metadata=meta)
def to_mapping_set_document(self) -> "MappingSetDocument":
"""Get a mapping set document."""
from .parsers import to_mapping_set_document
return to_mapping_set_document(self)
def to_mapping_set(self) -> MappingSet:
"""Get a mapping set."""
return self.to_mapping_set_document().mapping_set
def to_mappings(self) -> List[SSSOM_Mapping]:
"""Get a mapping set."""
return self.to_mapping_set().mappings
def clean_context(self) -> None:
"""Clean up the context."""
self.converter = curies.chain([_get_built_in_prefix_map(), self.converter])
def standardize_references(self) -> None:
"""Standardize this MSDF's dataframe and metadata with respect to its converter."""
self._standardize_metadata_references()
self._standardize_df_references()
def _standardize_df_references(self) -> None:
"""Standardize this MSDF's dataframe with respect to its converter."""
func = partial(_standardize_curie_or_iri, converter=self.converter)
for column, schema_data in _get_sssom_schema_object().dict["slots"].items():
if schema_data["range"] != "EntityReference":
continue
if column not in self.df.columns:
continue
self.df[column] = self.df[column].map(func)
def _standardize_metadata_references(self, *, raise_on_invalid: bool = False) -> None:
"""Standardize this MSDF's metadata with respect to its converter."""
_standardize_metadata(
converter=self.converter, metadata=self.metadata, raise_on_invalid=raise_on_invalid
)
def merge(self, *msdfs: "MappingSetDataFrame", inplace: bool = True) -> "MappingSetDataFrame":
"""Merge two MappingSetDataframes.
:param msdfs: Multiple/Single MappingSetDataFrame(s) to merge with self
:param inplace: If true, msdf2 is merged into the calling MappingSetDataFrame,
if false, it simply return the merged data frame.
:return: Merged MappingSetDataFrame
"""
msdf = merge_msdf(self, *msdfs)
if inplace:
self.df = msdf.df
self.converter = msdf.converter
self.metadata = msdf.metadata
return self
else:
return msdf
def __str__(self) -> str: # noqa:D105
description = "SSSOM data table \n"
description += f"Number of extended prefix map records: {len(self.converter.records)} \n"
description += f"Metadata: {json.dumps(self.metadata)} \n"
description += f"Number of mappings: {len(self.df.index)} \n"
description += "\nFirst rows of data: \n"
description += self.df.head().to_string() + "\n"
description += "\nLast rows of data: \n"
description += self.df.tail().to_string() + "\n"
return description
def clean_prefix_map(self, strict: bool = True) -> None:
"""
Remove unused prefixes from the internal prefix map based on the internal dataframe.
:param strict: Boolean if True, errors out if all prefixes in dataframe are not
listed in the 'curie_map'.
:raises ValueError: If prefixes absent in 'curie_map' and strict flag = True
"""
prefixes_in_table = get_prefixes_used_in_table(self.df, converter=self.converter)
if self.metadata:
prefixes_in_table.update(get_prefixes_used_in_metadata(self.metadata))
missing_prefixes = prefixes_in_table - self.converter.get_prefixes()
if missing_prefixes and strict:
raise ValueError(
f"{missing_prefixes} are used in the SSSOM mapping set but it does not exist in the prefix map"
)
subconverter = self.converter.get_subconverter(prefixes_in_table)
for prefix in missing_prefixes:
subconverter.add_prefix(prefix, f"{UNKNOWN_IRI}{prefix.lower()}/")
self.converter = subconverter
def remove_mappings(self, msdf: "MappingSetDataFrame") -> None:
"""Remove mappings in right msdf from left msdf.
:param msdf: MappingSetDataframe object to be removed from primary msdf object.
"""
merge_on = KEY_FEATURES.copy()
if PREDICATE_MODIFIER not in self.df.columns:
merge_on.remove(PREDICATE_MODIFIER)
self.df = (
pd.merge(
self.df,
msdf.df,
on=merge_on,
how="outer",
suffixes=("", "_2"),
indicator=True,
)
.query("_merge == 'left_only'")
.drop("_merge", axis=1)
.reset_index(drop=True)
)
self.df = self.df[self.df.columns.drop(list(self.df.filter(regex=r"_2")))]
self.clean_prefix_map()
def _standardize_curie_or_iri(curie_or_iri: str, *, converter: Converter) -> str:
"""Standardize a CURIE or IRI, returning the original if not possible.
:param curie_or_iri: Either a string representing a CURIE or an IRI
:returns:
- If the string represents an IRI, tries to standardize it. If not possible, returns the original value
- If the string represents a CURIE, tries to standardize it. If not possible, returns the original value
- Otherwise, return the original value
"""
if converter.is_uri(curie_or_iri):
# TODO switch to compress, or fully replace _standardize_curie_or_iri with
# https://curies.readthedocs.io/en/latest/tutorial.html#extended-expansion-and-compression
return converter.standardize_uri(curie_or_iri, strict=True)
if converter.is_curie(curie_or_iri):
return converter.standardize_curie(curie_or_iri, strict=True)
return curie_or_iri
def _standardize_metadata(
converter: Converter, metadata: Dict[str, Any], *, raise_on_invalid: bool = False
) -> None:
schema_object = _get_sssom_schema_object()
slots_dict = schema_object.dict["slots"]
# remove all falsy values. This has to be
# done this way and not by making a new object
# since we work in place
for k, v in list(metadata.items()):
if not k or not v:
del metadata[k]
for key, value in metadata.items():
slot_metadata = slots_dict.get(key)
if slot_metadata is None:
text = f"invalid metadata key {key}"
if raise_on_invalid:
raise ValueError(text)
logging.warning(text)
continue
if slot_metadata["range"] != "EntityReference":
continue
if is_multivalued_slot(key):
if isinstance(value, str):
metadata[key] = [
_standardize_curie_or_iri(v.strip(), converter=converter)
for v in value.split("|")
]
elif isinstance(value, list):
metadata[key] = [_standardize_curie_or_iri(v, converter=converter) for v in value]
else:
raise TypeError(f"{key} requires either a string or a list, got: {value}")
elif isinstance(value, list):
print("here")
if len(value) > 1:
raise TypeError(
f"value for {key} should have been a single value, but got a list: {value}"
)
print("also here")
# note that the scenario len(value) == 0 is already
# taken care of by the "if not value:" line above
metadata[key] = _standardize_curie_or_iri(value[0], converter=converter)
else:
metadata[key] = _standardize_curie_or_iri(value, converter=converter)
@dataclass
class EntityPair:
"""
A tuple of entities.
Note that (e1,e2) == (e2,e1)
"""
subject_entity: Uriorcurie
object_entity: Uriorcurie
def __hash__(self) -> int: # noqa:D105
if self.subject_entity <= self.object_entity:
t = self.subject_entity, self.object_entity
else:
t = self.object_entity, self.subject_entity
return hash(t)
@dataclass
class MappingSetDiff:
"""
Represents a difference between two mapping sets.
Currently this is limited to diffs at the level of entity-pairs.
For example, if file1 has A owl:equivalentClass B, and file2 has A skos:closeMatch B,
this is considered a mapping in common.
"""
unique_tuples1: Optional[Set[EntityPair]] = None
unique_tuples2: Optional[Set[EntityPair]] = None
common_tuples: Optional[Set[EntityPair]] = None
combined_dataframe: Optional[pd.DataFrame] = None
"""
Dataframe that combines with left and right dataframes with information injected into
the comment column
"""
def parse(filename: Union[str, Path]) -> pd.DataFrame:
"""Parse a TSV to a pandas frame."""
logging.info(f"Parsing {filename}")
return pd.read_csv(filename, sep="\t", comment="#")
def collapse(df: pd.DataFrame) -> pd.DataFrame:
"""Collapse rows with same S/P/O and combines confidence."""
df2 = df.groupby([SUBJECT_ID, PREDICATE_ID, OBJECT_ID])[CONFIDENCE].apply(max).reset_index()
return df2
def sort_sssom(df: pd.DataFrame) -> pd.DataFrame:
"""Sort SSSOM by columns.
:param df: SSSOM DataFrame to be sorted.
:return: Sorted SSSOM DataFrame
"""
df.sort_values(by=sorted(df.columns), ascending=False, inplace=True)
return df
def filter_redundant_rows(df: pd.DataFrame, ignore_predicate: bool = False) -> pd.DataFrame:
"""Remove rows if there is another row with same S/O and higher confidence.
:param df: Pandas DataFrame to filter
:param ignore_predicate: If true, the predicate_id column is ignored, defaults to False
:return: Filtered pandas DataFrame
"""
# tie-breaker
# create a 'sort' method and then replce the following line by sort()
df = sort_sssom(df)
# df[CONFIDENCE] = df[CONFIDENCE].apply(lambda x: x + random.random() / 10000)
confidence_in_original = CONFIDENCE in df.columns
df, nan_df = assign_default_confidence(df)
if ignore_predicate:
key = [SUBJECT_ID, OBJECT_ID]
else:
key = [SUBJECT_ID, OBJECT_ID, PREDICATE_ID]
dfmax: pd.DataFrame
dfmax = df.groupby(key, as_index=False)[CONFIDENCE].apply(max).drop_duplicates()
max_conf: Dict[Tuple[str, ...], float] = {}
for _, row in dfmax.iterrows():
if ignore_predicate:
max_conf[(row[SUBJECT_ID], row[OBJECT_ID])] = row[CONFIDENCE]
else:
max_conf[(row[SUBJECT_ID], row[OBJECT_ID], row[PREDICATE_ID])] = row[CONFIDENCE]
if ignore_predicate:
df = df[
df.apply(
lambda x: x[CONFIDENCE] >= max_conf[(x[SUBJECT_ID], x[OBJECT_ID])],
axis=1,
)
]
else:
df = df[
df.apply(
lambda x: x[CONFIDENCE] >= max_conf[(x[SUBJECT_ID], x[OBJECT_ID], x[PREDICATE_ID])],
axis=1,
)
]
# We are preserving confidence = NaN rows without making assumptions.
# This means that there are potential duplicate mappings
# FutureWarning: The frame.append method is deprecated and
# will be removed from pandas in a future version.
# Use pandas.concat instead.
# return_df = df.append(nan_df).drop_duplicates()
confidence_reconciled_df = pd.concat([df, nan_df]).drop_duplicates()
# Reconciling dataframe rows based on the predicates with equal confidence.
if PREDICATE_MODIFIER in confidence_reconciled_df.columns:
tmp_df = confidence_reconciled_df[
[SUBJECT_ID, OBJECT_ID, PREDICATE_ID, CONFIDENCE, PREDICATE_MODIFIER]
]
tmp_df = tmp_df[tmp_df[PREDICATE_MODIFIER] != PREDICATE_MODIFIER_NOT].drop(
PREDICATE_MODIFIER, axis=1
)
else:
tmp_df = confidence_reconciled_df[[SUBJECT_ID, OBJECT_ID, PREDICATE_ID, CONFIDENCE]]
tmp_df_grp = tmp_df.groupby([SUBJECT_ID, OBJECT_ID, CONFIDENCE], as_index=False).count()
tmp_df_grp = tmp_df_grp[tmp_df_grp[PREDICATE_ID] > 1].drop(PREDICATE_ID, axis=1)
non_predicate_reconciled_df = (
confidence_reconciled_df.merge(
tmp_df_grp, on=list(tmp_df_grp.columns), how="left", indicator=True
)
.query('_merge == "left_only"')
.drop(columns="_merge")
)
multiple_predicate_df = (
confidence_reconciled_df.merge(
tmp_df_grp, on=list(tmp_df_grp.columns), how="right", indicator=True
)
.query('_merge == "both"')
.drop(columns="_merge")
)
return_df = non_predicate_reconciled_df
for _, row in tmp_df_grp.iterrows():
logic_df = multiple_predicate_df[list(tmp_df_grp.columns)] == row
concerned_row_index = logic_df[logic_df[list(tmp_df_grp.columns)]].dropna().index
concerned_df = multiple_predicate_df.iloc[concerned_row_index]
# Go down the hierarchical list of PREDICATE_LIST and grab the first match
return_df = pd.concat(
[get_row_based_on_hierarchy(concerned_df), return_df], axis=0
).drop_duplicates()
if not confidence_in_original:
return_df = return_df.drop(columns=[CONFIDENCE], axis=1)
return return_df
def get_row_based_on_hierarchy(df: pd.DataFrame):
"""Get row based on hierarchy of predicates.
The hierarchy is as follows:
# owl:equivalentClass
# owl:equivalentProperty
# rdfs:subClassOf
# rdfs:subPropertyOf
# owl:sameAs
# skos:exactMatch
# skos:closeMatch
# skos:broadMatch
# skos:narrowMatch
# oboInOwl:hasDbXref
# skos:relatedMatch
# rdfs:seeAlso
:param df: Dataframe containing multiple predicates for same subject and object.
:return: Dataframe with a single row which ranks higher in the hierarchy.
"""
for pred in PREDICATE_LIST:
hierarchical_df = df[df[PREDICATE_ID] == pred]
if not hierarchical_df.empty:
return hierarchical_df
def assign_default_confidence(
df: pd.DataFrame,
) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""Assign :data:`numpy.nan` to confidence that are blank.
:param df: SSSOM DataFrame
:return: A Tuple consisting of the original DataFrame and dataframe consisting of empty confidence values.
"""
# Get rows having numpy.NaN as confidence
if df is None:
ValueError("DataFrame cannot be empty to 'assign_default_confidence'.")
new_df = df.copy()
if CONFIDENCE not in new_df.columns:
new_df[CONFIDENCE] = 0.0 # np.NaN
nan_df = pd.DataFrame(columns=new_df.columns)
else:
new_df = df[~df[CONFIDENCE].isna()]
nan_df = df[df[CONFIDENCE].isna()]
return new_df, nan_df
def remove_unmatched(df: pd.DataFrame) -> pd.DataFrame:
"""Remove rows where no match is found.
TODO: https://github.com/OBOFoundry/SSSOM/issues/28
:param df: Pandas DataFrame
:return: Pandas DataFrame with 'PREDICATE_ID' not 'noMatch'.
"""
return df[df[PREDICATE_ID] != "noMatch"]
def create_entity(identifier: str, mappings: Dict[str, Any]) -> Uriorcurie:
"""
Create an Entity object.
:param identifier: Entity Id
:param mappings: Mapping dictionary
:return: An Entity object
"""
entity = Uriorcurie(identifier) # Entity(id=identifier)
for key, value in mappings.items():
if key in entity:
entity[key] = value
return entity
def group_mappings(df: pd.DataFrame) -> Dict[EntityPair, List[pd.Series]]:
"""Group mappings by EntityPairs."""
mappings: DefaultDict[EntityPair, List[pd.Series]] = defaultdict(list)
for _, row in df.iterrows():
subject_entity = create_entity(
identifier=row[SUBJECT_ID],
mappings={
"label": SUBJECT_LABEL,
"category": SUBJECT_CATEGORY,
"source": SUBJECT_SOURCE,
},
)
object_entity = create_entity(
identifier=row[OBJECT_ID],
mappings={
"label": OBJECT_LABEL,
"category": OBJECT_CATEGORY,
"source": OBJECT_SOURCE,
},
)
mappings[EntityPair(subject_entity, object_entity)].append(row)
return dict(mappings)
def compare_dataframes(df1: pd.DataFrame, df2: pd.DataFrame) -> MappingSetDiff:
"""Perform a diff between two SSSOM dataframes.
:param df1: A mapping dataframe
:param df2: A mapping dataframe
:returns: A mapping set diff
.. warning:: currently does not discriminate between mappings with different predicates
"""
mappings1 = group_mappings(df1.copy())
mappings2 = group_mappings(df2.copy())
tuples1 = set(mappings1.keys())
tuples2 = set(mappings2.keys())
d = MappingSetDiff()
d.unique_tuples1 = tuples1.difference(tuples2)
d.unique_tuples2 = tuples2.difference(tuples1)
d.common_tuples = tuples1.intersection(tuples2)
all_tuples = tuples1.union(tuples2)
all_ids = set()
for t in all_tuples:
all_ids.update({t.subject_entity, t.object_entity})
rows = []
for t in d.unique_tuples1:
for r in mappings1[t]:
r[COMMENT] = "UNIQUE_1"
rows += mappings1[t]
for t in d.unique_tuples2:
for r in mappings2[t]:
r[COMMENT] = "UNIQUE_2"
rows += mappings2[t]
for t in d.common_tuples:
new_rows = mappings1[t] + mappings2[t]
for r in new_rows:
r[COMMENT] = "COMMON_TO_BOTH"
rows += new_rows
# for r in rows:
# r['other'] = 'synthesized sssom file'
d.combined_dataframe = pd.DataFrame(rows).drop_duplicates()
return d
def add_default_confidence(df: pd.DataFrame, confidence: float = np.NAN) -> pd.DataFrame:
"""Add `confidence` column to DataFrame if absent and initializes to 0.95.
If `confidence` column already exists, only fill in the None ones by 0.95.
:param df: DataFrame whose `confidence` column needs to be filled.
:return: DataFrame with a complete `confidence` column.
"""
if CONFIDENCE in df.columns:
df[CONFIDENCE] = df[CONFIDENCE].apply(lambda x: confidence * x if x is not None else x)
df[CONFIDENCE].fillna(float(confidence), inplace=True)
else:
df[CONFIDENCE] = float(confidence)
return df
def dataframe_to_ptable(
df: pd.DataFrame, *, inverse_factor: float = None, default_confidence: float = None
):
"""Export a KBOOM table.
:param df: Pandas DataFrame
:param inverse_factor: Multiplier to (1 - confidence), defaults to 0.5
:param default_confidence: Default confidence to be assigned if absent.
:raises ValueError: Predicate value error
:raises ValueError: Predicate type value error
:return: List of rows
"""
if not inverse_factor:
inverse_factor = 0.5
if default_confidence:
df = add_default_confidence(df, default_confidence)
df = collapse(df)
rows = []
for _, row in df.iterrows():
subject_id = row[SUBJECT_ID]
object_id = row[OBJECT_ID]
confidence = row[CONFIDENCE]
# confidence of inverse
# e.g. if Pr(super) = 0.2, then Pr(sub) = (1-0.2) * IF
inverse_confidence = (1.0 - confidence) * inverse_factor
residual_confidence = (1 - (confidence + inverse_confidence)) / 2.0
predicate = row[PREDICATE_ID]
if predicate == OWL_EQUIVALENT_CLASS:
predicate_type = PREDICATE_EQUIVALENT
elif predicate == SKOS_EXACT_MATCH:
predicate_type = PREDICATE_EQUIVALENT
elif predicate == SKOS_CLOSE_MATCH:
# TODO: consider distributing
predicate_type = PREDICATE_EQUIVALENT
elif predicate == RDFS_SUBCLASS_OF:
predicate_type = PREDICATE_SUBCLASS
elif predicate == SKOS_BROAD_MATCH:
predicate_type = PREDICATE_SUBCLASS
elif predicate == SSSOM_SUPERCLASS_OF:
predicate_type = PREDICATE_SUPERCLASS
elif predicate == SKOS_NARROW_MATCH:
predicate_type = PREDICATE_SUPERCLASS
elif predicate == OWL_DIFFERENT_FROM:
predicate_type = PREDICATE_SIBLING
# * Added by H2 ############################
elif predicate == OBO_HAS_DB_XREF:
predicate_type = PREDICATE_HAS_DBXREF
elif predicate == SKOS_RELATED_MATCH:
predicate_type = PREDICATE_RELATED_MATCH
# * ########################################
else:
raise ValueError(f"Unhandled predicate: {predicate}")
if predicate_type == PREDICATE_SUBCLASS:
ps = (
confidence,
inverse_confidence,
residual_confidence,
residual_confidence,
)
elif predicate_type == PREDICATE_SUPERCLASS:
ps = (
inverse_confidence,
confidence,
residual_confidence,
residual_confidence,
)
elif predicate_type == PREDICATE_EQUIVALENT:
ps = (
residual_confidence,
residual_confidence,
confidence,
inverse_confidence,
)
elif predicate_type == PREDICATE_SIBLING:
ps = (
residual_confidence,
residual_confidence,
inverse_confidence,
confidence,
)
# * Added by H2 ############################
elif predicate_type == PREDICATE_HAS_DBXREF:
ps = (
residual_confidence,
residual_confidence,
confidence,
inverse_confidence,
)
elif predicate_type == PREDICATE_RELATED_MATCH:
ps = (
residual_confidence,
residual_confidence,
confidence,
inverse_confidence,
)
# * #########################################
else:
raise ValueError(f"predicate: {predicate_type}")
row = [subject_id, object_id] + [str(p) for p in ps]
rows.append(row)
return rows
PREDICATE_SUBCLASS = 0
PREDICATE_SUPERCLASS = 1
PREDICATE_EQUIVALENT = 2
PREDICATE_SIBLING = 3
# * Added by H2 ############################
PREDICATE_HAS_DBXREF = 4
PREDICATE_RELATED_MATCH = 5
# * ########################################
RDF_FORMATS = {"ttl", "turtle", "nt", "xml"}
def merge_msdf(
*msdfs: MappingSetDataFrame,
reconcile: bool = False,
) -> MappingSetDataFrame:
"""Merge multiple MappingSetDataFrames into one.
:param msdfs: A Tuple of MappingSetDataFrames to be merged
:param reconcile: If reconcile=True, then dedupe(remove redundant lower confidence mappings)
and reconcile (if msdf contains a higher confidence _negative_ mapping,
then remove lower confidence positive one. If confidence is the same,
prefer HumanCurated. If both HumanCurated, prefer negative mapping).
Defaults to True.
:returns: Merged MappingSetDataFrame.
"""
# Inject metadata of msdf into df
msdf_with_meta = [inject_metadata_into_df(msdf) for msdf in msdfs]
# merge df [# 'outer' join in pandas == FULL JOIN in SQL]
# df_merged = reduce(
# lambda left, right: left.merge(right, how="outer", on=list(left.columns)),
# [msdf.df for msdf in msdf_with_meta],
# )
# Concat is an alternative to merge when columns are not the same.
df_merged = reduce(
lambda left, right: pd.concat([left, right], axis=0, ignore_index=True),
[msdf.df for msdf in msdf_with_meta],
).drop_duplicates(ignore_index=True)
converter = curies.chain(msdf.converter for msdf in msdf_with_meta)
merged_msdf = MappingSetDataFrame.with_converter(df=df_merged, converter=converter)
if reconcile:
merged_msdf.df = filter_redundant_rows(merged_msdf.df)
if (
PREDICATE_MODIFIER in merged_msdf.df.columns
and PREDICATE_MODIFIER_NOT in merged_msdf.df[PREDICATE_MODIFIER]
):
merged_msdf.df = deal_with_negation(merged_msdf.df) # deals with negation
# TODO: Add default values for license and mapping_set_id.
return merged_msdf
def deal_with_negation(df: pd.DataFrame) -> pd.DataFrame:
"""Combine negative and positive rows with matching [SUBJECT_ID, OBJECT_ID, CONFIDENCE] combination.
Rule: negative trumps positive if modulus of confidence values are equal.
:param df: Merged Pandas DataFrame
:return: Pandas DataFrame with negations addressed
:raises ValueError: If the dataframe is none after assigning default confidence
"""
"""
1. Mappings in mapping1 trump mappings in mapping2 (if mapping2 contains a conflicting mapping in mapping1,
the one in mapping1 is preserved).
2. Reconciling means two things
[i] if the same s,p,o (subject_id, object_id, predicate_id) is present multiple times,
only preserve the highest confidence one. If confidence is same, rule 1 (above) applies.
[ii] If s,!p,o and s,p,o , then prefer higher confidence and remove the other.
If same confidence prefer "HumanCurated" .If same again prefer negative.
3. Prefixes:
[i] if there is the same prefix in mapping1 as in mapping2, and the prefix URL is different,
throw an error and fail hard
else just merge the two prefix maps
4. Metadata: same as rule 1.
#1; #2(i) #3 and $4 are taken care of by 'filtered_merged_df' Only #2(ii) should be performed here.
"""
# Handle DataFrames with no 'confidence' column (basically adding a np.NaN to all non-numeric confidences)
confidence_in_original = CONFIDENCE in df.columns
df, nan_df = assign_default_confidence(df)
# If s,!p,o and s,p,o , then prefer higher confidence and remove the other. ###
negation_df: pd.DataFrame
negation_df = df.loc[df[PREDICATE_MODIFIER] == PREDICATE_MODIFIER_NOT]
normalized_negation_df = negation_df.reset_index()
# This step ONLY if 'NOT' is expressed by the symbol '!' in 'predicate_id' #####
# normalized_negation_df[PREDICATE_ID] = normalized_negation_df[
# PREDICATE_ID
# ].str.replace("!", "")
########################################################
normalized_negation_df = normalized_negation_df.drop(["index"], axis=1)
# remove the NOT rows from the main DataFrame
condition = negation_df.isin(df)
positive_df = df.drop(condition.index)
positive_df = positive_df.reset_index().drop(["index"], axis=1)
columns_of_interest = [
SUBJECT_ID,
PREDICATE_ID,
OBJECT_ID,
CONFIDENCE,
MAPPING_JUSTIFICATION,
]
negation_subset = normalized_negation_df[columns_of_interest]
positive_subset = positive_df[columns_of_interest]
combined_normalized_subset = pd.concat([positive_subset, negation_subset]).drop_duplicates()
# GroupBy and SELECT ONLY maximum confidence
max_confidence_df: pd.DataFrame
max_confidence_df = combined_normalized_subset.groupby(TRIPLES_IDS, as_index=False)[
CONFIDENCE
].max()
# If same confidence prefer "HumanCurated".
reconciled_df_subset = pd.DataFrame(columns=combined_normalized_subset.columns)
for _, row_1 in max_confidence_df.iterrows():
match_condition_1 = (
(combined_normalized_subset[SUBJECT_ID] == row_1[SUBJECT_ID])
& (combined_normalized_subset[OBJECT_ID] == row_1[OBJECT_ID])
& (combined_normalized_subset[CONFIDENCE] == row_1[CONFIDENCE])
)
# match_condition_1[match_condition_1] gives the list of 'True's.
# In other words, the rows that match the condition (rules declared).
# Ideally, there should be 1 row. If not apply an extra rule to look for 'HumanCurated'.
if len(match_condition_1[match_condition_1].index) > 1:
match_condition_1 = (
(combined_normalized_subset[SUBJECT_ID] == row_1[SUBJECT_ID])
& (combined_normalized_subset[OBJECT_ID] == row_1[OBJECT_ID])
& (combined_normalized_subset[CONFIDENCE] == row_1[CONFIDENCE])
& (
combined_normalized_subset[MAPPING_JUSTIFICATION]
== SEMAPV.ManualMappingCuration.value
)
)
# In spite of this, if match_condition_1
# is returning multiple rows, pick any random row from above.
if len(match_condition_1[match_condition_1].index) > 1:
match_condition_1 = match_condition_1[match_condition_1].sample()
# FutureWarning: The frame.append method is deprecated and will be removed
# from pandas in a future version. Use pandas.concat instead.
# reconciled_df_subset = reconciled_df_subset.append(
# combined_normalized_subset.loc[
# match_condition_1[match_condition_1].index, :
# ],
# ignore_index=True,
# )
reconciled_df_subset = pd.concat(
[
reconciled_df_subset,
combined_normalized_subset.loc[match_condition_1[match_condition_1].index, :],
],
ignore_index=True,
)
# Add negations (PREDICATE_MODIFIER) back to DataFrame
# NOTE: negative TRUMPS positive if negative and positive with same
# [SUBJECT_ID, OBJECT_ID, PREDICATE_ID] exist
for _, row_2 in negation_df.iterrows():
match_condition_2 = (
(reconciled_df_subset[SUBJECT_ID] == row_2[SUBJECT_ID])
& (reconciled_df_subset[OBJECT_ID] == row_2[OBJECT_ID])
& (reconciled_df_subset[CONFIDENCE] == row_2[CONFIDENCE])
)
reconciled_df_subset.loc[
match_condition_2[match_condition_2].index, PREDICATE_MODIFIER
] = row_2[PREDICATE_MODIFIER]
if PREDICATE_MODIFIER in reconciled_df_subset.columns:
reconciled_df_subset[PREDICATE_MODIFIER] = reconciled_df_subset[PREDICATE_MODIFIER].fillna(
""
)
# .fillna(df) towards the end fills an empty value
# with a corresponding value from df.
# This needs to happen because the columns in df
# not in reconciled_df_subset will be NaN otherwise
# which is incorrect.
reconciled_df = df.merge(
reconciled_df_subset, how="right", on=list(reconciled_df_subset.columns)
).fillna(df)
if nan_df.empty:
return_df = reconciled_df
else:
return_df = reconciled_df.append(nan_df).drop_duplicates()
if not confidence_in_original:
return_df = return_df.drop(columns=[CONFIDENCE], axis=1)
return return_df
def inject_metadata_into_df(msdf: MappingSetDataFrame) -> MappingSetDataFrame:
"""Inject metadata dictionary key-value pair into DataFrame columns in a MappingSetDataFrame.DataFrame.
:param msdf: MappingSetDataFrame with metadata separate.
:return: MappingSetDataFrame with metadata as columns
"""
# TODO add this into the "standardize" function introduced in
# https://github.com/mapping-commons/sssom-py/pull/438
# TODO Check if 'k' is a valid 'slot' for 'mapping' [sssom.yaml]
with open(SCHEMA_YAML) as file:
schema = yaml.safe_load(file)
slots = schema["classes"]["mapping"]["slots"]
for k, v in msdf.metadata.items():
if k not in msdf.df.columns and k in slots:
if k == MAPPING_SET_ID:
k = MAPPING_SET_SOURCE
if isinstance(v, list):
v = "|".join(x for x in v)
msdf.df[k] = str(v)
return msdf
def get_file_extension(file: Union[str, Path, TextIO]) -> str:
"""Get file extension.
:param file: File path
:return: format of the file passed, default tsv
"""
if isinstance(file, Path):
if file.suffix:
return file.suffix.strip(punctuation)
else:
logging.warning(