Skip to content

exprop

Classes:

  • ExprList

    A list-based representation of a RPN expression.

  • ExprOp

    Represents operators used in RPN expressions.

  • ExprToken

    Enumeration for symbolic constants used in norm_expr.

  • TupleExprList

    A tuple of multiple ExprList expressions, applied sequentially to the clip(s).

ExprList

Bases: StrList

A list-based representation of a RPN expression.

Methods:

  • __call__

    Apply the expression to one or more input clips.

__call__

__call__(
    *clips: VideoNodeIterableT[VideoNode],
    planes: Planes = None,
    format: HoldsVideoFormat | VideoFormatLike | None = None,
    opt: bool = False,
    boundary: bool = True,
    func: FuncExcept | None = None,
    split_planes: bool = False,
    **kwargs: Any
) -> ConstantFormatVideoNode

Apply the expression to one or more input clips.

Parameters:

  • clips

    (VideoNodeIterableT[VideoNode], default: () ) –

    Input clip(s).

  • planes

    (Planes, default: None ) –

    Plane to process, defaults to all.

  • format

    (HoldsVideoFormat | VideoFormatLike | None, default: None ) –

    Output format, defaults to the first clip format.

  • opt

    (bool, default: False ) –

    Forces integer evaluation as much as possible.

  • boundary

    (bool, default: True ) –

    Specifies the default boundary condition for relative pixel accesses:

    • True (default): Mirrored edges.
    • False: Clamped edges.
  • func

    (FuncExcept | None, default: None ) –

    Function returned for custom error handling. This should only be set by VS package developers.

  • split_planes

    (bool, default: False ) –

    Splits the VideoNodes into their individual planes.

  • kwargs

    (Any, default: {} ) –

    Additional keyword arguments passed to norm_expr.

Returns:

  • ConstantFormatVideoNode

    Evaluated clip.

Source code in vsexprtools/exprop.py
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def __call__(
    self,
    *clips: VideoNodeIterableT[vs.VideoNode],
    planes: Planes = None,
    format: HoldsVideoFormat | VideoFormatLike | None = None,
    opt: bool = False,
    boundary: bool = True,
    func: FuncExcept | None = None,
    split_planes: bool = False,
    **kwargs: Any,
) -> ConstantFormatVideoNode:
    """
    Apply the expression to one or more input clips.

    Args:
        clips: Input clip(s).
        planes: Plane to process, defaults to all.
        format: Output format, defaults to the first clip format.
        opt: Forces integer evaluation as much as possible.
        boundary: Specifies the default boundary condition for relative pixel accesses:

               - True (default): Mirrored edges.
               - False: Clamped edges.
        func: Function returned for custom error handling. This should only be set by VS package developers.
        split_planes: Splits the VideoNodes into their individual planes.
        kwargs: Additional keyword arguments passed to [norm_expr][vsexprtools.norm_expr].

    Returns:
        Evaluated clip.
    """
    from .funcs import norm_expr

    return norm_expr(clips, self, planes, format, opt, boundary, func, split_planes, **kwargs)

ExprOp

Bases: ExprOpBase

Represents operators used in RPN expressions.

Each class attribute corresponds to a specific expression operator with its associated symbol and arity (number of required operands).

Note: format strings can include placeholders for dynamic substitution (e.g., {N:d}, {name:s}).

Methods:

  • __call__

    Combines multiple video clips using the selected expression operator

  • acos

    Build an expression to approximate arccosine using an identity:

  • asin

    Build an expression to approximate arcsine using an identity:

  • atan

    Build an expression to compute arctangent (atan) using domain reduction.

  • atanf

    Approximate atan(x) using a Taylor series centered at 0.

  • clamp

    Create an expression to clamp a value between min and max.

  • combine

    Combines multiple video clips using the selected expression operator.

  • convert_extra

    Converts an 'extra' operator into a valid akarin.Expr expression string.

  • convolution

    Builds an expression that performs a weighted convolution-like operation.

  • is_extra

    Check if the operator is an 'extra' operator.

  • mae

    Build an expression to compute the Mean Absolute Error (MAE) between two plane sets.

  • masked_merge

    Build a masked merge expression from two inputs and a mask.

  • matrix

    Generate a matrix expression layout for convolution-like operations.

  • polyval

    Build an expression to evaluate a polynomial at a given value using Horner's method.

  • rmse

    Build an expression to compute the Root Mean Squared Error (RMSE) between two plane sets.

Attributes:

  • ABS

    Absolute value.

  • ABS_PIX

    Get value of absolute pixel at coordinates ({x},{y}) on clip {char}.

  • ACOS

    Arccosine (inverse cosine).

  • ADD

    Addition.

  • AND

    Logical AND.

  • ASIN

    Arcsine (inverse sine).

  • ATAN

    Arctangent.

  • BITAND

    Bitwise AND.

  • BITNOT

    Bitwise NOT.

  • BITOR

    Bitwise OR.

  • BITXOR

    Bitwise XOR.

  • CEIL

    Round up to nearest integer.

  • CLAMP

    Clamp a value between min and max.

  • COS

    Cosine (radians).

  • DIV

    Division.

  • DROP

    Remove top value from the stack.

  • DROPN

    Remove top N values from the stack.

  • DUP

    Duplicate the top of the stack.

  • DUPN

    Duplicate the top N items on the stack.

  • EQ

    Equality (x == y).

  • EXP

    Exponential function (e^x).

  • FLOOR

    Round down to nearest integer.

  • GT

    Greater than (x > y).

  • GTE

    Greater than or equal.

  • HEIGHT

    Frame height.

  • LERP

    Linear interpolation of a value between two border values.

  • LOG

    Natural logarithm.

  • LT

    Less than (x < y).

  • LTE

    Less than or equal.

  • MAX

    Maximum of two values.

  • MIN

    Minimum of two values.

  • MMG

    MaskedMerge implementation from std lib.

  • MOD

    Modulo operation (remainder).

  • MUL

    Multiplication.

  • N

    Current frame number.

  • NEG

    Negation (multiply by -1).

  • NOT

    Logical NOT.

  • OR

    Logical OR.

  • PI

    Mathematical constant π (pi).

  • POLYVAL

    Evaluate a degree-N polynomial at the top value on the stack.

  • POW

    Exponentiation (x^y).

  • REL_PIX

    Get value of relative pixel at offset ({x},{y}) on clip {char}.

  • ROUND

    Round to nearest integer.

  • SGN

    Sign function: -1, 0, or 1 depending on value.

  • SIN

    Sine (radians).

  • SORTN

    Sort top N values on the stack.

  • SQRT

    Square root.

  • SUB

    Subtraction.

  • SWAP

    Swap top two values on the stack.

  • SWAPN

    Swap the top N values (custom depth).

  • TAN

    Tangent (radians).

  • TERN

    Ternary operation: cond ? if_true : if_false.

  • TRUNC

    Truncate to integer (toward zero).

  • VAR_PUSH

    Push value of variable {name} to the stack.

  • VAR_STORE

    Store value in variable named {name}.

  • WIDTH

    Frame width.

  • X

    Current pixel X-coordinate.

  • XOR

    Logical XOR.

  • Y

    Current pixel Y-coordinate.

  • n_op (int) –

    The number of operands the operator requires.

