Skip to content

Commit

Permalink
validating sequence and device serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
a-corni committed Jul 7, 2023
1 parent ecc81dd commit a7e0917
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 15 deletions.
9 changes: 7 additions & 2 deletions pulser-core/pulser/devices/_device_datacls.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,13 @@
from dataclasses import dataclass, field, fields
from typing import Any, Literal, cast, get_args

import jsonschema
import numpy as np
from scipy.spatial.distance import pdist, squareform

from pulser.channels.base_channel import Channel
from pulser.devices.interaction_coefficients import c6_dict
from pulser.json.abstract_repr.serializer import AbstractReprEncoder
from pulser.json.abstract_repr.serializer import AbstractReprEncoder, schemas
from pulser.json.utils import obj_to_dict
from pulser.register.base_register import BaseRegister, QubitId
from pulser.register.mappable_reg import MappableRegister
Expand Down Expand Up @@ -417,7 +418,11 @@ def _to_abstract_repr(self) -> dict[str, Any]:

def to_abstract_repr(self) -> str:
"""Serializes the Sequence into an abstract JSON object."""
return json.dumps(self, cls=AbstractReprEncoder)
abstr_dev_txt = json.dumps(self, cls=AbstractReprEncoder)
abstr_dev_dict = json.loads(abstr_dev_txt)
# Validate the format of the data against the JSON schema.
jsonschema.validate(instance=abstr_dev_dict, schema=schemas["device"])
return abstr_dev_txt


@dataclass(frozen=True, repr=False)
Expand Down
13 changes: 1 addition & 12 deletions pulser-core/pulser/json/abstract_repr/deserializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@

import dataclasses
import json
from pathlib import Path
from typing import TYPE_CHECKING, Any, Type, Union, cast, overload

import jsonschema
Expand All @@ -28,6 +27,7 @@
from pulser.channels.base_channel import Channel
from pulser.channels.eom import RydbergBeam, RydbergEOM
from pulser.devices import Device, VirtualDevice
from pulser.json.abstract_repr.serializer import resolver, schemas
from pulser.json.abstract_repr.signatures import (
BINARY_OPERATORS,
UNARY_OPERATORS,
Expand Down Expand Up @@ -58,17 +58,6 @@

ExpReturnType = Union[int, float, ParamObj]

schemas_path = Path(__file__).parent / "schemas"
schemas = {}
for obj_type in ("device", "sequence"):
with open(schemas_path / f"{obj_type}-schema.json") as f:
schemas[obj_type] = json.load(f)

resolver = jsonschema.validators.RefResolver(
base_uri=f"{schemas_path.resolve().as_uri()}/",
referrer=schemas["sequence"],
)


@overload
def _deserialize_parameter(param: int, vars: dict[str, Variable]) -> int:
Expand Down
24 changes: 23 additions & 1 deletion pulser-core/pulser/json/abstract_repr/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@
import inspect
import json
from itertools import chain
from pathlib import Path
from typing import TYPE_CHECKING, Any
from typing import Sequence as abcSequence
from typing import Union, cast

import jsonschema
import numpy as np

from pulser.json.abstract_repr.signatures import SIGNATURES
Expand All @@ -32,6 +34,18 @@
from pulser.sequence._call import _Call


schemas_path = Path(__file__).parent / "schemas"
schemas = {}
for obj_type in ("device", "sequence"):
with open(schemas_path / f"{obj_type}-schema.json") as f:
schemas[obj_type] = json.load(f)

resolver = jsonschema.validators.RefResolver(
base_uri=f"{schemas_path.resolve().as_uri()}/",
referrer=schemas["sequence"],
)


class AbstractReprEncoder(json.JSONEncoder):
"""The custom encoder for abstract representation of Pulser objects."""

Expand Down Expand Up @@ -292,4 +306,12 @@ def get_all_args(
else:
raise AbstractReprError(f"Unknown call '{call.name}'.")

return json.dumps(res, cls=AbstractReprEncoder, **json_dumps_options)
abstr_seq_txt = json.dumps(
res, cls=AbstractReprEncoder, **json_dumps_options
)
abstr_seq_dict = json.loads(abstr_seq_txt)
# Validate the format of the data against the JSON schema.
jsonschema.validate(
instance=abstr_seq_dict, schema=schemas["sequence"], resolver=resolver
)
return abstr_seq_txt

0 comments on commit a7e0917

Please sign in to comment.