Skip to content

embarrassment

clean(attr_df)

Clean attribute triple values.

Remove datatype tags and return values as string.

Parameters:

Name Type Description Default
attr_df DataFrame

Attribute triples.

required

Returns:

Type Description
DataFrame

Cleaned attribute triples.

Examples:

>>> import pandas as pd
>>> attr = pd.DataFrame([("e1","attr1","'lorem ipsum'^^xsd:string"), ("e2","attr2","dolor")], columns=["head","relation","tail"])
>>> from embarrassment import clean
>>> clean(attr)
  head relation         tail
0   e1    attr1  lorem ipsum
1   e2    attr2        dolor
Source code in embarrassment/api.py
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
@check_triple
def clean(attr_df: pd.DataFrame) -> pd.DataFrame:
    """Clean attribute triple values.

    Remove datatype tags and return values as string.

    Args:
      attr_df: Attribute triples.

    Returns:
      Cleaned attribute triples.

    Examples:
        >>> import pandas as pd
        >>> attr = pd.DataFrame([("e1","attr1","'lorem ipsum'^^xsd:string"), ("e2","attr2","dolor")], columns=["head","relation","tail"])
        >>> from embarrassment import clean
        >>> clean(attr)
          head relation         tail
        0   e1    attr1  lorem ipsum
        1   e2    attr2        dolor
    """

    def _clean(line) -> str:
        if line is None:
            return ""
        value = str(line).rsplit("^^", 1)[0]
        if (
            value.startswith('"')
            and value.endswith('"')
            or value.startswith("'")
            and value.endswith("'")
        ):
            return value[1:-1]
        return value

    tail_name = attr_df.columns[2]
    attr_df.loc[:, tail_name] = attr_df[tail_name].fillna("").map(_clean)
    return attr_df

neighbor_attr_triples(rel_df, attr_df, wanted_eid, in_out_both='both')

Find attribute triples of neighbor entities of specific entity.

Parameters:

Name Type Description Default
rel_df DataFrame

Relation triples.

required
attr_df DataFrame

Attribute triples.

required
wanted_eid str

Wanted entity id of which the neighborhood is used.

required
in_out_both InOutBoth

Whether to look at ("in","out","both") edges.

'both'

Returns:

Type Description
DataFrame

Attribute triples of neighboring entities.

Raises:

Type Description
ValueError

if unknown in_out_both value.

Examples:

>>> import pandas as pd
>>> rel = pd.DataFrame([("e1","rel1","e2"), ("e3", "rel2", "e1")], columns=["head","relation","tail"])
>>> attr = pd.DataFrame([("e1","attr1","lorem ipsum"), ("e2","attr2","dolor")], columns=["head","relation","tail"])
>>> from embarrassment import neighbor_attr_triples
>>> neighbor_attr_triples(rel, attr, "e1")
  head relation   tail
1   e2    attr2  dolor
Source code in embarrassment/api.py
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
@check_triple
def neighbor_attr_triples(
    rel_df: pd.DataFrame,
    attr_df: pd.DataFrame,
    wanted_eid: str,
    in_out_both: InOutBoth = "both",
) -> pd.DataFrame:
    """Find attribute triples of neighbor entities of specific entity.

    Args:
      rel_df: Relation triples.
      attr_df: Attribute triples.
      wanted_eid: Wanted entity id of which the neighborhood is used.
      in_out_both: Whether to look at ("in","out","both") edges.

    Returns:
      Attribute triples of neighboring entities.

    Raises:
        ValueError: if unknown in_out_both value.

    Examples:
        >>> import pandas as pd
        >>> rel = pd.DataFrame([("e1","rel1","e2"), ("e3", "rel2", "e1")], columns=["head","relation","tail"])
        >>> attr = pd.DataFrame([("e1","attr1","lorem ipsum"), ("e2","attr2","dolor")], columns=["head","relation","tail"])
        >>> from embarrassment import neighbor_attr_triples
        >>> neighbor_attr_triples(rel, attr, "e1")
          head relation   tail
        1   e2    attr2  dolor
    """
    neighbor_ids = neighbor_set(
        rel_df=rel_df, wanted_eid=wanted_eid, in_out_both=in_out_both
    )
    head_col = attr_df.columns[0]
    return attr_df[attr_df[head_col].isin(neighbor_ids)]

