Skip to content

Math

oqd_core.interface.math

SupportedFuncNames = Literal['abs', 'sin', 'cos', 'tan', 'exp', 'log', 'sinh', 'cosh', 'tanh', 'atan', 'acos', 'asin', 'atanh', 'asinh', 'acosh', 'heaviside', 'conj', 'real', 'imag', 'atan2'] module-attribute

List of supported functions

MathExprSubtypes = Annotated[Union[Annotated[MathNum, Tag('MathNum')], Annotated[MathVar, Tag('MathVar')], Annotated[MathImag, Tag('MathImag')], Annotated[MathFunc, Tag('MathFunc')], Annotated[MathAdd, Tag('MathAdd')], Annotated[MathSub, Tag('MathSub')], Annotated[MathMul, Tag('MathMul')], Annotated[MathDiv, Tag('MathDiv')], Annotated[MathPow, Tag('MathPow')]], Discriminator(lambda v: v['class_'] if isinstance(v, dict) else getattr(v, 'class_'))] module-attribute

Alias for the union of concrete MathExpr subtypes

CastMathExpr = Annotated[MathExprSubtypes, BeforeValidator(MathExpr.cast)] module-attribute

Annotated type that cast typical numeric python types to MathExpr

ConstantMathExpr = Annotated[CastMathExpr, AfterValidator(_isconstant)] module-attribute

Annotated type for constant MathExpr

MathExpr

Bases: TypeReflectBaseModel

Class representing the abstract syntax tree (AST) for a mathematical expression

Source code in oqd-core/src/oqd_core/interface/math.py
class MathExpr(TypeReflectBaseModel):
    """
    Class representing the abstract syntax tree (AST) for a mathematical expression
    """

    @classmethod
    def cast(cls, value: Any):
        if isinstance(value, dict):
            return value
        if isinstance(value, MathExpr):
            return value
        if isinstance(value, (int, float)):
            value = MathNum(value=value)
            return value
        if isinstance(value, (complex, np.complex128)):
            value = MathNum(value=value.real) + MathImag() * value.imag
            return value
        if isinstance(value, str):
            raise TypeError(
                "Tried to cast a string to MathExpr. "
                + f'Wrap your string ("{value}") with MathStr(string="{value}").'
            )
        raise TypeError

    def __neg__(self):
        return MathMul(expr1=MathNum(value=-1), expr2=self)

    def __pos__(self):
        return self

    def __add__(self, other):
        return MathAdd(expr1=self, expr2=other)

    def __sub__(self, other):
        return MathSub(expr1=self, expr2=other)

    def __mul__(self, other):
        try:
            return MathMul(expr1=self, expr2=other)
        except TypeError:  # make sure this is the right error to catch
            return other * self

    def __truediv__(self, other):
        return MathDiv(expr1=self, expr2=other)

    def __pow__(self, other):
        return MathPow(expr1=self, expr2=other)

    def __radd__(self, other):
        other = MathExpr.cast(other)
        return other + self

    def __rsub__(self, other):
        other = MathExpr.cast(other)
        return other - self

    def __rmul__(self, other):
        other = MathExpr.cast(other)
        return other * self

    def __rpow__(self, other):
        other = MathExpr.cast(other)
        return other**self

    def __rtruediv__(self, other):
        other = MathExpr.cast(other)
        return other / self

MathTerminal

Bases: MathExpr

Class representing a terminal in the MathExpr abstract syntax tree (AST)

Source code in oqd-core/src/oqd_core/interface/math.py
class MathTerminal(MathExpr):
    """
    Class representing a terminal in the [`MathExpr`][oqd_core.interface.math.MathExpr] abstract syntax tree (AST)
    """

    pass

MathVar

Bases: MathTerminal

Class representing a variable in a MathExpr

Examples:

>>> MathVar("t")
Source code in oqd-core/src/oqd_core/interface/math.py
class MathVar(MathTerminal):
    """
    Class representing a variable in a [`MathExpr`][oqd_core.interface.math.MathExpr]

    Examples:
        >>> MathVar("t")

    """

    name: VarName

MathNum

Bases: MathTerminal

Class representing a number in a MathExpr

Source code in oqd-core/src/oqd_core/interface/math.py
class MathNum(MathTerminal):
    """
    Class representing a number in a [`MathExpr`][oqd_core.interface.math.MathExpr]
    """

    value: Union[int, float]

MathImag

Bases: MathTerminal

Class representing the imaginary unit in a MathExpr abstract syntax tree (AST)

Source code in oqd-core/src/oqd_core/interface/math.py
class MathImag(MathTerminal):
    """
    Class representing the imaginary unit in a [`MathExpr`][oqd_core.interface.math.MathExpr] abstract syntax tree (AST)
    """

    pass

MathFunc

Bases: MathExpr

Class representing a named function applied to a MathExpr abstract syntax tree (AST)

Attributes:

Name Type Description
func SupportedFuncNames

Named function to apply

expr Union[CastMathExpr, List[CastMathExpr]]

Arguments of the named function

