Skip to content

Arrays

Fixed-size bounded array circuits and traceable array utilities.

concrete_fhe_toolkit.arrays

Fixed-size bounded array operations for Concrete FHE.

array_add

array_add(array1: Union[ndarray, List[Any]], array2: Union[ndarray, List[Any]]) -> Any

Perform element-wise addition of two encrypted arrays.

Parameters:

Name Type Description Default
array1 Union[ndarray, List[Any]]

The first encrypted array.

required
array2 Union[ndarray, List[Any]]

The second encrypted array.

required

Returns:

Name Type Description
Any Any

The element-wise sum of the two arrays.

Example
from concrete_fhe_toolkit import array_add

print(array_add([1, 2], [3, 4]))  # [4, 6]
Source code in src/concrete_fhe_toolkit/arrays/arithmetic.py
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def array_add(array1: Union[np.ndarray, List[Any]],array2: Union[np.ndarray, List[Any]]) -> Any:
    """Perform element-wise addition of two encrypted arrays.

    Args:
        array1 (Union[np.ndarray, List[Any]]): The first encrypted array.
        array2 (Union[np.ndarray, List[Any]]): The second encrypted array.

    Returns:
        Any: The element-wise sum of the two arrays.

    Example:
        ```python
        from concrete_fhe_toolkit import array_add

        print(array_add([1, 2], [3, 4]))  # [4, 6]
        ```
    """
    return _ensure_tensor(array1) + _ensure_tensor(array2)

array_multiply

array_multiply(array1: Union[ndarray, List[Any]], array2: Union[ndarray, List[Any]]) -> Any

Perform element-wise multiplication of two encrypted arrays.

Parameters:

Name Type Description Default
array1 Union[ndarray, List[Any]]

The first encrypted array.

required
array2 Union[ndarray, List[Any]]

The second encrypted array.

required

Returns:

Name Type Description
Any Any

The element-wise product of the two arrays.

Example
from concrete_fhe_toolkit import array_multiply

print(array_multiply([1, 2], [3, 4]))  # [3, 8]
Source code in src/concrete_fhe_toolkit/arrays/arithmetic.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def array_multiply(array1: Union[np.ndarray, List[Any]],array2: Union[np.ndarray, List[Any]]) -> Any:
    """Perform element-wise multiplication of two encrypted arrays.

    Args:
        array1 (Union[np.ndarray, List[Any]]): The first encrypted array.
        array2 (Union[np.ndarray, List[Any]]): The second encrypted array.

    Returns:
        Any: The element-wise product of the two arrays.

    Example:
        ```python
        from concrete_fhe_toolkit import array_multiply

        print(array_multiply([1, 2], [3, 4]))  # [3, 8]
        ```
    """
    return _ensure_tensor(array1) * _ensure_tensor(array2)

array_scale

array_scale(array: Union[ndarray, List[Any]], factor: int) -> Union[np.ndarray, List[Any]]

Multiply every element of an encrypted array by a scalar constant.

Parameters:

Name Type Description Default
array Union[ndarray, List[Any]]

The encrypted array or list of elements.

required
factor int

The scalar constant to multiply by.

required

Returns:

Type Description
Union[ndarray, List[Any]]

Union[np.ndarray, List[Any]]: The scaled array.

Example
from concrete_fhe_toolkit import array_scale

print(array_scale([1, 2, 3], factor=3))  # [3, 6, 9]
Source code in src/concrete_fhe_toolkit/arrays/arithmetic.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def array_scale(array: Union[np.ndarray, List[Any]],factor: int) -> Union[np.ndarray, List[Any]]:
    """Multiply every element of an encrypted array by a scalar constant.

    Args:
        array (Union[np.ndarray, List[Any]]): The encrypted array or list of elements.
        factor (int): The scalar constant to multiply by.

    Returns:
        Union[np.ndarray, List[Any]]: The scaled array.

    Example:
        ```python
        from concrete_fhe_toolkit import array_scale

        print(array_scale([1, 2, 3], factor=3))  # [3, 6, 9]
        ```
    """
    return _ensure_tensor(array) * factor

array_sub

array_sub(array1: Union[ndarray, List[Any]], array2: Union[ndarray, List[Any]]) -> Any

Perform element-wise subtraction of two encrypted arrays.

Parameters:

Name Type Description Default
array1 Union[ndarray, List[Any]]

The first encrypted array.

required
array2 Union[ndarray, List[Any]]

The second encrypted array.

required

Returns:

Name Type Description
Any Any

The element-wise difference between the two arrays.

Example
from concrete_fhe_toolkit import array_sub

print(array_sub([5, 5], [2, 1]))  # [3, 4]
Source code in src/concrete_fhe_toolkit/arrays/arithmetic.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def array_sub(array1: Union[np.ndarray, List[Any]],array2: Union[np.ndarray, List[Any]]) -> Any:
    """Perform element-wise subtraction of two encrypted arrays.

    Args:
        array1 (Union[np.ndarray, List[Any]]): The first encrypted array.
        array2 (Union[np.ndarray, List[Any]]): The second encrypted array.

    Returns:
        Any: The element-wise difference between the two arrays.

    Example:
        ```python
        from concrete_fhe_toolkit import array_sub

        print(array_sub([5, 5], [2, 1]))  # [3, 4]
        ```
    """
    return _ensure_tensor(array1) - _ensure_tensor(array2)

array_sum

array_sum(elements: Union[ndarray, List[Any]]) -> Any

Calculate the sum of all elements in an encrypted array using a tournament reduction.

Parameters:

Name Type Description Default
elements Union[ndarray, List[Any]]

The encrypted array or list of elements.

required

Returns:

Name Type Description
Any Any

The computed encrypted sum of all elements in the array.

Example
from concrete_fhe_toolkit import array_sum

print(array_sum([1, 2, 3, 4]))  # 10
Source code in src/concrete_fhe_toolkit/arrays/arithmetic.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
def array_sum(elements: Union[np.ndarray, List[Any]]) -> Any:
    """Calculate the sum of all elements in an encrypted array using a tournament reduction.

    Args:
        elements (Union[np.ndarray, List[Any]]): The encrypted array or list of elements.

    Returns:
        Any: The computed encrypted sum of all elements in the array.

    Example:
        ```python
        from concrete_fhe_toolkit import array_sum

        print(array_sum([1, 2, 3, 4]))  # 10
        ```
    """
    total = np.sum(_ensure_tensor(elements))
    return total

array_all_equal

array_all_equal(array1: Union[ndarray, List[Any]], array2: Union[ndarray, List[Any]]) -> Any

Check if two encrypted arrays are identical (returns 1 or 0).

Parameters:

Name Type Description Default
array1 Union[ndarray, List[Any]]

The first encrypted array.

required
array2 Union[ndarray, List[Any]]

The second encrypted array.

required

Returns:

Name Type Description
Any Any

1 if all elements are equal, 0 otherwise.

Example
from concrete_fhe_toolkit import array_all_equal

