1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
|
### pyhegp --- Homomorphic encryption of genotypes and phenotypes
### Copyright © 2025 Arun Isaac <arunisaac@systemreboot.net>
###
### This file is part of pyhegp.
###
### pyhegp is free software: you can redistribute it and/or modify it
### under the terms of the GNU General Public License as published by
### the Free Software Foundation, either version 3 of the License, or
### (at your option) any later version.
###
### pyhegp is distributed in the hope that it will be useful, but
### WITHOUT ANY WARRANTY; without even the implied warranty of
### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
### General Public License for more details.
###
### You should have received a copy of the GNU General Public License
### along with pyhegp. If not, see <https://www.gnu.org/licenses/>.
from itertools import pairwise
import math
from pathlib import Path
import shutil
from click.testing import CliRunner
from hypothesis import given, settings, strategies as st
from hypothesis.extra.numpy import arrays, array_shapes
import numpy as np
import pandas as pd
import pytest
from pytest import approx
from pyhegp.pyhegp import Stats, main, hegp_encrypt, hegp_decrypt, random_key, pool_stats, standardize, unstandardize, cat_genotype
from pyhegp.serialization import Summary, read_summary, read_genotype, is_genotype_metadata_column
from pyhegp.utils import negate
from helpers.strategies import *
@given(st.lists(st.lists(arrays("float64",
st.shared(array_shapes(min_dims=1, max_dims=1),
key="pool-vector-length"),
elements=st.floats(min_value=-100, max_value=100)),
min_size=2),
min_size=1))
def test_pool_stats(pools):
combined_pool = sum(pools, [])
pooled_stats = pool_stats([Stats(len(pool),
np.mean(pool, axis=0),
np.std(pool, axis=0, ddof=1))
for pool in pools])
assert (pooled_stats.n == len(combined_pool)
and pooled_stats.mean == approx(np.mean(combined_pool, axis=0),
rel=1e-6)
and pooled_stats.std == approx(np.std(combined_pool, axis=0, ddof=1),
rel=1e-6))
def test_encrypt_command(tmp_path):
shutil.copy("test-data/encrypt-test-genotype.tsv", tmp_path)
ciphertext = tmp_path / "encrypt-test-genotype.tsv.hegp"
result = CliRunner().invoke(main, ["encrypt",
"-s", "test-data/encrypt-test-summary",
str(tmp_path / "encrypt-test-genotype.tsv")])
assert result.exit_code == 0
assert ciphertext.exists()
assert "Dropped 1 SNP(s)" in result.output
with ciphertext.open("rb") as genotype_file:
encrypted_genotype = read_genotype(genotype_file)
# TODO: Properly compare encrypted genotype data frame with
# expected output once it is possible to specify the key.
assert len(encrypted_genotype) == 3
def no_column_zero_standard_deviation(matrix):
return not np.any(np.isclose(np.std(matrix, axis=0), 0))
@given(st.one_of(
arrays("int32",
array_shapes(min_dims=2, max_dims=2, min_side=2),
elements=st.integers(min_value=0, max_value=2)),
# The array above is the only realistic input, but we test more
# kinds of inputs for good measure.
arrays("int32",
array_shapes(min_dims=2, max_dims=2, min_side=2),
elements=st.integers(min_value=0, max_value=100)),
arrays("float64",
array_shapes(min_dims=2, max_dims=2, min_side=2),
elements=st.floats(min_value=0, max_value=100))))
def test_hegp_encryption_decryption_are_inverses(plaintext):
rng = np.random.default_rng()
key = random_key(rng, len(plaintext))
assert hegp_decrypt(hegp_encrypt(plaintext, key), key) == approx(plaintext)
@given(arrays("float64",
array_shapes(min_dims=2, max_dims=2),
elements=st.floats(min_value=0, max_value=100))
# Reject matrices with zero standard deviation columns since
# they trigger a division by zero.
.filter(no_column_zero_standard_deviation))
def test_standardize_unstandardize_are_inverses(matrix):
mean = np.mean(matrix, axis=0)
standard_deviation = np.std(matrix, axis=0)
assert unstandardize(standardize(matrix, mean, standard_deviation),
mean, standard_deviation) == approx(matrix)
def square_matrices(order, elements=None):
def generate(draw):
n = draw(order)
return draw(arrays("float64", (n, n), elements=elements))
return st.composite(generate)
def is_singular(matrix):
# We want to avoid nearly singular matrices as well. Hence, we set
# a looser absolute tolerance.
return math.isclose(np.linalg.det(matrix), 0, abs_tol=1e-6)
@given(square_matrices(st.shared(st.integers(min_value=2, max_value=7),
key="n"),
elements=st.floats(min_value=0, max_value=10))()
.filter(negate(is_singular)),
arrays("float64",
st.shared(st.integers(min_value=2, max_value=7),
key="n"),
elements=st.floats(min_value=0, max_value=10)))
def test_conservation_of_solutions(genotype, phenotype):
rng = np.random.default_rng()
key = random_key(rng, len(genotype))
assert (approx(np.linalg.solve(genotype, phenotype),
abs=1e-6, rel=1e-6)
== np.linalg.solve(hegp_encrypt(genotype, key),
hegp_encrypt(phenotype, key)))
def test_pool_command(tmp_path):
columns = ["chromosome", "position", "reference", "mean", "std"]
complete_summary = tmp_path / "complete-summary"
result = CliRunner().invoke(main, ["pool",
"-o", complete_summary,
"test-data/pool-test-summary1",
"test-data/pool-test-summary2"],
catch_exceptions=True)
assert result.exit_code == 0
assert complete_summary.exists()
assert "Dropped 2 SNP(s)" in result.output
with complete_summary.open("rb") as summary_file:
pooled_summary = read_summary(summary_file)
with open("test-data/pool-test-complete-summary", "rb") as summary_file:
expected_pooled_summary = read_summary(summary_file)
pd.testing.assert_frame_equal(pooled_summary.data,
expected_pooled_summary.data)
assert pooled_summary.n == expected_pooled_summary.n
@st.composite
def catenable_genotype_frames(draw):
genotype = draw(genotype_frames())
metadata_columns = list(filter(is_genotype_metadata_column,
genotype.columns))
metadata = genotype[metadata_columns]
sample_names = [column
for column in genotype.columns
if column not in metadata_columns]
genotype_matrix = genotype[sample_names]
split_points = sorted(draw(st.lists(st.integers(min_value=0,
max_value=len(sample_names)),
min_size=0,
## Something reasonably small.
max_size=len(sample_names))))
return [pd.concat((metadata, genotype_matrix[sample_names[start:end]]),
axis="columns")
for start, end
in pairwise([0] + split_points + [len(sample_names)])]
@pytest.mark.xfail
@given(catenable_genotype_frames())
def test_cat_genotype(genotypes):
def metadata_columns(genotype):
return list(filter(is_genotype_metadata_column,
genotype.columns))
def sample_columns(genotype):
return list(filter(negate(is_genotype_metadata_column),
genotype.columns))
complete_genotype = cat_genotype(genotypes)
# Assert that the result has the correct shape.
assert (complete_genotype.shape
== (genotypes[0].shape[0],
sum(len(sample_columns(genotype)) for genotype in genotypes)
+ len(metadata_columns(genotypes[0]))))
# Assert that the result has samples from all data frames.
assert (sample_columns(complete_genotype)
== [column
for genotype in genotypes
for column in sample_columns(genotype)])
def test_simple_workflow(tmp_path):
shutil.copy(f"test-data/genotype.tsv", tmp_path)
ciphertext = tmp_path / "genotype.tsv.hegp"
result = CliRunner().invoke(main,
["encrypt", str(tmp_path / "genotype.tsv")])
assert result.exit_code == 0
assert ciphertext.exists()
def test_joint_workflow(tmp_path):
runner = CliRunner()
for i in range(4):
shutil.copy(f"test-data/genotype{i}.tsv", tmp_path)
summary = tmp_path / f"summary{i}"
result = runner.invoke(
main, ["summary", str(tmp_path / f"genotype{i}.tsv"),
"-o", summary])
assert result.exit_code == 0
assert summary.exists()
complete_summary = tmp_path / "complete-summary"
result = runner.invoke(
main, ["pool",
"-o", complete_summary,
*(str(tmp_path / f"summary{i}") for i in range(4))])
assert result.exit_code == 0
assert complete_summary.exists()
for i in range(4):
ciphertext = tmp_path / f"genotype{i}.tsv.hegp"
result = runner.invoke(
main, ["encrypt",
"-s", complete_summary,
str(tmp_path / f"genotype{i}.tsv")])
assert result.exit_code == 0
assert ciphertext.exists()
complete_ciphertext = tmp_path / "complete-genotype.tsv.hegp"
result = runner.invoke(
main, ["cat",
"-o", complete_ciphertext,
*(str(tmp_path / f"genotype{i}.tsv.hegp") for i in range(4))])
assert result.exit_code == 0
assert complete_ciphertext.exists()
|