HEaaN.SDK core
- class heaan_sdk.context.Context(parameter: HEParameter, key_dir_path: str | Path, generate_keys: bool = False, load_keys: str = 'none', use_gpu: bool = True, rk_indices: List[int] | None = None, gpu_list: Set[int] | None = {0})
A Context is an object containing information for HE, such as parameter for HE, whether to generate keys, which keys will be loaded on memory, which to use GPU, and so on.
- __init__(parameter: HEParameter, key_dir_path: str | Path, generate_keys: bool = False, load_keys: str = 'none', use_gpu: bool = True, rk_indices: List[int] | None = None, gpu_list: Set[int] | None = {0})
Create Context object.
- Parameters:
parameter (HEParameter) – Parameter for HE.
key_dir_path (Union[str, Path]) – Path to the key.
generate_keys (bool, optional) – Whether you generate new keys or use existing keys. Defaults to False.
load_keys (str, optional) – Determine which type of keys to be loaded. Defaults to “none”. If load_keys is “all”, load both public keys and secret key. If load_keys is “pk”, load public keys only. If load_keys is “enc”, load encryption key only. If load_keys is “enc_dec”, load encryption key and decryption key(secret key). If load_keys is “dec”, load decryption key(secret key) only.
use_gpu (bool, optional) – If use_gpu is True / False, send input items to GPU / CPU. If GPU is not available, it becomes False even if it is set to True. Defaults to True.
rk_indices (Optional[List[int]], optional) – Indices of left rotation indices for additional rotation keys. Defaults to None.
gpu_list (Optional[Set[int]], optional) – GPU device IDs identified by CUDA driver. Check how many GPUs are installed in your system and how enumerated by CUDA driver first before trying manual assignment. Defaults to {0}.
Examples
>>> import heaan_sdk >>> params = heaan_sdk.HEParameter.from_preset("FGb") >>> context = heaan_sdk.Context(params, key_dir_path="keys", load_keys="all", generate_keys=True) The currently used HEaaN library does not support GPU acceleration (if HEaaN.lib is designed for CPU.) CUDA is not available. (if CUDA is not availiable.) HEaaN-SDK uses CUDA v11.7 (> v11.2) (if CUDA is installed and CUDA version satisfies for using HEaaN-SDK.) >>> context Context( heaan type: real, parameter: FGb, key dir path: "keys", loaded key type: "all", GPU: Not available )
- generate_bootstrapper() None
Generate HEaaN.Bootstrapper.
- generate_homevaluator() None
Generate HEaaN.homEvaluator.
- generate_public_key(rk_indices: List[int] | None = None)
Generate publick keys from secret key. Assumes that secret key is already generated and key_dir_path is already setted.
- Parameters:
rk_indices (Optional, optinal[List[int]]) – Indices of left rotation indices for additional rotation keys. If not None, then generate the corresponding rotation keys and remove other rotation keys. Defaults to None.
- generate_secret_key() None
Generate secret key.
- get_available_memory(device_type, device_id: int = 0) int
Return available memory for homomorphic operations. :param device_type: Device type one of the followings:
heaan.DeviceType.CPU
heaan.DeviceType.GPU
“cpu”
“gpu”
- Parameters:
device_id (int) – GPU ID if device_type is heaan.DeviceType.GPU.
- Returns:
Total memory of device minus memory for context.
- Return type:
int
- Raises:
ValueError – When trying to get a GPU device and with_gpu == False.
- get_device(device_type, device_id: int = 0) Any | None
Return device for computation :param device_type: Device type one of the followings:
heaan.DeviceType.CPU
heaan.DeviceType.GPU
“cpu”
“gpu”
- Parameters:
device_id (int) – GPU ID if device_type is heaan.DeviceType.GPU.
- Returns:
Corresponding computing device. None is returned if there is no such device.
- Raises:
ValueError – When trying to get a GPU device and with_gpu == False.
- get_duration() int
Privide an walltime latency(in ms unit) that could be approximately expected on real HEaaN.
- get_key_dir_path() Path
Return path of the KeyPack of the context.
- Returns:
Path of the KeyPack of the context.
- Return type:
Path
- history(verbose: bool = False)
Get the history of all operations from heaan.
- init_pk() None
Init HEaaN.KeyPack.
- property level_after_full_slot_bootstrap: int
Level after (full-slot) bootstrapped.
- Raises:
Exception – When parameter is not bootstrappable.
- Returns:
Level after full-slot bootstrap.
- Return type:
int
- load_all_keys() None
Load EncKey, MultKey, ConjKey, RotKeys, and secretkey.
- load_all_pks() None
Load EncKey, MultKey, ConjKey, and RotKeys.
- load_conjk() None
Load conjugation key.
- load_ek() None
Load encryption key.
- load_mk() None
Load multiplication key.
- load_rk(idx: int) None
Load (left) rotation key of given index.
- load_rks() None
Load all rotation keys.
- load_sk() None
Load secret key.
- property min_level_for_bootstrap: int
The smallest bootstrappable level.
- Raises:
Exception – When parameter is not bootstrappable.
- Returns:
The smallest bootstrappable level.
- Return type:
int
- property min_level_for_bootstrap_extended: int
The smallest large-range-bootstrappable level.
- Raises:
Exception – When parameter is not bootstrappable.
- Returns:
The smallest large-range-bootstrappable level.
- Return type:
int
- property num_slots: int
Return number of slots of context.
- Returns:
Number of slots of context.
- Return type:
int
- set_key_dir_path(key_dir_path: str | Path) None
Set path of the KeyPack of the Context.
- simulate_error(onoff: bool = True)
En/disable to simulate HEaaN approximation errors for simulator.
- start_stopwatch()
Mark the starting point of temporal boundary where arbitrary HE operations can be consumed within.
- stop_stopwatch()
Mark the ending point of temporal boundary.
- class heaan_sdk.keypack.KeyPack
KeyPack manages homomorphic encryption keys. Key directory structure is organized as follow:
key_dir_path ├ public_keypack │ └ PK │ ├ EncKey.bin │ ├ MultKey.bin │ ├ ConjKey.bin │ ├ RotKey1.bin │ ├ RotKey2.bin │ └ ... └ secret_keypack └ secretkey.bin
- __init__() None
Create KeyPack object.
- generate_public_key(context, rk_indices: List[int] | None = None) None
Generate publick keys from secret key. Assumes that secret key is already generated and key_dir_path is already setted.
- Parameters:
context (Context) – heaan_sdk context.
rk_indices (Optional, optinal[List[int]]) – Indices of left rotation indices for additional rotation keys. If not None, then generate the corresponding rotation keys and remove other rotation keys. Defaults to None.
- generate_secret_key(context, path: str | Path | None = None) None
Generate secret key.
- Parameters:
context (Context) – heaan_sdk context.
path (Optional[Union[str, Path]], optional) – Directory to save secret key. Expect to ends with directory name secret_keypack. If None, it assumes that _key_dir_path is setted before. Defaults to None.
- get_key_dir_path() Path
Return path of the KeyPack.
- Returns:
Path of the KeyPack.
- Return type:
Path
- get_public_key_dir_path() Path
Return path of the public Keypack.
- Returns:
Path of the public Keypack.
- Return type:
Path
- get_secret_key_dir_path() Path
Return path of the secret Keypack.
- Returns:
Path of the secret Keypack.
- Return type:
Path
- init_public_key(context) None
Init HEaaN.KeyPack.
- load_all_keys(context) None
Load all public keys (encryption key, multiplication key, rotation keys, conjugation key), secret_key.
- Parameters:
context (Context) – heaan_sdk context.
- load_all_public_keys(context) None
Load all public keys (encryption key, multiplication key, rotation keys, conjugation key).
- Parameters:
context (Context) – heaan_sdk context.
- load_conjugation_key() None
Load conjugation key.
- load_encryption_key() None
Load encryption key.
- load_multiplication_key() None
Load multiplication key.
- load_rotation_key(idx: int) None
Load (left) rotation key corresponds to a given index.
- Parameters:
idx (int) – Index of rotation key.
- load_rotation_keys() None
Load all rotation keys.
- load_secret_key(context) None
Load secret key.
- static remove_rot_keys(pk_path: str | Path, indices: List[int] = [])
Remove rotation keys.
- Parameters:
pk_path (Union[str, Path]) – Public key path.
indices (List[int], optional) – (Left) rotation indices of keys to be removed. Defaults to [].
- set_key_dir_path(key_dir_path: str | Path) None
Set path of the KeyPack.
- class heaan_sdk.block.Block(context: Context, encrypted: bool = False, data: Iterable[Number] | None = None, is_complex: bool = False, is_identical: bool = False)
- Parameters:
context (Context) – Context of block.
encrypted (bool, optional) – Whether block is encrypted or not.
data (Optional[Iterable[Number]], optional) – Data to initialize block. Defaults to None.
is_complex (bool, optional) – Whether the data in block is complex or not. Defaults to False.
is_identical (bool, optional) – Whether block has identical values (all the entries are the same) or not. Defaults to False.
- Raises:
Exception – When path and data are both given.
- __init__(context: Context, encrypted: bool = False, data: Iterable[Number] | None = None, is_complex: bool = False, is_identical: bool = False)
- argminmax(minmax: str = 'min', numiter_g: int = 8, numiter_f: int = 3, log_slots: int | None = None) Block
For rows packed in the size size 2^`log_slots`, set the slot of minimum or maximum value in each row to 1. If there are ties, at least one position is set to 1.
- Parameters:
minmiax (str, optional) – Either “min” or “max”. Non-“max” values are considered to be “min”.
numiter_g (int, optional) – Number of iterations of approximating function g. Defaults to 8.
numiter_f (int, optional) – Number of iterations of approximating function f. Defaults to 3.
log_slots (int, optional) – Size of packed row in log2. If None, consinder the whole block as a row.
- Returns:
Result block.
- Return type:
- bootstrap(**kwargs) Block
Bootstrap block. If this is message, this method does nothing. If this is ciphertext, performs bootstrap. The encrypted values must fit in [-1.0, 1.0].
- Returns:
Bootstrapped block.
- Return type:
- bootstrap_extended(**kwargs) Block
Bootstrap block in large range. If this is message, this method does nothing. If this is ciphertext, performs bootstrap. The encrypted values must fit in [-2^20, 2^20].
- Returns:
Bootstrapped block.
- Return type:
- static bootstrap_extended_two_ctxts(block1, block2) Tuple[Block, Block]
Bootstrap two REAL ciphertexts in large range at once. Two blocks must be ciphertexts, otherwise this function raises TypeError. The encrypted values of blocks must fit in [-2^20, 2^20].
- static bootstrap_two_ctxts(block1: Block, block2: Block) Tuple[Block, Block]
Bootstrap two REAL ciphertexts at once. Two blocks must be ciphertexts, otherwise this function raises TypeError. The encrypted values of blocks must fit in [-1.0, 1.0].
- compare(other: Block, numiter_g: int = 8, numiter_f: int = 3) Block
Compare whether self is greater than other. If this is message, the result is exactly calculated. Otherwise, the result is approximated. In this case, |self - other| must fit in [2^-18, 1]. This range could be changed if numiter_g and numiter_f are different from the default values.
\[\begin{split}&\text{If } self - other \in [-1, 1],\\ &Compare(self, other) = \begin{cases} 0 &\text{if} & -1 & \leq & self - other & < & -2^{-18},\\ y \in (0, 1) & \text{if} & -2^{-18} & < & self - other & < & 2^{-18},\\ 1 & \text{if} & 2^{-18} & < & self - other & \leq & 1. \end{cases}\end{split}\]- Parameters:
- Returns:
Block where the data are the result of the comparison.
- Return type:
- conjugate(inplace=False) Block
Complex conjugation of block. Does not cost depth.
- Parameters:
inplace (bool, optional) – Whether to modify block rather than creating a new one. Defaults to False.
- Returns:
Complex conjugated block.
- Return type:
- copy(path: str | None = None) Block
Copy block to new location on memory.
- Returns:
Copied block
- Return type:
- decrypt(inplace: bool = True) Block
Decrypt block.
- Parameters:
inplace (bool, optional) – Whether to modify block rather than creating a new one. Defaults to True.
- Returns:
Decrypted block.
- Return type:
- Raises:
TypeError – When block is already plaintext.
- discrete_equal(other: Block | float | int, log_range: int = 12) Block
Evaluates whether self is equal to other discretely, where the discretely means that it distinguishes only whether self is either very close to other or at least 1 far from other. In other words, it returns 1 if self is almost equal to other, 0 if self is more than 1 away from other. If this is message, the result is exactly calculated. Otherwise, the result is approximated. In this case, all elements of the difference self - other must fit in [-2**log_range, 2**log_range]. The log_range shall be chosen in the range of [3, 15].
\[\begin{split}&\text{If } self - other \in [-2^{\text{log_range}}, 2^{\text{log_range}}],\\ &\text{self.discrete_equal(other)} = \begin{cases} 1 & \text{if} & & & |self - other| & \leq & \frac{1}{4},\\ y \in (0, 1) & \text{if} & \frac{1}{4} & < & |self - other| & < & \frac{3}{4},\\ 0 & \text{if} & \frac{3}{4} & \leq & |self - other| & \leq & 2^{\text{log_range}}. \end{cases}\end{split}\]- Parameters:
- Returns:
Block where the data are the result of the comparison.
- Return type:
- discrete_equal_zero(log_range: int = 12, inplace: bool = False) Block
Evaluates ‘self == 0’ if self is either very close to 0 or at least 1 far from 0. Returns 1 if self is equal to zero, 0 otherwise. If this is message, the result is exactly calculated. Otherwise, it uses an approximated method. log_range shall be chosen in the range of [3, 15]. In this case, all elements of self must fit in [-2**log_range, 2**log_range].
\[\begin{split}&\text{If } self \in [-2^{\text{log_range}}, 2^{\text{log_range}}],\\ &\text{self.discrete_equal(other)} = \begin{cases} 1 & \text{if} & & & |self| & \leq & \frac{1}{4},\\ y \in (0, 1) & \text{if} & \frac{1}{4} & < & |self| & < & \frac{3}{4},\\ 0 & \text{if} & \frac{3}{4} & \leq & |self| & \leq & 2^{\text{log_range}}. \end{cases}\end{split}\]- Parameters:
log_range (int, optional) – Value of log of the range such that the difference of self and other must fit in [-2**log_range, 2**log_range]. Defaults to 12.
inplace (bool, optional) – Whether to modify block rather than creating a new one. Defaults to False.
- Returns:
Block where the data are the result of the comparison with zero.
- Return type:
- encrypt(inplace: bool = True, target_level: int | None = None) Block
Encrypt block.
- Parameters:
inplace (bool, optional) – Whether to modify block rather than creating a new one. Defaults to False.
target_level (Optional[int], optional) – Target level for encryption. If None, then the result ciphertext would have maximum level. Defaults to None.
- Returns:
Encrypted block.
- Return type:
- Raises:
TypeError – When block is already encrypted.
- exp(base: float = 2.718281828459045) Block
Evaluates base^x if x is nonpositive. It uses an approximated method. TODO: range check?
- exp_remez() Block
Exponential function of e using remez approximation. If this is message, the result is exactly calculated. Otherwise, it uses an approximated method. In this case, it is approximated as exp(x) = g(x)^8, where g(x) = exp(x/8) is approximated using minimax approximation of degree 8 on [-1, 1]. It must fit in [-10.0, 10.0]. If block is message, a precise value is returned.
- exp_wide(n: int = 3) Block
Exponential function. If block is ciphertext, it is approximated as exp(x) = g(x)^8, where g(x) = exp(x/8) is approximated using minimax approximation of degree 8 on [-1, 1]. If block is message, a precise value is returned.
- classmethod fill(context: Context, value: Number, encrypted: bool = False, **kwargs) Block
Build block filled with a given value.
- Parameters:
context (Context) – Context of block.
value (Number) – Value to fill block with.
encrypted (bool, optional) – Whether block would be encrypted. Defaults to False.
- classmethod from_path(context: Context, path: str | Path, encrypted: bool = False, is_complex: bool = False, is_identical: bool = False, **kwargs) Block
Create block and load data from path into block.
- Parameters:
context (Context) – Context of block to be loaded.
path (Union[str, Path]) – Path to load data.
encrypted (bool, optional) – If block is encrypted or not. Defaults to False.
is_complex (bool, optional) – If the data are complex or not. It should be True if you are loading Message with complex values or Ciphertext with complex values encrypted. Defaults to False.
is_identical (bool, optional) – If block contains identical values or not. It should be True if you are loading Message with identical values. Defaults to False.
- Returns:
Loaded block.
- Return type:
- greater_than_zero(numiter_g: int = 8, numiter_f: int = 3) Block
Calculates whether self is greater than zero. If this is message, the result is exactly calculated. Otherwise, the result is approximated. In this case, |self| must fit in [2^-18, 1] respectively. This range could be changed if numiter_g and numiter_f are different from the default values.
\[\begin{split}&\text{If } self \in [-1, 1] \text{ and } other \in [-1, 1],\\ &\text{self.greater_than_zero()} = res\\ &\text{where }\\ &res = \begin{cases} 0 &\text{if} & -1 & \leq & self & < & -2^{-18},\\ y \in (0, 1) & \text{if} & -2^{-18} & < & self & < & 2^{-18},\\ 1 & \text{if} & 2^{-18} & < & self & \leq & 1, \end{cases}\\\end{split}\]- Parameters:
self (Block) – Block to compare with zero.
numiter_g (int, optional) – Number of iterations of approximating function g. Defaults to 8.
numiter_f (int, optional) – Number of iterations of approximating function f. Defaults to 3.
- Returns:
Block where contains the result of the comparison with 0.
- Return type:
- greater_than_zero_pair(other: Block, numiter_g: int = 8, numiter_f: int = 3) Tuple[Block, Block]
Simultaneously calculates whether self is greater than zero and whether other is greater than zero. If this is message, the result is exactly calculated. Otherwise, the result is approximated. In this case, |self| and |other| must fit in [2^-18, 1] respectively. This range could be changed if numiter_g and numiter_f are different from the default values.
\[\begin{split}&\text{If } self \in [-1, 1] \text{ and } other \in [-1, 1],\\ &\text{self.greater_than_zero_pair(other)} = res1 \text{, }res2\\ &\text{where }\\ &res1 = \begin{cases} 0 &\text{if} & -1 & \leq & self & < & -2^{-18},\\ y \in (0, 1) & \text{if} & -2^{-18} & < & self & < & 2^{-18},\\ 1 & \text{if} & 2^{-18} & < & self & \leq & 1, \end{cases}\\ &res2 = \begin{cases} 0 &\text{if} & -1 & \leq & other & < & -2^{-18},\\ y \in (0, 1) & \text{if} & -2^{-18} & < & other & < & 2^{-18},\\ 1 & \text{if} & 2^{-18} & < & other & \leq & 1. \end{cases}\end{split}\]- Parameters:
- Returns:
Two blocks where each contains the result of the comparison with 0.
- Return type:
- i_mult(inplace=False) Block
Multiply sqrt(-1) to block. Does not cost depth. is_complex attribute is always set to True, even when the data in block contains only pure imaginary numbers (sqrt(-1) * real).
- Parameters:
inplace (bool, optional) – Whether to modify block rather than creating a new one. Defaults to False.
- Returns:
Block multiplied by sqrt(-1).
- Return type:
- inverse(greater_than_one: bool = True, init: float | None = None, num_iter: int | None = None, inplace: bool = False) Block
Calculates 1/x. If this is message, the result is exactly calculated. Otherwise, it uses an approximated method. In this case, if greater_than_one is true, the input value must fit in [1, 2^18]. If greater_than_one is false, the input value must fit in [2^-10, 1]. These ranges could be changed if init and num_iter are given.
- Parameters:
greater_than_one (bool, optional) – Whether the inputs are greater than one or not, which is guaranteed in some special cases. If True, then the inputs must fit in [1, 2^18] (for default options). If False, then the inputs must fit in [2^-10, 1] (for default options). Defaults to True.
init (float, optional) – Initial value for the approximation. Defaults to None, which gives default value 2^-18 for greater_than_one=True and 2^-10 for greater_than_one=False.
num_iter (int, optional) – Iteration number for the approximation. Defaults to None, which gives default value 23 for greater_than_one=True and 15 for greater_than_one=False.
inplace (bool, optional) – Whether to modify block rather than creating a new one. Defaults to False.
- Returns:
Block where the data are the reciprocal of the originals.
- Return type:
- property level: int
Return level of block.
- Returns:
Level of block.
- Return type:
int
- level_down(target_level: int, inplace: bool = True) Block
Down level of block to the target level.
- Parameters:
target_level (int) – Down level of block with specified level.
inplace (bool, optional) – Whether to modify block rather than creating a new one. Defaults to True.
- Returns:
Block with specific level.
- Return type:
- static mask(context: Context, index: int, axis: int, unit_shape: Tuple[int, int], encrypted: bool = False, const: float | None = None) Block
Generate a mask block filled with ones. If const is not None, then the mask will be multiplied by it.
- need_bootstrap(cost_level: int = 2) bool
Whether bootstrapping is required to multiply by cost level number of times.
- Returns:
Whether bootstrapping is required to multiply by cost level number of times.
- Return type:
bool
- need_bootstrap_extended(cost_level: int = 2) bool
Whether extended bootstrapping is required to multiply by cost level number of times.
- Returns:
Whether extended bootstrapping is required to multiply by cost level number of times.
- Return type:
bool
- property num_slots: int
Return number of slots of the context of block.
- Returns:
Number of slots of the context of block.
- Return type:
int
- on_cpu() bool
Returns true if block is on CPU.
- Returns:
True if block is on CPU, false otherwise.
- Return type:
bool
- on_gpu() bool
Returns true if block is on GPU.
- Returns:
True if block is on GPU, false otherwise.
- Return type:
bool
- rotate_sum(rot_num: int | None = None, left_rotate: bool = True, inplace=False) Block
- Rotate block and accumulate the rotated ones to add them up. The result is block
such that each slot is the sum of ‘2**rot_num’ consecutive values.
- Parameters:
rot_num (Optional[int], optional) – How many times to repeat rotation and addition. If this is None, the number of iterations is set to context.log_slots. Defaults to None.
left_rotate (bool, optional) – Direction of rotation. Defaults to True.
inplace (bool, optional) – Whether to modify block rather than creating a new one. Defaults to False.
- Returns:
Block filled with sum of all slots.
- Return type:
- save(dst_path: str | Path, target_level: int | None = None) Block
Save block.
- Parameters:
dst_path (Union[str, Path]) – Path to save block.
target_level (Optional[int], optional) – If not None, then save block with the specified level. Defaults to None.
- shift(r: Block, direction: str = 'left', log_row_size: int | None = None, numiter_g: int = 8, numiter_f: int = 3) Block
Assuming that data is packed in a row of size power of 2, shift each row by encrypted amount to given direction. The shift operands are also assumed to be packed in the same shape as the input data to be shifted. If the shift operand is a float, rows are shifted by the `floor`ed operand. Note that all values in a row in the shift operand are identical.
Example
``` direction = “left” self = [1.1 1.2 1.3 1.4]
[2.1 2.2 2.3 2.4]
- r = [1.9 1.9 1.9 1.9]
[2.3 2.3 2.3 2.3]
- result = [1.2 1.3 1.4 * ]
[2.3 2.4 * * ]
- Parameters:
r (Block) – Encrypted shift amount.
direction (str) – Shift direction.
log_row_size (int) – Size of a packed row in log2.
numiter_g (int, optional) – Number of iterations of approximating function g. Defaults to 8.
numiter_f (int, optional) – Number of iterations of approximating function f. Defaults to 3.
- Returns:
Shifted block.
- Return type:
- sigmoid(domain_range: float = 8.0, wide: bool = False, domain_range_wide: float = 27.0, domain_extension_order: int = 10, domain_extension_rate: float = 2.0) Block
Approximated sigmoid. If this is message, the result is exactly calculated. Otherwise, the result is approximated. The domain is [-domain_range, domain_range].
- Parameters:
block (Block) – Input block.
domain_range (float, optional) – Input range of the (non-wide) sigmoid function, which corresponds to [-r, r]. Defaults to 8.0.
wide (bool, optional) – Whether to use sigmoid_wide (domain extended version of sigmoid) or not. Defaults to False.
domain_range_wide (float, optional) – domain range of the sigmoid_wide function. Defaults to 27.0.
domain_extension_order (int, optional) – domain extension order of the sigmoid_wide function. Defaults to 10.
domain_extension_rate (float, optional) – domain extension rate of the sigmoid_wide function. Defaults to 2.0.
- Returns:
Result block.
- Return type:
- sign(inplace: bool = False, log_range: int = 0) Block
Evaluates sign function, which is 1 when positive, -1 otherwise. If this is message, the result is exactly calculated. Otherwise, it uses an approximated method. Appropriate domain of approximation is [-R, -r] U [r, R], where R = 2^log_range and r = 2^(-18).
- Parameters:
inplace (bool, optional) – Whether to modify block rather than creating a new one. Defaults to False.
log_range (int, optional) – Log of the input range. Integer less than or equal to 38. Defaults to 0, which means that the domain of approximation is [-1, 1].
- Returns:
Result block.
- Return type:
- sort(N: int, ascent: bool = True, inplace: bool = False, only_last_stage: bool = False) Block
Sorts values. If this is message, the result is exactly calculated. Otherwise, the result is approximated. In this case, all elements must fit in [-0.5, 0.5].
- Parameters:
N (int) – Number of data. It must be a power of 2.
ascent (bool) – If true, sort in ascending order.
only_last_stage (bool) – If true, it only performs bitonic merge(the last part for the entire sort) rather than the entire sort. Defaults to False
- Returns:
Sorted block.
- Return type:
- sqrt(inplace: bool = False) Block
Calculates sqrt(x). If this is message, the result is exactly calculated. Otherwise, it uses an approximated method. In this case, the input value must fit in [2^-18, 2].
- Parameters:
inplace (bool, optional) – Whether to modify block rather than creating a new one. Defaults to False.
- Returns:
Block where the data are the square root of the originals.
- Return type:
- sqrt_inv(greater_than_one: bool = True, init: float | None = None, num_iter: int | None = None, inplace: bool = False) Block
Calculates 1/sqrt(x). If this is message, the result is exactly calculated. Otherwise, it uses an approximated method. In this case, if greater_than_one is true, the input value must fit in [1, 2^18]. If greater_than_one is false, the input value must fit in [2^-10, 1].
- Parameters:
greater_than_one (bool, optional) – Whether the inputs are greater than one or not, which is guaranteed in some special cases. If True, then the inputs must fit in [1, 2^18] (for default options). If False, then the inputs must fit in [2^-10, 1] (for default options). Defaults to True.
inplace (bool, optional) – Whether to modify block rather than creating a new one. Defaults to False.
- Returns:
Block where the data are the square root of reciprocal of the originals.
- Return type:
- subsort(log_row_size: int, numiter_g: int = 8, numiter_f: int = 3) Block
Sort packed rows respectively.
Example) self = [3 2 9 7 4 8 2 1]
[7 7 2 1 9 7 7 2] [1 0 2 3 2 8 8 1] [8 7 2 1 0 7 1 3]
log_row_size = 3 result = [1 2 2 3 4 7 8 9]
[1 2 2 7 7 7 7 9] [0 1 1 2 2 3 8 8] [0 1 1 2 2 7 7 8]
- Parameters:
log_row_size (int) – Size of a packed row in log2.
numiter_g (int, optional) – Number of iterations of approximating function g for Block.compare(). Defaults to 8.
numiter_f (int, optional) – Number of iterations of approximating function f for Block.compare(). Defaults to 3.
- Result:
Block: Row-wise sorted block
- sum(axis: int, direction: int, unit_shape: Tuple[int, int]) Block
Row-wise or Column-wise summation of block, packed in a row-major manner. Used for HESubMatrix and HEMatrix related methds.
- Parameters:
axis (int) – Axis to sum. 0 for row-wise, 1 for column-wise.
direction (int) – Direction to sum. 0 for forward, 1 for backward.
unit_shape (Tuple[int, int]) – Unit encoding shape for matrix.
- Raises:
ValueError – If axis or direct are not in (0, 1)
- Returns:
Result block.
- Return type:
- to(device) Block
Send block to specified device. :param device: The device where the ciphrtext or message is sent to. :type device: heaan.DeviceType
- Returns:
Transfered block.
- Return type:
- to_device() Block
Send block to GPU. It works only when a GPU device is available.
- Returns:
Block on GPU if GPU is available.
- Return type:
- to_ndarray() ndarray
Convert block to a 1d numpy array of shape (self.context.num_slots,)
- Raises:
Exception – When block is encrypted.
- Returns:
1D numpy array.
- Return type:
np.ndarray
- to_series() Series
Convert block to pandas Series.
- Returns:
Pandas Series created from block.
- Return type:
pd.Series
- Raises:
TypeError – When block is encrypted.
- twice_of_imag_part(inplace=False) Block
Compute 2 * Im(x) = (x.conjugate() - x).i_mult(). Use for algorithms based on complex packing. Result block will contain real data.