fastmixture2 2.0.7__tar.gz → 2.0.9__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. {fastmixture2-2.0.7/fastmixture2.egg-info → fastmixture2-2.0.9}/PKG-INFO +1 -1
  2. fastmixture2-2.0.9/fastmixture2/__init__.py +1 -0
  3. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/fastmixture2/defaults.py +8 -0
  4. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/fastmixture2/em.pyx +36 -31
  5. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/fastmixture2/functions.py +12 -21
  6. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/fastmixture2/gpu.py +14 -4
  7. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/fastmixture2/shared.pyx +26 -0
  8. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/fastmixture2/sqp.pyx +12 -4
  9. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/fastmixture2/utils.py +43 -18
  10. {fastmixture2-2.0.7 → fastmixture2-2.0.9/fastmixture2.egg-info}/PKG-INFO +1 -1
  11. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_adversarial_io.py +25 -0
  12. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_cli.py +7 -0
  13. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_cpu_scaling.py +227 -92
  14. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_genotypes.py +65 -0
  15. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_plink_files.py +18 -0
  16. fastmixture2-2.0.7/fastmixture2/__init__.py +0 -1
  17. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/LICENSE +0 -0
  18. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/MANIFEST.in +0 -0
  19. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/README.md +0 -0
  20. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/fastmixture2/fastmixture2.py +0 -0
  21. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/fastmixture2/kernels.py +0 -0
  22. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/fastmixture2/main.py +0 -0
  23. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/fastmixture2/packed.pxd +0 -0
  24. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/fastmixture2/plink.py +0 -0
  25. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/fastmixture2/svd.pyx +0 -0
  26. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/fastmixture2/threads.pxd +0 -0
  27. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/fastmixture2.egg-info/SOURCES.txt +0 -0
  28. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/fastmixture2.egg-info/dependency_links.txt +0 -0
  29. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/fastmixture2.egg-info/entry_points.txt +0 -0
  30. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/fastmixture2.egg-info/requires.txt +0 -0
  31. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/fastmixture2.egg-info/top_level.txt +0 -0
  32. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/pyproject.toml +0 -0
  33. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/setup.cfg +0 -0
  34. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/setup.py +0 -0
  35. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/check_portable.py +0 -0
  36. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/helpers.py +0 -0
  37. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/run_tests.py +0 -0
  38. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_bootstrap.py +0 -0
  39. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_convergence.py +0 -0
  40. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_cpu_subset.py +0 -0
  41. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_cross_validation.py +0 -0
  42. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_distribution.py +0 -0
  43. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_frequency_cache.py +0 -0
  44. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_gpu_called.py +0 -0
  45. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_gpu_em.py +0 -0
  46. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_gpu_gl_precision.py +0 -0
  47. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_gpu_large.py +0 -0
  48. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_gpu_modes.py +0 -0
  49. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_gpu_precision.py +0 -0
  50. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_gpu_safety.py +0 -0
  51. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_gpu_stat_reuse.py +0 -0
  52. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_gpu_streamed.py +0 -0
  53. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_gpu_subset.py +0 -0
  54. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_gpu_supervision.py +0 -0
  55. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_gpu_svd_cache.py +0 -0
  56. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_initialization.py +0 -0
  57. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_likelihoods.py +0 -0
  58. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_numerical_equivalence.py +0 -0
  59. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_optimizers.py +0 -0
  60. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_q_constraints.py +0 -0
  61. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_restarts.py +0 -0
  62. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_sqp_scoring.py +0 -0
  63. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_sqp_solver.py +0 -0
  64. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_subset_modes.py +0 -0
  65. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/test_threads.py +0 -0
  66. {fastmixture2-2.0.7 → fastmixture2-2.0.9}/tests/validate_distribution.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fastmixture2
3
- Version: 2.0.7
3
+ Version: 2.0.9
4
4
  Summary: Biobank-scale ancestry estimation in unrelated individuals
5
5
  Author-email: "J. Meisner" <meisnerucph@gmail.com>, "L. Thunegard" <lisathunegard@icloud.com>
6
6
  License-Expression: GPL-3.0-only
