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

ExprList(iterable: Iterable[SupportsString | None] | None = ...)

Bases: StrList

A list-based representation of a RPN expression.

Methods:

Attributes:

Source code in jetpytools/types/funcs.py
20
def __init__(self, iterable: Iterable[SupportsString | None] | None = ..., /) -> None: ...

mlength property

mlength: int

string property

string: str

__call__

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

Apply the expression to one or more input clips.

Parameters:

  • clips

    (VideoNodeIterable, 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:

  • VideoNode

    Evaluated clip.

Source code in vsexprtools/exprop.py
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
def __call__(
    self,
    *clips: VideoNodeIterable,
    planes: Planes = None,
    format: HoldsVideoFormat | VideoFormatLike | None = None,
    opt: bool = False,
    boundary: bool = True,
    func: FuncExcept | None = None,
    split_planes: bool = False,
    **kwargs: Any,
) -> vs.VideoNode:
    """
    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)

append

append(*__object: SupportsString) -> None
Source code in jetpytools/types/funcs.py
47
48
49
def append(self, *__object: SupportsString) -> None:
    for __obj in __object:
        super().append(__obj)

to_str

to_str() -> str
Source code in jetpytools/types/funcs.py
26
27
def to_str(self) -> str:
    return str(self)

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 or returns a formatted version

  • acos

    Build an expression to approximate arccosine using an identity: acos(x) = π/2 - asin(x)

  • asin

    Build an expression to approximate arcsine using an identity: asin(x) = atan(x / sqrt(1 - x²))

  • 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.

  • combine_expr

    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.

  • from_param

    Return the enum value from a parameter.

  • 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.

  • value

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: VideoNodeIterable,
    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
) -> VideoNode
__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

  • VideoNode | str

    or formatted version of this ExprOp.

Source code in vsexprtools/exprop.py
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
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][vsexprtools.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][vsexprtools.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:

Source code in vsexprtools/exprop.py
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
@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][vsexprtools.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:

Source code in vsexprtools/exprop.py
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
@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][vsexprtools.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:

Source code in vsexprtools/exprop.py
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
@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][vsexprtools.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 ExprOp.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:

Source code in vsexprtools/exprop.py
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
@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 [ExprOp.atan][vsexprtools.ExprOp.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][vsexprtools.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:

Source code in vsexprtools/exprop.py
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
@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][vsexprtools.ExprList] containing the clamping expression.
    """
    return ExprList([c, min, max, ExprOp.CLAMP])

combine

Combines multiple video clips using the selected expression operator.

Parameters:

Returns:

  • VideoNode

    A clip representing the combined result of applying the expression.

Source code in vsexprtools/exprop.py
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
def combine(
    self,
    *clips: VideoNodeIterable,
    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,
) -> vs.VideoNode:
    """
    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)

combine_expr

Combines multiple video clips using the selected expression operator.

Parameters:

Returns:

  • ExprList

    A clip representing the combined result of applying the expression.

Source code in vsexprtools/exprop.py
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
def combine_expr(
    self,
    n: SupportsIndex | Sequence[SupportsString] | HoldsVideoFormat | VideoFormatLike,
    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,
) -> ExprList:
    """
    Combines multiple video clips using the selected expression operator.

    Args:
        n: Object from which to infer the variables.
        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.

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

    return combine_expr(n, self, suffix, prefix, expr_suffix, expr_prefix)

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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
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 * -"
        case ExprOp.POLYVAL:
            assert degree is not None
            return self.polyval("", *[""] * (degree + 1)).to_str()
        case _:
            raise NotImplementedError

convolution classmethod

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:

Raises:

Source code in vsexprtools/exprop.py
777
778
779
780
781
782
783
784
785
786
787
788
789
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
859
860
861
862
863
864
865
@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][vsexprtools.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 and multiply != 1.0:
            out.append(multiply, cls.MUL)

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

    return output

from_param classmethod

from_param(value: Any, func_except: FuncExcept | None = None) -> Self

Return the enum value from a parameter.

Parameters:

  • value

    (Any) –

    Value to instantiate the enum class.

  • func_except

    (FuncExcept | None, default: None ) –

    Exception function.

Returns:

  • Self

    Enum value.

Raises:

Source code in jetpytools/enums/base.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
@classmethod
def from_param(cls, value: Any, func_except: FuncExcept | None = None) -> Self:
    """
    Return the enum value from a parameter.

    Args:
        value: Value to instantiate the enum class.
        func_except: Exception function.

    Returns:
        Enum value.

    Raises:
        NotFoundEnumValue: Variable not found in the given enum.
    """
    func_except = func_except or cls.from_param

    try:
        return cls(value)
    except (ValueError, TypeError):
        pass

    if isinstance(func_except, tuple):
        func_name, var_name = func_except
    else:
        func_name, var_name = func_except, repr(cls)

    raise NotFoundEnumValueError(
        'The given value for "{var_name}" argument must be a valid {enum_name}, not "{value}"!\n'
        "Valid values are: [{readable_enum}].",
        func_name,
        var_name=var_name,
        enum_name=cls,
        value=value,
        readable_enum=(f"{name} ({value!r})" for name, value in cls.__members__.items()),
        reason=value,
    ) from None

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
619
620
621
622
623
624
625
626
627
628
629
630
@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:

Source code in vsexprtools/exprop.py
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
@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][vsexprtools.ExprList] representing the MAE expression across all planes.
    """
    planesa, planesb = cls._parse_planes(planesa, planesb, cls.mae)
    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:

Source code in vsexprtools/exprop.py
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
@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][vsexprtools.ExprList] representing the MaskedMerge expression.
    """
    return ExprList([c_a, c_b, [mask, ExprToken.RangeMax, ExprToken.RangeMin, cls.SUB, cls.DIV], cls.LERP])

