Skip to content

Commit

Permalink
introduce Attribute class
Browse files Browse the repository at this point in the history
  • Loading branch information
matthiasprobst committed Apr 19, 2024
1 parent 40b8103 commit 403e507
Show file tree
Hide file tree
Showing 8 changed files with 260 additions and 76 deletions.
7 changes: 4 additions & 3 deletions h5rdmtoolbox/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
"""h5rdtoolbox repository"""

import appdirs
import logging
import pathlib
from logging.handlers import RotatingFileHandler

import appdirs

_logdir = pathlib.Path(appdirs.user_log_dir('h5rdmtoolbox'))
_logdir.mkdir(parents=True, exist_ok=True)

Expand Down Expand Up @@ -38,14 +39,14 @@

from . import convention
from .convention.core import Convention
from .convention.rdf import RDFAttribute
from . import wrapper
from ._user import UserDir
from ._version import __version__
from . import utils
from .wrapper.core import lower, Lower, File, Group, Dataset
from . import warnings, errors
from .wrapper import jsonld
from .wrapper.h5attr import Attribute
from .wrapper.accessory import register_special_dataset
import json

Expand Down Expand Up @@ -232,7 +233,7 @@ def clean_temp_data(full: bool = False):

__all__ = ('__version__', '__author__', '__author_orcid__',
'UserDir', 'use',
'File', 'Group', 'Dataset', 'RDFAttribute',
'File', 'Group', 'Dataset', 'Attribute',
'dump', 'dumps', 'cv_h5py', 'lower', 'Lower',
'set_config', 'get_config', 'get_ureg',
'Convention', 'jsonld')
35 changes: 24 additions & 11 deletions h5rdmtoolbox/_repr.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import h5py
import importlib_resources
import numpy as np
import os
import re
import typing
import warnings
import xarray as xr
from IPython.display import HTML, display
from abc import abstractmethod
from numpy import ndarray
from time import perf_counter_ns

import h5py
import importlib_resources
import numpy as np
import xarray as xr
from IPython.display import HTML, display
from numpy import ndarray
from ontolutils import M4I, Thing

from . import get_config, identifiers, protected_attributes
from .convention.rdf import RDF_SUBJECT_ATTR_NAME, RDF_PREDICATE_ATTR_NAME, RDF_OBJECT_ATTR_NAME