neighbor_rel_triples(rel_df, wanted_eid, in_out_both='both', filter_self=True)

Find relation triples of immediate neighbors.

Parameters:

Name Type Description Default
rel_df DataFrame

Relation triples.

required
wanted_eid str

Wanted entity id, to search neighborhood.

required
in_out_both InOutBoth

Whether to look at ("in","out","both") edges.

'both'
filter_self bool

Remove triples containing wanted entity id.

True

Returns:

Type Description
DataFrame

relation triples of immediate neighbors of search entity.

Raises:

Type Description
ValueError

if unknown in_out_both value.

Examples:

>>> import pandas as pd
>>> rel = pd.DataFrame([("e1","rel1","e2"), ("e3", "rel2", "e1"), ("e3", "rel2", "e4"), ("e2", "rel2", "e4")], columns=["head","relation","tail"])
>>> from embarrassment import neighbor_rel_triples
>>> neighbor_rel_triples(rel, "e1")
  head relation tail
2   e3     rel2   e4
3   e2     rel2   e4
>>> neighbor_rel_triples(rel, "e1", "in")
  head relation tail
2   e3     rel2   e4
>>> neighbor_rel_triples(rel, "e1", "in", filter_self=False)
  head relation tail
1   e3     rel2   e1
2   e3     rel2   e4
Source code in embarrassment/api.py
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
@check_triple
def neighbor_rel_triples(
    rel_df: pd.DataFrame,
    wanted_eid: str,
    in_out_both: InOutBoth = "both",
    filter_self: bool = True,
) -> pd.DataFrame:
    """Find relation triples of immediate neighbors.

    Args:
      rel_df: Relation triples.
      wanted_eid: Wanted entity id, to search neighborhood.
      in_out_both: Whether to look at ("in","out","both") edges.
      filter_self: Remove triples containing wanted entity id.

    Returns:
      relation triples of immediate neighbors of search entity.

    Raises:
        ValueError: if unknown in_out_both value.

    Examples:
        >>> import pandas as pd
        >>> rel = pd.DataFrame([("e1","rel1","e2"), ("e3", "rel2", "e1"), ("e3", "rel2", "e4"), ("e2", "rel2", "e4")], columns=["head","relation","tail"])
        >>> from embarrassment import neighbor_rel_triples
        >>> neighbor_rel_triples(rel, "e1")
          head relation tail
        2   e3     rel2   e4
        3   e2     rel2   e4
        >>> neighbor_rel_triples(rel, "e1", "in")
          head relation tail
        2   e3     rel2   e4
        >>> neighbor_rel_triples(rel, "e1", "in", filter_self=False)
          head relation tail
        1   e3     rel2   e1
        2   e3     rel2   e4
    """
    neighbor_ids = neighbor_set(
        rel_df=rel_df,
        wanted_eid=wanted_eid,
        in_out_both=in_out_both,
    )
    head_col = rel_df.columns[0]
    tail_col = rel_df.columns[2]
    head_n = rel_df[rel_df[head_col].isin(neighbor_ids)]
    tail_n = rel_df[rel_df[tail_col].isin(neighbor_ids)]
    if filter_self:
        head_n = head_n[head_n[tail_col] != wanted_eid]
        tail_n = tail_n[tail_n[head_col] != wanted_eid]
    return pd.concat([head_n, tail_n])

neighbor_set(rel_df, wanted_eid, in_out_both='both')

Get set of neighboring entities.

Parameters:

Name Type Description Default
rel_df DataFrame

Relation triples.

required
wanted_eid str

Entity id of which the neighborhood is investigated.

required
in_out_both InOutBoth

Whether to look at ("in","out","both") edges.

'both'

Returns:

Type Description
Set[str]

Set of neighboring ids.

Raises:

Type Description
ValueError

if unknown in_out_both value.

Examples:

>>> import pandas as pd
>>> rel = pd.DataFrame([("e1","rel1","e2"), ("e3", "rel2", "e1")], columns=["head","relation","tail"])
>>> from embarrassment import neighbor_set
>>> neighbor_set(rel, "e1")
{'e2', 'e3'}
Source code in embarrassment/api.py
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
@check_triple
def neighbor_set(
    rel_df: pd.DataFrame, wanted_eid: str, in_out_both: InOutBoth = "both"
) -> Set[str]:
    """Get set of neighboring entities.

    Args:
      rel_df: Relation triples.
      wanted_eid: Entity id of which the neighborhood is investigated.
      in_out_both: Whether to look at ("in","out","both") edges.

    Returns:
      Set of neighboring ids.

    Raises:
        ValueError: if unknown in_out_both value.

    Examples:
        >>> import pandas as pd
        >>> rel = pd.DataFrame([("e1","rel1","e2"), ("e3", "rel2", "e1")], columns=["head","relation","tail"])
        >>> from embarrassment import neighbor_set
        >>> neighbor_set(rel, "e1") # doctest: +SKIP
        {'e2', 'e3'}
    """
    head_set, tail_set = _neighbor_set_head_tail(
        rel_df=rel_df, wanted_eid=wanted_eid, in_out_both=in_out_both
    )
    return head_set.union(tail_set)

search(attr_df, query, method='exact')

Search for triples with values in attribute triples.

Parameters:

Name Type Description Default
attr_df DataFrame

Attribute triples.

required
query str

Query string.

required
method SearchMethod

Search method ("exact", "substring", "close").

'exact'

Returns:

Type Description
DataFrame

Triples where tail matches query.

Raises:

Type Description
ValueError

if unknown search method.

Examples:

>>> import pandas as pd
>>> attr = pd.DataFrame([("e1","attr1","lorem ipsum"), ("e2","attr2","dolor")], columns=["head","relation","tail"])
>>> from embarrassment import search
>>> search(attr, "lorem ipsum")
  head relation         tail
0   e1    attr1  lorem ipsum
>>> search(attr, "lorem", method="substring")
  head relation         tail
0   e1    attr1  lorem ipsum
Source code in embarrassment/api.py
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
@check_triple
def search(
    attr_df: pd.DataFrame, query: str, method: SearchMethod = "exact"
) -> pd.DataFrame:
    """Search for triples with values in attribute triples.

    Args:
      attr_df: Attribute triples.
      query: Query string.
      method: Search method ("exact", "substring", "close").

    Returns:
      Triples where tail matches query.

    Raises:
        ValueError: if unknown search method.

    Examples:
        >>> import pandas as pd
        >>> attr = pd.DataFrame([("e1","attr1","lorem ipsum"), ("e2","attr2","dolor")], columns=["head","relation","tail"])
        >>> from embarrassment import search
        >>> search(attr, "lorem ipsum")
          head relation         tail
        0   e1    attr1  lorem ipsum
        >>> search(attr, "lorem", method="substring")
          head relation         tail
        0   e1    attr1  lorem ipsum
    """
    val_col = attr_df.columns[2]
    if method == "exact":
        return _select_single(attr_df, query=query, hrt=val_col)
    if method == "close":
        return attr_df[
            attr_df[val_col].apply(
                lambda x, query: any(difflib.get_close_matches(x, [query])), query=query
            )
        ]
    if method == "substring":
        return attr_df[attr_df[val_col].str.contains(query)]
    raise ValueError(
        f"Unknown search method {method}, choose from {get_args(SearchMethod)}"
    )

select(trdf, query, hrt='head')

Select triples containing the queried id(s) in specified column.

Parameters:

Name Type Description Default
trdf DataFrame

Triple DataFrame.

required
query Union[Sequence[str], str]

Query id(s).

required
hrt str

head, relation or tail column name.

'head'

Returns:

Type Description
DataFrame

Triples containing the queried id(s) in specified column.

Examples:

>>> import pandas as pd
>>> rel = pd.DataFrame([("e1","rel1","e2"), ("e3", "rel2", "e1")], columns=["head","relation","tail"])
>>> from embarrassment import select
>>> select(rel, "e1")
  head relation tail
0   e1     rel1   e2
>>> select(rel, ["e1","e3"])
  head relation tail
0   e1     rel1   e2
1   e3     rel2   e1
>>> select(rel, ["e1","e3"], hrt="tail")
  head relation tail
1   e3     rel2   e1
Source code in embarrassment/api.py
 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