ABS class-attribute instance-attribute

ABS = ('abs', 1)

Absolute value.

ABS_PIX class-attribute instance-attribute

ABS_PIX = ('{x:d} {y:d} {char:s}[]', 3)

Get value of absolute pixel at coordinates ({x},{y}) on clip {char}.

ACOS class-attribute instance-attribute

ACOS = ('acos', 1)

Arccosine (inverse cosine).

ADD class-attribute instance-attribute

ADD = ('+', 2)

Addition.

AND class-attribute instance-attribute

AND = ('and', 2)

Logical AND.

ASIN class-attribute instance-attribute

ASIN = ('asin', 1)

Arcsine (inverse sine).

ATAN class-attribute instance-attribute

ATAN = ('atan', 1)

Arctangent.

BITAND class-attribute instance-attribute

BITAND = ('bitand', 2)

Bitwise AND.

BITNOT class-attribute instance-attribute

BITNOT = ('bitnot', 1)

Bitwise NOT.

BITOR class-attribute instance-attribute

BITOR = ('bitor', 2)

Bitwise OR.

BITXOR class-attribute instance-attribute

BITXOR = ('bitxor', 2)

Bitwise XOR.

CEIL class-attribute instance-attribute

CEIL = ('ceil', 1)

Round up to nearest integer.

CLAMP class-attribute instance-attribute

CLAMP = ('clamp', 3)

Clamp a value between min and max.

COS class-attribute instance-attribute

COS = ('cos', 1)

Cosine (radians).

DIV class-attribute instance-attribute

DIV = ('/', 2)

Division.

DROP class-attribute instance-attribute

DROP = ('drop', 1)

Remove top value from the stack.

DROPN class-attribute instance-attribute

DROPN = ('drop{N:d}', 1)

Remove top N values from the stack.

DUP class-attribute instance-attribute

DUP = ('dup', 1)

Duplicate the top of the stack.

DUPN class-attribute instance-attribute

DUPN = ('dup{N:d}', 1)

Duplicate the top N items on the stack.

EQ class-attribute instance-attribute

EQ = ('=', 2)

Equality (x == y).

EXP class-attribute instance-attribute

EXP = ('exp', 1)

Exponential function (e^x).

FLOOR class-attribute instance-attribute

FLOOR = ('floor', 1)

Round down to nearest integer.

GT class-attribute instance-attribute

GT = ('>', 2)

Greater than (x > y).

GTE class-attribute instance-attribute

GTE = ('>=', 2)

Greater than or equal.

HEIGHT class-attribute instance-attribute

HEIGHT = ('height', 0)

Frame height.

LERP class-attribute instance-attribute

LERP = ('lerp', 3)

Linear interpolation of a value between two border values.

LOG class-attribute instance-attribute

LOG = ('log', 1)

Natural logarithm.

LT class-attribute instance-attribute

LT = ('<', 2)

Less than (x < y).

LTE class-attribute instance-attribute

LTE = ('<=', 2)

Less than or equal.

MAX class-attribute instance-attribute

MAX = ('max', 2)

Maximum of two values.

MIN class-attribute instance-attribute

MIN = ('min', 2)

Minimum of two values.

MMG class-attribute instance-attribute

MMG = ('mmg', 3)

MaskedMerge implementation from std lib.

MOD class-attribute instance-attribute

MOD = ('%', 2)

Modulo operation (remainder).

MUL class-attribute instance-attribute

MUL = ('*', 2)

Multiplication.

N class-attribute instance-attribute

N = ('N', 0)

Current frame number.

NEG class-attribute instance-attribute

NEG = ('neg', 1)

Negation (multiply by -1).

NOT class-attribute instance-attribute

NOT = ('not', 1)

Logical NOT.

OR class-attribute instance-attribute

OR = ('or', 2)

Logical OR.

PI class-attribute instance-attribute

PI = ('pi', 0)

Mathematical constant π (pi).

POLYVAL class-attribute instance-attribute

POLYVAL = ('polyval{N:d}', cast(int, inf))

Evaluate a degree-N polynomial at the top value on the stack.

Uses N coefficients below the top value (x), ordered from highest to lowest degree.

POW class-attribute instance-attribute

POW = ('pow', 2)

Exponentiation (x^y).

REL_PIX class-attribute instance-attribute

REL_PIX = ('{char:s}[{x:d},{y:d}]', 3)

Get value of relative pixel at offset ({x},{y}) on clip {char}.

ROUND class-attribute instance-attribute

ROUND = ('round', 1)

Round to nearest integer.

SGN class-attribute instance-attribute

SGN = ('sgn', 1)

Sign function: -1, 0, or 1 depending on value.

SIN class-attribute instance-attribute

SIN = ('sin', 1)

Sine (radians).

SORTN class-attribute instance-attribute

SORTN = ('sort{N:d}', 1)

Sort top N values on the stack.

SQRT class-attribute instance-attribute

SQRT = ('sqrt', 1)

Square root.

SUB class-attribute instance-attribute

SUB = ('-', 2)

Subtraction.

SWAP class-attribute instance-attribute

SWAP = ('swap', 2)

Swap top two values on the stack.

SWAPN class-attribute instance-attribute

SWAPN = ('swap{N:d}', 2)

Swap the top N values (custom depth).

TAN class-attribute instance-attribute

TAN = ('tan', 1)

Tangent (radians).

TERN class-attribute instance-attribute

TERN = ('?', 3)

Ternary operation: cond ? if_true : if_false.

TRUNC class-attribute instance-attribute

TRUNC = ('trunc', 1)

Truncate to integer (toward zero).

VAR_PUSH class-attribute instance-attribute

VAR_PUSH = ('{name:s}@', 1)

Push value of variable {name} to the stack.

VAR_STORE class-attribute instance-attribute

VAR_STORE = ('{name:s}!', 1)

Store value in variable named {name}.

WIDTH class-attribute instance-attribute

WIDTH = ('width', 0)

Frame width.

X class-attribute instance-attribute

X = ('X', 0)

Current pixel X-coordinate.

XOR class-attribute instance-attribute

XOR = ('xor', 2)

Logical XOR.

Y class-attribute instance-attribute

Y = ('Y', 0)

Current pixel Y-coordinate.

n_op instance-attribute

n_op: int

The number of operands the operator requires.

__call__