print(array_all_equal([1, 2], [1, 2]))  # 1
Source code in src/concrete_fhe_toolkit/arrays/manipulation.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def array_all_equal(array1: Union[np.ndarray, List[Any]], array2: Union[np.ndarray, List[Any]]) -> Any:
    """Check if two encrypted arrays are identical (returns 1 or 0).

    Args:
        array1 (Union[np.ndarray, List[Any]]): The first encrypted array.
        array2 (Union[np.ndarray, List[Any]]): The second encrypted array.

    Returns:
        Any: 1 if all elements are equal, 0 otherwise.

    Example:
        ```python
        from concrete_fhe_toolkit import array_all_equal

        print(array_all_equal([1, 2], [1, 2]))  # 1
        ```
    """
    tensor1 = _ensure_tensor(array1)
    tensor2 = _ensure_tensor(array2)

    return np.sum(tensor1 == tensor2) == len(tensor1)

array_concat

array_concat(*arrays: Union[ndarray, List[Any]]) -> Union[np.ndarray, List[Any]]

Concatenate encrypted arrays along their public length.

Parameters:

Name Type Description Default
*arrays Union[ndarray, List[Any]]

A variable number of arrays to concatenate.

()

Returns:

Type Description
Union[ndarray, List[Any]]

Union[np.ndarray, List[Any]]: The concatenated array.

Example
from concrete_fhe_toolkit import array_concat

print(array_concat([1, 2], [3, 4]))  # [1, 2, 3, 4]
Source code in src/concrete_fhe_toolkit/arrays/manipulation.py
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def array_concat(*arrays: Union[np.ndarray, List[Any]]) -> Union[np.ndarray, List[Any]]:
    """Concatenate encrypted arrays along their public length.

    Args:
        *arrays (Union[np.ndarray, List[Any]]): A variable number of arrays to concatenate.

    Returns:
        Union[np.ndarray, List[Any]]: The concatenated array.

    Example:
        ```python
        from concrete_fhe_toolkit import array_concat

        print(array_concat([1, 2], [3, 4]))  # [1, 2, 3, 4]
        ```
    """
    combined: List[Any] = []
    for array in arrays:
        combined.extend(list(array))
    return fhe.array(combined)

array_cumsum

array_cumsum(array: Union[ndarray, List[Any]]) -> Union[np.ndarray, List[Any]]

Return the running prefix sums of an encrypted array.

Parameters:

Name Type Description Default
array Union[ndarray, List[Any]]

The encrypted array or list of elements.

required

Returns:

Type Description
Union[ndarray, List[Any]]

Union[np.ndarray, List[Any]]: The array of prefix sums.

Example
from concrete_fhe_toolkit import array_cumsum

print(array_cumsum([1, 2, 3]))  # [1, 3, 6]
Source code in src/concrete_fhe_toolkit/arrays/manipulation.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def array_cumsum(array: Union[np.ndarray, List[Any]]) -> Union[np.ndarray, List[Any]]:
    """Return the running prefix sums of an encrypted array.

    Args:
        array (Union[np.ndarray, List[Any]]): The encrypted array or list of elements.

    Returns:
        Union[np.ndarray, List[Any]]: The array of prefix sums.

    Example:
        ```python
        from concrete_fhe_toolkit import array_cumsum

        print(array_cumsum([1, 2, 3]))  # [1, 3, 6]
        ```
    """
    sums: List[Any] = []
    running: Any = 0
    for item in array:
        running = running + item
        sums.append(running)
    return fhe.array(sums)

array_reverse

array_reverse(array: Union[ndarray, List[Any]]) -> Union[np.ndarray, List[Any]]

Return the array with its (public) element order reversed.

Parameters:

Name Type Description Default
array Union[ndarray, List[Any]]

The encrypted array or list of elements.

required

Returns:

Type Description
Union[ndarray, List[Any]]

Union[np.ndarray, List[Any]]: The reversed array.

Example
from concrete_fhe_toolkit import array_reverse

print(array_reverse([1, 2, 3]))  # [3, 2, 1]
Source code in src/concrete_fhe_toolkit/arrays/manipulation.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def array_reverse(array: Union[np.ndarray, List[Any]]) -> Union[np.ndarray, List[Any]]:
    """Return the array with its (public) element order reversed.

    Args:
        array (Union[np.ndarray, List[Any]]): The encrypted array or list of elements.

    Returns:
        Union[np.ndarray, List[Any]]: The reversed array.

    Example:
        ```python
        from concrete_fhe_toolkit import array_reverse

        print(array_reverse([1, 2, 3]))  # [3, 2, 1]
        ```
    """
    return _ensure_tensor(array)[::-1]

array_slice

array_slice(array: Union[ndarray, List[Any]], begin_index: Any, end_index: Any) -> Any

Slice an encrypted array (return elements from begin_index to end_index - 1).

Parameters:

Name Type Description Default
array Union[ndarray, List[Any]]

The encrypted array or list of elements.

required
begin_index Any

The starting index (inclusive).

required
end_index Any

The ending index (exclusive).

required

Returns:

Name Type Description
Any Any

The sliced array.

Example
from concrete_fhe_toolkit import array_slice

print(array_slice([10, 20, 30, 40], 1, 3))  # [20, 30]
Source code in src/concrete_fhe_toolkit/arrays/manipulation.py
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
def array_slice(array: Union[np.ndarray, List[Any]], begin_index: Any, end_index: Any) -> Any:
    """Slice an encrypted array (return elements from begin_index to end_index - 1).

    Args:
        array (Union[np.ndarray, List[Any]]): The encrypted array or list of elements.
        begin_index (Any): The starting index (inclusive).
        end_index (Any): The ending index (exclusive).

    Returns:
        Any: The sliced array.

    Example:
        ```python
        from concrete_fhe_toolkit import array_slice

        print(array_slice([10, 20, 30, 40], 1, 3))  # [20, 30]
        ```
    """
    raw_list = list(array)
    list_length = len(raw_list)
    if(list_length < begin_index or list_length < end_index or end_index < begin_index):
        raise ValueError(
            "indexes must be within the array size and begin_index cannot be greater than end_index"
        )

    return fhe.array(raw_list[begin_index:end_index])

make_array_pad

make_array_pad(size: int, target_size: int, min_value: int = -15, max_value: int = 15) -> Callable

Create a fixed-size array padding function.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
target_size int

The desired size of the array after padding.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

-15
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15

Returns:

Name Type Description
Callable Callable

A function that pads the input array with zeros.

Example
from concrete_fhe_toolkit import make_array_pad

pad_fn = make_array_pad(size=2, target_size=4, min_value=0, max_value=10)
print(pad_fn([1, 2]))  # [1, 2, 0, 0]
Source code in src/concrete_fhe_toolkit/arrays/manipulation.py
130
131
132
133
134
135
136
137
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
def make_array_pad(
    size: int,
    target_size: int,
    min_value: int = -15,
    max_value: int = 15,
) -> Callable:
    """Create a fixed-size array padding function.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        target_size (int): The desired size of the array after padding.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.

    Returns:
        Callable: A function that pads the input array with zeros.

    Example:
        ```python
        from concrete_fhe_toolkit import make_array_pad

        pad_fn = make_array_pad(size=2, target_size=4, min_value=0, max_value=10)
        print(pad_fn([1, 2]))  # [1, 2, 0, 0]
        ```
    """
    size = validate_size(size)
    target_size = validate_size(target_size)
    minimum, maximum = validate_bounds(min_value, max_value)
    if size > target_size:
        raise ValueError("target_size must be at least the array size")

    def array_pad(array: Union[np.ndarray, List[Any]]) -> Any:
        """Pad an encrypted array with zeros up to the specified target size.
        Args:
            array (Union[np.ndarray, List[Any]]): The encrypted array or list of elements.

        Returns:
            Any: The zero-padded array.

        """
        raw_list = list(array)
        padded_list = raw_list + [0] * (target_size - len(raw_list))
        return fhe.array(padded_list)

    return array_pad

