Skip to content

qref.schema_v1

Pydantic models used for defining V1 schema of Routine.

NAME_PATTERN module-attribute

NAME_PATTERN = '[A-Za-z_][A-Za-z0-9_]*'

OPTIONALLY_NAMESPACED_NAME_PATTERN module-attribute

OPTIONALLY_NAMESPACED_NAME_PATTERN = (
    f"({NAME_PATTERN}\.)?{NAME_PATTERN}"
)

MULTINAMESPACED_NAME_PATTERN module-attribute

MULTINAMESPACED_NAME_PATTERN = (
    f"({NAME_PATTERN}\.)+{NAME_PATTERN}"
)

OPTIONALLY_MULTINAMESPACED_NAME_PATTERN module-attribute

OPTIONALLY_MULTINAMESPACED_NAME_PATTERN = (
    f"({NAME_PATTERN}\.)*{NAME_PATTERN}"
)

CONNECTION_PATTERN module-attribute

CONNECTION_PATTERN = f"{OPTIONALLY_MULTINAMESPACED_NAME_PATTERN} -> {OPTIONALLY_MULTINAMESPACED_NAME_PATTERN}"

T module-attribute

T = TypeVar('T')

CONNECTION_SCHEMA module-attribute

CONNECTION_SCHEMA = {
    "type": "array",
    "items": {
        "anyOf": [
            {"$ref": "#/$defs/Connection"},
            {
                "pattern": f"^{CONNECTION_PATTERN}$",
                "type": "string",
            },
        ]
    },
    "title": "Connections",
    "type": "array",
}

NamedList

Bases: list[T]

Source code in src/qref/schema_v1.py
class NamedList(list[T]):
    @property
    def by_name(self) -> _ProxyMapping[T]:
        return _ProxyMapping(self)

    @classmethod
    def __get_pydantic_core_schema__(cls, source, handler):
        args = get_args(source)
        schema = handler.generate_schema(list[args[0]])
        return core_schema.no_info_after_validator_function(NamedList, schema)

by_name property

by_name: _ProxyMapping[T]

__get_pydantic_core_schema__ classmethod

__get_pydantic_core_schema__(source, handler)
Source code in src/qref/schema_v1.py
@classmethod
def __get_pydantic_core_schema__(cls, source, handler):
    args = get_args(source)
    schema = handler.generate_schema(list[args[0]])
    return core_schema.no_info_after_validator_function(NamedList, schema)

PortV1

Bases: BaseModel

Description of Port in V1 schema

Source code in src/qref/schema_v1.py
class PortV1(BaseModel):
    """Description of Port in V1 schema"""

    name: _Name
    direction: Literal["input", "output", "through"]
    size: _Value | None
    model_config = ConfigDict(title="Port")

name instance-attribute

name: _Name

direction instance-attribute

direction: Literal['input', 'output', 'through']

size instance-attribute

size: _Value | None

model_config class-attribute instance-attribute

model_config = ConfigDict(title='Port')

ConnectionV1

Bases: BaseModel

Description of Connection in V1 schema

Source code in src/qref/schema_v1.py
class ConnectionV1(BaseModel):
    """Description of Connection in V1 schema"""

    source: _OptionallyNamespacedName
    target: _OptionallyNamespacedName

    model_config = ConfigDict(title="Connection", use_enum_values=True)

source instance-attribute

source: _OptionallyNamespacedName

target instance-attribute

target: _OptionallyNamespacedName

model_config class-attribute instance-attribute

model_config = ConfigDict(
    title="Connection", use_enum_values=True
)

ResourceV1

Bases: BaseModel

Description of Resource in V1 schema

Source code in src/qref/schema_v1.py
class ResourceV1(BaseModel):
    """Description of Resource in V1 schema"""

    name: _Name
    type: Literal["additive", "multiplicative", "qubits", "other"]
    value: _Value | None

    model_config = ConfigDict(title="Resource")

name instance-attribute

name: _Name

type instance-attribute

type: Literal[
    "additive", "multiplicative", "qubits", "other"
]

value instance-attribute

value: _Value | None

model_config class-attribute instance-attribute

model_config = ConfigDict(title='Resource')

ParamLinkV1

Bases: BaseModel

Description of Parameter link in V1 schema