__call__(
    *clips: VideoNodeIterableT[VideoNodeT],
    suffix: SupportsString | Iterable[SupportsString] | None = None,
    prefix: SupportsString | Iterable[SupportsString] | None = None,
    expr_suffix: SupportsString | Iterable[SupportsString] | None = None,
    expr_prefix: SupportsString | Iterable[SupportsString] | None = None,
    planes: Planes = None,
    **kwargs: Any
) -> VideoNodeT
__call__(*pos_args: Any, **kwargs: Any) -> str
__call__(*pos_args: Any, **kwargs: Any) -> VideoNode | str

Combines multiple video clips using the selected expression operator or returns a formatted version of the ExprOp, using substitutions from pos_args and kwargs.

Parameters:

  • *pos_args

    (Any, default: () ) –

    Positional arguments.

  • **kwargs

    (Any, default: {} ) –

    Keywords arguments.

Returns:

  • VideoNode | str

    A clip representing the combined result of applying the expression or formatted version of this ExprOp.

Source code in vsexprtools/exprop.py
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
def __call__(self, *pos_args: Any, **kwargs: Any) -> vs.VideoNode | str:
    """
    Combines multiple video clips using the selected expression operator
    or returns a formatted version of the ExprOp, using substitutions from pos_args and kwargs.

    Args:
        *pos_args: Positional arguments.
        **kwargs: Keywords arguments.

    Returns:
        A clip representing the combined result of applying the expression or formatted version of this ExprOp.
    """
    args = list(flatten(pos_args))

    if args and isinstance(args[0], vs.VideoNode):
        return self.combine(*args, **kwargs)

    while True:
        try:
            return self.format(*args, **kwargs)
        except KeyError as key:
            if not args:
                raise
            kwargs[key.args[0]] = args.pop(0)

acos classmethod

acos(c: SupportsString = '', n: int = 10) -> ExprList
Build an expression to approximate arccosine using an identity

acos(x) = π/2 - asin(x)

Parameters:

  • c

    (SupportsString, default: '' ) –

    The input expression variable.

  • n

    (int, default: 10 ) –

    Number of terms to use in the internal asin approximation.

Returns:

  • ExprList

    An ExprList representing the acos(x) expression.

Source code in vsexprtools/exprop.py
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
@classmethod
def acos(cls, c: SupportsString = "", n: int = 10) -> ExprList:
    """
    Build an expression to approximate arccosine using an identity:
        acos(x) = π/2 - asin(x)

    Args:
        c: The input expression variable.
        n: Number of terms to use in the internal asin approximation.

    Returns:
        An `ExprList` representing the acos(x) expression.
    """
    return ExprList([c, "__acosvar!", cls.PI, 2, cls.DIV, cls.asin("__acosvar@", n), cls.SUB])

asin classmethod

asin(c: SupportsString = '', n: int = 10) -> ExprList
Build an expression to approximate arcsine using an identity

asin(x) = atan(x / sqrt(1 - x²))

Parameters:

  • c

    (SupportsString, default: '' ) –

    The input expression variable.

  • n

    (int, default: 10 ) –

    Number of terms to use in the internal atan approximation.

Returns:

  • ExprList

    An ExprList representing the asin(x) expression.

Source code in vsexprtools/exprop.py
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
@classmethod
def asin(cls, c: SupportsString = "", n: int = 10) -> ExprList:
    """
    Build an expression to approximate arcsine using an identity:
        asin(x) = atan(x / sqrt(1 - x²))

    Args:
        c: The input expression variable.
        n: Number of terms to use in the internal atan approximation.

    Returns:
        An `ExprList` representing the asin(x) expression.
    """
    return cls.atan(ExprList([c, cls.DUP, cls.DUP, cls.MUL, 1, cls.SWAP, cls.SUB, cls.SQRT, cls.DIV]).to_str(), n)

atan classmethod

atan(c: SupportsString = '', n: int = 10) -> ExprList

Build an expression to compute arctangent (atan) using domain reduction.

Parameters:

  • c

    (SupportsString, default: '' ) –

    The expression variable or string input.

  • n

    (int, default: 10 ) –

    The number of terms to use in the Taylor series approximation.

Returns:

  • ExprList

    An ExprList representing the arctangent expression.

Source code in vsexprtools/exprop.py
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
@classmethod
def atan(cls, c: SupportsString = "", n: int = 10) -> ExprList:
    """
    Build an expression to compute arctangent (atan) using domain reduction.

    Args:
        c: The expression variable or string input.
        n: The number of terms to use in the Taylor series approximation.

    Returns:
        An `ExprList` representing the arctangent expression.
    """
    # Using domain reduction when |x| > 1
    expr = ExprList(
        [
            ExprList([c, cls.DUP, "__atanvar!", cls.ABS, 1, cls.GT]),
            ExprList(
                [
                    "__atanvar@",
                    cls.SGN.convert_extra(),
                    cls.PI,
                    cls.MUL,
                    2,
                    cls.DIV,
                    1,
                    "__atanvar@",
                    cls.DIV,
                    cls.atanf("", n),
                    cls.SUB,
                ]
            ),
            ExprList([cls.atanf("__atanvar@", n)]),
            cls.TERN,
        ]
    )

    return expr

atanf classmethod

atanf(c: SupportsString = '', n: int = 10) -> ExprList

Approximate atan(x) using a Taylor series centered at 0.

This is accurate for inputs in [-1, 1]. Use atan for full-range values.

Parameters:

  • c

    (SupportsString, default: '' ) –

    The expression variable or string input.

  • n

    (int, default: 10 ) –

    The number of terms in the Taylor series (min 2).

Returns:

  • ExprList

    An ExprList approximating atan(x).

Source code in vsexprtools/exprop.py
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
@classmethod
def atanf(cls, c: SupportsString = "", n: int = 10) -> ExprList:
    """
    Approximate atan(x) using a Taylor series centered at 0.

    This is accurate for inputs in [-1, 1]. Use `atan` for full-range values.

    Args:
        c: The expression variable or string input.
        n: The number of terms in the Taylor series (min 2).

    Returns:
        An `ExprList` approximating atan(x).
    """
    # Approximation using Taylor series
    n = max(2, n)

    expr = ExprList([c, cls.DUP, "__atanfvar!"])

    for i in range(1, n):
        expr.append("__atanfvar@", 2 * i + 1, cls.POW, 2 * i + 1, cls.DIV, cls.SUB if i % 2 else cls.ADD)

    return expr

clamp classmethod

clamp(
    min: float | ExprToken = RangeMin,
    max: float | ExprToken = RangeMax,
    c: str = "",
) -> ExprList

Create an expression to clamp a value between min and max.

Parameters:

Returns:

  • ExprList

    An ExprList containing the clamping expression.