matrix classmethod

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:

Source code in vsexprtools/exprop.py
707
708
709
710
711
712
713
714
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
772
773
774
775
@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 = [(x, y) for (y, x) in product(range(-radius, radius + 1), repeat=2)]
        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

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:

Raises:

Source code in vsexprtools/exprop.py
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
@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][vsexprtools.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:

Source code in vsexprtools/exprop.py
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
@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][vsexprtools.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

value

value() -> str
Source code in jetpytools/enums/base.py
97
98
@enum_property
def value(self) -> str: ...

ExprOpBase

Bases: CustomStrEnum

Base class for expression operators used in RPN expressions.

Methods:

  • __call__

    Combines multiple video clips using the selected expression operator or returns a formatted version

  • combine

    Combines multiple video clips using the selected expression operator.

  • combine_expr

    Combines multiple video clips using the selected expression operator.

  • from_param

    Return the enum value from a parameter.

  • value

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: VideoNodeIterable,
    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
) -> VideoNode
__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

  • VideoNode | str

    or formatted version of this ExprOp.

Source code in vsexprtools/exprop.py
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
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][vsexprtools.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][vsexprtools.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

Combines multiple video clips using the selected expression operator.

Parameters:

Returns:

  • VideoNode

    A clip representing the combined result of applying the expression.

Source code in vsexprtools/exprop.py
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
def combine(
    self,
    *clips: VideoNodeIterable,
    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,
) -> vs.VideoNode:
    """
    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)

combine_expr

Combines multiple video clips using the selected expression operator.

Parameters:

Returns:

  • ExprList

    A clip representing the combined result of applying the expression.

Source code in vsexprtools/exprop.py
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
def combine_expr(
    self,
    n: SupportsIndex | Sequence[SupportsString] | HoldsVideoFormat | VideoFormatLike,
    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,
) -> ExprList:
    """
    Combines multiple video clips using the selected expression operator.

    Args:
        n: Object from which to infer the variables.
        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.

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

    return combine_expr(n, self, suffix, prefix, expr_suffix, expr_prefix)

from_param classmethod

from_param(value: Any, func_except: FuncExcept | None = None) -> Self

Return the enum value from a parameter.

Parameters:

  • value

    (Any) –

    Value to instantiate the enum class.

  • func_except

    (FuncExcept | None, default: None ) –

    Exception function.

Returns:

  • Self

    Enum value.

Raises:

Source code in jetpytools/enums/base.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
@classmethod
def from_param(cls, value: Any, func_except: FuncExcept | None = None) -> Self:
    """
    Return the enum value from a parameter.

    Args:
        value: Value to instantiate the enum class.
        func_except: Exception function.

    Returns:
        Enum value.

    Raises:
        NotFoundEnumValue: Variable not found in the given enum.
    """
    func_except = func_except or cls.from_param

    try:
        return cls(value)
    except (ValueError, TypeError):
        pass

    if isinstance(func_except, tuple):
        func_name, var_name = func_except
    else:
        func_name, var_name = func_except, repr(cls)

    raise NotFoundEnumValueError(
        'The given value for "{var_name}" argument must be a valid {enum_name}, not "{value}"!\n'
        "Valid values are: [{readable_enum}].",
        func_name,
        var_name=var_name,
        enum_name=cls,
        value=value,
        readable_enum=(f"{name} ({value!r})" for name, value in cls.__members__.items()),
        reason=value,
    ) from None

value

value() -> str
Source code in jetpytools/enums/base.py
97
98
@enum_property
def value(self) -> str: ...

ExprOpExtraMeta

Bases: EnumMeta

ExprToken

Bases: CustomStrEnum

Enumeration for symbolic constants used in norm_expr.

Methods:

  • from_param

    Return the enum value from a parameter.

  • get_value

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

  • value

Attributes:

  • MaskMax

    Maximum value in mask clips.

  • Neutral

    Neutral value for chroma & MakeDiff/MergeDiff (e.g. 128 for 8-bit, 0 for float).

  • PlaneMax

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

  • PlaneMin

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

  • RangeMax

    Maximum value in full range (chroma-aware).

  • RangeMin

    Minimum value in full range (chroma-aware).

  • RangeSize

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

MaskMax class-attribute instance-attribute

MaskMax = 'mask_max'

Maximum value in mask clips.

Neutral class-attribute instance-attribute

Neutral = 'neutral'

Neutral value for chroma & MakeDiff/MergeDiff (e.g. 128 for 8-bit, 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).

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).

