1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 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 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 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
|
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward/blob/main/LICENSE
from __future__ import annotations
import numpy
import pytest
import awkward as ak
def test():
class SuperVector:
def add(self, other):
"""Add two vectors together elementwise using `x` and `y` components"""
return ak.zip(
{"x": self.x + other.x, "y": self.y + other.y},
with_name="VectorTwoD",
behavior=self.behavior,
)
# first sub-class
@ak.mixin_class(ak.behavior)
class VectorTwoD(SuperVector):
def __eq__(self, other):
return ak.all(self.x == other.x) and ak.all(self.y == other.y)
v = ak.Array(
[
[{"x": 1, "y": 1.1}, {"x": 2, "y": 2.2}],
[],
[{"x": 3, "y": 3.3}],
[
{"x": 4, "y": 4.4},
{"x": 5, "y": 5.5},
{"x": 6, "y": 6.6},
],
],
with_name="VectorTwoD",
behavior=ak.behavior,
)
v_added = ak.Array(
[
[{"x": 2, "y": 2.2}, {"x": 4, "y": 4.4}],
[],
[{"x": 6, "y": 6.6}],
[
{"x": 8, "y": 8.8},
{"x": 10, "y": 11},
{"x": 12, "y": 13.2},
],
],
with_name="VectorTwoD",
behavior=ak.behavior,
)
# add method works but the binary operator does not
assert v.add(v) == v_added
with pytest.raises(TypeError):
v + v
# registering the operator makes everything work
ak.behavior[numpy.add, "VectorTwoD", "VectorTwoD"] = lambda v1, v2: v1.add(v2)
assert v + v == v_added
# instead of registering every operator again, just copy the behaviors of
# another class to this class
ak.behavior.update(
ak._util.copy_behaviors("VectorTwoD", "VectorTwoDAgain", ak.behavior)
)
# second sub-class
@ak.mixin_class(ak.behavior)
class VectorTwoDAgain(VectorTwoD):
pass
v = ak.Array(
[
[{"x": 1, "y": 1.1}, {"x": 2, "y": 2.2}],
[],
[{"x": 3, "y": 3.3}],
[
{"x": 4, "y": 4.4},
{"x": 5, "y": 5.5},
{"x": 6, "y": 6.6},
],
],
with_name="VectorTwoDAgain",
behavior=ak.behavior,
)
assert v.add(v) == v_added
assert v + v == v_added
# instead of registering every operator again, just copy the behaviors of
# another class to this class
ak.behavior.update(
ak._util.copy_behaviors("VectorTwoDAgain", "VectorTwoDAgainAgain", ak.behavior)
)
# third sub-class
@ak.mixin_class(ak.behavior)
class VectorTwoDAgainAgain(VectorTwoDAgain):
pass
v = ak.Array(
[
[{"x": 1, "y": 1.1}, {"x": 2, "y": 2.2}],
[],
[{"x": 3, "y": 3.3}],
[
{"x": 4, "y": 4.4},
{"x": 5, "y": 5.5},
{"x": 6, "y": 6.6},
],
],
with_name="VectorTwoDAgainAgain",
behavior=ak.behavior,
)
assert v.add(v) == v_added
assert v + v == v_added
|