compile_array_pad

compile_array_pad(size: int, target_size: int, min_value: int = -15, max_value: int = 15, *, configuration: Optional[Configuration] = None) -> fhe.Circuit

Compile a fixed-size array padding circuit.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
target_size int

The desired size of the array after padding.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

-15
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15
configuration Optional[Configuration]

Optional FHE compiler configuration object.

None

Returns:

Type Description
Circuit

fhe.Circuit: The compiled padding circuit.

Example
from concrete_fhe_toolkit import compile_array_pad

circuit = compile_array_pad(size=2, target_size=4, min_value=0, max_value=10)
print(circuit.encrypt_run_decrypt([1, 2]))  # [1, 2, 0, 0]
Source code in src/concrete_fhe_toolkit/arrays/manipulation.py
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
def compile_array_pad(
    size: int,
    target_size: int,
    min_value: int = -15,
    max_value: int = 15,
    *,
    configuration: Optional[fhe.Configuration] = None,
) -> fhe.Circuit:
    """Compile a fixed-size array padding circuit.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        target_size (int): The desired size of the array after padding.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.
        configuration (Optional[fhe.Configuration]): Optional FHE compiler configuration object.

    Returns:
        fhe.Circuit: The compiled padding circuit.

    Example:
        ```python
        from concrete_fhe_toolkit import compile_array_pad

        circuit = compile_array_pad(size=2, target_size=4, min_value=0, max_value=10)
        print(circuit.encrypt_run_decrypt([1, 2]))  # [1, 2, 0, 0]
        ```
    """
    func = make_array_pad(size, target_size, min_value, max_value)
    inputset = array_inputset(size, min_value, max_value)
    return compile_function(func, {"array": "encrypted"}, inputset, configuration)

compile_array_index

compile_array_index(size: int, min_value: int = -15, max_value: int = 15, *, configuration: Optional[Configuration] = None) -> fhe.Circuit

Compile an oblivious-read circuit.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

-15
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15
configuration Optional[Configuration]

Optional FHE compiler configuration object.

None

Returns:

Type Description
Circuit

fhe.Circuit: The compiled oblivious-read circuit.

Example
from concrete_fhe_toolkit import compile_array_index

circuit = compile_array_index(size=3, min_value=0, max_value=30)
print(circuit.encrypt_run_decrypt([10, 20, 30], 1))  # 20
Source code in src/concrete_fhe_toolkit/arrays/access.py
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
def compile_array_index(
    size: int,
    min_value: int = -15,
    max_value: int = 15,
    *,
    configuration: Optional[fhe.Configuration] = None,
) -> fhe.Circuit:
    """Compile an oblivious-read circuit.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.
        configuration (Optional[fhe.Configuration]): Optional FHE compiler configuration object.

    Returns:
        fhe.Circuit: The compiled oblivious-read circuit.

    Example:
        ```python
        from concrete_fhe_toolkit import compile_array_index

        circuit = compile_array_index(size=3, min_value=0, max_value=30)
        print(circuit.encrypt_run_decrypt([10, 20, 30], 1))  # 20
        ```
    """
    func = make_array_index(size, min_value, max_value)
    base_arrays = array_inputset(size, min_value, max_value)
    inputset = []
    for arr in base_arrays:
        inputset.append((arr, 0))
        inputset.append((arr, size - 1))
    return compile_function(
        func, {"array": "encrypted", "index": "encrypted"}, inputset, configuration
    )

compile_array_set

compile_array_set(size: int, min_value: int = -15, max_value: int = 15, *, configuration: Optional[Configuration] = None) -> fhe.Circuit

Compile an FHE circuit for oblivious array writing.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

-15
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15
configuration Optional[Configuration]

Optional FHE compiler configuration object.

None

Returns:

Type Description
Circuit

fhe.Circuit: The compiled circuit for oblivious array writing.

Example
from concrete_fhe_toolkit.arrays import compile_array_set

circuit = compile_array_set(size=5)
# circuit.encrypt_run_decrypt(arr, index, value)
Source code in src/concrete_fhe_toolkit/arrays/access.py
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
def compile_array_set(
    size: int,
    min_value: int = -15,
    max_value: int = 15,
    *,
    configuration: Optional[fhe.Configuration] = None,
) -> fhe.Circuit:
    """Compile an FHE circuit for oblivious array writing.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.
        configuration (Optional[fhe.Configuration]): Optional FHE compiler configuration object.

    Returns:
        fhe.Circuit: The compiled circuit for oblivious array writing.

    Example:
        ```python
        from concrete_fhe_toolkit.arrays import compile_array_set

        circuit = compile_array_set(size=5)
        # circuit.encrypt_run_decrypt(arr, index, value)
        ```
    """
    array_set_func = make_array_set(size, min_value, max_value)
    base_arrays = array_inputset(size, min_value, max_value)
    inputset = []
    for arr in base_arrays:
        inputset.append((arr, 0, min_value))
        inputset.append((arr, size - 1, max_value))
    return compile_function(
        array_set_func,
        {"array": "encrypted", "index": "encrypted", "value": "encrypted"},
        inputset,
        configuration,
    )

make_array_index

make_array_index(size: int, min_value: int = -15, max_value: int = 15) -> Callable

Create an oblivious-read function for bounded encrypted arrays.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

-15
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15

Returns:

Name Type Description
Callable Callable

A function that obliviously reads an element from the array at a given index.

Example
from concrete_fhe_toolkit import make_array_index

index_fn = make_array_index(size=3, min_value=0, max_value=30)
print(index_fn([10, 20, 30], 1))  # 20
Source code in src/concrete_fhe_toolkit/arrays/access.py
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
def make_array_index(
    size: int,
    min_value: int = -15,
    max_value: int = 15,
) -> Callable:
    """Create an oblivious-read function for bounded encrypted arrays.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.

    Returns:
        Callable: A function that obliviously reads an element from the array at a given index.

    Example:
        ```python
        from concrete_fhe_toolkit import make_array_index

        index_fn = make_array_index(size=3, min_value=0, max_value=30)
        print(index_fn([10, 20, 30], 1))  # 20
        ```
    """
    size = validate_size(size)
    minimum, maximum = validate_bounds(min_value, max_value)

    def array_index(array: Union[np.ndarray, List[Any]], index: Any) -> Any:
        """Oblivious read: return array[index] without revealing the encrypted index.
        Args:
            array (Union[np.ndarray, List[Any]]): The encrypted array or list of elements.
            index (Any): The encrypted index to read.

        Returns:
            Any: The encrypted value at the given index.

        """
        tensor = _ensure_tensor(array)
        if len(tensor) == 0:
            raise ValueError("array must contain at least one element")

        positions = np.arange(len(tensor))
        mask = positions == index
        return np.sum(tensor * mask)

    return array_index

make_array_set

make_array_set(size: int, min_value: int = -15, max_value: int = 15) -> Callable

Create a function for oblivious array writing.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

-15
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15

Returns:

Name Type Description
Callable Callable

A function that updates an element in the encrypted array obliviously.