from_param classmethod

from_param(value: Any, func_except: FuncExcept | None = None) -> Self

Return the enum value from a parameter.

Parameters:

  • value

    (Any) –

    Value to instantiate the enum class.

  • func_except

    (FuncExcept | None, default: None ) –

    Exception function.

Returns:

  • Self

    Enum value.

Raises:

Source code in jetpytools/enums/base.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
@classmethod
def from_param(cls, value: Any, func_except: FuncExcept | None = None) -> Self:
    """
    Return the enum value from a parameter.

    Args:
        value: Value to instantiate the enum class.
        func_except: Exception function.

    Returns:
        Enum value.

    Raises:
        NotFoundEnumValue: Variable not found in the given enum.
    """
    func_except = func_except or cls.from_param

    try:
        return cls(value)
    except (ValueError, TypeError):
        pass

    if isinstance(func_except, tuple):
        func_name, var_name = func_except
    else:
        func_name, var_name = func_except, repr(cls)

    raise NotFoundEnumValueError(
        'The given value for "{var_name}" argument must be a valid {enum_name}, not "{value}"!\n'
        "Valid values are: [{readable_enum}].",
        func_name,
        var_name=var_name,
        enum_name=cls,
        value=value,
        readable_enum=(f"{name} ({value!r})" for name, value in cls.__members__.items()),
        reason=value,
    ) from None

get_value cached

get_value(
    clip: VideoNode,
    chroma: bool = False,
    range_in: ColorRangeLike | 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

    (ColorRangeLike | None, default: None ) –

    Optional override for the color range.

Returns:

  • float

    The value corresponding to the symbolic token.

Source code in vsexprtools/exprop.py
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
@cache
def get_value(self, clip: vs.VideoNode, chroma: bool = False, range_in: ColorRangeLike | 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.
    """
    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

    raise NotImplementedError

value

value() -> str
Source code in jetpytools/enums/base.py
97
98
@enum_property
def value(self) -> str: ...

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: VideoNodeIterable,
    planes: Planes = None,
    format: HoldsVideoFormat | VideoFormatLike | None = None,
    opt: bool = False,
    boundary: bool = True,
    func: FuncExcept | None = None,
    split_planes: bool = False,
    **kwargs: Any
) -> VideoNode

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

    (VideoNodeIterable, 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:

  • VideoNode

    Evaluated clip.

Raises:

Source code in vsexprtools/exprop.py
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def __call__(
    self,
    *clips: VideoNodeIterable,
    planes: Planes = None,
    format: HoldsVideoFormat | VideoFormatLike | None = None,
    opt: bool = False,
    boundary: bool = True,
    func: FuncExcept | None = None,
    split_planes: bool = False,
    **kwargs: Any,
) -> vs.VideoNode:
    """
    Apply a sequence of expressions to the input clip(s), one after another.

    Each [ExprList][vsexprtools.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][vsexprtools.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