Source code in src/qref/schema_v1.py
class ParamLinkV1(BaseModel):
    """Description of Parameter link in V1 schema"""

    source: _OptionallyNamespacedName
    targets: list[_MultiNamespacedName]

    model_config = ConfigDict(title="ParamLink")

source instance-attribute

source: _OptionallyNamespacedName

targets instance-attribute

targets: list[_MultiNamespacedName]

model_config class-attribute instance-attribute

model_config = ConfigDict(title='ParamLink')

RoutineV1

Bases: BaseModel

Description of Routine in V1 schema.

Note

This is NOT a top-level object in the schema. Instead, RoutineV1 is wrapped in SchemaV1.

Source code in src/qref/schema_v1.py
class RoutineV1(BaseModel):
    """Description of Routine in V1 schema.

    Note:
        This is NOT a top-level object in the schema. Instead, RoutineV1 is wrapped in
        SchemaV1.
    """

    name: _Name
    children: Annotated[NamedList[RoutineV1], _name_sorter] = Field(default_factory=list)
    type: str | None = None
    ports: Annotated[NamedList[PortV1], _name_sorter] = Field(default_factory=list)
    resources: Annotated[NamedList[ResourceV1], _name_sorter] = Field(default_factory=list)
    connections: Annotated[list[Annotated[ConnectionV1, _connection_parser]], _source_sorter] = Field(
        default_factory=list
    )
    input_params: list[_OptionallyMultiNamespacedName] = Field(default_factory=list)
    local_variables: dict[str, str] = Field(default_factory=dict)
    linked_params: Annotated[list[ParamLinkV1], _source_sorter] = Field(default_factory=list)
    meta: dict[str, Any] = Field(default_factory=dict)

    model_config = ConfigDict(title="Routine", validate_assignment=True)

    def __init__(self, **data: Any):
        super().__init__(**{k: v for k, v in data.items() if v != [] and v != {}})

    @model_validator(mode="after")
    def _validate_connections(self) -> Self:
        children_port_names = [f"{child.name}.{port.name}" for child in self.children for port in child.ports]
        parent_port_names = [port.name for port in self.ports]
        available_port_names = set(children_port_names + parent_port_names)

        missed_ports = [
            port
            for connection in self.connections
            for port in (connection.source, connection.target)
            if port not in available_port_names
        ]
        if missed_ports:
            raise ValueError(
                "The following ports appear in a connection but are not "
                f"among routine's port or their children's ports: {missed_ports}."
            )
        return self

name instance-attribute

name: _Name

children class-attribute instance-attribute

children: Annotated[NamedList[RoutineV1], _name_sorter] = (
    Field(default_factory=list)
)

type class-attribute instance-attribute

type: str | None = None

ports class-attribute instance-attribute

ports: Annotated[NamedList[PortV1], _name_sorter] = Field(
    default_factory=list
)

resources class-attribute instance-attribute

resources: Annotated[
    NamedList[ResourceV1], _name_sorter
] = Field(default_factory=list)

connections class-attribute instance-attribute

connections: Annotated[
    list[Annotated[ConnectionV1, _connection_parser]],
    _source_sorter,
] = Field(default_factory=list)

input_params class-attribute instance-attribute

input_params: list[_OptionallyMultiNamespacedName] = Field(
    default_factory=list
)

local_variables class-attribute instance-attribute

local_variables: dict[str, str] = Field(
    default_factory=dict
)

linked_params class-attribute instance-attribute

linked_params: Annotated[
    list[ParamLinkV1], _source_sorter
] = Field(default_factory=list)

meta class-attribute instance-attribute

meta: dict[str, Any] = Field(default_factory=dict)

model_config class-attribute instance-attribute

model_config = ConfigDict(
    title="Routine", validate_assignment=True
)

__init__

__init__(**data: Any)
Source code in src/qref/schema_v1.py
def __init__(self, **data: Any):
    super().__init__(**{k: v for k, v in data.items() if v != [] and v != {}})

generate_schema_v1

generate_schema_v1() -> dict[str, Any]

Generate Routine schema V1.

The schema is generated from DocumentRootV1 model, and then enriched with additional fields "title" and "$schema".

Source code in src/qref/schema_v1.py
def generate_schema_v1() -> dict[str, Any]:
    """Generate Routine schema V1.

    The schema is generated from DocumentRootV1 model, and then enriched with
    additional fields "title" and "$schema".
    """
    return SchemaV1.model_json_schema(schema_generator=_GenerateV1JsonSchema)