Skip to content
10 changes: 5 additions & 5 deletions sdk/basyx/aas/adapter/json/formats/value_only_serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ def _remove_children_of_elements(cls, data: dict[str, object]) -> dict[str, obje

@classmethod
def _submodel_to_value_only_no_children(cls, obj: model.Submodel) -> dict[str, object]:
data = cls._get_aas_class_serializers()[model.Submodel](obj)
data = cls._cached_mapping(cls._get_aas_class_serializers)[model.Submodel](obj)
# Direct child SubmodelElementCollections and SubmodelElementLists are always serialized with an empty value,
# even if they contain no elements with a value
for element in obj.submodel_element:
Expand All @@ -281,14 +281,14 @@ def _submodel_to_value_only_no_children(cls, obj: model.Submodel) -> dict[str, o

@classmethod
def _submodel_element_list_to_value_only_no_children(cls, obj: model.SubmodelElementList) -> list[object]:
data = cls._get_aas_class_serializers()[model.SubmodelElementList](obj)
data = cls._cached_mapping(cls._get_aas_class_serializers)[model.SubmodelElementList](obj)
return [cls._remove_children(element) for element in data]

@classmethod
def _submodel_element_collection_to_value_only_no_children(
cls, obj: model.SubmodelElementCollection
) -> dict[str, object]:
data = cls._get_aas_class_serializers()[model.SubmodelElementCollection](obj)
data = cls._cached_mapping(cls._get_aas_class_serializers)[model.SubmodelElementCollection](obj)
# Direct child SubmodelElementCollections and SubmodelElementLists are always serialized with an empty value,
# even if they contain no elements with a value
for element in obj.value:
Expand All @@ -300,7 +300,7 @@ def _submodel_element_collection_to_value_only_no_children(
def _annotated_relationship_element_to_value_only_no_children(
cls, obj: model.AnnotatedRelationshipElement
) -> dict[str, object]:
data = cls._get_aas_class_serializers()[model.AnnotatedRelationshipElement](obj)
data = cls._cached_mapping(cls._get_aas_class_serializers)[model.AnnotatedRelationshipElement](obj)
annotations = data.get("annotations")
if isinstance(annotations, dict):
# No checking for child SubmodelElementCollections and SubmodelElementLists necessary
Expand All @@ -309,7 +309,7 @@ def _annotated_relationship_element_to_value_only_no_children(

@classmethod
def _entity_to_value_only_no_children(cls, obj: model.Entity) -> dict[str, object]:
data = cls._get_aas_class_serializers()[model.Entity](obj)
data = cls._cached_mapping(cls._get_aas_class_serializers)[model.Entity](obj)
statements = data.get("statements")
if isinstance(statements, dict):
# Direct child SubmodelElementCollections and SubmodelElementLists are always serialized with an empty
Expand Down
51 changes: 32 additions & 19 deletions sdk/basyx/aas/adapter/json/json_deserialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def _get_ts(dct: Dict[str, object], key: str, type_: Type[T]) -> T:
return val


def _expect_type(object_: object, type_: Type, context: str, failsafe: bool) -> bool:
def _expect_type(object_: object, type_: Type, context: object, failsafe: bool) -> bool:
"""
Helper function to check type of an embedded object.

Expand All @@ -111,13 +111,14 @@ def _expect_type(object_: object, type_: Type, context: str, failsafe: bool) ->
and raise a TypeError if not. In failsafe mode, we want to log the error and prevent the object from being added
to the parent object. A typical use of this function would look like this:

if _expect_type(element, model.SubmodelElement, str(submodel), failsafe):
if _expect_type(element, model.SubmodelElement, submodel, failsafe):
submodel.submodel_element.add(element)

:param object_: The object to be type-checked
:param type_: The expected type
:param context: A string to add to the exception message / log message, that describes the context in that the
object has been found
:param context: An object (typically the parent object) describing the context in that the object has been
found. It is only converted to a string for the exception message / log message, if the check
fails, since computing the string representation of a Referable is expensive.
:param failsafe: Log error and return false instead of raising a TypeError
:return: True if the object is of the expected type
:raises TypeError: If the object is not of the expected type and the failsafe mode is not active
Expand Down Expand Up @@ -236,7 +237,12 @@ def object_hook(cls, dct: Dict[str, object]) -> object:
if "modelType" not in dct:
return dct

AAS_CLASS_PARSERS = cls._get_aas_class_parsers()
# Computed once per decoder class, since it is needed for every single JSON object. Look up in __dict__ (not
# via getattr), so subclasses don't reuse the parsers of their base class
AAS_CLASS_PARSERS = cls.__dict__.get("_aas_class_parsers_cache")
if AAS_CLASS_PARSERS is None:
AAS_CLASS_PARSERS = cls._get_aas_class_parsers()
setattr(cls, "_aas_class_parsers_cache", AAS_CLASS_PARSERS)

# Get modelType and constructor function
if not isinstance(dct["modelType"], str):
Expand Down Expand Up @@ -264,24 +270,31 @@ def object_hook(cls, dct: Dict[str, object]) -> object:
try:
return AAS_CLASS_PARSERS[model_type](dct)
except (KeyError, TypeError, model.AASConstraintViolation) as e:
error_message = (
"Error while trying to convert JSON object into {}: {} >>> {}".format(
model_type,
e,
pprint.pformat(dct, depth=2, width=2**14, compact=True),
)
)
if cls.failsafe:
logger.error(error_message, exc_info=e)
# Formatting the JSON object is expensive, so we skip it, if the message would be discarded anyway
if logger.isEnabledFor(logging.ERROR):
logger.error(
cls._object_hook_error_message(model_type, e, dct), exc_info=e
)
# In failsafe mode, we return the raw JSON object dict, if there were errors while parsing an object, so
# a client application is able to handle this data. The read_json_aas_file() function and all
# constructors for complex objects will skip those items by using _expect_type().
return dct
else:
raise (type(e) if isinstance(e, (KeyError, TypeError)) else TypeError)(
error_message
cls._object_hook_error_message(model_type, e, dct)
) from e

@staticmethod
def _object_hook_error_message(
model_type: str, e: Exception, dct: Dict[str, object]
) -> str:
return "Error while trying to convert JSON object into {}: {} >>> {}".format(
model_type,
e,
pprint.pformat(dct, depth=2, width=2**14, compact=True),
)

# ##################################################################################################
# Utility Methods used in constructor methods to add general attributes (from abstract base classes)
# ##################################################################################################
Expand Down Expand Up @@ -680,7 +693,7 @@ def _construct_entity(
cls._amend_abstract_attributes(ret, dct)
if not cls.stripped and "statements" in dct:
for element in _get_ts(dct, "statements", list):
if _expect_type(element, model.SubmodelElement, str(ret), cls.failsafe):
if _expect_type(element, model.SubmodelElement, ret, cls.failsafe):
ret.statement.add(element)
return ret

Expand Down Expand Up @@ -732,7 +745,7 @@ def _construct_submodel(
cls._amend_abstract_attributes(ret, dct)
if not cls.stripped and "submodelElements" in dct:
for element in _get_ts(dct, "submodelElements", list):
if _expect_type(element, model.SubmodelElement, str(ret), cls.failsafe):
if _expect_type(element, model.SubmodelElement, ret, cls.failsafe):
ret.submodel_element.add(element)
return ret

Expand Down Expand Up @@ -842,7 +855,7 @@ def _construct_annotated_relationship_element(
cls._amend_abstract_attributes(ret, dct)
if not cls.stripped and "annotations" in dct:
for element in _get_ts(dct, "annotations", list):
if _expect_type(element, model.DataElement, str(ret), cls.failsafe):
if _expect_type(element, model.DataElement, ret, cls.failsafe):
ret.annotation.add(element)
return ret

Expand All @@ -854,7 +867,7 @@ def _construct_submodel_element_collection(
cls._amend_abstract_attributes(ret, dct)
if not cls.stripped and "value" in dct:
for element in _get_ts(dct, "value", list):
if _expect_type(element, model.SubmodelElement, str(ret), cls.failsafe):
if _expect_type(element, model.SubmodelElement, ret, cls.failsafe):
ret.value.add(element)
return ret

Expand Down Expand Up @@ -894,7 +907,7 @@ def _construct_submodel_element_list(
if not cls.stripped and "value" in dct:
for element in _get_ts(dct, "value", list):
if _expect_type(
element, type_value_list_element, str(ret), cls.failsafe
element, type_value_list_element, ret, cls.failsafe
):
ret.value.add(element)
return ret
Expand Down
54 changes: 37 additions & 17 deletions sdk/basyx/aas/adapter/json/json_serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
Optional,
TextIO,
Type,
TypeVar,
get_args,
)

Expand All @@ -47,6 +48,7 @@
from .. import _generic, _ordering
from .._generic import JSON_AAS_TOP_LEVEL_KEYS_TO_TYPES

_M = TypeVar("_M")

class AASToJsonEncoder(json.JSONEncoder):
"""
Expand Down Expand Up @@ -165,18 +167,31 @@ def default(self, obj: object) -> object:
:return: The serialized object
"""
if not self.deep:
no_children_mapping = self._get_aas_class_no_children_serializers()
for typ in no_children_mapping:
for typ, mapping_method in self._cached_mapping(self._get_aas_class_no_children_serializers).items():
if isinstance(obj, typ):
no_children_mapping_method = no_children_mapping[typ]
return no_children_mapping_method(obj)
mapping = self._get_aas_class_serializers()
for typ in mapping:
return mapping_method(obj)
for typ, mapping_method in self._cached_mapping(self._get_aas_class_serializers).items():
if isinstance(obj, typ):
mapping_method = mapping[typ]
return mapping_method(obj)
return super().default(obj)

@classmethod
def _cached_mapping(cls, get_mapping: Callable[[], _M]) -> _M:
"""
Returns the result of ``get_mapping``, one of the ``_get_aas_class_*()`` methods. It is computed only once per
encoder class, since it is needed for every single serialized object.

:param get_mapping: The bound ``_get_aas_class_*()`` method building the mapping
:return: The mapping
"""
# Look up in cls.__dict__ (not via getattr), so subclasses don't reuse the mappings of their base class
key = "_cache" + get_mapping.__name__
mapping = cls.__dict__.get(key)
if mapping is None:
mapping = get_mapping()
setattr(cls, key, mapping)
return mapping

@classmethod
def _abstract_classes_to_json(cls, obj: object) -> Dict[str, object]:
"""
Expand Down Expand Up @@ -847,8 +862,8 @@ def _remove_children(cls, obj: object) -> object:
:return: dict with the serialized attributes of the child element without its children or the child element
itself, if it cannot contain children
"""
mapping = cls._get_aas_class_serializers()
children_keys = cls._get_aas_class_children_keys()
mapping = cls._cached_mapping(cls._get_aas_class_serializers)
children_keys = cls._cached_mapping(cls._get_aas_class_children_keys)
for typ in children_keys:
if isinstance(obj, typ):
data = mapping[typ](obj)
Expand All @@ -864,7 +879,7 @@ def _submodel_to_json_no_children(cls, obj: model.Submodel) -> Dict[str, object]
:param obj: object of class Submodel
:return: dict with the serialized attributes of this object
"""
data = cls._get_aas_class_serializers()[model.Submodel](obj)
data = cls._cached_mapping(cls._get_aas_class_serializers)[model.Submodel](obj)
children = data.get("submodelElements")
if isinstance(children, list):
data["submodelElements"] = [cls._remove_children(child) for child in children]
Expand All @@ -880,7 +895,7 @@ def _submodel_element_collection_to_json_no_children(
:param obj: object of class SubmodelElementCollection
:return: dict with the serialized attributes of this object
"""
data = cls._get_aas_class_serializers()[model.SubmodelElementCollection](obj)
data = cls._cached_mapping(cls._get_aas_class_serializers)[model.SubmodelElementCollection](obj)
children = data.get("value")
if isinstance(children, list):
data["value"] = [cls._remove_children(child) for child in children]
Expand All @@ -896,7 +911,7 @@ def _submodel_element_list_to_json_no_children(
:param obj: object of class SubmodelElementList
:return: dict with the serialized attributes of this object
"""
data = cls._get_aas_class_serializers()[model.SubmodelElementList](obj)
data = cls._cached_mapping(cls._get_aas_class_serializers)[model.SubmodelElementList](obj)
children = data.get("value")
if isinstance(children, list):
data["value"] = [cls._remove_children(child) for child in children]
Expand All @@ -913,7 +928,7 @@ def _annotated_relationship_element_to_json_no_children(
:param obj: object of class AnnotatedRelationshipElement
:return: dict with the serialized attributes of this object
"""
data = cls._get_aas_class_serializers()[model.AnnotatedRelationshipElement](obj)
data = cls._cached_mapping(cls._get_aas_class_serializers)[model.AnnotatedRelationshipElement](obj)
children = data.get("annotations")
if isinstance(children, list):
data["annotations"] = [cls._remove_children(child) for child in children]
Expand All @@ -927,7 +942,7 @@ def _entity_to_json_no_children(cls, obj: model.Entity) -> Dict[str, object]:
:param obj: object of class Entity
:return: dict with the serialized attributes of this object
"""
data = cls._get_aas_class_serializers()[model.Entity](obj)
data = cls._cached_mapping(cls._get_aas_class_serializers)[model.Entity](obj)
children = data.get("statements")
if isinstance(children, list):
data["statements"] = [cls._remove_children(child) for child in children]
Expand Down Expand Up @@ -1028,18 +1043,21 @@ def write_aas_json_file(
Write a set of AAS objects to an Asset Administration Shell JSON file according to 'Details of the Asset
Administration Shell', chapter 5.5

The whole JSON string is built in memory before it is written, so writing a very large file needs about as much
additional memory as the file size.

:param file: A filename or file-like object to write the JSON-serialized data to
:param data: :class:`ObjectStore <basyx.aas.model.provider.AbstractObjectStore>` which contains different objects of
the AAS metamodel which should be serialized to a JSON file
:param stripped: If `True`, objects are serialized to stripped json objects.
See https://git.rwth-aachen.de/acplt/pyi40aas/-/issues/91
This parameter is ignored if an encoder class is specified.
:param encoder: The encoder class used to encode the JSON objects
:param kwargs: Additional keyword arguments to be passed to `json.dump()`
:param kwargs: Additional keyword arguments to be passed to `json.dumps()`
"""
encoder_ = _select_encoder(stripped, encoder)

# json.dump() only accepts TextIO
# we write str, so we need TextIO
cm: ContextManager[TextIO]
if isinstance(file, get_args(_generic.Path)):
# 'file' is a path, needs to be opened first
Expand All @@ -1054,5 +1072,7 @@ def write_aas_json_file(
cm = contextlib.nullcontext(file) # type: ignore[arg-type]

# serialize object to json
# We use json.dumps() instead of json.dump(), since the latter always uses the (much slower) pure-Python encoder,
# while json.dumps() uses the C-accelerated one. The downside is that the whole JSON string is held in memory.
with cm as fp:
json.dump(_create_dict(data), fp, cls=encoder_, **kwargs)
fp.write(json.dumps(_create_dict(data), cls=encoder_, **kwargs))
63 changes: 35 additions & 28 deletions sdk/basyx/aas/model/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
Any,
Callable,
Dict,
Final,
Generic,
Iterable,
Iterator,
Expand Down Expand Up @@ -304,6 +305,39 @@ class StateOfEvent(Enum):
OFF = 1


def _compile_language_tag_re() -> re.Pattern[str]:
alphanum = "[a-zA-Z0-9]"
singleton = "[0-9A-WY-Za-wy-z]"
extension = f"{singleton}(-({alphanum}){{2,8}})+"
extlang = "[a-zA-Z]{3}(-[a-zA-Z]{3}){0,2}"
irregular = (
"(en-GB-oed|i-ami|i-bnn|i-default|i-enochian|i-hak|"
"i-klingon|i-lux|i-mingo|i-navajo|i-pwn|i-tao|i-tay|"
"i-tsu|sgn-BE-FR|sgn-BE-NL|sgn-CH-DE)"
)
regular = (
"(art-lojban|cel-gaulish|no-bok|no-nyn|zh-guoyu|zh-hakka|"
"zh-min|zh-min-nan|zh-xiang)"
)
grandfathered = f"({irregular}|{regular})"
language = f"([a-zA-Z]{{2,3}}(-{extlang})?|[a-zA-Z]{{4}}|[a-zA-Z]{{5,8}})"
script = "[a-zA-Z]{4}"
region = "([a-zA-Z]{2}|[0-9]{3})"
variant = f"(({alphanum}){{5,8}}|[0-9]({alphanum}){{3}})"
privateuse = f"[xX](-({alphanum}){{1,8}})+"
langtag = (
f"{language}(-{script})?(-{region})?(-{variant})*(-{extension})*(-"
f"{privateuse})?"
)
language_tag = f"({langtag}|{privateuse}|{grandfathered})"

return re.compile(f"^{language_tag}$")


# Compiled once at import, since language tags are checked for every LangStringSet entry.
_LANGUAGE_TAG_RE: Final[re.Pattern[str]] = _compile_language_tag_re()


class LangStringSet(MutableMapping[str, str]):
"""
A mapping of language code to string. Must be non-empty.
Expand All @@ -329,34 +363,7 @@ def __init__(self, dict_: Dict[str, str]):

@classmethod
def _check_language_tag_constraints(cls, ltag: str):
alphanum = "[a-zA-Z0-9]"
singleton = "[0-9A-WY-Za-wy-z]"
extension = f"{singleton}(-({alphanum}){{2,8}})+"
extlang = "[a-zA-Z]{3}(-[a-zA-Z]{3}){0,2}"
irregular = (
"(en-GB-oed|i-ami|i-bnn|i-default|i-enochian|i-hak|"
"i-klingon|i-lux|i-mingo|i-navajo|i-pwn|i-tao|i-tay|"
"i-tsu|sgn-BE-FR|sgn-BE-NL|sgn-CH-DE)"
)
regular = (
"(art-lojban|cel-gaulish|no-bok|no-nyn|zh-guoyu|zh-hakka|"
"zh-min|zh-min-nan|zh-xiang)"
)
grandfathered = f"({irregular}|{regular})"
language = f"([a-zA-Z]{{2,3}}(-{extlang})?|[a-zA-Z]{{4}}|[a-zA-Z]{{5,8}})"
script = "[a-zA-Z]{4}"
region = "([a-zA-Z]{2}|[0-9]{3})"
variant = f"(({alphanum}){{5,8}}|[0-9]({alphanum}){{3}})"
privateuse = f"[xX](-({alphanum}){{1,8}})+"
langtag = (
f"{language}(-{script})?(-{region})?(-{variant})*(-{extension})*(-"
f"{privateuse})?"
)
language_tag = f"({langtag}|{privateuse}|{grandfathered})"

pattern = f"^{language_tag}$"

if re.match(pattern, ltag) is None:
if _LANGUAGE_TAG_RE.match(ltag) is None:
raise ValueError(
f"The language tag must follow the format defined in BCP 47. "
f"Given language tag: {ltag}"
Expand Down
Loading