Example
from concrete_fhe_toolkit.arrays import make_array_set

array_set = make_array_set(size=5)
# new_arr = array_set(arr, index, value)
Source code in src/concrete_fhe_toolkit/arrays/access.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def make_array_set(
    size : int,
    min_value: int = -15,
    max_value: int = 15,
) -> Callable:
    """Create a function for oblivious array writing.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.

    Returns:
        Callable: A function that updates an element in the encrypted array obliviously.

    Example:
        ```python
        from concrete_fhe_toolkit.arrays import make_array_set

        array_set = make_array_set(size=5)
        # new_arr = array_set(arr, index, value)
        ```
    """
    size = validate_size(size)
    minimum, maximum = validate_bounds(min_value,max_value) 

    def array_set(array: Union[np.ndarray, List[Any]], index: Any, value: Any) -> Union[np.ndarray, List[Any]]:
        """Oblivious write: return a copy with array[index] replaced by value.

        Args:
            array (Union[np.ndarray, List[Any]]): The encrypted array or list of elements.
            index (Any): The encrypted index to update.
            value (Any): The encrypted value to process or validate.

        Returns:
            Union[np.ndarray, List[Any]]: The updated array.

        Example:
            ```python
            from concrete_fhe_toolkit import array_set

            print(array_set([10, 20, 30], index=1, value=99))  # [10, 99, 30]
            ```
        """
        arr_tensor = fhe.array(array)
        tensor_size = len(arr_tensor)
        if tensor_size == 0:
            raise ValueError("array must contain at least one element")

        positions = np.arange(tensor_size)
        # Use tensor broadcasting to avoid FHE scalar boolean op failures
        mask = (positions == index) * 1
        return mask * value + (1 - mask) * arr_tensor

    return array_set    

compile_argmax

compile_argmax(size: int, min_value: int = 0, max_value: int = 15, *, tie_break: TieBreak = 'first', configuration: Optional[Configuration] = None) -> fhe.Circuit

Compile an argmax reduction circuit.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

0
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15
tie_break TieBreak

Which index to return if multiple elements are equal to the maximum.

'first'
configuration Optional[Configuration]

Optional FHE compiler configuration object.

None

Returns:

Type Description
Circuit

fhe.Circuit: The compiled argmax reduction circuit.

Example
from concrete_fhe_toolkit import compile_argmax

circuit = compile_argmax(size=4, min_value=0, max_value=10)
print(circuit.encrypt_run_decrypt([4, 1, 3, 2]))  # 0
Source code in src/concrete_fhe_toolkit/arrays/extremes.py
335
336
337
338
339
340
341
342
343
344
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
def compile_argmax(
    size: int,
    min_value: int = 0,
    max_value: int = 15,
    *,
    tie_break: TieBreak = "first",
    configuration: Optional[fhe.Configuration] = None,
) -> fhe.Circuit:
    """Compile an argmax reduction circuit.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.
        tie_break (TieBreak): Which index to return if multiple elements are equal to the maximum.
        configuration (Optional[fhe.Configuration]): Optional FHE compiler configuration object.

    Returns:
        fhe.Circuit: The compiled argmax reduction circuit.

    Example:
        ```python
        from concrete_fhe_toolkit import compile_argmax

        circuit = compile_argmax(size=4, min_value=0, max_value=10)
        print(circuit.encrypt_run_decrypt([4, 1, 3, 2]))  # 0
        ```
    """
    size = validate_size(size)
    minimum, maximum = validate_bounds(min_value, max_value)
    function = make_argmax(
        size,
        minimum,
        maximum,
        tie_break=tie_break,
    )
    return _compile_array_function(function, size, minimum, maximum, configuration)

compile_argmin

compile_argmin(size: int, min_value: int = 0, max_value: int = 15, *, tie_break: TieBreak = 'first', configuration: Optional[Configuration] = None) -> fhe.Circuit

Compile an argmin reduction circuit.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

0
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15
tie_break TieBreak

Which index to return if multiple elements are equal to the minimum.

'first'
configuration Optional[Configuration]

Optional FHE compiler configuration object.

None

Returns:

Type Description
Circuit

fhe.Circuit: The compiled argmin reduction circuit.

Example
from concrete_fhe_toolkit import compile_argmin

circuit = compile_argmin(size=4, min_value=0, max_value=10)
print(circuit.encrypt_run_decrypt([4, 1, 3, 2]))  # 1
Source code in src/concrete_fhe_toolkit/arrays/extremes.py
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
296
297
298
299
300
301
302
303
def compile_argmin(
    size: int,
    min_value: int = 0,
    max_value: int = 15,
    *,
    tie_break: TieBreak = "first",
    configuration: Optional[fhe.Configuration] = None,
) -> fhe.Circuit:
    """Compile an argmin reduction circuit.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.
        tie_break (TieBreak): Which index to return if multiple elements are equal to the minimum.
        configuration (Optional[fhe.Configuration]): Optional FHE compiler configuration object.

    Returns:
        fhe.Circuit: The compiled argmin reduction circuit.

    Example:
        ```python
        from concrete_fhe_toolkit import compile_argmin

        circuit = compile_argmin(size=4, min_value=0, max_value=10)
        print(circuit.encrypt_run_decrypt([4, 1, 3, 2]))  # 1
        ```
    """
    size = validate_size(size)
    minimum, maximum = validate_bounds(min_value, max_value)
    function = make_argmin(
        size,
        minimum,
        maximum,
        tie_break=tie_break,
    )
    return _compile_array_function(function, size, minimum, maximum, configuration)

compile_array_maximum

compile_array_maximum(size: int, min_value: int = 0, max_value: int = 15, *, configuration: Optional[Configuration] = None) -> fhe.Circuit

Compile a maximum reduction circuit.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

0
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15
configuration Optional[Configuration]

Optional FHE compiler configuration object.

None

Returns:

Type Description
Circuit

fhe.Circuit: The compiled maximum reduction circuit.

Example
from concrete_fhe_toolkit import compile_array_maximum

circuit = compile_array_maximum(size=4, min_value=0, max_value=10)
print(circuit.encrypt_run_decrypt([4, 1, 3, 2]))  # 4
Source code in src/concrete_fhe_toolkit/arrays/extremes.py
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
def compile_array_maximum(
    size: int,
    min_value: int = 0,
    max_value: int = 15,
    *,
    configuration: Optional[fhe.Configuration] = None,
) -> fhe.Circuit:
    """Compile a maximum reduction circuit.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.
        configuration (Optional[fhe.Configuration]): Optional FHE compiler configuration object.

    Returns:
        fhe.Circuit: The compiled maximum reduction circuit.

    Example:
        ```python
        from concrete_fhe_toolkit import compile_array_maximum

        circuit = compile_array_maximum(size=4, min_value=0, max_value=10)
        print(circuit.encrypt_run_decrypt([4, 1, 3, 2]))  # 4
        ```
    """
    size = validate_size(size)
    minimum, maximum = validate_bounds(min_value, max_value)
    function = make_array_maximum(size, minimum, maximum)
    return _compile_array_function(function, size, minimum, maximum, configuration)

compile_array_minimum

compile_array_minimum(size: int, min_value: int = 0, max_value: int = 15, *, configuration: Optional[Configuration] = None) -> fhe.Circuit

Compile a minimum reduction circuit.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