Source code in vsexprtools/exprop.py
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
@classmethod
def clamp(
    cls, min: float | ExprToken = ExprToken.RangeMin, max: float | ExprToken = ExprToken.RangeMax, c: str = ""
) -> ExprList:
    """
    Create an expression to clamp a value between `min` and `max`.

    Args:
        min: The minimum value.
        max: The maximum value.
        c: Optional expression variable or prefix to clamp.

    Returns:
        An `ExprList` containing the clamping expression.
    """
    return ExprList([c, min, max, ExprOp.CLAMP])

combine

combine(
    *clips: VideoNode | Iterable[VideoNode | Iterable[VideoNode]],
    suffix: SupportsString | Iterable[SupportsString] | None = None,
    prefix: SupportsString | Iterable[SupportsString] | None = None,
    expr_suffix: SupportsString | Iterable[SupportsString] | None = None,
    expr_prefix: SupportsString | Iterable[SupportsString] | None = None,
    planes: Planes = None,
    **kwargs: Any
) -> ConstantFormatVideoNode

Combines multiple video clips using the selected expression operator.

Parameters:

  • clips

    (VideoNode | Iterable[VideoNode | Iterable[VideoNode]], default: () ) –

    Input clip(s).

  • suffix

    (SupportsString | Iterable[SupportsString] | None, default: None ) –

    Optional suffix string(s) to append to each input variable in the expression.

  • prefix

    (SupportsString | Iterable[SupportsString] | None, default: None ) –

    Optional prefix string(s) to prepend to each input variable in the expression.

  • expr_suffix

    (SupportsString | Iterable[SupportsString] | None, default: None ) –

    Optional expression to append after the combined input expression.

  • expr_prefix

    (SupportsString | Iterable[SupportsString] | None, default: None ) –

    Optional expression to prepend before the combined input expression.

  • planes

    (Planes, default: None ) –

    Which planes to process. Defaults to all.

  • **kwargs

    (Any, default: {} ) –

    Additional keyword arguments forwarded to combine.

Returns:

  • ConstantFormatVideoNode

    A clip representing the combined result of applying the expression.

Source code in vsexprtools/exprop.py
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
def combine(
    self,
    *clips: vs.VideoNode | Iterable[vs.VideoNode | Iterable[vs.VideoNode]],
    suffix: SupportsString | Iterable[SupportsString] | None = None,
    prefix: SupportsString | Iterable[SupportsString] | None = None,
    expr_suffix: SupportsString | Iterable[SupportsString] | None = None,
    expr_prefix: SupportsString | Iterable[SupportsString] | None = None,
    planes: Planes = None,
    **kwargs: Any,
) -> ConstantFormatVideoNode:
    """
    Combines multiple video clips using the selected expression operator.

    Args:
        clips: Input clip(s).
        suffix: Optional suffix string(s) to append to each input variable in the expression.
        prefix: Optional prefix string(s) to prepend to each input variable in the expression.
        expr_suffix: Optional expression to append after the combined input expression.
        expr_prefix: Optional expression to prepend before the combined input expression.
        planes: Which planes to process. Defaults to all.
        **kwargs: Additional keyword arguments forwarded to [combine][vsexprtools.combine].

    Returns:
        A clip representing the combined result of applying the expression.
    """
    from .funcs import combine

    return combine(clips, self, suffix, prefix, expr_suffix, expr_prefix, planes, **kwargs)

convert_extra

convert_extra(degree: int | None = None) -> str

Converts an 'extra' operator into a valid akarin.Expr expression string.

Parameters:

  • degree

    (int | None, default: None ) –

    If calling from POLYVAL, the degree of the polynomial.

Returns:

  • str

    A string representation of the equivalent expression.

Raises:

Source code in vsexprtools/exprop.py
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
def convert_extra(  # type: ignore[misc]
    self: Literal[
        ExprOp.SGN,
        ExprOp.NEG,
        ExprOp.TAN,
        ExprOp.ATAN,
        ExprOp.ASIN,
        ExprOp.ACOS,
        ExprOp.CEIL,
        ExprOp.MMG,
        ExprOp.LERP,
        ExprOp.POLYVAL,
    ],  # pyright: ignore[reportGeneralTypeIssues]
    degree: int | None = None,
) -> str:
    """
    Converts an 'extra' operator into a valid `akarin.Expr` expression string.

    Args:
        degree: If calling from POLYVAL, the degree of the polynomial.

    Returns:
        A string representation of the equivalent expression.

    Raises:
        ValueError: If the operator is not marked as extra.
        NotImplementedError: If the extra operator has no defined conversion.
    """
    if not self.is_extra():
        raise CustomValueError

    match self:
        case ExprOp.SGN:
            return "dup 0 > swap 0 < -"
        case ExprOp.NEG:
            return "-1 *"
        case ExprOp.TAN:
            return "dup sin swap cos /"
        case ExprOp.ATAN:
            return self.atan().to_str()
        case ExprOp.ASIN:
            return self.asin().to_str()
        case ExprOp.ACOS:
            return self.acos().to_str()
        case ExprOp.CEIL:
            return "-1 * floor -1 *"
        case ExprOp.MMG:
            return self.masked_merge().to_str()
        case ExprOp.LERP:
            if bytes(self, "utf-8") in _get_akarin_expr_version()["expr_features"]:
                return str(self)
            return "dup 1 - swap2 * swap2 * - __LERP! range_max 1 <= __LERP@ __LERP@ round ?"
        case ExprOp.POLYVAL:
            assert degree is not None
            return self.polyval("", *[""] * (degree + 1)).to_str()
        case _:
            raise NotImplementedError

convolution classmethod

convolution(
    var: SupportsString | Collection[SupportsString],
    matrix: (
        Iterable[SupportsSumNoDefaultT]
        | Iterable[Iterable[SupportsSumNoDefaultT]]
    ),
    bias: SupportsString | None = None,
    divisor: SupportsString | bool = True,
    saturate: bool = True,
    mode: ConvMode = SQUARE,
    premultiply: SupportsString | None = None,
    multiply: SupportsString | None = None,
    clamp: bool = False,
) -> TupleExprList

Builds an expression that performs a weighted convolution-like operation.

Parameters:

  • var

    (SupportsString | Collection[SupportsString]) –

    The variable used as the central value or elements proportional to the radius if mode is Literal[ConvMode.TEMPORAL].

  • matrix

    (Iterable[SupportsSumNoDefaultT] | Iterable[Iterable[SupportsSumNoDefaultT]]) –

    A flat or 2D iterable representing the convolution weights.

  • bias

    (SupportsString | None, default: None ) –

    A constant value to add to the result after convolution (default: None).

  • divisor

    (SupportsString | bool, default: True ) –

    If True, normalizes by the sum of weights; if False, skips division; Otherwise, divides by this value.

  • saturate

    (bool, default: True ) –

    If False, applies abs() to avoid negatives.

  • mode

    (ConvMode, default: SQUARE ) –

    The convolution shape.

  • premultiply

    (SupportsString | None, default: None ) –

    Optional scalar to multiply the result before normalization.

  • multiply

    (SupportsString | None, default: None ) –

    Optional scalar to multiply the result at the end.

  • clamp

    (bool, default: False ) –

    If True, clamps the final result to [RangeMin, RangeMax].