Expand All @@ -28,6 +29,7 @@
# if IRI_ICON.exists():
# IRI_ICON = rf'file:///{IRI_ICON}'
# else:
DEF_ICON = "https://github.com/matthiasprobst/h5RDMtoolbox/blob/dev-FAIRattrs/h5rdmtoolbox/data/def_icon.png?raw=true"
IRI_ICON = "https://github.com/matthiasprobst/h5RDMtoolbox/blob/dev/h5rdmtoolbox/data/iri_icon.png?raw=true"
hasUnitIRI = str(M4I.hasUnit)
"""
Expand Down Expand Up @@ -165,6 +167,12 @@ def get_iri_icon_href(iri: typing.Union[str, typing.Dict], tooltiptext=None) ->
f'<img class="size_of_img" src="{IRI_ICON}" alt="IRI_ICON" width="16" height="16" />' \
f' <span class="tooltiptext">{tooltiptext or iri}</span></a>'

def get_def_icon_href(def_text: str) -> str:
"""get html representation of an attribute definition with icon"""
return f'<div class="tooltip">' \
f'<img class="size_of_img" src="{DEF_ICON}" alt="D" width="16" height="16" />' \
f'<span class="tooltiptext">{def_text}</span></div>'


class _HDF5StructureRepr:

Expand Down Expand Up @@ -283,19 +291,20 @@ def __attrs__(self, name, h5obj) -> str:
use_attr_name = name
else:
pred = h5obj.rdf[name].get(RDF_PREDICATE_ATTR_NAME, None)
if pred:
attrsdef = h5obj.attrsdef.get(name, None)
if pred and attrsdef:
use_attr_name = f'{name} (p={pred}, def={attrsdef})'
elif pred:
use_attr_name = f'{name} (p={pred})'
elif attrsdef:
use_attr_name = f'{name} (def={attrsdef})'
else:
use_attr_name = name

obj_iri = h5obj.rdf[name].get(RDF_OBJECT_ATTR_NAME, None)
if obj_iri:
attr_value = f'{attr_value} (o={obj_iri})'

attrsdef = h5obj.attrsdef.get(name, None)
if attrsdef:
attr_value = f'{attr_value} (def={attrsdef})'

# if isinstance(attr_value, h5py.Group):
# attr_value = f'grp:{attr_value.name}'
# elif isinstance(attr_value, h5py.Dataset):
Expand Down Expand Up @@ -547,6 +556,10 @@ def __attrs__(self, name, h5obj):
if rdf_predicate is not None:
name += get_iri_icon_href(rdf_predicate)

attrs_def = h5obj.attrsdef.get(name, None)
if attrs_def is not None:
name += get_def_icon_href(attrs_def)

rdf_object = rdf.object

if isinstance(attr_value, ndarray):
Expand Down
7 changes: 3 additions & 4 deletions h5rdmtoolbox/convention/definition.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,9 @@ def __getitem__(self, item) -> Optional[str]:
return self.get(item)

def __setitem__(self, key, value):
if DEFINITION_ATTR_NAME not in self._attr:
attrdef = self._attr.get(DEFINITION_ATTR_NAME, {})
attrdef.update({key: value})
self._attr[DEFINITION_ATTR_NAME] = attrdef
attr_def = self._attr.get(DEFINITION_ATTR_NAME, {})
attr_def.update({key: value})
self._attr[DEFINITION_ATTR_NAME] = attr_def

def get(self, item, default=None) -> Optional[str]:
if DEFINITION_ATTR_NAME not in self._attr:
Expand Down
86 changes: 43 additions & 43 deletions h5rdmtoolbox/convention/rdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,49 +18,49 @@ class RDFError(Exception):
pass


class RDFAttribute:
"""Helper class for quick assignment of RDF attributes to the HDF5 file.
Examples
--------
>>> import h5rdmtoolbox as h5tbx
>>> from ontolutils import M4I
>>> rdf_attr = h5tbx.RDFAttribute('0000-0001-8729-0482', rdf_predicate=M4I.orcidId,
... rdf_object='https://orcid.org/0000-0001-8729-0482')
>>> with h5tbx.File('test.h5', 'w') as h5:
... grp = h5.create_group('person')
... grp.attrs['orcid'] = rdf_attr
... # equal to:
... # grp.attrs['orcid'] = '0000-0001-8729-0482'
... # grp.rdf.predicate['orcid'] = str(M4I.orcidId)
... # grp.rdf.object['orcid'] = 'https://orcid.org/0000-0001-8729-0482'
"""

def __init__(self, value, rdf_predicate: str = None, rdf_object: str = None):
self.value = value

if rdf_predicate:
try:
str(HttpUrl(rdf_predicate))
except pydantic.ValidationError as e:
raise RDFError(f'Invalid predicate IRI: "{rdf_predicate}". '
f'Expecting a valid URL. This was validated with pydantic. Pydantic error: {e}')

if rdf_object:
try:
str(HttpUrl(rdf_object))
except pydantic.ValidationError as e:
raise RDFError(f'Invalid object IRI: "{rdf_object}". '
f'Expecting a valid URL. This was validated with pydantic. Pydantic error: {e}')

self.rdf_predicate = rdf_predicate
self.rdf_object = rdf_object

def __repr__(self) -> str:
return f'{self.__class__.__name__}({self.value}, rdf_predicate={self.rdf_predicate}, rdf_object={self.rdf_object})'

def __str__(self) -> str:
return self.__repr__()
# class RDFAttribute:
# """Helper class for quick assignment of RDF attributes to the HDF5 file.
#
# Examples
# --------
# >>> import h5rdmtoolbox as h5tbx
# >>> from ontolutils import M4I
# >>> rdf_attr = h5tbx.RDFAttribute('0000-0001-8729-0482', rdf_predicate=M4I.orcidId,
# ... rdf_object='https://orcid.org/0000-0001-8729-0482')
# >>> with h5tbx.File('test.h5', 'w') as h5:
# ... grp = h5.create_group('person')
# ... grp.attrs['orcid'] = rdf_attr
# ... # equal to:
# ... # grp.attrs['orcid'] = '0000-0001-8729-0482'
# ... # grp.rdf.predicate['orcid'] = str(M4I.orcidId)
# ... # grp.rdf.object['orcid'] = 'https://orcid.org/0000-0001-8729-0482'
# """
#
# def __init__(self, value, rdf_predicate: str = None, rdf_object: str = None):
# self.value = value
#
# if rdf_predicate:
# try:
# str(HttpUrl(rdf_predicate))
# except pydantic.ValidationError as e:
# raise RDFError(f'Invalid predicate IRI: "{rdf_predicate}". '
# f'Expecting a valid URL. This was validated with pydantic. Pydantic error: {e}')
#
# if rdf_object:
# try:
# str(HttpUrl(rdf_object))
# except pydantic.ValidationError as e:
# raise RDFError(f'Invalid object IRI: "{rdf_object}". '
# f'Expecting a valid URL. This was validated with pydantic. Pydantic error: {e}')
#
# self.rdf_predicate = rdf_predicate
# self.rdf_object = rdf_object
#
# def __repr__(self) -> str:
# return f'{self.__class__.__name__}({self.value}, rdf_predicate={self.rdf_predicate}, rdf_object={self.rdf_object})'
#
# def __str__(self) -> str:
# return self.__repr__()


def set_predicate(attr: h5py.AttributeManager, attr_name: str, value: str) -> None:
Expand Down
Binary file added h5rdmtoolbox/data/def_icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
83 changes: 83 additions & 0 deletions h5rdmtoolbox/data/def_icon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading

0 comments on commit 403e507

Please sign in to comment.