0
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15
configuration Optional[Configuration]

Optional FHE compiler configuration object.

None

Returns:

Type Description
Circuit

fhe.Circuit: The compiled minimum reduction circuit.

Example
from concrete_fhe_toolkit import compile_array_minimum

circuit = compile_array_minimum(size=4, min_value=0, max_value=10)
print(circuit.encrypt_run_decrypt([4, 1, 3, 2]))  # 1
Source code in src/concrete_fhe_toolkit/arrays/extremes.py
 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
def compile_array_minimum(
    size: int,
    min_value: int = 0,
    max_value: int = 15,
    *,
    configuration: Optional[fhe.Configuration] = None,
) -> fhe.Circuit:
    """Compile a minimum reduction circuit.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.
        configuration (Optional[fhe.Configuration]): Optional FHE compiler configuration object.

    Returns:
        fhe.Circuit: The compiled minimum reduction circuit.

    Example:
        ```python
        from concrete_fhe_toolkit import compile_array_minimum

        circuit = compile_array_minimum(size=4, min_value=0, max_value=10)
        print(circuit.encrypt_run_decrypt([4, 1, 3, 2]))  # 1
        ```
    """
    size = validate_size(size)
    minimum, maximum = validate_bounds(min_value, max_value)
    function = make_array_minimum(size, minimum, maximum)
    return _compile_array_function(function, size, minimum, maximum, configuration)

make_argmax

make_argmax(size: int, min_value: int = 0, max_value: int = 15, *, tie_break: TieBreak = 'first') -> UnaryArrayFunction

Create an argmax reduction with deterministic tie handling.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

0
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15
tie_break TieBreak

Which index to return if multiple elements are equal to the maximum.

'first'

Returns:

Name Type Description
UnaryArrayFunction UnaryArrayFunction

A function that returns the index of the maximum value.

Example
from concrete_fhe_toolkit import make_argmax

argmax_fn = make_argmax(size=4, min_value=0, max_value=10)
# Use `argmax_fn(array)` inside an FHE program compilation
Source code in src/concrete_fhe_toolkit/arrays/extremes.py
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
def make_argmax(
    size: int,
    min_value: int = 0,
    max_value: int = 15,
    *,
    tie_break: TieBreak = "first",
) -> UnaryArrayFunction:
    """Create an argmax reduction with deterministic tie handling.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.
        tie_break (TieBreak): Which index to return if multiple elements are equal to the maximum.

    Returns:
        UnaryArrayFunction: A function that returns the index of the maximum value.

    Example:
        ```python
        from concrete_fhe_toolkit import make_argmax

        argmax_fn = make_argmax(size=4, min_value=0, max_value=10)
        # Use `argmax_fn(array)` inside an FHE program compilation
        ```
    """
    return _make_arg_extreme("max", size, min_value, max_value, tie_break)

make_argmin

make_argmin(size: int, min_value: int = 0, max_value: int = 15, *, tie_break: TieBreak = 'first') -> UnaryArrayFunction

Create an argmin reduction with deterministic tie handling.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

0
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15
tie_break TieBreak

Which index to return if multiple elements are equal to the minimum.

'first'

Returns:

Name Type Description
UnaryArrayFunction UnaryArrayFunction

A function that returns the index of the minimum value.

Example
from concrete_fhe_toolkit import make_argmin

argmin_fn = make_argmin(size=4, min_value=0, max_value=10)
# Use `argmin_fn(array)` inside an FHE program compilation
Source code in src/concrete_fhe_toolkit/arrays/extremes.py
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def make_argmin(
    size: int,
    min_value: int = 0,
    max_value: int = 15,
    *,
    tie_break: TieBreak = "first",
) -> UnaryArrayFunction:
    """Create an argmin reduction with deterministic tie handling.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.
        tie_break (TieBreak): Which index to return if multiple elements are equal to the minimum.

    Returns:
        UnaryArrayFunction: A function that returns the index of the minimum value.

    Example:
        ```python
        from concrete_fhe_toolkit import make_argmin

        argmin_fn = make_argmin(size=4, min_value=0, max_value=10)
        # Use `argmin_fn(array)` inside an FHE program compilation
        ```
    """
    return _make_arg_extreme("min", size, min_value, max_value, tie_break)

make_array_maximum

make_array_maximum(size: int, min_value: int = 0, max_value: int = 15) -> UnaryArrayFunction

Create a tournament reduction that returns the maximum value.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

0
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15

Returns:

Name Type Description
UnaryArrayFunction UnaryArrayFunction

A function that returns the maximum value.

Example
from concrete_fhe_toolkit import make_array_maximum

max_fn = make_array_maximum(size=4, min_value=0, max_value=10)
# Use `max_fn(array)` inside an FHE program compilation
Source code in src/concrete_fhe_toolkit/arrays/extremes.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def make_array_maximum(
    size: int,
    min_value: int = 0,
    max_value: int = 15,
) -> UnaryArrayFunction:
    """Create a tournament reduction that returns the maximum value.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.

    Returns:
        UnaryArrayFunction: A function that returns the maximum value.

    Example:
        ```python
        from concrete_fhe_toolkit import make_array_maximum

        max_fn = make_array_maximum(size=4, min_value=0, max_value=10)
        # Use `max_fn(array)` inside an FHE program compilation
        ```
    """
    return _make_extreme("max", size, min_value, max_value)

make_array_minimum

make_array_minimum(size: int, min_value: int = 0, max_value: int = 15) -> UnaryArrayFunction

Create a tournament reduction that returns the minimum value.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

0
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15

Returns:

Name Type Description
UnaryArrayFunction UnaryArrayFunction

A function that returns the minimum value.

Example
from concrete_fhe_toolkit import make_array_minimum

min_fn = make_array_minimum(size=4, min_value=0, max_value=10)
# Use `min_fn(array)` inside an FHE program compilation
Source code in src/concrete_fhe_toolkit/arrays/extremes.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
def make_array_minimum(
    size: int,
    min_value: int = 0,
    max_value: int = 15,
) -> UnaryArrayFunction:
    """Create a tournament reduction that returns the minimum value.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.

    Returns:
        UnaryArrayFunction: A function that returns the minimum value.

    Example:
        ```python
        from concrete_fhe_toolkit import make_array_minimum

        min_fn = make_array_minimum(size=4, min_value=0, max_value=10)
        # Use `min_fn(array)` inside an FHE program compilation
        ```
    """
    return _make_extreme("min", size, min_value, max_value)

compile_array_contains

compile_array_contains(size: int, min_value: int = -15, max_value: int = 15, *, configuration: Optional[Configuration] = None) -> fhe.Circuit

Compile a membership-test circuit.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

-15
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15
configuration Optional[Configuration]

Optional FHE compiler configuration object.

None

Returns:

Type Description
Circuit

fhe.Circuit: The compiled membership-test circuit.

Example
from concrete_fhe_toolkit import compile_array_contains