Returns:

  • TupleExprList

    A TupleExprList representing the expression-based convolution.

Raises:

  • CustomValueError

    If matrix length is invalid or doesn't match the mode.

Source code in vsexprtools/exprop.py
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
@classmethod
def convolution(
    cls,
    var: SupportsString | Collection[SupportsString],
    matrix: Iterable[SupportsSumNoDefaultT] | Iterable[Iterable[SupportsSumNoDefaultT]],
    bias: SupportsString | None = None,
    divisor: SupportsString | bool = True,
    saturate: bool = True,
    mode: ConvMode = ConvMode.SQUARE,
    premultiply: SupportsString | None = None,
    multiply: SupportsString | None = None,
    clamp: bool = False,
) -> TupleExprList:
    """
    Builds an expression that performs a weighted convolution-like operation.

    Args:
        var: The variable used as the central value
            or elements proportional to the radius if mode is `Literal[ConvMode.TEMPORAL]`.
        matrix: A flat or 2D iterable representing the convolution weights.
        bias: A constant value to add to the result after convolution (default: None).
        divisor: If True, normalizes by the sum of weights; if False, skips division;
            Otherwise, divides by this value.
        saturate: If False, applies `abs()` to avoid negatives.
        mode: The convolution shape.
        premultiply: Optional scalar to multiply the result before normalization.
        multiply: Optional scalar to multiply the result at the end.
        clamp: If True, clamps the final result to [RangeMin, RangeMax].

    Returns:
        A `TupleExprList` representing the expression-based convolution.

    Raises:
        CustomValueError: If matrix length is invalid or doesn't match the mode.
    """
    convolution = list[SupportsSumNoDefaultT](flatten(matrix))

    if not (conv_len := len(convolution)) % 2:
        raise CustomValueError("Convolution length must be odd!", cls.convolution, matrix)
    elif conv_len < 3:
        raise CustomValueError("You must pass at least 3 convolution items!", cls.convolution, matrix)
    elif mode == ConvMode.SQUARE and conv_len != isqrt(conv_len) ** 2:
        raise CustomValueError(
            "With square mode, convolution must represent a horizontal*vertical square (radius*radius n items)!",
            cls.convolution,
        )

    radius = conv_len // 2 if mode != ConvMode.SQUARE else isqrt(conv_len) // 2

    rel_pixels = cls.matrix(var, radius, mode)

    output = TupleExprList(
        [
            ExprList(
                [
                    rel_pix if weight == 1 else [rel_pix, weight, cls.MUL]
                    for rel_pix, weight in zip(rel_px, convolution)
                    if weight != 0
                ]
            )
            for rel_px in rel_pixels
        ]
    )

    for out in output:
        out.extend(cls.ADD * out.mlength)

        if premultiply is not None:
            out.append(premultiply, cls.MUL)

        if divisor is not False:
            div = sum(convolution) if divisor is True else divisor

            if div not in {0, 1}:
                out.append(str(div), cls.DIV)

        if bias is not None:
            out.append(bias, cls.ADD)

        if not saturate:
            out.append(cls.ABS)

        if multiply is not None:
            out.append(multiply, cls.MUL)

        if clamp:
            out.append(cls.clamp(ExprToken.RangeMin, ExprToken.RangeMax))

    return output

is_extra cached

is_extra() -> bool

Check if the operator is an 'extra' operator.

Extra operators are not natively supported by VapourSynth's std.Expr or akarin.Expr and require conversion to a valid equivalent expression.

Returns:

  • bool

    True if the operator is considered extra and requires conversion.

Source code in vsexprtools/exprop.py
702
703
704
705
706
707
708
709
710
711
712
713
@cache
def is_extra(self) -> bool:
    """
    Check if the operator is an 'extra' operator.

    Extra operators are not natively supported by VapourSynth's `std.Expr` or `akarin.Expr`
    and require conversion to a valid equivalent expression.

    Returns:
        True if the operator is considered extra and requires conversion.
    """
    return self.name in ExprOp._extra_op_names_

mae classmethod

Build an expression to compute the Mean Absolute Error (MAE) between two plane sets.

Parameters:

Returns:

  • ExprList

    An ExprList representing the MAE expression across all planes.

Source code in vsexprtools/exprop.py
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
@classmethod
def mae(
    cls,
    planesa: ExprVars | HoldsVideoFormat | VideoFormatLike | SupportsIndex,
    planesb: ExprVars | HoldsVideoFormat | VideoFormatLike | SupportsIndex | None = None,
) -> ExprList:
    """
    Build an expression to compute the Mean Absolute Error (MAE) between two plane sets.

    Args:
        planesa: The first plane set or clip.
        planesb: The second plane set or clip. If None, uses same as `planesa`.

    Returns:
        An `ExprList` representing the MAE expression across all planes.
    """
    planesa, planesb = cls._parse_planes(planesa, planesb, cls.rmse)
    expr = ExprList()

    for a, b in zip(planesa, planesb):
        expr.append([a, b, cls.SUB, cls.ABS])

    expr.append(cls.MAX * expr.mlength)

    return expr

masked_merge classmethod

masked_merge(
    c_a: SupportsString = "",
    c_b: SupportsString = "",
    mask: SupportsString = "",
) -> ExprList

Build a masked merge expression from two inputs and a mask.

Parameters:

  • c_a

    (SupportsString, default: '' ) –

    The first input expression variable.

  • c_b

    (SupportsString, default: '' ) –

    The second input expression variable.

  • mask

    (SupportsString, default: '' ) –

    The mask expression that determines how c_a and c_b are combined.

Returns:

  • ExprList

    An ExprList representing the MaskedMerge expression.

Source code in vsexprtools/exprop.py
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
@classmethod
def masked_merge(cls, c_a: SupportsString = "", c_b: SupportsString = "", mask: SupportsString = "") -> ExprList:
    """
    Build a masked merge expression from two inputs and a mask.

    Args:
        c_a: The first input expression variable.
        c_b: The second input expression variable.
        mask: The mask expression that determines how `c_a` and `c_b` are combined.

    Returns:
        An `ExprList` representing the MaskedMerge expression.
    """
    return ExprList([c_a, c_b, [mask, ExprToken.RangeMax, ExprToken.RangeMin, cls.SUB, cls.DIV], cls.LERP])

matrix classmethod

matrix(
    var: SupportsString | Collection[SupportsString],
    radius: int,
    mode: ConvMode,
    exclude: Iterable[tuple[int, int]] | None = None,
    include: Iterable[tuple[int, int]] | None = None,
) -> TupleExprList

Generate a matrix expression layout for convolution-like operations.