@@ -0,0 +1 @@
1
+ __version__ = "2.0.9"
@@ -100,6 +100,14 @@ def sqpMarkerChunk(M, K, chunk=SQP_MARKER_CHUNK):
100
100
  return max(1, min(M, chunk, SQP_MARKER_WORKSPACE_BYTES // b))
101
101
 
102
102
 
103
+ ### Bound CPU sample shards
104
+ def sqpSampleChunk(N, K, chunk=None):
105
+ if chunk is None:
106
+ chunk = 16_384 if K <= 16 else SQP_SAMPLE_CHUNK
107
+ n = max(1, SQP_SAMPLE_WORKSPACE_BYTES // (8 * K * (K + 1)))
108
+ return min(N, chunk, n)
109
+
110
+
103
111
  ### Bound the CUDA tile size
104
112
  def gpuTileBytes(size, limit=GPU_TILE_BYTES):
105
113
  return min(limit, max(GPU_MIN_TILE_BYTES, size // 8))
@@ -27,6 +27,10 @@ cdef extern from *:
27
27
  #include <stddef.h>
28
28
  #include <stdint.h>
29
29
 
30
+ static inline void fm_em_barrier(void) {
31
+ #pragma omp barrier
32
+ }
33
+
30
34
  // Select vectorized portable EM rows
31
35
  #if defined(FASTMIXTURE2_DISPATCH) && defined(__GLIBC__) && \
32
36
  (defined(__x86_64__) || defined(__i386__)) && \
@@ -511,6 +515,7 @@ cdef extern from *:
511
515
  void fm_q_weight_15(const f64*, const f64*, f64*, const u8*, size_t, u32) noexcept nogil
512
516
  void fm_q_weight_16(const f64*, const f64*, f64*, const u8*, size_t, u32) noexcept nogil
513
517
  size_t fm_em_workspace_bytes(size_t, size_t) noexcept nogil
518
+ void fm_em_barrier() noexcept nogil
514
519
 
515
520
  cdef const f64 PRO_MIN = 1e-5
516
521
  cdef const f64 PRO_MAX = 1.0 - 1e-5
@@ -1733,7 +1738,6 @@ cdef int _tiledEm(
1733
1738
  Py_ssize_t n_blk = min(4096, max(16, _EM_STATS_TILE_BYTES // (8 * K)))
1734
1739
  Py_ssize_t mb, nb, b, e, beg, end, j, marker, z, i, k, x, r
1735
1740
  int tid, n_thr, n_use
1736
- int used[1]
1737
1741
  bint fixed = P1 is None
1738
1742
  bint masked = fold >= 0
1739
1743
  bint weighted = weights is not None
@@ -1757,32 +1761,28 @@ cdef int _tiledEm(
1757
1761
  pa = pb = NULL
1758
1762
  n_use = min(N, omp.omp_get_max_threads())
1759
1763
  n_thr = n_use
1760
- used[0] = n_use
1761
1764
  g_all = <u8*>calloc(n_use * n_blk, sizeof(u8)) if not gl else NULL
1762
1765
  p_all = NULL if fixed else <f64*>calloc(n_use * c * 2 * K, sizeof(f64))
1763
1766
  if (not gl and g_all is NULL) or (not fixed and p_all is NULL):
1764
1767
  free(g_all)
1765
1768
  free(p_all)
1766
1769
  _memoryError()
1767
- for mb in range((M + c - 1) // c):
1768
- b = mb * c
1769
- e = min(b + c, M)
1770
- with nogil, parallel(num_threads=n_use):
1771
- tid = omp.omp_get_thread_num()
1772
- n_thr = omp.omp_get_num_threads()
1773
-
1774
- # Initialize thread-local scratch before storage dispatch
1775
- g = NULL
1776
- g_buf = NULL
1777
- pa = pb = NULL
1778
- sa = sb = 0.0
1779
- if tid == 0:
1780
- used[0] = n_thr
1781
- beg = N * tid // n_thr
1782
- end = N * (tid + 1) // n_thr
1783
- if not gl:
1784
- g_buf = &g_all[tid * n_blk]
1785
- g = g_buf
1770
+ with nogil, parallel(num_threads=n_use):
1771
+ # Reuse workers and buffers across marker blocks
1772
+ tid = omp.omp_get_thread_num()
1773
+ n_thr = omp.omp_get_num_threads()
1774
+ g = NULL
1775
+ g_buf = NULL
1776
+ pa = pb = NULL
1777
+ sa = sb = 0.0
1778
+ beg = N * tid // n_thr
1779
+ end = N * (tid + 1) // n_thr
1780
+ if not gl:
1781
+ g_buf = &g_all[tid * n_blk]
1782
+ g = g_buf
1783
+ for mb in range((M + c - 1) // c):
1784
+ b = mb * c
1785
+ e = min(b + c, M)
1786
1786
  if not fixed:
1787
1787
  for x in range(c * 2 * K):
1788
1788
  p_all[tid * c * 2 * K + x] = 0.0
@@ -1846,16 +1846,21 @@ cdef int _tiledEm(
1846
1846
  fm_em_partial_generic(
1847
1847
  &P[marker, 0], &Q[z, 0], &T[z, 0], g, r, pa, pb, w, K
1848
1848
  )
1849
- if not fixed:
1850
- for j in prange(e - b, schedule="static", num_threads=min(n_use, e - b)):
1851
- marker = b + j if s is None else s[b + j]
1852
- for k in range(2 * K):
1853
- for tid in range(1, used[0]):
1854
- p_all[j * 2 * K + k] += p_all[(tid * c + j) * 2 * K + k]
1855
- _outerAccelP(
1856
- &P[marker, 0], &P1[marker, 0],
1857
- &p_all[j * 2 * K], &p_all[j * 2 * K + K], K
1858
- )
1849
+ if not fixed:
1850
+ # Reduce P in a fixed worker order
1851
+ fm_em_barrier()
1852
+ for j in range((e - b) * tid // n_thr, (e - b) * (tid + 1) // n_thr):
1853
+ marker = b + j if s is None else s[b + j]
1854
+ for k in range(2 * K):
1855
+ for i in range(1, n_thr):
1856
+ p_all[j * 2 * K + k] += p_all[(i * c + j) * 2 * K + k]
1857
+ _outerAccelP(
1858
+ &P[marker, 0], &P1[marker, 0],
1859
+ &p_all[j * 2 * K], &p_all[j * 2 * K + K], K
1860
+ )
1861
+
1862
+ # Keep sample shards on the same marker block
1863
+ fm_em_barrier()
1859
1864
  free(g_all)
1860
1865
  free(p_all)
1861
1866
  return 0
@@ -447,21 +447,10 @@ def simplexBasis(K):
447
447
 
448
448
 
449
449
  ### Allocate bounded SQP workspaces
450
- def sqpState(
451
- P,
452
- Q,
453
- m_chunk=defaults.SQP_MARKER_CHUNK,
454
- n_chunk=defaults.SQP_SAMPLE_CHUNK,
455
- fixed=False,
456
- score=False,
457
- ):
450
+ def sqpState(P, Q, m_chunk=defaults.SQP_MARKER_CHUNK, n_chunk=None, fixed=False, score=False):
458
451
  K = defaults.validateK(Q.shape[1])
459
452
  m_chunk = defaults.sqpMarkerChunk(P.shape[0], K, m_chunk)
460
-
461
- # Bound Q statistics independently of panel size
462
- b = (K * K + K) * 8
463
- N = max(1, defaults.SQP_SAMPLE_WORKSPACE_BYTES // b)
464
- n_chunk = min(Q.shape[0], n_chunk, N)
453
+ n_chunk = defaults.sqpSampleChunk(Q.shape[0], K, n_chunk)
465
454
 
466
455
  # Omit P curvature buffers in projection mode
467
456
  S = {
@@ -532,8 +521,14 @@ def sqpMap(G, P, Q, P_out, Q_out, S, y=None, markers=None, weights=None, score=F
532
521
  try:
533
522
  for b in range(0, 0 if reuse else stop, c):
534
523
  e = min(b + c, stop)
535
- if y is not None and y.ndim == 1 and np.all(y[b:e]):
536
- continue
524
+ if y is not None and y.ndim == 1:
525
+ # Trim fixed rows at shard boundaries
526
+ u = y[b:e]
527
+ if np.all(u):
528
+ continue
529
+ if u[0] or u[-1]:
530
+ v = u == 0
531
+ b, e = b + v.argmax(), e - v[::-1].argmax()
537
532
  q = e - b
538
533
  if touch:
539
534
  shared.prefaultPacked(g, b, e, rows=rows)
@@ -675,7 +670,7 @@ def sqpRun(G, P, Q, q_nrm, y, run, L0=None, fixed=False, subset=False):
675
670
  E,
676
671
  Q,
677
672
  run.get("m_chunk", defaults.SQP_MARKER_CHUNK),
678
- run.get("n_chunk", defaults.SQP_SAMPLE_CHUNK),
673
+ run.get("n_chunk"),
679
674
  fixed=fixed,
680
675
  score=(
681
676
  y is None
@@ -876,11 +871,7 @@ def likelihoodRun(G, P, Q, q_nrm, y, run, L0=None, fixed=False, subset=False):
876
871
  T = None
877
872
 
878
873
  S = sqpState(
879
- P,
880
- Q,
881
- run.get("m_chunk", defaults.SQP_MARKER_CHUNK),
882
- run.get("n_chunk", defaults.SQP_SAMPLE_CHUNK),
883
- fixed=fixed,
874
+ P, Q, run.get("m_chunk", defaults.SQP_MARKER_CHUNK), run.get("n_chunk"), fixed=fixed
884
875
  )
885
876
  S["Z"] = zalState(P[:0] if fixed else P, Q)
886
877
  S["tol"] = tole * nrm
@@ -1140,10 +1140,20 @@ __device__ void tile_weights_impl(
1140
1140
  }
1141
1141
  const T eps = sizeof(T) == 4 ? T(1e-7) : T(1e-10);
1142
1142
  const T h = min(max(score[z], eps), T(1) - eps);
1143
- const T a = g >= 1 ? T(g) / h : T(0);
1144
- const T b = g <= 1 ? T(2 - g) / (T(1) - h) : T(0);
1145
- score[z] = a - b;
1146
- weight[z] = a / h + b / (T(1) - h);
1143
+ if constexpr (sizeof(T) == 4) {
1144
+ // Reuse float reciprocals as in the resident mixed path.
1145
+ const T x = g >= 1 ? T(1) / h : T(0);
1146
+ const T y = g <= 1 ? T(1) / (T(1) - h) : T(0);
1147
+ const T a = T(g) * x;
1148
+ const T b = T(2 - g) * y;
1149
+ score[z] = a - b;
1150
+ weight[z] = a * x + b * y;
1151
+ } else {
1152
+ const T a = g >= 1 ? T(g) / h : T(0);
1153
+ const T b = g <= 1 ? T(2 - g) / (T(1) - h) : T(0);
1154
+ score[z] = a - b;
1155
+ weight[z] = a / h + b / (T(1) - h);
1156
+ }
1147
1157
  #else
1148
1158
  const float *gl = (const float *)data + ((long long)row * L + n) * 3;
1149
1159
  if (signbit(gl[0]) || gl_flat(gl)) {
@@ -5,6 +5,8 @@
5
5
 
6
6
  __author__ = "Jonas Meisner"
7
7
 
8
+ from cpython.unicode cimport Py_UNICODE_ISSPACE
9
+
8
10
  cimport openmp as omp
9
11
  from cython.parallel import parallel, prange
10
12
  from libc.math cimport fabs, fmax, fmin, isfinite, log, pow
@@ -1955,3 +1957,27 @@ cpdef f64 loglikeWeighted(
1955
1957
  packedRow(B, rows, j), &P[j, 0], &Q[0, 0], N, K, j, fold, folds, seed
1956
1958
  )
1957
1959
  return total
1960
+
1961
+
1962
+ ### Count metadata rows across Unicode blocks
1963
+ def textRows(str text not None, Py_ssize_t[::1] state not None, int fields):
1964
+ if state.shape[0] != 3 or fields < 1:
1965
+ raise ValueError("Invalid text-row state")
1966
+ cdef:
1967
+ Py_ssize_t row = state[0], n = state[1]
1968
+ bint word = state[2]
1969
+ Py_UCS4 c
1970
+ for c in text:
1971
+ if c == 10:
1972
+ if n != fields:
1973
+ return -row - 1
1974
+ row += 1
1975
+ n = 0
1976
+ word = False
1977
+ elif Py_UNICODE_ISSPACE(c):
1978
+ word = False
1979
+ elif not word:
1980
+ n += 1
1981
+ word = True
1982
+ state[0], state[1], state[2] = row, n, word
1983
+ return 0
@@ -715,6 +715,14 @@ def _blasSetter(fn):
715
715
  return setThreads
716
716
 
717
717
 
718
+ ### Balance sample tiles across worker waves
719
+ cdef inline int _sampleTile(Py_ssize_t N, int nt) noexcept nogil:
720
+ cdef Py_ssize_t n = nt
721
+ if nt > 1:
722
+ n *= max(1, (N + 64 * nt - 1) // (64 * nt))
723
+ return min(64, max(8, ((N + n - 1) // n + 7) // 8 * 8))
724
+
725
+
718
726
  ### Bind SciPy BLAS lazily and bound the tile scratch across workers
719
727
  def blasWorkspace(
720
728
  int K, int M, int N, bint fixed=False,
@@ -728,7 +736,7 @@ def blasWorkspace(
728
736
  cdef:
729
737
  int kp = K * (K + 1) // 2
730
738
  int nt = max(1, omp.omp_get_max_threads())
731
- int ti = min(64, max(8, ((<Py_ssize_t>N + nt - 1) // nt + 7) // 8 * 8))
739
+ int ti = _sampleTile(N, nt)
732
740
  int tiles = (<Py_ssize_t>N + ti - 1) // ti
733
741
  Py_ssize_t width = 2 * 64 * 64 + 64 * kp + 64 * (kp + K) + 64 * K
734
742
  object cap, info
@@ -1000,7 +1008,7 @@ def updateBlas(
1000
1008
  return 0.0 if score else None
1001
1009
  ms, ws = &markers[0], &weights[0]
1002
1010
  if q_side:
1003
- ti = min(64, max(8, ((<Py_ssize_t>N + nt - 1) // nt + 7) // 8 * 8))
1011
+ ti = _sampleTile(N, nt)
1004
1012
  owner = ti if q_side else tj
1005
1013
  source = tj if q_side else ti
1006
1014
  tiles = ((<Py_ssize_t>N if q_side else <Py_ssize_t>M) + owner - 1) // owner
@@ -1015,9 +1023,9 @@ def updateBlas(
1015
1023
  if work.shape[1] < width:
1016
1024
  raise ValueError("BLAS workspace is smaller than one tile")
1017
1025
 
1018
- # Keep high-K products and worker scratch within 64 MiB
1026
+ # Cache reused products within the worker memory budget
1019
1027
  nr = P.shape[0] if q_side else N
1020
- if K >= 16 and ms == NULL and (
1028
+ if tiles > 1 and (not q_side or (K >= 16 and ms == NULL)) and (
1021
1029
  8 * (nr * <Py_ssize_t>kp + work.shape[0] * work.shape[1]) <= 64 << 20
1022
1030
  ):
1023
1031
  import numpy as np
@@ -56,20 +56,34 @@ def _validateDimensions(M, N):
56
56
 
57
57
  ### Count and validate one PLINK metadata table
58
58
  def _plinkRowCount(pth, fields, name):
59
- n = 0
59
+ state = np.zeros(3, dtype=np.intp)
60
+ last = "\n"
60
61
  try:
61
62
  with open(pth, "r", buffering=1024 * 1024) as src:
62
- for i, line in enumerate(src, start=1):
63
- if len(line.split(None, fields)) != fields:
64
- raise ValueError(f"Invalid {name} row {i}")
65
- n += 1
63
+ while block := src.read(1 << 20):
64
+ bad = shared.textRows(block, state, fields)
65
+ if bad:
66
+ raise ValueError(f"Invalid {name} row {-bad}")
67
+ last = block[-1]
68
+ if last != "\n":
69
+ bad = shared.textRows("\n", state, fields)
70
+ if bad:
71
+ raise ValueError(f"Invalid {name} row {-bad}")
66
72
  except UnicodeDecodeError as err:
67
73
  raise ValueError(f"Invalid text encoding in PLINK .{name.lower()} file") from err
68
- return n
74
+ return int(state[0])
69
75
 
70
76
 
71
77
  ### Verify identical sample IDs and order without retaining FAM tables
72
78
  def _sameSamples(a, b):
79
+ # Skip reparsing identical copies of the validated FAM
80
+ with open(a, "rb") as ref, open(b, "rb") as src:
81
+ while block := ref.read(1 << 20):
82
+ if block != src.read(len(block)):
83
+ break
84
+ else:
85
+ if not src.read(1):
86
+ return
73
87
  with open(a) as ref, open(b) as src:
74
88
  for i, (x, y) in enumerate(zip_longest(ref, src), start=1):
75
89
  if x is None or y is None:
@@ -940,7 +954,7 @@ def _refineSubset(G, P, Q, s, run, fit, limit=None, order=None):
940
954
  if order is not None:
941
955
  Q = np.ascontiguousarray(Q[order])
942
956
  if N > 1:
943
- sub["n_chunk"] = min(defaults.SQP_SAMPLE_CHUNK, N - N // 2)
957
+ sub["n_chunk"] = defaults.sqpSampleChunk(N - N // 2, Q.shape[1])
944
958
  y = Q[N - N // 2 :].copy()
945
959
  res = fit(X, P, Q, nrm, y, sub)
946
960
  if order is not None:
@@ -1057,23 +1071,34 @@ def _saveInfo(pth, X, rows, head, pops, chunk):
1057
1071
  ### Stream matrix rows and their identifiers to an open output
1058
1072
  def _writeInfo(out, X, rows, head, pops, chunk):
1059
1073
  miss = object()
1060
- fmt = "\t".join([defaults.OUTPUT_FORMAT] * X.shape[1]) + "\n"
1061
1074
  out.write("\t".join((*head, *pops)) + "\n")
1062
- for b in range(0, X.shape[0], chunk):
1063
- e = min(b + chunk, X.shape[0])
1075
+ for text in _matrixText(X, "\t", chunk):
1064
1076
  buf = []
1065
- for x in X[b:e]:
1077
+ for line in text.splitlines(keepends=True):
1066
1078
  row = next(rows, miss)
1067
1079
  if row is miss or len(row) != len(head):
1068
1080
  raise ValueError("Output metadata do not match the matrix rows")
1069
- buf.append("\t".join(row) + "\t" + fmt % tuple(x))
1081
+ buf.append("\t".join(row) + "\t" + line)
1070
1082
  out.writelines(buf)
1071
1083
  if next(rows, miss) is not miss:
1072
1084
  raise ValueError("Output metadata do not match the matrix rows")
1073
1085
 
1074
1086
 
1075
- ### Stream a plain matrix in bounded row chunks
1087
+ ### Format matrix text in bounded blocks
1088
+ def _matrixText(X, sep, chunk):
1089
+ fmt = sep.join([defaults.OUTPUT_FORMAT] * X.shape[1]) + "\n"
1090
+ n = min(chunk, max(1, 8_192 // max(1, X.shape[1])))
1091
+ for b in range(0, X.shape[0], n):
1092
+ x = X[b : b + n]
1093
+ yield (fmt * len(x)) % tuple(x.flat)
1094
+
1095
+
1096
+ ### Stream a plain matrix in bounded scalar blocks
1076
1097
  def _writeMatrix(out, X, chunk):
1098
+ X = np.asarray(X)
1099
+ if X.ndim == 2 and not np.iscomplexobj(X):
1100
+ out.writelines(_matrixText(X, " ", chunk))
1101
+ return
1077
1102
  for b in range(0, X.shape[0], chunk):
1078
1103
  np.savetxt(out, X[b : b + chunk], fmt=defaults.OUTPUT_FORMAT)
1079
1104
 
@@ -1081,17 +1106,17 @@ def _writeMatrix(out, X, chunk):
1081
1106
  ### Write Q with optional FID/IID columns
1082
1107
  def saveQ(pth, Q, rows=None, pops=None, chunk=65_536):
1083
1108
  if rows is None:
1084
- _atomicText(pth, np.savetxt, Q, fmt=defaults.OUTPUT_FORMAT)
1109
+ _atomicText(pth, _writeMatrix, Q, chunk)
1085
1110
  else:
1086
1111
  _saveInfo(pth, Q, rows, ("FID", "IID"), pops, chunk)
1087
1112
 
1088
1113
 
1089
- ### Write P in bounded marker chunks with optional SNP/allele columns
1114
+ ### Write P with optional SNP/allele columns
1090
1115
  def saveP(pth, P, rows=None, pops=None, chunk=65_536):
1091
- if rows is not None:
1116
+ if rows is None:
1117
+ _atomicText(pth, _writeMatrix, P, chunk)
1118
+ else:
1092
1119
  _saveInfo(pth, P, rows, ("SNP", "A1", "A2"), pops, chunk)
1093
- return
1094
- _atomicText(pth, _writeMatrix, P, chunk)
1095
1120
 
1096
1121
 
1097
1122
  ### Compute a thin SVD through its smaller Gram matrix
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fastmixture2
3
- Version: 2.0.7
3
+ Version: 2.0.9
4
4
  Summary: Biobank-scale ancestry estimation in unrelated individuals
5
5
  Author-email: "J. Meisner" <meisnerucph@gmail.com>, "L. Thunegard" <lisathunegard@icloud.com>
6
6
  License-Expression: GPL-3.0-only
@@ -306,6 +306,31 @@ class AdversarialIoTest(unittest.TestCase):
306
306
  with self.assertRaisesRegex(ValueError, "Invalid BIM row 1"):
307
307
  utils.readPlink(pfx)
308
308
 
309
+ def test_plink_metadata_validates_unicode_block_boundaries_and_line_endings(self):
310
+ row = "α" * (1_048_576 + 1) + " b c d e f\n"
311
+ cases = (
312
+ (b"", 0),
313
+ (b"a b c d e f", 1),
314
+ (b"a b c d e f\r\na b c d e f\r", 2),
315
+ ("a\u2003b\t\vc\fd\u00a0e\u202ff\n".encode(), 1),
316
+ (row.encode(), 1),
317
+ (b"\n", "Invalid BIM row 1"),
318
+ (b"a b c d e f g\n", "Invalid BIM row 1"),
319
+ (b"a b c d e f\n ", "Invalid BIM row 2"),
320
+ ((row + "a b c d e\n").encode(), "Invalid BIM row 2"),
321
+ (b"\xff", "Invalid text encoding"),
322
+ )
323
+ with tempfile.TemporaryDirectory() as dr:
324
+ pth = Path(dr) / "panel.bim"
325
+ for i, (data, want) in enumerate(cases):
326
+ with self.subTest(case=i):
327
+ pth.write_bytes(data)
328
+ if isinstance(want, int):
329
+ self.assertEqual(utils._plinkRowCount(pth, 6, "BIM"), want)
330
+ else:
331
+ with self.assertRaisesRegex(ValueError, want):
332
+ utils._plinkRowCount(pth, 6, "BIM")
333
+
309
334
  def test_plink_always_returns_packed_storage_with_exact_missing_counts(self):
310
335
  G = np.array([[0, 1, 2, 9, 1], [9, 9, 9, 9, 9], [2, 9, 0, 1, 2]], dtype=np.uint8)
311
336
  expected = 2.0 * np.sum(G != 9, axis=0)
@@ -252,6 +252,13 @@ print(int("numpy" in sys.modules), *(os.environ[key] for key in THREAD_ENV))
252
252
  self.assertEqual(defaults.K_MAX, 128)
253
253
  self.assertEqual(defaults.SQP_MARKER_CHUNK, 65_536)
254
254
  self.assertEqual(defaults.sqpMarkerChunk(1_000_000, 3), 65_536)
255
+ for k in (1, 5, 10, 16, 17, 32, 128):
256
+ n = 16_384 if k <= 16 else 4_096
257
+ self.assertEqual(defaults.sqpSampleChunk(100_000, k), n)
258
+ self.assertEqual(defaults.sqpSampleChunk(137, k), 137)
259
+ self.assertEqual(defaults.sqpSampleChunk(100_000, k, 73), 73)
260
+ n = defaults.sqpSampleChunk(1_000_000, k, 1_000_000)
261
+ self.assertLessEqual(n * 8 * k * (k + 1), defaults.SQP_SAMPLE_WORKSPACE_BYTES)
255
262
  for k in (3, 16, defaults.K_MAX):
256
263
  chunk = defaults.sqpMarkerChunk(1_000_000, k)
257
264
  b = (k * k + k) * 8
@@ -16,6 +16,54 @@ from fastmixture2 import defaults, functions, kernels, plink, shared, sqp
16
16
 
17
17
  ### Compare tiled CPU maps across storage layouts
18
18
  class CpuScalingTest(unittest.TestCase):
19
+ def test_supervised_shards_skip_fixed_boundaries(self):
20
+ rng = np.random.default_rng(928)
21
+ p = rng.uniform(0.1, 0.9, (17, 3))
22
+ q = rng.dirichlet(np.ones(3), 19)
23
+ y = np.zeros(19, np.uint8)
24
+ y[:3], y[-4:] = 1, 2
25
+ kernels.superQ(q, y)
26
+ x = rng.integers(0, 3, (17, 19), dtype=np.uint8)
27
+ L = np.stack([1.0 + 9.0 * (x == k) for k in range(3)], axis=2).astype(np.float32)
28
+ L /= L.sum(axis=2, keepdims=True)
29
+ for g in (packGenotypes(x), kernels.likelihoodData(L)):
30
+ ref, out = np.empty_like(q), np.empty_like(q)
31
+ S = functions.sqpState(p, q, n_chunk=16, fixed=True)
32
+ functions.sqpMap(g, p, q, None, ref, S)
33
+ kernels.superQ(ref, y)
34
+ with patch.object(sqp, "updateBlas", wraps=sqp.updateBlas) as update:
35
+ functions.sqpMap(g, p, q, None, out, S, y)
36
+ self.assertEqual(sum(call.args[3].shape[0] for call in update.call_args_list), 12)
37
+ np.testing.assert_allclose(out, ref, atol=2e-10, rtol=2e-10)
38
+
39
+ def test_wider_default_shards_preserve_called_and_likelihood_maps(self):
40
+ rng = np.random.default_rng(927)
41
+ m, n, k = 41, 16_401, 5
42
+ p = rng.uniform(0.1, 0.9, (m, k))
43
+ q = rng.dirichlet(np.ones(k), n)
44
+ x = rng.integers(0, 3, (m, n), dtype=np.uint8)
45
+ L = np.full((m, n, 3), 0.025, dtype=np.float32)
46
+ np.put_along_axis(L, x[..., None], 0.95, axis=2)
47
+ L[0], L[:, 7] = np.float32(1 / 3), np.float32(1 / 3)
48
+ x[0], x[:, 7] = 9, 9
49
+ for g in (packGenotypes(x), kernels.likelihoodData(L)):
50
+ for fixed in (False, True):
51
+ for score in (False,) if kernels.isLikelihood(g) else (False, True):
52
+ with self.subTest(likelihood=kernels.isLikelihood(g), fixed=fixed, score=score):
53
+ pr, qr = None if fixed else np.empty_like(p), np.empty_like(q)
54
+ pn, qn = None if fixed else np.empty_like(p), np.empty_like(q)
55
+ ref = functions.sqpState(p, q, n_chunk=4096, fixed=fixed)
56
+ cur = functions.sqpState(p, q, fixed=fixed, score=score)
57
+ self.assertEqual(cur["n"], 16_384)
58
+ functions.sqpMap(g, p, q, pr, qr, ref)
59
+ ll = functions.sqpMap(g, p, q, pn, qn, cur, score=score)
60
+ if not fixed:
61
+ np.testing.assert_allclose(pn, pr, atol=2e-10, rtol=2e-10)
62
+ np.testing.assert_allclose(qn, qr, atol=2e-10, rtol=2e-10)
63
+ assertValid(p if fixed else pn, qn)
64
+ if score:
65
+ self.assertAlmostEqual(ll, kernels.loglikeMissing(g, p, q), delta=2e-8)
66
+
19
67
  def test_full_likelihood_em_matches_extended_precision_posteriors(self):
20
68
  m, n = 43, 137
21
69
  tiny = np.nextafter(np.float32(0), np.float32(1))
@@ -103,6 +151,30 @@ class CpuScalingTest(unittest.TestCase):
103
151
  np.testing.assert_array_equal(P, p.astype(float))
104
152
  np.testing.assert_array_equal(Q, q.astype(float))
105
153
 
154
+ def test_tiled_em_preserves_repeated_updates_with_unbalanced_missingness(self):
155
+ rng = np.random.default_rng(712)
156
+ m, n, k = 389, 137, 5
157
+ x = rng.integers(0, 3, (m, n), dtype=np.uint8)
158
+ L = np.full((m, n, 3), 0.025, np.float32)
159
+ np.put_along_axis(L, x[..., None], 0.95, axis=2)
160
+ x[:, :68], x[127] = 9, 9
161
+ L[:, :68], L[127] = np.float32(1 / 3), np.float32(1 / 3)
162
+ P = rng.uniform(0.1, 0.9, (m, k))
163
+ Q = rng.dirichlet(np.ones(k), n)
164
+ t0 = rng.random(Q.shape)
165
+ for G in (packGenotypes(x), kernels.likelihoodData(L)):
166
+ for fixed in (False, True):
167
+ fn = kernels.stepQ if fixed else kernels.accelP
168
+ pr, tr = P.copy(), t0.copy()
169
+ with patch.object(defaults, "EM_TILED_MIN_SAMPLES", 10**9):
170
+ fn(G, *(P, Q, tr) if fixed else (P, pr, Q, tr))
171
+ with patch.object(defaults, "EM_TILED_MIN_SAMPLES", 0):
172
+ for _ in range(3):
173
+ p, t = P.copy(), t0.copy()
174
+ fn(G, *(P, Q, t) if fixed else (P, p, Q, t))
175
+ np.testing.assert_allclose(p, pr, atol=1e-12, rtol=2e-13)
176
+ np.testing.assert_allclose(t, tr, atol=1e-10, rtol=2e-13)
177
+
106
178
  def test_tiled_em_matches_marker_reduction(self):
107
179
  for K in (2, 5, 10, 16, 17, 64, 128):
108
180
  with self.subTest(K=K):
@@ -397,105 +469,168 @@ class BlasTest(unittest.TestCase):
397
469
  self.assertEqual(events, ["MADV_RANDOM", "q", "MADV_NORMAL"])
398
470
 
399
471
  def test_outer_products_are_fresh_and_match_allocation_fallback(self):
400
- for k in (1, 5, 16, 32, 64, 128):
401
- G, P, Q, _ = makeEmFixture("packed", 139, 137, k)
402
- G["data"].flags.writeable = False
403
- pool, work = sqp.blasWorkspace(k, P.shape[0], Q.shape[0])
404
- B = functions.simplexBasis(k)
405
- for q_side in (False, True):
406
- shape = Q.shape if q_side else P.shape
407
- out, ref = np.empty(shape), np.empty(shape)
408
- H, H0 = np.empty((*shape, k)), np.empty((*shape, k))
409
- g, g0 = np.empty(shape), np.empty(shape)
410
- for changed in (False, True):
411
- if changed:
412
- P[:] = 1.0 - P
413
- Q[:] = np.roll(Q, 1, axis=1)
414
- P.flags.writeable = Q.flags.writeable = False
472
+ for kind in ("packed", "likelihood"):
473
+ for k in (1, 2, 5, 10, 16, 32, 64, 128):
474
+ G, P, Q, _ = makeEmFixture(kind, 139, 137, k)
475
+ G["data"].flags.writeable = False
476
+ gl = kernels.isLikelihood(G)
477
+ data = (None, G["data"]) if gl else (G["data"], None)
478
+ pool, work = sqp.blasWorkspace(k, P.shape[0], Q.shape[0])
479
+ B = functions.simplexBasis(k)
480
+ for q_side in (False, True):
481
+ shape = Q.shape if q_side else P.shape
482
+ out, ref = np.empty(shape), np.empty(shape)
483
+ H, H0 = np.empty((*shape, k)), np.empty((*shape, k))
484
+ g, g0 = np.empty(shape), np.empty(shape)
485
+ for changed in (False, True):
486
+ if changed:
487
+ P[:] = 1.0 - P
488
+ Q[:] = np.roll(Q, 1, axis=1)
489
+ P.flags.writeable = Q.flags.writeable = False
490
+ with (
491
+ self.subTest(kind=kind, K=k, q_side=q_side, changed=changed),
492
+ pool.limit(limits=1, user_api="blas"),
493
+ ):
494
+ with patch.object(np, "empty", wraps=np.empty) as alloc:
495
+ sqp.updateBlas(
496
+ *data, P, Q, out, H, g, B, work, q_side, gl, Q.shape[0]
497
+ )
498
+ nr = P.shape[0] if q_side else Q.shape[0]
499
+ size = nr * k * (k + 1) // 2 * 8
500
+ cached = (not q_side or k >= 16) and work.nbytes + size <= 64 << 20
501
+ self.assertEqual(alloc.call_count, int(cached))
502
+ if cached:
503
+ self.assertEqual(alloc.call_args.args[0], (nr, k * (k + 1) // 2))
504
+ with patch.object(np, "empty", side_effect=MemoryError):
505
+ sqp.updateBlas(
506
+ *data, P, Q, ref, H0, g0, B, work, q_side, gl, Q.shape[0]
507
+ )
508
+ np.testing.assert_allclose(H, H0, atol=3e-12, rtol=3e-12)
509
+ np.testing.assert_allclose(g, g0, atol=3e-12, rtol=3e-12)
510
+ np.testing.assert_allclose(out, ref, atol=3e-12, rtol=3e-12)
511
+ P.flags.writeable = Q.flags.writeable = True
512
+
513
+ def test_outer_products_respect_worker_memory_and_weighted_rows(self):
514
+ for kind in ("packed", "likelihood"):
515
+ for k in (5, 16):
516
+ G, P, Q, _ = makeEmFixture(kind, 139, 137, k)
517
+ gl = kernels.isLikelihood(G)
518
+ data = (None, G["data"]) if gl else (G["data"], None)
519
+ pool, work = sqp.blasWorkspace(k, P.shape[0], Q.shape[0])
520
+ B = functions.simplexBasis(k)
521
+ wide = np.empty((work.shape[0], (64 << 20) // (8 * work.shape[0]) + 1))
522
+ ids = np.arange(0, P.shape[0], 2, dtype=np.uint32)
523
+ weights = np.arange(ids.size, dtype=np.uint32) % 3
524
+ p = P.copy()
525
+ for q_side in (False, True):
526
+ P = p.copy()
527
+ shape = Q.shape if q_side else P.shape
528
+ out, ref = np.empty(shape), np.empty(shape)
529
+ H, H0 = np.empty((*shape, k)), np.empty((*shape, k))
530
+ g, g0 = np.empty(shape), np.empty(shape)
415
531
  with (
416
- self.subTest(K=k, q_side=q_side, changed=changed),
532
+ self.subTest(kind=kind, K=k, q_side=q_side),
417
533
  pool.limit(limits=1, user_api="blas"),
418
534
  ):
419
- with patch.object(np, "empty", wraps=np.empty) as alloc:
420
- sqp.updateBlas(
421
- G["data"], None, P, Q, out, H, g, B, work, q_side, False, Q.shape[0]
422
- )
423
- nr = P.shape[0] if q_side else Q.shape[0]
424
- size = nr * k * (k + 1) // 2 * 8
425
- cached = k >= 16 and work.nbytes + size <= 64 << 20
426
- self.assertEqual(alloc.call_count, int(cached))
427
- if cached:
428
- self.assertEqual(alloc.call_args.args[0], (nr, k * (k + 1) // 2))
429
- with patch.object(np, "empty", side_effect=MemoryError):
430
- sqp.updateBlas(
431
- G["data"],
432
- None,
433
- P,
434
- Q,
435
- ref,
436
- H0,
437
- g0,
438
- B,
439
- work,
440
- q_side,
441
- False,
442
- Q.shape[0],
443
- )
535
+ sqp.updateBlas(*data, P, Q, ref, H0, g0, B, work, q_side, gl, Q.shape[0])
536
+ with patch.object(np, "empty", side_effect=AssertionError("Cache budget")):
537
+ sqp.updateBlas(*data, P, Q, out, H, g, B, wide, q_side, gl, Q.shape[0])
444
538
  np.testing.assert_allclose(H, H0, atol=3e-12, rtol=3e-12)
445
539
  np.testing.assert_allclose(g, g0, atol=3e-12, rtol=3e-12)
446
540
  np.testing.assert_allclose(out, ref, atol=3e-12, rtol=3e-12)
447
- P.flags.writeable = Q.flags.writeable = True
541
+ P[ids[weights == 0]] = np.nan
542
+ P.flags.writeable = Q.flags.writeable = False
543
+ for cached in (True, False):
544
+ with patch.object(
545
+ np,
546
+ "empty",
547
+ wraps=np.empty,
548
+ side_effect=None if cached else MemoryError,
549
+ ) as alloc:
550
+ sqp.updateBlas(
551
+ *data,
552
+ P,
553
+ Q,
554
+ out,
555
+ H,
556
+ g,
557
+ B,
558
+ work,
559
+ q_side,
560
+ gl,
561
+ Q.shape[0],
562
+ markers=ids,
563
+ weights=weights,
564
+ )
565
+ self.assertEqual(alloc.call_count, int(not q_side))
566
+ active = np.arange(Q.shape[0]) if q_side else ids[weights > 0]
567
+ self.assertTrue(np.isfinite(out[active]).all())
568
+ if cached:
569
+ ref[:], H0[:], g0[:] = out, H, g
570
+ else:
571
+ np.testing.assert_allclose(
572
+ H[active], H0[active], atol=3e-12, rtol=3e-12
573
+ )
574
+ np.testing.assert_allclose(
575
+ g[active], g0[active], atol=3e-12, rtol=3e-12
576
+ )
577
+ np.testing.assert_allclose(
578
+ out[active], ref[active], atol=3e-12, rtol=3e-12
579
+ )
580
+ P.flags.writeable = Q.flags.writeable = True
448
581
 
449
- def test_outer_products_respect_worker_memory_and_weighted_rows(self):
450
- k = 16
451
- G, P, Q, _ = makeEmFixture("packed", 139, 137, k)
452
- pool, work = sqp.blasWorkspace(k, P.shape[0], Q.shape[0])
453
- B = functions.simplexBasis(k)
454
- wide = np.empty((work.shape[0], (64 << 20) // (8 * work.shape[0]) + 1))
455
- ids = np.arange(0, P.shape[0], 2, dtype=np.uint32)
456
- weights = np.arange(ids.size, dtype=np.uint32) % 3
457
- p = P.copy()
458
- for q_side in (False, True):
459
- P = p.copy()
460
- shape = Q.shape if q_side else P.shape
461
- out, ref = np.empty(shape), np.empty(shape)
462
- H, H0 = np.empty((*shape, k)), np.empty((*shape, k))
463
- g, g0 = np.empty(shape), np.empty(shape)
464
- with self.subTest(q_side=q_side), pool.limit(limits=1, user_api="blas"):
465
- sqp.updateBlas(
466
- G["data"], None, P, Q, ref, H0, g0, B, work, q_side, False, Q.shape[0]
467
- )
468
- with patch.object(np, "empty", side_effect=AssertionError("Cache exceeded budget")):
469
- sqp.updateBlas(
470
- G["data"], None, P, Q, out, H, g, B, wide, q_side, False, Q.shape[0]
471
- )
472
- np.testing.assert_allclose(H, H0, atol=3e-12, rtol=3e-12)
473
- np.testing.assert_allclose(g, g0, atol=3e-12, rtol=3e-12)
474
- np.testing.assert_allclose(out, ref, atol=3e-12, rtol=3e-12)
475
- P[ids[weights == 0]] = np.nan
476
- P.flags.writeable = Q.flags.writeable = False
477
- with patch.object(
478
- np, "empty", side_effect=AssertionError("Weighted cache allocated")
582
+ def test_single_tile_skips_unused_product_cache(self):
583
+ for k in (5, 16):
584
+ for q_side in (False, True):
585
+ m, n = (139, 7) if q_side else (63, 137)
586
+ G, P, Q, _ = makeEmFixture("packed", m, n, k)
587
+ pool, work = sqp.blasWorkspace(k, m, n)
588
+ B = functions.simplexBasis(k)
589
+ shape = Q.shape if q_side else P.shape
590
+ out, H, g = np.empty(shape), np.empty((*shape, k)), np.empty(shape)
591
+ with (
592
+ self.subTest(K=k, q_side=q_side),
593
+ pool.limit(limits=1, user_api="blas"),
594
+ patch.object(np, "empty", side_effect=AssertionError("Unused cache")),
479
595
  ):
480
- sqp.updateBlas(
481
- G["data"],
482
- None,
483
- P,
484
- Q,
485
- out,
486
- H,
487
- g,
488
- B,
489
- work,
490
- q_side,
491
- False,
492
- Q.shape[0],
493
- markers=ids,
494
- weights=weights,
495
- )
496
- active = np.arange(Q.shape[0]) if q_side else ids[weights > 0]
497
- self.assertTrue(np.isfinite(out[active]).all())
498
- P.flags.writeable = Q.flags.writeable = True
596
+ sqp.updateBlas(G["data"], None, P, Q, out, H, g, B, work, q_side, False, n)
597
+ self.assertTrue(np.isfinite(out).all())
598
+
599
+ def test_balanced_q_tiles_preserve_sharded_scores_and_statistics(self):
600
+ for n in (157, 626, 2504):
601
+ G, P, Q, _ = makeEmFixture("packed", 131, n, 5)
602
+ G["data"].flags.writeable = False
603
+ pool, work = sqp.blasWorkspace(5, 131, n, fixed=True, score=True)
604
+ B = functions.simplexBasis(5)
605
+ result = []
606
+ for c in (n, 53):
607
+ out, H, g = np.empty_like(Q), np.empty((n, 5, 5)), np.empty_like(Q)
608
+ ll = 0.0
609
+ with pool.limit(limits=1, user_api="blas"):
610
+ for b in range(0, n, c):
611
+ e = min(b + c, n)
612
+ ll += sqp.updateBlas(
613
+ G["data"],
614
+ None,
615
+ P,
616
+ Q[b:e],
617
+ out[b:e],
618
+ H[b:e],
619
+ g[b:e],
620
+ B,
621
+ work,
622
+ True,
623
+ False,
624
+ n,
625
+ n0=b,
626
+ score=True,
627
+ )
628
+ result.append((out, H, g))
629
+ np.testing.assert_allclose(
630
+ ll, kernels.loglikeMissing(G, P, Q), atol=2e-8, rtol=2e-13
631
+ )
632
+ for a, b in zip(*result, strict=True):
633
+ np.testing.assert_allclose(a, b, atol=2e-10, rtol=2e-10)
499
634
 
500
635
  def test_all_components_and_panel_sizes_use_blas(self):
501
636
  for k in (2, 3, 4, 5, 6, 7, 8, 16, 128):
@@ -803,7 +938,7 @@ class BlasTest(unittest.TestCase):
803
938
 
804
939
  with patch.object(sqp, "updateBlas", side_effect=update):
805
940
  functions.sqpMap(G, P, Q, p, q, S, y)
806
- self.assertEqual(qs, [] if full else [(32, 32)])
941
+ self.assertEqual(qs, [] if full else [(33, 31)])
807
942
  self.assertEqual(len(ps), 3)
808
943
  np.testing.assert_array_equal(q[y > 0], Q[y > 0])
809
944
  np.testing.assert_allclose(q, qr, atol=2e-11, rtol=2e-10)
@@ -351,6 +351,67 @@ class GenotypesTest(unittest.TestCase):
351
351
  actual = np.loadtxt(output)
352
352
  np.testing.assert_allclose(actual, P, atol=5e-11, rtol=0.0)
353
353
 
354
+ def test_matrix_blocks_match_savetxt_bytes_at_rounding_and_storage_edges(self):
355
+ edge = np.array(
356
+ [
357
+ 0.0,
358
+ -0.0,
359
+ 1e-5,
360
+ 1.0 - 1e-5,
361
+ 0.12345678905,
362
+ np.nextafter(0.12345678905, 0.0),
363
+ np.nextafter(0.12345678905, 1.0),
364
+ np.finfo(float).tiny,
365
+ np.nextafter(0.0, 1.0),
366
+ np.finfo(float).max,
367
+ np.nan,
368
+ np.inf,
369
+ -np.inf,
370
+ ]
371
+ )
372
+ x = np.resize(edge, (2741, 3))
373
+ cases = (
374
+ x,
375
+ x.T,
376
+ x[::2, ::2],
377
+ x.astype(np.longdouble),
378
+ x[:0],
379
+ x[:3, :0],
380
+ x[:3, 0],
381
+ np.array([[0.0, -0.0, 0.1], [1e-5, 0.5, 1.0]], np.float32),
382
+ np.arange(12, dtype=np.int64).reshape(4, 3),
383
+ np.ma.array([[0.1, 0.2], [0.3, 0.4]], mask=[[True, False], [False, True]]),
384
+ np.array([[0.1 + 0.2j, -0.0 - 0.5j]]),
385
+ )
386
+ with tempfile.TemporaryDirectory() as dr:
387
+ for i, a in enumerate(cases):
388
+ expected = Path(dr) / "reference.txt"
389
+ np.savetxt(expected, a, fmt=defaults.OUTPUT_FORMAT)
390
+ for save in (utils.saveP, utils.saveQ):
391
+ for chunk in (7, 65_536):
392
+ with self.subTest(case=i, writer=save.__name__, chunk=chunk):
393
+ path = Path(dr) / "matrix.txt"
394
+ save(path, a, chunk=chunk)
395
+ self.assertEqual(path.read_bytes(), expected.read_bytes())
396
+
397
+ def test_annotated_blocks_preserve_exact_text_and_streamed_metadata(self):
398
+ rng = np.random.default_rng(229)
399
+ x = rng.uniform(1e-5, 1.0 - 1e-5, (2741, 3))
400
+ x[:2] = [0.0, -0.0, 0.12345678905]
401
+ with tempfile.TemporaryDirectory() as dr:
402
+ for save, head in ((utils.saveP, ("SNP", "A1", "A2")), (utils.saveQ, ("FID", "IID"))):
403
+ rows = [tuple(f"{key}α{i}" for key in head) for i in range(len(x))]
404
+ fmt = "\t".join([defaults.OUTPUT_FORMAT] * x.shape[1]) + "\n"
405
+ ref = "\t".join((*head, "POP1", "POP2", "POP3")) + "\n"
406
+ ref += "".join("\t".join(row) + "\t" + fmt % tuple(a) for row, a in zip(rows, x))
407
+ expected = Path(dr) / "reference.txt"
408
+ expected.write_text(ref)
409
+ for chunk in (7, 65_536):
410
+ with self.subTest(writer=save.__name__, chunk=chunk):
411
+ path = Path(dr) / "matrix.txt"
412
+ save(path, x, rows=iter(rows), chunk=chunk)
413
+ self.assertEqual(path.read_bytes(), expected.read_bytes())
414
+
354
415
  def test_matrix_writers_use_fixed_precision_and_dimensions(self):
355
416
  q = np.array([[0.123456789123, 0.4, 0.476543210877], [1e-5, 0.5, 0.49999]])
356
417
  p = np.array([[1e-5, 0.123456789123, 0.5], [1.0 - 1e-5, 0.7, 0.3]])
@@ -392,6 +453,10 @@ class GenotypesTest(unittest.TestCase):
392
453
  utils.saveP(pth, P[:2], rows=rows)
393
454
  self.assertEqual(pth.read_text(), "accepted\n")
394
455
  self.assertEqual(list(Path(dr).glob(".ancestry.P.*.tmp")), [])
456
+ with self.assertRaises(TypeError):
457
+ utils.saveP(pth, np.array([[0.1, "invalid"]], dtype=object))
458
+ self.assertEqual(pth.read_text(), "accepted\n")
459
+ self.assertEqual(list(Path(dr).glob(".ancestry.P.*.tmp")), [])
395
460
 
396
461
  def test_annotated_matrix_io_validates_and_aligns_metadata(self):
397
462
  with tempfile.TemporaryDirectory() as dr:
@@ -48,6 +48,24 @@ class PlinkFilesTest(unittest.TestCase):
48
48
  self.root = Path(tmp.name)
49
49
  self.merged, self.paths, self.g = panel(self.root)
50
50
 
51
+ def test_identical_fam_validation_preserves_non_id_metadata_fallback(self):
52
+ a, an, _, _ = utils.readPlink(self.paths)
53
+ fam = self.paths[1].with_suffix(".fam")
54
+ rows = fam.read_text().splitlines()
55
+ row = rows[-1].split()
56
+ row[-1] = "1"
57
+ rows[-1] = " ".join(row)
58
+ fam.write_text("\n".join(rows) + "\n")
59
+ b, bn, _, _ = utils.readPlink(self.paths)
60
+ np.testing.assert_array_equal(an, bn)
61
+ np.testing.assert_array_equal(a["freq"], b["freq"])
62
+
63
+ # Identical malformed files still require a validated reference
64
+ for p in self.paths:
65
+ p.with_suffix(".fam").write_text("F I 0 0 0\n")
66
+ with self.assertRaisesRegex(ValueError, "Invalid FAM row 1"):
67
+ utils.readPlink(self.paths)
68
+
51
69
  def test_mapping_preserves_bytes_order_addresses_and_ownership(self):
52
70
  a, an, M, N = utils.readPlink(self.merged)
53
71
  b, bn, m, n = utils.readPlink(self.paths)
@@ -1 +0,0 @@
1
- __version__ = "2.0.7"
File without changes
File without changes
File without changes
File without changes
File without changes