circuit = compile_array_contains(size=3, min_value=0, max_value=10)
print(circuit.encrypt_run_decrypt([1, 3, 5], 3))  # 1
Source code in src/concrete_fhe_toolkit/arrays/search.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
def compile_array_contains(
    size: int,
    min_value: int = -15,
    max_value: int = 15,
    *,
    configuration: Optional[fhe.Configuration] = None,
) -> fhe.Circuit:
    """Compile a membership-test circuit.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.
        configuration (Optional[fhe.Configuration]): Optional FHE compiler configuration object.

    Returns:
        fhe.Circuit: The compiled membership-test circuit.

    Example:
        ```python
        from concrete_fhe_toolkit import compile_array_contains

        circuit = compile_array_contains(size=3, min_value=0, max_value=10)
        print(circuit.encrypt_run_decrypt([1, 3, 5], 3))  # 1
        ```
    """
    func = make_array_contains(size, min_value, max_value)
    base_arrays = array_inputset(size, min_value, max_value)
    inputset = []
    for arr in base_arrays:
        inputset.append((arr, min_value))
        inputset.append((arr, max_value))
    return compile_function(
        func, {"array": "encrypted", "value": "encrypted"}, inputset, configuration
    )

compile_array_count

compile_array_count(size: int, min_value: int = -15, max_value: int = 15, *, configuration: Optional[Configuration] = None) -> fhe.Circuit

Compile a value-counting circuit.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

-15
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15
configuration Optional[Configuration]

Optional FHE compiler configuration object.

None

Returns:

Type Description
Circuit

fhe.Circuit: The compiled counting circuit.

Example
from concrete_fhe_toolkit import compile_array_count

circuit = compile_array_count(size=4, min_value=0, max_value=10)
print(circuit.encrypt_run_decrypt([1, 2, 2, 3], 2))  # 2
Source code in src/concrete_fhe_toolkit/arrays/search.py
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
def compile_array_count(
    size: int,
    min_value: int = -15,
    max_value: int = 15,
    *,
    configuration: Optional[fhe.Configuration] = None,
) -> fhe.Circuit:
    """Compile a value-counting circuit.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.
        configuration (Optional[fhe.Configuration]): Optional FHE compiler configuration object.

    Returns:
        fhe.Circuit: The compiled counting circuit.

    Example:
        ```python
        from concrete_fhe_toolkit import compile_array_count

        circuit = compile_array_count(size=4, min_value=0, max_value=10)
        print(circuit.encrypt_run_decrypt([1, 2, 2, 3], 2))  # 2
        ```
    """
    func = make_array_count(size, min_value, max_value)
    base_arrays = array_inputset(size, min_value, max_value)
    inputset = []
    for arr in base_arrays:
        inputset.append((arr, min_value))
        inputset.append((arr, max_value))
    return compile_function(
        func, {"array": "encrypted", "value": "encrypted"}, inputset, configuration
    )

compile_array_index_of

compile_array_index_of(size: int, min_value: int = -15, max_value: int = 15, *, missing_result: Optional[int] = None, configuration: Optional[Configuration] = None) -> fhe.Circuit

Compile a first-index-of search circuit.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

-15
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15
missing_result Optional[int]

The value to return if the target is not found (default: size).

None
configuration Optional[Configuration]

Optional FHE compiler configuration object.

None

Returns:

Type Description
Circuit

fhe.Circuit: The compiled search circuit.

Example
from concrete_fhe_toolkit import compile_array_index_of

circuit = compile_array_index_of(size=3, min_value=0, max_value=10)
print(circuit.encrypt_run_decrypt([10, 20, 30], 20))  # 1
Source code in src/concrete_fhe_toolkit/arrays/search.py
 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
120
def compile_array_index_of(
    size: int,
    min_value: int = -15,
    max_value: int = 15,
    *,
    missing_result: Optional[int] = None,
    configuration: Optional[fhe.Configuration] = None,
) -> fhe.Circuit:
    """Compile a first-index-of search circuit.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.
        missing_result (Optional[int]): The value to return if the target is not found (default: size).
        configuration (Optional[fhe.Configuration]): Optional FHE compiler configuration object.

    Returns:
        fhe.Circuit: The compiled search circuit.

    Example:
        ```python
        from concrete_fhe_toolkit import compile_array_index_of

        circuit = compile_array_index_of(size=3, min_value=0, max_value=10)
        print(circuit.encrypt_run_decrypt([10, 20, 30], 20))  # 1
        ```
    """
    func = make_array_index_of(size, min_value, max_value, missing_result=missing_result)
    base_arrays = array_inputset(size, min_value, max_value)
    inputset = []
    for arr in base_arrays:
        inputset.append((arr, min_value))
        inputset.append((arr, max_value))
    return compile_function(
        func, {"array": "encrypted", "value": "encrypted"}, inputset, configuration
    )

make_array_contains

make_array_contains(size: int, min_value: int = -15, max_value: int = 15) -> Callable

Create a membership-test function for bounded encrypted arrays.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

-15
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15

Returns:

Name Type Description
Callable Callable

A function that tests whether a value exists in the array.

Example
from concrete_fhe_toolkit import make_array_contains

contains_fn = make_array_contains(size=3, min_value=0, max_value=10)
print(contains_fn([1, 3, 5], 3))  # 1
Source code in src/concrete_fhe_toolkit/arrays/search.py
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
def make_array_contains(
    size: int,
    min_value: int = -15,
    max_value: int = 15,
) -> Callable:
    """Create a membership-test function for bounded encrypted arrays.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.

    Returns:
        Callable: A function that tests whether a value exists in the array.

    Example:
        ```python
        from concrete_fhe_toolkit import make_array_contains

        contains_fn = make_array_contains(size=3, min_value=0, max_value=10)
        print(contains_fn([1, 3, 5], 3))  # 1
        ```
    """
    size = validate_size(size)
    minimum, maximum = validate_bounds(min_value, max_value)

    def array_contains(array: Union[np.ndarray, List[Any]], value: Any) -> Any:
        """Check if an encrypted array contains a specific target value (returns 1 or 0).
        Args:
            array (Union[np.ndarray, List[Any]]): The encrypted array or list of elements.
            value (Any): The encrypted value to process or validate.

        Returns:
            Any: 1 if the value exists in the array, 0 otherwise.

        """
        contains = np.max(_ensure_tensor(array) == value)
        return contains

    return array_contains

make_array_count

make_array_count(size: int, min_value: int = -15, max_value: int = 15) -> Callable

Create a value-counting function for bounded encrypted arrays.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

-15
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15

Returns:

Name Type Description
Callable Callable

A function that counts occurrences of a value.

Example
from concrete_fhe_toolkit import make_array_count

count_fn = make_array_count(size=4, min_value=0, max_value=10)
print(count_fn([1, 2, 2, 3], 2))  # 2
Source code in src/concrete_fhe_toolkit/arrays/search.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
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
def make_array_count(
    size: int,
    min_value: int = -15,
    max_value: int = 15,
) -> Callable:
    """Create a value-counting function for bounded encrypted arrays.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.

    Returns:
        Callable: A function that counts occurrences of a value.

    Example:
        ```python
        from concrete_fhe_toolkit import make_array_count

        count_fn = make_array_count(size=4, min_value=0, max_value=10)
        print(count_fn([1, 2, 2, 3], 2))  # 2
        ```
    """
    size = validate_size(size)
    minimum, maximum = validate_bounds(min_value, max_value)

    def array_count(array: Union[np.ndarray, List[Any]], value: Any) -> Any:
        """Count occurrences of a specific value in an encrypted array.
        Args:
            array (Union[np.ndarray, List[Any]]): The encrypted array or list of elements.
            value (Any): The encrypted value to process or validate.

        Returns:
            Any: The encrypted count of occurrences.

        """
        count = np.sum(_ensure_tensor(array) == value)
        return count

    return array_count