Parameters:

  • var

    (SupportsString | Collection[SupportsString]) –

    The variable representing the central pixel or elements proportional to the radius if mode is Literal[ConvMode.TEMPORAL].

  • radius

    (int) –

    The radius of the kernel in pixels (e.g., 1 for 3x3).

  • mode

    (ConvMode) –

    The convolution mode.

  • exclude

    (Iterable[tuple[int, int]] | None, default: None ) –

    Optional set of (x, y) coordinates to exclude from the matrix.

  • include

    (Iterable[tuple[int, int]] | None, default: None ) –

    Optional set of (x, y) coordinates to include in the matrix.

Returns:

Raises:

  • CustomValueError

    If the input variable is not sized correctly for temporal mode.

  • NotImplementedError

    If the convolution mode is unsupported.

Source code in vsexprtools/exprop.py
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
@classmethod
def matrix(
    cls,
    var: SupportsString | Collection[SupportsString],
    radius: int,
    mode: ConvMode,
    exclude: Iterable[tuple[int, int]] | None = None,
    include: Iterable[tuple[int, int]] | None = None,
) -> TupleExprList:
    """
    Generate a matrix expression layout for convolution-like operations.

    Args:
        var: The variable representing the central pixel
            or elements proportional to the radius if mode is `Literal[ConvMode.TEMPORAL]`.
        radius: The radius of the kernel in pixels (e.g., 1 for 3x3).
        mode: The convolution mode.
        exclude: Optional set of (x, y) coordinates to exclude from the matrix.
        include: Optional set of (x, y) coordinates to include in the matrix.

    Returns:
        A [TupleExprList][vsexprtools.TupleExprList] representing the matrix of expressions.

    Raises:
        CustomValueError: If the input variable is not sized correctly for temporal mode.
        NotImplementedError: If the convolution mode is unsupported.
    """
    match mode:
        case ConvMode.SQUARE:
            coordinates = list(product(range(-radius, radius + 1), range(-radius, radius + 1)))
        case ConvMode.VERTICAL:
            coordinates = [(0, y) for y in range(-radius, radius + 1)]
        case ConvMode.HORIZONTAL:
            coordinates = [(x, 0) for x in range(-radius, radius + 1)]
        case ConvMode.HV:
            return TupleExprList(
                [
                    cls.matrix(var, radius, ConvMode.VERTICAL, exclude, include)[0],
                    cls.matrix(var, radius, ConvMode.HORIZONTAL, exclude, include)[0],
                ]
            )
        case ConvMode.TEMPORAL:
            assert isinstance(var, Collection)

            if len(var) != radius * 2 + 1:
                raise CustomValueError(
                    "`var` must have a number of elements proportional to the radius", cls.matrix, var
                )

            return TupleExprList([ExprList(v for v in var)])
        case _:
            raise NotImplementedError

    assert isinstance(var, SupportsString)

    exclude = list(exclude) if exclude else []
    include = list(include) if include else coordinates

    return TupleExprList(
        [
            ExprList(
                [
                    var if x == y == 0 else ExprOp.REL_PIX(var, x, y)
                    for (x, y) in coordinates
                    if (x, y) not in exclude and (x, y) in include
                ]
            )
        ]
    )

polyval classmethod

polyval(c: SupportsString, *coeffs: SupportsString) -> ExprList

Build an expression to evaluate a polynomial at a given value using Horner's method.

Parameters:

  • c

    (SupportsString) –

    The input expression variable at which the polynomial is evaluated (the 'x' value).

  • *coeffs

    (SupportsString, default: () ) –

    Coefficients of the polynomial. Must provide at least one coefficient.

Returns:

  • ExprList

    An ExprList representing the polyval expression.

Raises:

  • CustomValueError

    If fewer than one coefficient is provided.

Source code in vsexprtools/exprop.py
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
@classmethod
def polyval(cls, c: SupportsString, *coeffs: SupportsString) -> ExprList:
    """
    Build an expression to evaluate a polynomial at a given value using Horner's method.

    Args:
        c: The input expression variable at which the polynomial is evaluated (the 'x' value).
        *coeffs: Coefficients of the polynomial. Must provide at least one coefficient.

    Returns:
        An `ExprList` representing the polyval expression.

    Raises:
        CustomValueError: If fewer than one coefficient is provided.
    """
    if len(coeffs) < 1:
        raise CustomValueError("You must provide at least one coefficient.", cls.polyval, coeffs)

    if b"polyval" in _get_akarin_expr_version()["expr_features"]:
        return ExprList([*coeffs, c, ExprOp.POLYVAL(len(coeffs) - 1)])

    stack_len = len(coeffs) + 1

    expr = ExprList([*coeffs, c, 0])

    for i in range(stack_len, 1, -1):
        expr.append(ExprOp.DUPN(1), ExprOp.MUL, ExprOp.DUPN(i), ExprOp.ADD)

    expr.append(ExprOp.SWAPN(stack_len), ExprOp.DROPN(stack_len))

    return expr

rmse classmethod

Build an expression to compute the Root Mean Squared Error (RMSE) between two plane sets.

Parameters:

Returns:

  • ExprList

    An ExprList representing the RMSE expression across all planes.

Source code in vsexprtools/exprop.py
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
@classmethod
def rmse(
    cls,
    planesa: ExprVars | HoldsVideoFormat | VideoFormatLike | SupportsIndex,
    planesb: ExprVars | HoldsVideoFormat | VideoFormatLike | SupportsIndex | None = None,
) -> ExprList:
    """
    Build an expression to compute the Root Mean Squared Error (RMSE) between two plane sets.

    Args:
        planesa: The first plane set or clip.
        planesb: The second plane set or clip. If None, uses same as `planesa`.

    Returns:
        An `ExprList` representing the RMSE expression across all planes.
    """
    planesa, planesb = cls._parse_planes(planesa, planesb, cls.rmse)

    expr = ExprList()

    for a, b in zip(planesa, planesb):
        expr.append([a, b, cls.SUB, cls.DUP, cls.MUL, cls.SQRT])

    expr.append(cls.MAX * expr.mlength)

    return expr

ExprOpBase

Bases: CustomStrEnum

Base class for expression operators used in RPN expressions.

Methods:

  • __call__

    Combines multiple video clips using the selected expression operator

  • combine

    Combines multiple video clips using the selected expression operator.

Attributes:

  • n_op (int) –

    The number of operands the operator requires.

n_op instance-attribute

n_op: int

The number of operands the operator requires.

__call__

__call__(
    *clips: VideoNodeIterableT[VideoNodeT],
    suffix: SupportsString | Iterable[SupportsString] | None = None,
    prefix: SupportsString | Iterable[SupportsString] | None = None,
    expr_suffix: SupportsString | Iterable[SupportsString] | None = None,
    expr_prefix: SupportsString | Iterable[SupportsString] | None = None,
    planes: Planes = None,
    **kwargs: Any
) -> VideoNodeT
__call__(*pos_args: Any, **kwargs: Any) -> str
__call__(*pos_args: Any, **kwargs: Any) -> VideoNode | str