@check_triple
def select(
    trdf: pd.DataFrame, query: Union[Sequence[str], str], hrt: str = "head"
) -> pd.DataFrame:
    """Select triples containing the queried id(s) in specified column.

    Args:
      trdf: Triple DataFrame.
      query: Query id(s).
      hrt: head, relation or tail column name.

    Returns:
      Triples containing the queried id(s) in specified column.

    Examples:
        >>> import pandas as pd
        >>> rel = pd.DataFrame([("e1","rel1","e2"), ("e3", "rel2", "e1")], columns=["head","relation","tail"])
        >>> from embarrassment import select
        >>> select(rel, "e1")
          head relation tail
        0   e1     rel1   e2
        >>> select(rel, ["e1","e3"])
          head relation tail
        0   e1     rel1   e2
        1   e3     rel2   e1
        >>> select(rel, ["e1","e3"], hrt="tail")
          head relation tail
        1   e3     rel2   e1
    """
    if len(query) == 1:
        query = query[0]
    if isinstance(query, str):
        return _select_single(trdf=trdf, query=query, hrt=hrt)
    return trdf[trdf[hrt].isin(query)]

select_by_type(rel_df, wanted_type, type_rel='http://www.w3.org/1999/02/22-rdf-syntax-ns#type')

Select triples by type.

Parameters:

Name Type Description Default
rel_df DataFrame

Triple DataFrame.

required
wanted_type str

Wanted type.

required
type_rel str

Type relation.

'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'

Returns:

Type Description
DataFrame

Triples with specified type.

Examples:

>>> import pandas as pd
>>> rel = pd.DataFrame([("e1","http://www.w3.org/1999/02/22-rdf-syntax-ns#type","type2"), ("e3", "http://www.w3.org/1999/02/22-rdf-syntax-ns#type", "type1")], columns=["head","relation","tail"])
>>> from embarrassment import select_by_type
>>> select_by_type(rel, "type1")
  head                                         relation   tail
1   e3  http://www.w3.org/1999/02/22-rdf-syntax-ns#type  type1
Source code in embarrassment/api.py
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
@check_triple
def select_by_type(
    rel_df: pd.DataFrame,
    wanted_type: str,
    type_rel: str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type",
) -> pd.DataFrame:
    """Select triples by type.

    Args:
      rel_df: Triple DataFrame.
      wanted_type: Wanted type.
      type_rel: Type relation.

    Returns:
      Triples with specified type.

    Examples:
        >>> import pandas as pd
        >>> rel = pd.DataFrame([("e1","http://www.w3.org/1999/02/22-rdf-syntax-ns#type","type2"), ("e3", "http://www.w3.org/1999/02/22-rdf-syntax-ns#type", "type1")], columns=["head","relation","tail"])
        >>> from embarrassment import select_by_type
        >>> select_by_type(rel, "type1")
          head                                         relation   tail
        1   e3  http://www.w3.org/1999/02/22-rdf-syntax-ns#type  type1
    """
    rel_col = rel_df.columns[1]
    tail_col = rel_df.columns[2]
    query_exp = f'{rel_col} == "{type_rel}" and {tail_col} == "{wanted_type}"'
    return rel_df.query(query_exp)

select_rel(trdf, rel)

Select triples with specific relation.

Parameters:

Name Type Description Default
trdf DataFrame

Triple DataFrame.

required
rel str

Wanted relation.

required

Returns:

Type Description
DataFrame

Triple DataFrame with specific relation.

Examples:

>>> import pandas as pd
>>> rel = pd.DataFrame([("e1","rel1","e2"), ("e3", "rel2", "e1")], columns=["head","relation","tail"])
>>> from embarrassment import select_rel
>>> select_rel(rel, "rel1")
  head relation tail
0   e1     rel1   e2
Source code in embarrassment/api.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
@check_triple
def select_rel(trdf: pd.DataFrame, rel: str) -> pd.DataFrame:
    """Select triples with specific relation.

    Args:
      trdf: Triple DataFrame.
      rel: Wanted relation.

    Returns:
      Triple DataFrame with specific relation.

    Examples:
        >>> import pandas as pd
        >>> rel = pd.DataFrame([("e1","rel1","e2"), ("e3", "rel2", "e1")], columns=["head","relation","tail"])
        >>> from embarrassment import select_rel
        >>> select_rel(rel, "rel1")
          head relation tail
        0   e1     rel1   e2
    """
    rel_col = trdf.columns[1]
    return _select_single(trdf, query=rel, hrt=rel_col)