make_array_index_of

make_array_index_of(size: int, min_value: int = -15, max_value: int = 15, *, missing_result: Optional[int] = None) -> Callable

Create a first-index-of search function for bounded encrypted arrays.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

-15
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15
missing_result Optional[int]

The value to return if the target is not found (default: size).

None

Returns:

Name Type Description
Callable Callable

A function that returns the index of a specified value.

Example
from concrete_fhe_toolkit import make_array_index_of

index_of_fn = make_array_index_of(size=3, min_value=0, max_value=10)
print(index_of_fn([10, 20, 30], 20))  # 1
Source code in src/concrete_fhe_toolkit/arrays/search.py
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
def make_array_index_of(
    size: int,
    min_value: int = -15,
    max_value: int = 15,
    *,
    missing_result: Optional[int] = None,
) -> Callable:
    """Create a first-index-of search function for bounded encrypted arrays.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.
        missing_result (Optional[int]): The value to return if the target is not found (default: size).

    Returns:
        Callable: A function that returns the index of a specified value.

    Example:
        ```python
        from concrete_fhe_toolkit import make_array_index_of

        index_of_fn = make_array_index_of(size=3, min_value=0, max_value=10)
        print(index_of_fn([10, 20, 30], 20))  # 1
        ```
    """
    size = validate_size(size)
    minimum, maximum = validate_bounds(min_value, max_value)
    missing = size if missing_result is None else int(missing_result)

    def array_index_of(array: Union[np.ndarray, List[Any]], value: Any) -> Any:
        """Return the first index holding value, or missing_result (default size).
        Args:
            array (Union[np.ndarray, List[Any]]): The encrypted array or list of elements.
            value (Any): The encrypted value to process or validate.

        Returns:
            Any: The encrypted index of the target value.

        """
        tensor = _ensure_tensor(array)
        tensor_size = len(tensor)
        if tensor_size == 0:
            raise ValueError("array must contain at least one element")

        # We subtract value first, then compare to 0.
        # This prevents the Zama compiler from creating a multi-input subgraph 
        # when 'value' is a cleartext runtime argument.
        diff = tensor - value
        found_array = (diff == 0)

        argmax_func = make_argmax(tensor_size, 0, 1)
        index = argmax_func(found_array)

        # Check if value exists using a single TLU over the sum.
        # This forces a PBS so it doesn't fuse with the select multiplication.
        sum_val = array_sum(found_array)
        any_found = fhe.LookupTable([0] + [1] * tensor_size)[sum_val]

        @fhe.multivariate
        def select_index(a: Any, i: Any) -> Any:
            """Select element at the specified index from array."""
            return i if a else missing

        return select_index(any_found, index)

    return array_index_of

compile_compare_swap

compile_compare_swap(min_value: int = 0, max_value: int = 15, *, configuration: Optional[Configuration] = None) -> fhe.Circuit

Compile an ascending compare-swap circuit.

Parameters:

Name Type Description Default
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

0
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15
configuration Optional[Configuration]

Optional FHE compiler configuration object.

None

Returns:

Type Description
Circuit

fhe.Circuit: The compiled compare-swap circuit.

Example
from concrete_fhe_toolkit import compile_compare_swap

circuit = compile_compare_swap(min_value=0, max_value=10)
print(circuit.encrypt_run_decrypt(5, 3))  # (3, 5)
Source code in src/concrete_fhe_toolkit/arrays/sorting.py
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
def compile_compare_swap(
    min_value: int = 0,
    max_value: int = 15,
    *,
    configuration: Optional[fhe.Configuration] = None,
) -> fhe.Circuit:
    """Compile an ascending compare-swap circuit.

    Args:
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.
        configuration (Optional[fhe.Configuration]): Optional FHE compiler configuration object.

    Returns:
        fhe.Circuit: The compiled compare-swap circuit.

    Example:
        ```python
        from concrete_fhe_toolkit import compile_compare_swap

        circuit = compile_compare_swap(min_value=0, max_value=10)
        print(circuit.encrypt_run_decrypt(5, 3))  # (3, 5)
        ```
    """
    minimum, maximum = validate_bounds(min_value, max_value)
    function = make_compare_swap(minimum, maximum)
    inputset = [
        (minimum, minimum),
        (minimum, maximum),
        (maximum, minimum),
        (maximum, maximum),
    ]
    return compile_function(
        function,
        {"x": "encrypted", "y": "encrypted"},
        inputset,
        configuration,
    )

compile_sort

compile_sort(size: int, min_value: int = 0, max_value: int = 15, *, descending: bool = False, configuration: Optional[Configuration] = None) -> fhe.Circuit

Compile a fixed-size bitonic sorting circuit.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

0
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15
descending bool

Whether to sort in descending order.

False
configuration Optional[Configuration]

Optional FHE compiler configuration object.

None

Returns:

Type Description
Circuit

fhe.Circuit: The compiled sorting circuit.

Example
from concrete_fhe_toolkit import compile_sort

circuit = compile_sort(size=4, min_value=0, max_value=10)
print(circuit.encrypt_run_decrypt([4, 1, 3, 2]))  # [1, 2, 3, 4]
Source code in src/concrete_fhe_toolkit/arrays/sorting.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
184
185
186
187
def compile_sort(
    size: int,
    min_value: int = 0,
    max_value: int = 15,
    *,
    descending: bool = False,
    configuration: Optional[fhe.Configuration] = None,
) -> fhe.Circuit:
    """Compile a fixed-size bitonic sorting circuit.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.
        descending (bool): Whether to sort in descending order.
        configuration (Optional[fhe.Configuration]): Optional FHE compiler configuration object.

    Returns:
        fhe.Circuit: The compiled sorting circuit.

    Example:
        ```python
        from concrete_fhe_toolkit import compile_sort

        circuit = compile_sort(size=4, min_value=0, max_value=10)
        print(circuit.encrypt_run_decrypt([4, 1, 3, 2]))  # [1, 2, 3, 4]
        ```
    """
    size = validate_size(size, power_of_two=True)
    minimum, maximum = validate_bounds(min_value, max_value)
    function = make_sort(
        size,
        minimum,
        maximum,
        descending=descending,
    )
    return _compile_array_function(function, size, minimum, maximum, configuration)

compile_top_k

compile_top_k(size: int, k: int, min_value: int = 0, max_value: int = 15, *, largest: bool = True, configuration: Optional[Configuration] = None) -> fhe.Circuit

Compile a top-k reduction circuit.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
k int

The number of top elements to return.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

0
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15
largest bool

Whether to return the largest values (True) or smallest values (False).

True
configuration Optional[Configuration]

Optional FHE compiler configuration object.

None

Returns:

Type Description
Circuit

fhe.Circuit: The compiled top-k reduction circuit.

Example
from concrete_fhe_toolkit import compile_top_k