Combines multiple video clips using the selected expression operator or returns a formatted version of the ExprOp, using substitutions from pos_args and kwargs.

Parameters:

  • *pos_args

    (Any, default: () ) –

    Positional arguments.

  • **kwargs

    (Any, default: {} ) –

    Keywords arguments.

Returns:

  • VideoNode | str

    A clip representing the combined result of applying the expression or formatted version of this ExprOp.

Source code in vsexprtools/exprop.py
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
def __call__(self, *pos_args: Any, **kwargs: Any) -> vs.VideoNode | str:
    """
    Combines multiple video clips using the selected expression operator
    or returns a formatted version of the ExprOp, using substitutions from pos_args and kwargs.

    Args:
        *pos_args: Positional arguments.
        **kwargs: Keywords arguments.

    Returns:
        A clip representing the combined result of applying the expression or formatted version of this ExprOp.
    """
    args = list(flatten(pos_args))

    if args and isinstance(args[0], vs.VideoNode):
        return self.combine(*args, **kwargs)

    while True:
        try:
            return self.format(*args, **kwargs)
        except KeyError as key:
            if not args:
                raise
            kwargs[key.args[0]] = args.pop(0)

combine

combine(
    *clips: VideoNode | Iterable[VideoNode | Iterable[VideoNode]],
    suffix: SupportsString | Iterable[SupportsString] | None = None,
    prefix: SupportsString | Iterable[SupportsString] | None = None,
    expr_suffix: SupportsString | Iterable[SupportsString] | None = None,
    expr_prefix: SupportsString | Iterable[SupportsString] | None = None,
    planes: Planes = None,
    **kwargs: Any
) -> ConstantFormatVideoNode

Combines multiple video clips using the selected expression operator.

Parameters:

  • clips

    (VideoNode | Iterable[VideoNode | Iterable[VideoNode]], default: () ) –

    Input clip(s).

  • suffix

    (SupportsString | Iterable[SupportsString] | None, default: None ) –

    Optional suffix string(s) to append to each input variable in the expression.

  • prefix

    (SupportsString | Iterable[SupportsString] | None, default: None ) –

    Optional prefix string(s) to prepend to each input variable in the expression.

  • expr_suffix

    (SupportsString | Iterable[SupportsString] | None, default: None ) –

    Optional expression to append after the combined input expression.

  • expr_prefix

    (SupportsString | Iterable[SupportsString] | None, default: None ) –

    Optional expression to prepend before the combined input expression.

  • planes

    (Planes, default: None ) –

    Which planes to process. Defaults to all.

  • **kwargs

    (Any, default: {} ) –

    Additional keyword arguments forwarded to combine.

Returns:

  • ConstantFormatVideoNode

    A clip representing the combined result of applying the expression.

Source code in vsexprtools/exprop.py
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
def combine(
    self,
    *clips: vs.VideoNode | Iterable[vs.VideoNode | Iterable[vs.VideoNode]],
    suffix: SupportsString | Iterable[SupportsString] | None = None,
    prefix: SupportsString | Iterable[SupportsString] | None = None,
    expr_suffix: SupportsString | Iterable[SupportsString] | None = None,
    expr_prefix: SupportsString | Iterable[SupportsString] | None = None,
    planes: Planes = None,
    **kwargs: Any,
) -> ConstantFormatVideoNode:
    """
    Combines multiple video clips using the selected expression operator.

    Args:
        clips: Input clip(s).
        suffix: Optional suffix string(s) to append to each input variable in the expression.
        prefix: Optional prefix string(s) to prepend to each input variable in the expression.
        expr_suffix: Optional expression to append after the combined input expression.
        expr_prefix: Optional expression to prepend before the combined input expression.
        planes: Which planes to process. Defaults to all.
        **kwargs: Additional keyword arguments forwarded to [combine][vsexprtools.combine].

    Returns:
        A clip representing the combined result of applying the expression.
    """
    from .funcs import combine

    return combine(clips, self, suffix, prefix, expr_suffix, expr_prefix, planes, **kwargs)

ExprOpExtraMeta

Bases: EnumMeta

ExprToken

Bases: CustomStrEnum

Enumeration for symbolic constants used in norm_expr.

Methods:

  • get_value

    Resolves the numeric value represented by this token based on the input clip and range.

Attributes:

ChromaMax class-attribute instance-attribute

ChromaMax = 'cmax'

ChromaMin class-attribute instance-attribute

ChromaMin = 'cmin'

ChromaRangeInMax class-attribute instance-attribute

ChromaRangeInMax = 'crange_in_max'

ChromaRangeInMin class-attribute instance-attribute

ChromaRangeInMin = 'crange_in_min'

ChromaRangeMax class-attribute instance-attribute

ChromaRangeMax = 'crange_max'

ChromaRangeMin class-attribute instance-attribute

ChromaRangeMin = 'crange_min'

LumaMax class-attribute instance-attribute

LumaMax = 'ymax'

LumaMin class-attribute instance-attribute

LumaMin = 'ymin'

LumaRangeInMax class-attribute instance-attribute

LumaRangeInMax = 'yrange_in_max'

LumaRangeInMin class-attribute instance-attribute

LumaRangeInMin = 'yrange_in_min'

LumaRangeMax class-attribute instance-attribute

LumaRangeMax = 'yrange_max'

LumaRangeMin class-attribute instance-attribute

LumaRangeMin = 'yrange_min'

MaskMax class-attribute instance-attribute

MaskMax = 'mask_max'

Maximum value in mask clips.

Neutral class-attribute instance-attribute

Neutral = 'neutral'

Neutral value (e.g. 128 for 8-bit limited, 0 for float).

PlaneMax class-attribute instance-attribute

PlaneMax = 'plane_max'

Maximum value in the clip's range (chroma-aware).

PlaneMin class-attribute instance-attribute

PlaneMin = 'plane_min'

Minimum value in the clip's range (chroma-aware).

RangeHalf class-attribute instance-attribute

RangeHalf = 'range_half'

RangeInMax class-attribute instance-attribute

RangeInMax = 'range_in_max'

RangeInMin class-attribute instance-attribute

RangeInMin = 'range_in_min'

RangeMax class-attribute instance-attribute

RangeMax = 'range_max'

Maximum value in full range (chroma-aware).

RangeMin class-attribute instance-attribute

RangeMin = 'range_min'

Minimum value in full range (chroma-aware).

RangeSize class-attribute instance-attribute

RangeSize = 'range_size'

Size of the full range (e.g. 256 for 8-bit, 65536 for 16-bit).

get_value cached

get_value(
    clip: VideoNode, chroma: bool = False, range_in: ColorRange | None = None
) -> float

Resolves the numeric value represented by this token based on the input clip and range.

