pyirk.core
Core module of pyirk
Module Contents
Classes
Abstract parent class for both Relations and Items. |
|
Provides objects to store all data that would be global otherwise |
|
Entity types. |
|
Statement types. |
|
Dict value types. |
|
Container for processed statement key |
|
This class processes all keyword args for entity creation |
|
This class processes a single keyword arg for entity creation |
|
Statement types. |
|
Class for a flexible and comprehensible key management. Every pyirk module must have its own (passed via) |
|
Precursor to a real Qualifier (which is a Statement) where the subject is yet unspecified (will be the qualified Statement). Instances of this class are produced by QualifierFactory |
|
Convenience class to create an RawQualifier. This allows syntax like: |
|
Models a concrete (instantiated/applied) relation between entities. This is basically a dict. |
|
Container class for context definitions |
|
Context manager for creating entities with a given uri |
|
uri Context manager for searching for entities with a given key |
|
Functions
Use the pydantic package to check for (complex) types from the typing module.
If type checking passes returns |
|
unpack a dict of length 1 :param l1d: :return: |
|
In IRK there are the following kinds of keys:
- a) short_key like |
|
get uri from prefix or from passed argument or from active module |
|
Check if the used label of a key_str matches the actual label (R1) of that entity |
|
convert index labeled key (R1234[“my relation”]) to name labeled key (R1234__my_relation) |
|
Convenience function converting “[prefix__]I1234__my_label” to “[moduri#]I1234”.
If no prefix is given the active module and |
|
:return: return new_kwargs, lang_related_kwargs |
|
This function processes language related keyword args for relations which have R32__is_functional_for_each_language=True |
|
:param key_str: “” or unique key of this item (something like |
|
Run (previously registered) hooks after the creation of entities. This can be used for sanity checking etc. |
|
Create a short key (int or str) (optionally with prefixes) from the reservoir. |
|
call sequence.remove(element) but tolerate KeyError and ValueError :param sequence: :param element: :return: |
|
:param key_str: “” or unique key of this relation (something like |
|
Utility function for the command line. |
|
print n random integer keys from the pregenerated list. |
|
Retrieve the name of an entity from a code line like
|
|
:param upcount: int; how many frames to go up :return: |
|
:param upcount: int; how many frames to go up at beginning upcount=2 (default) means: start int the caller frame. Example: fnc1()->fnc2()->fnc3() where fnc3 is this function, called by fnc2, which itself is called by fnc1 (the caller) :return: list of mod_id-objects (type str) |
|
Delete all references to entities coming from a module with |
|
Remove the occurrence of this the respective entity from all relevant data structures |
|
Replace all statements where |
|
Register the uri for the _uri_stack. |
|
check if item is subproperty of parent_property. item == parent_p will return True as well. |
Data
API
- pyirk.core.allowed_literal_types
()
- pyirk.core.RELKEYS_WITH_LITERAL_RANGE
(‘R1’, ‘R2’, ‘R77’)
- pyirk.core.check_type(obj, expected_type, strict=True)
Use the pydantic package to check for (complex) types from the typing module. If type checking passes returns
True. This allows to useassert check_type(...)which allows to omit those type checks (together with other assertions) for performance reasons, e.g. withpython -O .... :param obj: the object to check :param expected_type: primitive or complex type (like typing.List[dict]) :return: True (or raise an TypeError)
- class pyirk.core.Entity(base_uri)
Bases:
abc.ABCAbstract parent class for both Relations and Items.
Do not forget to call self.post_init at the end of init in subclasses.
Initialization
- short_key: str
None
- __call__(*args, **kwargs)
- idoc(adhoc_label: str)
idoc means “inline doc”. This function allows to attach a label to entities when using them in code because it returns just the Entity-object itself. Thus one can use the following expressions interchangeably:
I1234andI1234.idoc("human readable item name")Note that there is a shortcut to this function: `I1234[“human readable item name”]
:return: self
- __getitem__(adhoc_label)
This magic method overloads the […]-operator. See docs for
idocfor more information.:param adhoc_label: :return: self
- __getattr__(attr_name)
- __setattr__(attr_name: str, attr_value: Any)
- __process_attribute_name(attr_name: str, exception_type=AttributeError) pyirk.core.ProcessedStmtKey
- __eq__(other)
- __post_init__()
- _perform_inheritance()
Transfer method prototypes from parent to child classes
:return:
- _perform_instantiation()
Convert all method prototypes from class-item into methods of instance-item :return:
- _get_relation_contents(rel_uri: str, lang_indicator=None)
- classmethod add_method_to_class(func)
Used to add methods to the class from the builtin_entities module. This mechanism (adding the method later) allows to keep the dependency monodirectional
- add_method(func: callable, name: Optional[str] = None)
Add a method to this instance (self). If there are R4 relations pointing from child items to self, this method is also inherited to those child items.
:param func: :param name: the name under which the callable object should be accessed :return:
- _set_relations_from_init_kwargs(**kwargs)
This method is called explicitly from the init-method of subclasses after preprocessing the kwargs
:param kwargs: :return:
- set_multiple_relations(relation: Union[pyirk.core.Relation, str], obj_seq: Union[tuple, list], *args, **kwargs) List[pyirk.core.Statement]
Convenience function to create multiple Statements at once
- set_relation(relation: Union[pyirk.core.Relation, str], obj, scope: pyirk.core.Entity = None, proxyitem: Optional[pyirk.core.Item] = None, qualifiers: Optional[List[pyirk.core.RawQualifier]] = None, prevent_duplicate=False) Optional[pyirk.core.Statement]
Allows to add a relation after the item was created.
:param relation: Relation-Entity (or its short_key) :param obj: target (object) of the relation (where self is the subject) :param scope: Entity for the scope in which the relation is defined :param proxyitem: optional item to which the Statement is associated (e.g. an equation-instance) :param qualifiers: optional list of RawQualifiers (see docstring of this class) :param prevent_duplicate bool; prevent the creation of a statement which already exists. :return:
- _set_relation(rel_uri: str, rel_content: object, scope: Optional[pyirk.core.Entity] = None, qualifiers: Optional[list] = None, proxyitem: Optional[pyirk.core.Item] = None) pyirk.core.Statement
- get_relations(key_str_or_uri: Optional[str] = None, return_subj: bool = False, return_obj: bool = False) Union[Dict[str, list], list]
Return all Statement instance where this item is subject
:param key_str_or_uri: optional; either a verbose key_str (of a builtin entity) or a full uri; if passed only return the result for this key :param return_subj: default False; if True only return the subject(s) of the relation edges, not the whole statement
:return: either the whole dict or just one value (of type list)
- get_inv_relations(key_str_or_uri: Optional[str] = None, return_subj: bool = False, return_obj: bool = False) Union[Dict[str, list], list]
Return all Statement instance where this item is object
:param key_str_or_uri: optional; either a verbose key_str (of a builtin entity) or a full uri; if passed only return the result for this key :param return_subj: default False; if True only return the subject(s) of the relation edge(s), not the whole statement :param return_obj: default False; if True only return the object(s) of the relation edge(s), not the whole statement
:return: either the whole dict or just one value (of type list)
- static _return_relations(base_dict, key_str_or_uri: str, return_subj: bool = False, return_obj: bool = False) Union[Dict[str, list], list]
:param base_dict: either ds.statements or ds.inv_statements :param key_str_or_uri: optional; either a verbose key_str (of a builtin entity) or a full uri; if passed only return the result for this key :param return_subj: default False; if True only return the subject(s) of the relation edge(s), not the whole statement :param return_obj: default False; if True only return the object(s) of the relation edge(s), not the whole statement :return:
- overwrite_statement(rel_key_str_or_uri: str, new_obj: pyirk.core.Entity, qualifiers=None) pyirk.core.Statement
- finalize()
Method which is intended to be explicitly called if an (automatically created) entity is finished.
Background: some entities like evaluated mappings are manipulated after creation. Hooks like consistency-checking have to be executed afterwards.
- __hash__()
Defining a hash method allows to use Entities as keys in dicts, or create sets of them.
- update_relations(**kwargs)
- pyirk.core.wrap_function_with_search_uri_context(func, uri=None)
- pyirk.core.pf
‘PrefixShortCut(…)’
- class pyirk.core.DataStore
Provides objects to store all data that would be global otherwise
Initialization
- initialize_hooks() dict
- get_item_by_label(label) pyirk.core.Entity
Search over all item and return the first item which has the provided label. Useful during interactive debugging. Not useful for production!
- get_entity_by_key_str(key_str, mod_uri=None) pyirk.core.Entity
:param key_str: str like I1234 or I1234__some_label :param mod_uri: optional uri of the module; if None the active module is assumed
:return: corresponding entity
- get_entity_by_uri(uri: str, etype=None, strict=True) Union[pyirk.core.Entity, None]
- static _default_subject_filter(entity)
used to prevent items from scopes showing up inside the results of
get_subjects_for_relation.
- get_subjects_for_relation(rel_uri: str, filter=None)
- get_statements(entity_uri: str, rel_uri: str) List[pyirk.core.Statement]
self.statements maps an entity_key to an inner_dict. The inner_dict maps an relation_key to a Statement or List[Statement].
:param entity_uri: :param rel_uri: :return:
- set_statement(stm: pyirk.core.Statement) None
Insert a Statement into the relevant data structures of the DataStorage (self)
This method does not handle the dual relation. It must be created and stored separately.
:param stm: Statement instance :return:
- get_uri_for_prefix(prefix: str) str
- preprocess_query(query)
- append_scope(scope)
Called when enter-ing a scoping context manager
- remove_scope(scope)
Called when exit-ing a scoping context manager
- get_current_scope()
- pyirk.core.ds
‘DataStore(…)’
- pyirk.core.YAML_VALUE
None
- class pyirk.core.EType(*args, **kwds)
Bases:
enum.EnumEntity types.
Initialization
- ITEM
0
- RELATION
1
- LITERAL
2
- class pyirk.core.SType(*args, **kwds)
Bases:
enum.EnumStatement types.
Initialization
- CREATION
0
- EXTENSION
1
- UNDEFINED
2
- class pyirk.core.VType(*args, **kwds)
Bases:
enum.EnumDict value types.
Initialization
- LITERAL
0
- ENTITY
1
- LIST
2
- DICT
3
- class pyirk.core.ProcessedStmtKey
Container for processed statement key
- short_key: str
None
- etype: pyirk.core.EType
None
- stype: pyirk.core.SType
None
- vtype: pyirk.core.VType
None
- content: object
None
- delimiter: str
None
- label: str
None
- prefix: str
None
- uri: str
None
- lang_indicator: str
None
- original_key_str: str
None
- pyirk.core.unpack_l1d(l1d: Dict[str, object])
unpack a dict of length 1 :param l1d: :return:
- pyirk.core.re_prefix_shortkey_suffix
‘compile(…)’
- pyirk.core.re_suffix_underscore
‘compile(…)’
- pyirk.core.re_suffix_square_brackets
‘compile(…)’
- pyirk.core.process_key_str(key_str: str, check: bool = True, resolve_prefix: bool = True, mod_uri: str = None) pyirk.core.ProcessedStmtKey
In IRK there are the following kinds of keys: - a) short_key like
R1234- b) name-labeled key likeR1234__my_relation(consisting of a short_key, a delimiter (__) and a label) - c) prefixed short_key likebi__R1234- d) prefixed name-labeled key likebi__R1234__my_relation- e) index-labeled key like `R1234["my relation"]` - f) prefixed index-labeled key like `bi__R1234["my relation"]`
See also: userdoc/overview.html#keys-in-pyirk
Also, the leading character indicates the entity type (EType).
This function expects any of these cases. :param key_str: a string like “R1234__my_relation” or “R1234” or “bi__R1234__my_relation” :param check: boolean flag; determines if the label part should be checked wrt its consistency to :param resolve_prefix: boolean flag; determines if :param mod_uri: optional uri of the module
:return: a data structure which allows to access short_key, type and label separately
- pyirk.core._resolve_prefix(pr_key: pyirk.core.ProcessedStmtKey, passed_mod_uri: str = None) None
get uri from prefix or from passed argument or from active module
- pyirk.core.langcode_end_pattern
‘compile(…)’
- pyirk.core.check_processed_key_label(pkey: pyirk.core.ProcessedStmtKey) None
Check if the used label of a key_str matches the actual label (R1) of that entity
:param pkey: :return:
- pyirk.core.ilk2nlk(ilk: str) str
convert index labeled key (R1234[“my relation”]) to name labeled key (R1234__my_relation)
- pyirk.core.u(key_str: str) str
Convenience function converting “[prefix__]I1234__my_label” to “[moduri#]I1234”. If no prefix is given the active module and
builtin_entitiesare searched for (in this order).:param key_str: :return:
- class pyirk.core.Item(base_uri: str, key_str: str, **kwargs)
Bases:
pyirk.core.Entity- __repr__()
- pyirk.core.get_active_mod_uri(strict: bool = True) Union[str, None]
- pyirk.core.process_kwargs_for_entity_creation(entity_key: str, kwargs: dict) tuple[dict, dict]
:return: return new_kwargs, lang_related_kwargs
- class pyirk.core.KWArgManager(entity_key: str, kwargs: dict)
This class processes all keyword args for entity creation
Initialization
- process()
- class pyirk.core.SingleKWArgProcessor(kwam: pyirk.core.KWArgManager, kwarg_name: str, kwarg_value: str)
This class processes a single keyword arg for entity creation
Initialization
- handle_kwarg_stage1()
Determine new_key
- handle_kwarg_stage2()
- dispatch_value_multiplicity_for_rk_with_lr()
Situation for relkeys with literal range: self.kwarg_value might be a ‘scalar’ value or list of ‘scalar’ values. This method handles the difference and then calls the actual processing
- handle_rk_with_lr(scalar_kwarg_value)
‘rk’ means relkeys ‘lr’ means literal range
Background: Relation keys like R1, R2 and R77 are used in triples where the object is a Literal. R1__has_label, R2__has_description are functional (R32__is_functional_for_each_language). R77__has_alternative_label is not functional (neither R22__is_functional nor R32).
This function handles the different cases
- _handle_kwarg_for_functional_rel(scalar_kwarg_value)
- _check_for_valid_language(scalar_kwarg_value, first_value=False)
- _handle_value(kwarg_value, lang_related_value_list=None) rdflib.Literal
This function processes language related keyword args for relations which have R32__is_functional_for_each_language=True
- pyirk.core.create_item(key_str: str = '', **kwargs) pyirk.core.Item
:param key_str: “” or unique key of this item (something like
I1234) :param kwargs: further relations:return: newly created item
- class pyirk.core.Relation(base_uri: str, short_key: str, **kwargs)
Bases:
pyirk.core.Entity- __repr__()
- class pyirk.core.RelationRole(*args, **kwds)
Bases:
enum.EnumStatement types.
Initialization
- SUBJECT
0
- PREDICATE
1
- OBJECT
2
- pyirk.core.VALID_HOOK_PHASES
[‘post-create’, ‘post-finalize’]
- pyirk.core.VALID_HOOK_TYPES
[‘post-create-entity’, ‘post-create-item’, ‘post-create-relation’, ‘post-finalize-entity’, ‘post-fin…
- pyirk.core.run_hooks(entity: pyirk.core.Entity, phase: str) None
Run (previously registered) hooks after the creation of entities. This can be used for sanity checking etc.
- pyirk.core.register_hook(type_str: str, func: callable) None
- class pyirk.core.KeyManager(minval=1000, maxval=99999, keyseed=None)
Class for a flexible and comprehensible key management. Every pyirk module must have its own (passed via)
Initialization
:param minval: int :param maxval: int :param keyseed: int; This allows a module to create its own random key order
- pop(index: int = -1) int
- _generate_key_numbers() None
Creates a reservoir of keynumbers, e.g. for automatically created entities. Due to the hardcoded seed value these numbers are stable between runs of the software, which simplifies development and debugging.
This function is also called after unloading a module because the respective keys are “free” again
Rationale behind random keys: During creation of knowledge bases it frees the mind of thinking too much about a meaningful order in which to create entities.
:return: list of integers
- pyirk.core.pop_uri_based_key(prefix: Optional[str] = None, prefix2: str = '') Union[int, str]
Create a short key (int or str) (optionally with prefixes) from the reservoir.
:param prefix: :param prefix2: :return:
- pyirk.core.repl_spc_by_udsc(txt: str) str
- class pyirk.core.RawQualifier(rel: pyirk.core.Relation, obj: Union[rdflib.Literal, pyirk.core.Entity])
Precursor to a real Qualifier (which is a Statement) where the subject is yet unspecified (will be the qualified Statement). Instances of this class are produced by QualifierFactory
Initialization
- __repr__()
- class pyirk.core.QualifierFactory(relation: pyirk.core.Relation, registry_name: Optional[str] = None)
Convenience class to create an RawQualifier. This allows syntax like:
start_date = QualifierFactory(R1234["start date"]) # ... I2746["Rudolf Kalman"].set_relation(R1833["has employer"], I7301["ETH Zürich"], qualifiers=[start_date(1973)])
Initialization
:param relation: :param registry_name: optional str; if not None this is the key under which this QF is stored in ds.qff_dict.
- __call__(obj)
- class pyirk.core.Statement(relation: pyirk.core.Relation = None, relation_tuple: tuple = None, role: pyirk.core.RelationRole = None, corresponding_entity: pyirk.core.Entity = None, corresponding_literal=None, scope=None, qualifiers: Optional[Union[List[pyirk.core.RawQualifier], List[pyirk.core.QualifierStatement]]] = None, proxyitem: Optional[pyirk.core.Item] = None)
Models a concrete (instantiated/applied) relation between entities. This is basically a dict.
Initialization
:param relation: :param relation_tuple: :param role: RelationRole.SUBJECT for normal and RelationRole.OBJECT for inverse statements :param corresponding_entity: This is the entity on the “other side” of the relation (depending of
role) or None in case that other side is a literal :param corresponding_literal: This is the literal on the “other side” of the relation (depending ofrole) or :param scope: None in case that other side is an Entity :param qualifiers: list of relation edges, that describeselfmore precisely (cf. wikidata qualifiers) :param proxyitem: associated item; e.g. a equation-item- property key_str
- __repr__()
- _process_qualifiers(qlist: Union[List[pyirk.core.RawQualifier], List[pyirk.core.QualifierStatement]], scope: Optional[pyirk.core.Entity] = None) None
- is_qualifier()
- get_first_qualifier_obj_with_rel(key=None, uri=None, tolerate_key_error=False)
- unlink(*args) None
Remove this Statement instance from all data structures in the global data storage :return:
- class pyirk.core.QualifierStatement(*args, **kwargs)
Bases:
pyirk.core.Statement
- pyirk.core.tolerant_removal(sequence, element)
call sequence.remove(element) but tolerate KeyError and ValueError :param sequence: :param element: :return:
- pyirk.core.create_relation(key_str: str = '', **kwargs) pyirk.core.Relation
:param key_str: “” or unique key of this relation (something like
R1234); if empty key will be retrieved via inspection of the caller code:param kwargs: further relations (e.g. R1__has_label etc.)
:return: newly created relation
- pyirk.core.create_builtin_item(*args, **kwargs) pyirk.core.Item
- pyirk.core.create_builtin_relation(*args, **kwargs) pyirk.core.Relation
- pyirk.core.generate_new_key(prefix, prefix2='', mod_uri=None)
Utility function for the command line.
:param prefix: :param prefix2: :param mod_uri: :return:
- pyirk.core.print_new_keys(n=30, loaded_mod=None)
print n random integer keys from the pregenerated list.
:return:
- pyirk.core.get_caller_frame(upcount: int) types.FrameType
- pyirk.core.get_key_str_by_inspection(upcount=1) str
Retrieve the name of an entity from a code line like
cm.new_var(M=p.instance_of(I9904["matrix"])):param upcount: int; how many frames to go up :return:
- pyirk.core.get_mod_name_by_inspection(upcount=1)
:param upcount: int; how many frames to go up :return:
- pyirk.core.get_mod_id_list_by_inspection(upcount=2) list
:param upcount: int; how many frames to go up at beginning upcount=2 (default) means: start int the caller frame. Example: fnc1()->fnc2()->fnc3() where fnc3 is this function, called by fnc2, which itself is called by fnc1 (the caller) :return: list of mod_id-objects (type str)
- class pyirk.core.Context(*args, **kwargs)
Container class for context definitions
Initialization
- pyirk.core._uri_stack
[]
- pyirk.core._search_uri_stack
[]
- class pyirk.core.abstract_uri_context(uri_stack: list, uri: str, prefix: str = None)
Initialization
- __enter__()
implicitly called in the head of the with statement :return:
- __exit__(exc_type, exc_val, exc_tb)
- class pyirk.core.uri_context(uri: str, prefix: str = None)
Bases:
pyirk.core.abstract_uri_contextContext manager for creating entities with a given uri
Initialization
- class pyirk.core.search_uri_context(uri: str, prefix: str = None)
Bases:
pyirk.core.abstract_uri_contexturi Context manager for searching for entities with a given key
Initialization
- pyirk.core.unload_mod(mod_uri: str, strict=True) None
Delete all references to entities coming from a module with
mod_id:param mod_uri: str; uri of the module, see its URI attribute :param strict: boolean; raise Exception if module seems be not loaded
:return: list of released keys
- pyirk.core._unlink_entity(uri: str, remove_from_mod=False) None
Remove the occurrence of this the respective entity from all relevant data structures
:param uri: entity uri :return: None
- pyirk.core.replace_and_unlink_entity(old_entity: pyirk.core.Entity, new_entity: pyirk.core.Entity)
Replace all statements where
old_entityis subject or object with new relations wherenew_entityis sub or obj. For the “subject-case” only process those statements for whichnew_entitydoes not yet have any relations. Thus do not replace e.g. the R4__is_instance_of statement ofnew_entity.Then unlink
old_entity.
- pyirk.core.register_mod(uri: str, keymanager: pyirk.core.KeyManager = None, check_uri=True, prefix=None)
- pyirk.core.start_mod(uri)
Register the uri for the _uri_stack.
Note: between start_mod and end_mod no it is not allowed to load other irk modules
:param uri: :return:
- pyirk.core.end_mod()
- pyirk.core.get_language_of_str_literal(obj: Union[str, rdflib.Literal])
- class pyirk.core.LanguageCode(langtag)
Initialization
- __rmatmul__(arg: str) rdflib.Literal
This enables syntax like
"test string" @ en(whereenis a LanguageCode instance):param arg: the string for which the language ist to be specified
:return: Literal instance with
.langattribute set
- pyirk.core.df
‘LanguageCode(…)’
- pyirk.core.en
‘LanguageCode(…)’
- pyirk.core.de
‘LanguageCode(…)’
- pyirk.core.fr
‘LanguageCode(…)’
- pyirk.core.it
‘LanguageCode(…)’
- pyirk.core.es
‘LanguageCode(…)’
- class pyirk.core.RuleResult
Initialization
- add_statement(stm: pyirk.core.Statement)
- add_statements(stms: List[pyirk.core.Statement])
- add_entity(entity: pyirk.core.Entity)
- extend(part: pyirk.core.RuleResult)
- add_partial(part: pyirk.core.RuleResult)
- __repr__()
- property rule
Convenience property for easy access to the corresponding rule
- pyirk.core.is_true(subject: pyirk.core.Entity, predicate: pyirk.core.Relation, object) tuple[bool, None]
- pyirk.core.format_entity_html(e: pyirk.core.Entity)
- pyirk.core.format_literal_html(obj)
- pyirk.core.script_main(fpath)
- pyirk.core.is_subclass(item: pyirk.core.Item, parent_item: pyirk.core.Item)
- pyirk.core.is_instance(item: pyirk.core.Item, parent_item: pyirk.core.Item)
- pyirk.core.is_subproperty(item: pyirk.core.Item, parent_property: pyirk.core.Item)
check if item is subproperty of parent_property. item == parent_p will return True as well.