circuit = compile_top_k(size=4, k=2, min_value=0, max_value=10)
print(circuit.encrypt_run_decrypt([4, 1, 3, 2]))  # [4, 3]
Source code in src/concrete_fhe_toolkit/arrays/sorting.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
def compile_top_k(
    size: int,
    k: int,
    min_value: int = 0,
    max_value: int = 15,
    *,
    largest: bool = True,
    configuration: Optional[fhe.Configuration] = None,
) -> fhe.Circuit:
    """Compile a top-k reduction circuit.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        k (int): The number of top elements to return.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.
        largest (bool): Whether to return the largest values (True) or smallest values (False).
        configuration (Optional[fhe.Configuration]): Optional FHE compiler configuration object.

    Returns:
        fhe.Circuit: The compiled top-k reduction circuit.

    Example:
        ```python
        from concrete_fhe_toolkit import compile_top_k

        circuit = compile_top_k(size=4, k=2, min_value=0, max_value=10)
        print(circuit.encrypt_run_decrypt([4, 1, 3, 2]))  # [4, 3]
        ```
    """
    size = validate_size(size)
    minimum, maximum = validate_bounds(min_value, max_value)
    function = make_top_k(size, k, minimum, maximum, largest=largest)
    return _compile_array_function(function, size, minimum, maximum, configuration)

make_compare_swap

make_compare_swap(min_value: int = 0, max_value: int = 15) -> BinaryScalarFunction

Create an ascending compare-swap function for bounded encrypted integers.

Parameters:

Name Type Description Default
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

0
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15

Returns:

Name Type Description
BinaryScalarFunction BinaryScalarFunction

A function that sorts two encrypted values.

Example
from concrete_fhe_toolkit import make_compare_swap

swap = make_compare_swap(min_value=0, max_value=10)
# Use `swap(x, y)` inside an FHE program compilation
Source code in src/concrete_fhe_toolkit/arrays/sorting.py
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
def make_compare_swap(
    min_value: int = 0,
    max_value: int = 15,
) -> BinaryScalarFunction:
    """Create an ascending compare-swap function for bounded encrypted integers.

    Args:
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.

    Returns:
        BinaryScalarFunction: A function that sorts two encrypted values.

    Example:
        ```python
        from concrete_fhe_toolkit import make_compare_swap

        swap = make_compare_swap(min_value=0, max_value=10)
        # Use `swap(x, y)` inside an FHE program compilation
        ```
    """
    minimum, maximum = validate_bounds(min_value, max_value)
    span = maximum - minimum

    if span == 0:
        def compare_equal(x: Any, y: Any) -> Any:
            """Compare two equal elements."""
            return x, y

        return compare_equal

    positive_difference = positive_difference_lut(span)

    def compare_swap(x: Any, y: Any) -> Any:
        """Compare and swap two elements."""
        positive = positive_difference[x - y + span]
        return x - positive, y + positive

    return compare_swap

make_sort

make_sort(size: int, min_value: int = 0, max_value: int = 15, *, descending: bool = False) -> UnaryArrayFunction

Create a fixed-size bitonic sorting network.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

0
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15
descending bool

Whether to sort in descending order instead of ascending.

False

Returns:

Name Type Description
UnaryArrayFunction UnaryArrayFunction

A function that sorts the input array.

Example
from concrete_fhe_toolkit import make_sort

sort_fn = make_sort(size=4, min_value=0, max_value=10)
# Use `sort_fn(array)` inside an FHE program compilation
Source code in src/concrete_fhe_toolkit/arrays/sorting.py
 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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def make_sort(
    size: int,
    min_value: int = 0,
    max_value: int = 15,
    *,
    descending: bool = False,
) -> UnaryArrayFunction:
    """Create a fixed-size bitonic sorting network.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.
        descending (bool): Whether to sort in descending order instead of ascending.

    Returns:
        UnaryArrayFunction: A function that sorts the input array.

    Example:
        ```python
        from concrete_fhe_toolkit import make_sort

        sort_fn = make_sort(size=4, min_value=0, max_value=10)
        # Use `sort_fn(array)` inside an FHE program compilation
        ```
    """
    size = validate_size(size, power_of_two=True)
    minimum, maximum = validate_bounds(min_value, max_value)
    compare_swap = make_compare_swap(minimum, maximum)

    def sort_values(x: Any) -> Any:
        """Sort an array of elements."""
        values = [x[index] for index in range(size)]
        width = 2

        while width <= size:
            distance = width // 2
            while distance > 0:
                for left in range(size):
                    right = left ^ distance
                    if right <= left:
                        continue

                    low, high = compare_swap(values[left], values[right])
                    if left & width:
                        values[left], values[right] = high, low
                    else:
                        values[left], values[right] = low, high
                distance //= 2
            width *= 2

        if descending:
            values.reverse()
        return fhe.array(values)

    return sort_values

make_top_k

make_top_k(size: int, k: int, min_value: int = 0, max_value: int = 15, *, largest: bool = True) -> UnaryArrayFunction

Create a reduction returning the k largest (or smallest) values in order.

Uses a sorting network (Bitonic Sort) and slices the top k elements, which is significantly more efficient in FHE than iterative greedy selection.

Note: Requires size to be a power of two (2, 4, 8...) due to the underlying sort.

Parameters:

Name Type Description Default
size int

The fixed size of the input array, must be known at compile time.

required
k int

The number of top elements to return.

required
min_value int

The lower bound for the encrypted inputs, used to dimension the FHE circuit.

0
max_value int

The upper bound for the encrypted inputs, used to dimension the FHE circuit.

15
largest bool

Whether to return the largest values (True) or smallest values (False).

True

Returns:

Name Type Description
UnaryArrayFunction UnaryArrayFunction

A function that returns the top k values of the input array.

Example
from concrete_fhe_toolkit import make_top_k

top_k_fn = make_top_k(size=4, k=2, min_value=0, max_value=10)
# Use `top_k_fn(array)` inside an FHE program compilation
Source code in src/concrete_fhe_toolkit/arrays/sorting.py
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
227
228
229
230
231
232
233
234
235
236
237
def make_top_k(
    size: int,
    k: int,
    min_value: int = 0,
    max_value: int = 15,
    *,
    largest: bool = True,
) -> UnaryArrayFunction:
    """Create a reduction returning the k largest (or smallest) values in order.

    Uses a sorting network (Bitonic Sort) and slices the top k elements,
    which is significantly more efficient in FHE than iterative greedy selection.

    Note: Requires `size` to be a power of two (2, 4, 8...) due to the underlying sort.

    Args:
        size (int): The fixed size of the input array, must be known at compile time.
        k (int): The number of top elements to return.
        min_value (int): The lower bound for the encrypted inputs, used to dimension the FHE circuit.
        max_value (int): The upper bound for the encrypted inputs, used to dimension the FHE circuit.
        largest (bool): Whether to return the largest values (True) or smallest values (False).

    Returns:
        UnaryArrayFunction: A function that returns the top k values of the input array.

    Example:
        ```python
        from concrete_fhe_toolkit import make_top_k

        top_k_fn = make_top_k(size=4, k=2, min_value=0, max_value=10)
        # Use `top_k_fn(array)` inside an FHE program compilation
        ```
    """
    size = validate_size(size, power_of_two=True)
    minimum, maximum = validate_bounds(min_value, max_value)
    k = validate_size(k)
    if k > size:
        raise ValueError("k cannot exceed size")

    # Use bitonic sort
    sort_fn = make_sort(size, minimum, maximum, descending=largest)

    def top_k(x: Any) -> Any:
        """Find the top k elements in an array."""
        sorted_arr = sort_fn(x)
        return sorted_arr[:k]

    return top_k