Parameters:

  • clip

    (VideoNode) –

    A clip used to determine bit depth and format.

  • chroma

    (bool, default: False ) –

    Optional override for whether to treat the token as chroma-related.

  • range_in

    (ColorRange | None, default: None ) –

    Optional override for the color range.

Returns:

  • float

    The value corresponding to the symbolic token.

Source code in vsexprtools/exprop.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
@cache
def get_value(self, clip: vs.VideoNode, chroma: bool = False, range_in: ColorRange | None = None) -> float:
    """
    Resolves the numeric value represented by this token based on the input clip and range.

    Args:
        clip: A clip used to determine bit depth and format.
        chroma: Optional override for whether to treat the token as chroma-related.
        range_in: Optional override for the color range.

    Returns:
        The value corresponding to the symbolic token.
    """
    assert check_variable(clip, self.get_value)

    if self is ExprToken.PlaneMin:
        return get_lowest_value(clip, chroma, range_in)

    if self is ExprToken.PlaneMax:
        return get_peak_value(clip, chroma, range_in)

    if self is ExprToken.MaskMax:
        return get_peak_value(clip, range_in=ColorRange.FULL)

    if self is ExprToken.Neutral:
        return get_neutral_value(clip)

    if self is ExprToken.RangeMin:
        return get_lowest_value(clip, chroma, ColorRange.FULL)

    if self is ExprToken.RangeMax:
        return get_peak_value(clip, chroma, ColorRange.FULL)

    if self is ExprToken.RangeSize:
        val = get_peak_value(clip, range_in=ColorRange.FULL)
        return val if clip.format.sample_type is vs.FLOAT else val + 1

    # TODO: remove this
    warnings.warn(
        f"This {self.name} ExprToken is deprecated and will be removed in a future version.", _TokenDeprecation
    )

    if self is ExprToken.LumaMin:
        return get_lowest_value(clip, False, ColorRange.LIMITED)

    if self is ExprToken.ChromaMin:
        return get_lowest_value(clip, True, ColorRange.LIMITED)

    if self is ExprToken.LumaMax:
        return get_peak_value(clip, False, ColorRange.LIMITED)

    if self is ExprToken.ChromaMax:
        return get_peak_value(clip, True, ColorRange.LIMITED)

    if self is ExprToken.RangeHalf:
        val = get_peak_value(clip, range_in=ColorRange.FULL)
        return (val + 1) / 2 if val > 1.0 else val

    if self is ExprToken.LumaRangeMin:
        return get_lowest_value(clip, False)

    if self is ExprToken.ChromaRangeMin:
        return get_lowest_value(clip, True)

    if self is ExprToken.LumaRangeMax:
        return get_peak_value(clip, False)

    if self is ExprToken.ChromaRangeMax:
        return get_peak_value(clip, True)

    if self is ExprToken.RangeInMin:
        return get_lowest_value(clip, chroma if chroma is not None else False, range_in)

    if self is ExprToken.LumaRangeInMin:
        return get_lowest_value(clip, False, range_in)

    if self is ExprToken.ChromaRangeInMin:
        return get_lowest_value(clip, True, range_in)

    if self is ExprToken.RangeInMax:
        return get_peak_value(clip, chroma if chroma is not None else False, range_in)

    if self is ExprToken.LumaRangeInMax:
        return get_peak_value(clip, False, range_in)

    if self is ExprToken.ChromaRangeInMax:
        return get_peak_value(clip, True, range_in)

    raise NotImplementedError

TupleExprList

Bases: tuple[ExprList, ...]

A tuple of multiple ExprList expressions, applied sequentially to the clip(s).

Methods:

  • __call__

    Apply a sequence of expressions to the input clip(s), one after another.

__call__

__call__(
    *clips: VideoNodeIterableT[VideoNode],
    planes: Planes = None,
    format: HoldsVideoFormat | VideoFormatLike | None = None,
    opt: bool = False,
    boundary: bool = True,
    func: FuncExcept | None = None,
    split_planes: bool = False,
    **kwargs: Any
) -> ConstantFormatVideoNode

Apply a sequence of expressions to the input clip(s), one after another.

Each ExprList in the tuple is applied to the result of the previous one.

Parameters:

  • clips

    (VideoNodeIterableT[VideoNode], default: () ) –

    Input clip(s).

  • planes

    (Planes, default: None ) –

    Plane to process, defaults to all.

  • format

    (HoldsVideoFormat | VideoFormatLike | None, default: None ) –

    Output format, defaults to the first clip format.

  • opt

    (bool, default: False ) –

    Forces integer evaluation as much as possible.

  • boundary

    (bool, default: True ) –

    Specifies the default boundary condition for relative pixel accesses:

    • True (default): Mirrored edges.
    • False: Clamped edges.
  • func

    (FuncExcept | None, default: None ) –

    Function returned for custom error handling. This should only be set by VS package developers.

  • split_planes

    (bool, default: False ) –

    Splits the VideoNodes into their individual planes.

  • kwargs

    (Any, default: {} ) –

    Extra keyword arguments passed to each ExprList.

Returns:

  • ConstantFormatVideoNode

    Evaluated clip.

Raises:

  • CustomRuntimeError

    If the TupleExprList is empty.

Source code in vsexprtools/exprop.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
def __call__(
    self,
    *clips: VideoNodeIterableT[vs.VideoNode],
    planes: Planes = None,
    format: HoldsVideoFormat | VideoFormatLike | None = None,
    opt: bool = False,
    boundary: bool = True,
    func: FuncExcept | None = None,
    split_planes: bool = False,
    **kwargs: Any,
) -> ConstantFormatVideoNode:
    """
    Apply a sequence of expressions to the input clip(s), one after another.

    Each `ExprList` in the tuple is applied to the result of the previous one.

    Args:
        clips: Input clip(s).
        planes: Plane to process, defaults to all.
        format: Output format, defaults to the first clip format.
        opt: Forces integer evaluation as much as possible.
        boundary: Specifies the default boundary condition for relative pixel accesses:

               - True (default): Mirrored edges.
               - False: Clamped edges.
        func: Function returned for custom error handling. This should only be set by VS package developers.
        split_planes: Splits the VideoNodes into their individual planes.
        kwargs: Extra keyword arguments passed to each `ExprList`.

    Returns:
        Evaluated clip.

    Raises:
        CustomRuntimeError: If the `TupleExprList` is empty.
    """
    if len(self) < 1:
        raise CustomRuntimeError("You need at least one ExprList.", func, self)

    clip = flatten_vnodes(*clips)

    for exprlist in self:
        clip = exprlist(
            clip,
            planes=planes,
            format=format,
            opt=opt,
            boundary=boundary,
            func=func,
            split_planes=split_planes,
            **kwargs,
        )

    return clip[0] if isinstance(clip, Sequence) else clip  # type: ignore[return-value]