Source code in oqd-core/src/oqd_core/interface/math.py
class MathFunc(MathExpr):
    """
    Class representing a named function applied to a [`MathExpr`][oqd_core.interface.math.MathExpr] abstract syntax tree (AST)

    Attributes:
        func (SupportedFuncNames): Named function to apply
        expr (Union[CastMathExpr, List[CastMathExpr]]): Arguments of the named function
    """

    func: SupportedFuncNames
    expr: Annotated[
        Union[
            Annotated[CastMathExpr, Tag("MathExpr")],
            Annotated[List[CastMathExpr], Tag("list")],
        ],
        Discriminator(lambda v: "list" if isinstance(v, list) else "MathExpr"),
    ]

    @model_validator(mode="before")
    @classmethod
    def args_validate(cls, data):
        if data["func"] in [
            "abs",
            "sin",
            "cos",
            "tan",
            "exp",
            "log",
            "sinh",
            "cosh",
            "tanh",
            "atan",
            "acos",
            "asin",
            "atanh",
            "asinh",
            "acosh",
            "heaviside",
            "conj",
            "real",
            "imag",
        ]:
            if isinstance(data["expr"], list):
                assert (
                    len(data["expr"]) == 1
                ), "Attempted to apply unary function on multiple arguments"
                data["expr"] = data["expr"][0]

        if data["func"] in [
            "atan2",
        ]:
            assert (
                isinstance(data["expr"], list) and len(data["expr"]) == 2
            ), "Attempted to apply binary function with incorrect number of arguments"

        return data

MathBinaryOp

Bases: MathExpr

Class representing binary operations on MathExprs abstract syntax tree (AST)

Source code in oqd-core/src/oqd_core/interface/math.py
class MathBinaryOp(MathExpr):
    """
    Class representing binary operations on [`MathExprs`][oqd_core.interface.math.MathExpr] abstract syntax tree (AST)
    """

    pass

MathAdd

Bases: MathBinaryOp

Class representing the addition of MathExprs

Attributes:

Name Type Description
expr1 MathExpr

Left hand side MathExpr

expr2 MathExpr

Right hand side MathExpr

Source code in oqd-core/src/oqd_core/interface/math.py
class MathAdd(MathBinaryOp):
    """
    Class representing the addition of [`MathExprs`][oqd_core.interface.analog.operator.Operator]

    Attributes:
        expr1 (MathExpr): Left hand side [`MathExpr`][oqd_core.interface.analog.operator.Operator]
        expr2 (MathExpr): Right hand side [`MathExpr`][oqd_core.interface.analog.operator.Operator]
    """

    expr1: CastMathExpr
    expr2: CastMathExpr

MathSub

Bases: MathBinaryOp

Class representing the subtraction of MathExprs

Attributes:

Name Type Description
expr1 MathExpr

Left hand side MathExpr

expr2 MathExpr

Right hand side MathExpr

Source code in oqd-core/src/oqd_core/interface/math.py
class MathSub(MathBinaryOp):
    """
    Class representing the subtraction of [`MathExprs`][oqd_core.interface.math.MathExpr]

    Attributes:
        expr1 (MathExpr): Left hand side [`MathExpr`][oqd_core.interface.math.MathExpr]
        expr2 (MathExpr): Right hand side [`MathExpr`][oqd_core.interface.math.MathExpr]
    """

    expr1: CastMathExpr
    expr2: CastMathExpr

MathMul

Bases: MathBinaryOp

Class representing the multiplication of MathExprs

Attributes:

Name Type Description
expr1 MathExpr

Left hand side MathExpr

expr2 MathExpr

Right hand side MathExpr

Source code in oqd-core/src/oqd_core/interface/math.py
class MathMul(MathBinaryOp):
    """
    Class representing the multiplication of [`MathExprs`][oqd_core.interface.math.MathExpr]

    Attributes:
        expr1 (MathExpr): Left hand side [`MathExpr`][oqd_core.interface.math.MathExpr]
        expr2 (MathExpr): Right hand side [`MathExpr`][oqd_core.interface.math.MathExpr]
    """

    expr1: CastMathExpr
    expr2: CastMathExpr

MathDiv

Bases: MathBinaryOp

Class representing the division of MathExprs

Attributes:

Name Type Description
expr1 MathExpr

Left hand side MathExpr

expr2 MathExpr

Right hand side MathExpr

Source code in oqd-core/src/oqd_core/interface/math.py
class MathDiv(MathBinaryOp):
    """
    Class representing the division of [`MathExprs`][oqd_core.interface.math.MathExpr]

    Attributes:
        expr1 (MathExpr): Left hand side [`MathExpr`][oqd_core.interface.math.MathExpr]
        expr2 (MathExpr): Right hand side [`MathExpr`][oqd_core.interface.math.MathExpr]
    """

    expr1: CastMathExpr
    expr2: CastMathExpr

MathPow

Bases: MathBinaryOp

Class representing the exponentiation of MathExprs

Attributes:

Name Type Description
expr1 MathExpr

Left hand side MathExpr

expr2 MathExpr

Right hand side MathExpr

Source code in oqd-core/src/oqd_core/interface/math.py
class MathPow(MathBinaryOp):
    """
    Class representing the exponentiation of [`MathExprs`][oqd_core.interface.math.MathExpr]

    Attributes:
        expr1 (MathExpr): Left hand side [`MathExpr`][oqd_core.interface.math.MathExpr]
        expr2 (MathExpr): Right hand side [`MathExpr`][oqd_core.interface.math.MathExpr]
    """

    expr1: CastMathExpr
    expr2: CastMathExpr