fastmixture2 2.0.8__tar.gz → 2.1.0__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 (67) hide show
  1. {fastmixture2-2.0.8/fastmixture2.egg-info → fastmixture2-2.1.0}/PKG-INFO +12 -24
  2. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/README.md +11 -23
  3. fastmixture2-2.1.0/fastmixture2/__init__.py +1 -0
  4. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/fastmixture2/defaults.py +2 -0
  5. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/fastmixture2/fastmixture2.py +3 -3
  6. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/fastmixture2/functions.py +1 -3
  7. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/fastmixture2/gpu.py +9 -1
  8. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/fastmixture2/shared.pyx +48 -0
  9. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/fastmixture2/sqp.pyx +12 -4
  10. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/fastmixture2/utils.py +102 -22
  11. {fastmixture2-2.0.8 → fastmixture2-2.1.0/fastmixture2.egg-info}/PKG-INFO +12 -24
  12. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/fastmixture2.egg-info/SOURCES.txt +1 -0
  13. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/check_portable.py +1 -0
  14. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_cpu_scaling.py +154 -91
  15. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_gpu_streamed.py +122 -0
  16. fastmixture2-2.1.0/tests/test_sample_subset.py +294 -0
  17. fastmixture2-2.0.8/fastmixture2/__init__.py +0 -1
  18. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/LICENSE +0 -0
  19. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/MANIFEST.in +0 -0
  20. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/fastmixture2/em.pyx +0 -0
  21. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/fastmixture2/kernels.py +0 -0
  22. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/fastmixture2/main.py +0 -0
  23. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/fastmixture2/packed.pxd +0 -0
  24. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/fastmixture2/plink.py +0 -0
  25. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/fastmixture2/svd.pyx +0 -0
  26. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/fastmixture2/threads.pxd +0 -0
  27. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/fastmixture2.egg-info/dependency_links.txt +0 -0
  28. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/fastmixture2.egg-info/entry_points.txt +0 -0
  29. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/fastmixture2.egg-info/requires.txt +0 -0
  30. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/fastmixture2.egg-info/top_level.txt +0 -0
  31. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/pyproject.toml +0 -0
  32. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/setup.cfg +0 -0
  33. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/setup.py +0 -0
  34. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/helpers.py +0 -0
  35. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/run_tests.py +0 -0
  36. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_adversarial_io.py +0 -0
  37. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_bootstrap.py +0 -0
  38. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_cli.py +0 -0
  39. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_convergence.py +0 -0
  40. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_cpu_subset.py +0 -0
  41. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_cross_validation.py +0 -0
  42. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_distribution.py +0 -0
  43. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_frequency_cache.py +0 -0
  44. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_genotypes.py +0 -0
  45. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_gpu_called.py +0 -0
  46. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_gpu_em.py +0 -0
  47. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_gpu_gl_precision.py +0 -0
  48. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_gpu_large.py +0 -0
  49. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_gpu_modes.py +0 -0
  50. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_gpu_precision.py +0 -0
  51. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_gpu_safety.py +0 -0
  52. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_gpu_stat_reuse.py +0 -0
  53. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_gpu_subset.py +0 -0
  54. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_gpu_supervision.py +0 -0
  55. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_gpu_svd_cache.py +0 -0
  56. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_initialization.py +0 -0
  57. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_likelihoods.py +0 -0
  58. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_numerical_equivalence.py +0 -0
  59. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_optimizers.py +0 -0
  60. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_plink_files.py +0 -0
  61. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_q_constraints.py +0 -0
  62. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_restarts.py +0 -0
  63. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_sqp_scoring.py +0 -0
  64. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_sqp_solver.py +0 -0
  65. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_subset_modes.py +0 -0
  66. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/test_threads.py +0 -0
  67. {fastmixture2-2.0.8 → fastmixture2-2.1.0}/tests/validate_distribution.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fastmixture2
3
- Version: 2.0.8
3
+ Version: 2.1.0
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
@@ -61,8 +61,7 @@ python -m pip install .
61
61
  ```
62
62
 
63
63
  Source builds need a C compiler with OpenMP. On macOS, install OpenMP with
64
- `brew install libomp`. On HPC, build on the compute-node type used for your
65
- analyses.
64
+ `brew install libomp`.
66
65
 
67
66
  With Conda, the [CPU](https://github.com/MeisnerLab/fastmixture2/blob/main/environment-cpu.yml)
68
67
  and [GPU](https://github.com/MeisnerLab/fastmixture2/blob/main/environment-gpu.yml)
@@ -153,17 +152,19 @@ CUDA keeps input data on the GPU when they fit and streams in blocks otherwise.
153
152
  Small CPU/GPU differences can arise from floating-point arithmetic.
154
153
 
155
154
  At K > 1, unsupervised fits use SVD/ALS on up to 50,000 genome-wide SNPs, with
156
- subset refinement for larger panels. All modes use safeguarded SQP/ZAL with EM/QN
155
+ subset refinement for larger panels. For called genotypes, joint subset refinement
156
+ uses up to 50,000 randomly selected individuals. The remaining Q rows are fitted
157
+ at fixed P before full-data fitting. All modes use safeguarded SQP/ZAL with EM/QN
157
158
  rescue and float64 likelihood checks. CPU fitting uses float64. CUDA uses
158
159
  mixed precision followed by float64 refinement.
159
160
 
160
161
  Processing uses bounded tiles. Total memory still grows with panel size and K.
161
- Initialization subsets use memory-mapped temporary files when needed. Temporary
162
- files use `TMPDIR`. For large panels, point it to disk-backed scratch with
163
- sufficient space.
162
+ Temporary files use `TMPDIR`. For large panels, use disk-backed scratch with
163
+ enough space.
164
164
 
165
165
  The defaults are `--threads 1`, `--seed 42`, `--iter 1000` and `--tole 1e-10`.
166
- `--threads` also controls CPU work during GPU fits.
166
+ `--threads` also controls CPU work during GPU fits. On HPC, use the allocated
167
+ CPU count.
167
168
  The optimizer scales the tolerance by observed genotypes or informative
168
169
  likelihood triplets. `--iter` and `--tole` apply to each refinement stage.
169
170
  Run `fastmixture2 --help` for the full CLI.
@@ -316,22 +317,9 @@ For `--out cohort --K 5 --seed 42`:
316
317
  | `cohort.K5.s42.Q_se` | Q standard errors when bootstrap is requested |
317
318
  | `cohort.K5.s42.log` | Settings, likelihood, convergence and CV/bootstrap summaries |
318
319
 
319
- Rows follow input order and columns correspond to components. Use
320
- `--write-info` for headers and sample or variant IDs, or `--no-freqs` to omit
321
- P. Projection does not write P. For PLINK, P is the frequency of BIM A1.
322
- For Beagle, it is the frequency of allele2.
323
-
324
- Matrices use ten decimal places. Logs retain full-precision likelihoods and
325
- iteration counts, including ALS when used.
326
-
327
- Outputs, checkpoints and caches use standard file permissions controlled by
328
- your umask.
329
-
330
- The log distinguishes convergence, iteration limits, stalled optimization and
331
- numerical failure. Unsuccessful fits retain the best accepted parameters.
332
-
333
- Parallel jobs should use distinct output prefixes. Build each likelihood cache
334
- with one job, then reuse it across fits, or use a separate cache path per job.
320
+ Rows follow input order and columns correspond to components. `--write-info`
321
+ adds headers and IDs. `--no-freqs` omits P, which is also omitted in projection.
322
+ P is the frequency of BIM A1 for PLINK and allele2 for Beagle.
335
323
 
336
324
  ## Authors and license
337
325
 
@@ -30,8 +30,7 @@ python -m pip install .
30
30
  ```
31
31
 
32
32
  Source builds need a C compiler with OpenMP. On macOS, install OpenMP with
33
- `brew install libomp`. On HPC, build on the compute-node type used for your
34
- analyses.
33
+ `brew install libomp`.
35
34
 
36
35
  With Conda, the [CPU](https://github.com/MeisnerLab/fastmixture2/blob/main/environment-cpu.yml)
37
36
  and [GPU](https://github.com/MeisnerLab/fastmixture2/blob/main/environment-gpu.yml)
@@ -122,17 +121,19 @@ CUDA keeps input data on the GPU when they fit and streams in blocks otherwise.
122
121
  Small CPU/GPU differences can arise from floating-point arithmetic.
123
122
 
124
123
  At K > 1, unsupervised fits use SVD/ALS on up to 50,000 genome-wide SNPs, with
125
- subset refinement for larger panels. All modes use safeguarded SQP/ZAL with EM/QN
124
+ subset refinement for larger panels. For called genotypes, joint subset refinement
125
+ uses up to 50,000 randomly selected individuals. The remaining Q rows are fitted
126
+ at fixed P before full-data fitting. All modes use safeguarded SQP/ZAL with EM/QN
126
127
  rescue and float64 likelihood checks. CPU fitting uses float64. CUDA uses
127
128
  mixed precision followed by float64 refinement.
128
129
 
129
130
  Processing uses bounded tiles. Total memory still grows with panel size and K.
130
- Initialization subsets use memory-mapped temporary files when needed. Temporary
131
- files use `TMPDIR`. For large panels, point it to disk-backed scratch with
132
- sufficient space.
131
+ Temporary files use `TMPDIR`. For large panels, use disk-backed scratch with
132
+ enough space.
133
133
 
134
134
  The defaults are `--threads 1`, `--seed 42`, `--iter 1000` and `--tole 1e-10`.
135
- `--threads` also controls CPU work during GPU fits.
135
+ `--threads` also controls CPU work during GPU fits. On HPC, use the allocated
136
+ CPU count.
136
137
  The optimizer scales the tolerance by observed genotypes or informative
137
138
  likelihood triplets. `--iter` and `--tole` apply to each refinement stage.
138
139
  Run `fastmixture2 --help` for the full CLI.
@@ -285,22 +286,9 @@ For `--out cohort --K 5 --seed 42`:
285
286
  | `cohort.K5.s42.Q_se` | Q standard errors when bootstrap is requested |
286
287
  | `cohort.K5.s42.log` | Settings, likelihood, convergence and CV/bootstrap summaries |
287
288
 
288
- Rows follow input order and columns correspond to components. Use
289
- `--write-info` for headers and sample or variant IDs, or `--no-freqs` to omit
290
- P. Projection does not write P. For PLINK, P is the frequency of BIM A1.
291
- For Beagle, it is the frequency of allele2.
292
-
293
- Matrices use ten decimal places. Logs retain full-precision likelihoods and
294
- iteration counts, including ALS when used.
295
-
296
- Outputs, checkpoints and caches use standard file permissions controlled by
297
- your umask.
298
-
299
- The log distinguishes convergence, iteration limits, stalled optimization and
300
- numerical failure. Unsuccessful fits retain the best accepted parameters.
301
-
302
- Parallel jobs should use distinct output prefixes. Build each likelihood cache
303
- with one job, then reuse it across fits, or use a separate cache path per job.
289
+ Rows follow input order and columns correspond to components. `--write-info`
290
+ adds headers and IDs. `--no-freqs` omits P, which is also omitted in projection.
291
+ P is the frequency of BIM A1 for PLINK and allele2 for Beagle.
304
292
 
305
293
  ## Authors and license
306
294
 
@@ -0,0 +1 @@
1
+ __version__ = "2.1.0"
@@ -16,6 +16,7 @@ LIKELIHOOD_FREQUENCY_VERSION = 2
16
16
 
17
17
  # Initialization
18
18
  INITIALIZATION_MARKERS = 50_000
19
+ INITIALIZATION_SAMPLES = 50_000
19
20
  SVD_POWER_ITERATIONS = 10
20
21
  SVD_CHUNK_MARKERS = 4_096
21
22
  SVD_WORKSPACE_BYTES = 512 << 20
@@ -38,6 +39,7 @@ LIKELIHOOD_CONVERGENCE_WINDOW = 10
38
39
  # CUDA storage
39
40
  GPU_TILE_BYTES = 512 << 20
40
41
  GPU_SQP_STAT_BYTES = 512 << 20
42
+ GPU_SQP_FULL_STAT_BYTES = 1 << 30
41
43
  GPU_SQP_WORKSPACE_BYTES = 128 << 20
42
44
  GPU_BOOT_STAT_BYTES = 64 << 20
43
45
  GPU_MIN_TILE_BYTES = 128 << 20
@@ -958,7 +958,7 @@ def _run(args, stack):
958
958
  # Run fixed-P projection or joint P/Q estimation
959
959
  res = functions.hybridRun(G, P, Q, q_nrm, y, run, fixed=args.projection is not None)
960
960
  if args.restarts:
961
- rs_rng = np.random.default_rng(np.random.SeedSequence([args.seed, 0x5253]))
961
+ rs_rng = np.random.default_rng([args.seed, 0x5253])
962
962
  res = functions.restartRun(G, P, Q, q_nrm, rs_rng, run, res, args.restarts)
963
963
  G.pop("freq", None)
964
964
 
@@ -970,7 +970,7 @@ def _run(args, stack):
970
970
  cv_run["tole"] = args.cv_tole
971
971
  cv_run["cv"] = args.cv
972
972
  cv_run["random_init"] = args.random_init
973
- cv_rng = np.random.default_rng(np.random.SeedSequence([args.seed, 0x4356]))
973
+ cv_rng = np.random.default_rng([args.seed, 0x4356])
974
974
  P0, Q0 = (None, None) if args.exact_cv else (P, Q)
975
975
  cv_res = cvRun(G, P0, Q0, q_nrm, args.K, cv_rng, cv_run)
976
976
 
@@ -987,7 +987,7 @@ def _run(args, stack):
987
987
  "boot_tole": args.bootstrap_tole,
988
988
  "log": runtime.append,
989
989
  }
990
- boot_rng = np.random.default_rng(np.random.SeedSequence([args.seed, 0x4253]))
990
+ boot_rng = np.random.default_rng([args.seed, 0x4253])
991
991
  Q_se = functions.bootRun(G, P, Q, y, boot_rng, boot_run)
992
992
 
993
993
  # Save estimates in physical input order
@@ -1044,9 +1044,7 @@ def restartRun(G, P, Q, q_nrm, rng, run, res, n):
1044
1044
  step = time()
1045
1045
  name = "merge/split" if t else "Q permutation"
1046
1046
  draw = (
1047
- np.random.default_rng(
1048
- np.random.SeedSequence([run["seed"], K, i, 0x4D53 if t else 0x4652])
1049
- )
1047
+ np.random.default_rng([run["seed"], K, i, 0x4D53 if t else 0x4652])
1050
1048
  if "seed" in run
1051
1049
  else rng
1052
1050
  )
@@ -2876,7 +2876,7 @@ def _initializeUnsupervised(cp, np, utils, G, K, rng, strict, f, run=None):
2876
2876
  )
2877
2877
  del U, S, V
2878
2878
  if refine:
2879
- utils._refineSubset(G, P, Q, s, run, fit, defaults.GPU_SVD_WORKSPACE_BYTES)
2879
+ utils._refineSubset(G, P, Q, s, run, fit, defaults.GPU_SVD_WORKSPACE_BYTES, rng=rng)
2880
2880
  T = _svdTiles(cp, np, G, f, K, defaults.GPU_SVD_WORKSPACE_BYTES)
2881
2881
  P0 = P
2882
2882
  P = _projectP(cp, np, utils, T, Q)
@@ -2950,6 +2950,14 @@ def _tiledWorkspace(D, kern, mixed=True, rows=None, fp64=True):
2950
2950
  free, _ = cp.cuda.runtime.memGetInfo()
2951
2951
  size = min(defaults.GPU_SQP_STAT_BYTES, max(0, free - reserve))
2952
2952
  qn = min(D["N"], max(r, size // (8 * (K + kp)) // r * r))
2953
+ if qn < D["N"] and "B" in D and not D.get("supervision_bytes", 0):
2954
+ # Avoid another scan while reserving the second input buffer
2955
+ size = 8 * D["N"] * (K + kp)
2956
+ if (
2957
+ size <= defaults.GPU_SQP_FULL_STAT_BYTES
2958
+ and size + D["B"].nbytes <= free - reserve
2959
+ ):
2960
+ qn = D["N"]
2953
2961
  W["qn"] = qn
2954
2962
  W["g"] = cp.empty((max(r, qn), K), dtype=cp.float64)
2955
2963
  W["h"] = cp.empty((max(r, qn), kp), dtype=cp.float64)
@@ -10,6 +10,7 @@ from cpython.unicode cimport Py_UNICODE_ISSPACE
10
10
  cimport openmp as omp
11
11
  from cython.parallel import parallel, prange
12
12
  from libc.math cimport fabs, fmax, fmin, isfinite, log, pow
13
+ from libc.stddef cimport size_t
13
14
  from libc.stdint cimport uint8_t, uint32_t, uint64_t, uintptr_t
14
15
  from libc.stdlib cimport calloc, free, malloc
15
16
  from fastmixture2.packed cimport (
@@ -965,6 +966,53 @@ cdef int _inspectPackedRows(
965
966
  return 0
966
967
 
967
968
 
969
+ cdef extern from *:
970
+ """
971
+ static inline void fm_select_samples(
972
+ const uint8_t *src, uint8_t *out, const uint32_t *idx, size_t n) {
973
+ size_t i = 0;
974
+ for (; i + 4 <= n; i += 4) {
975
+ const uint32_t a = idx[i], b = idx[i + 1];
976
+ const uint32_t c = idx[i + 2], d = idx[i + 3];
977
+ out[i >> 2] = ((src[a >> 2] >> (2 * (a & 3))) & 3)
978
+ | (((src[b >> 2] >> (2 * (b & 3))) & 3) << 2)
979
+ | (((src[c >> 2] >> (2 * (c & 3))) & 3) << 4)
980
+ | (((src[d >> 2] >> (2 * (d & 3))) & 3) << 6);
981
+ }
982
+ if (i < n) {
983
+ /* Pad unused calls as missing */
984
+ uint8_t v = 0x55;
985
+ for (size_t j = 0; i + j < n; ++j) {
986
+ const uint32_t a = idx[i + j];
987
+ const uint8_t c = (src[a >> 2] >> (2 * (a & 3))) & 3;
988
+ v = (v & ~(3U << (2 * j))) | (c << (2 * j));
989
+ }
990
+ out[i >> 2] = v;
991
+ }
992
+ }
993
+ """
994
+ void fm_select_samples(const u8*, u8*, const u32*, size_t) noexcept nogil
995
+
996
+
997
+ ### Split selected marker rows into two packed sample panels
998
+ def splitSamples(
999
+ const u8[:, ::1] B, u8[:, ::1] A, u8[:, ::1] C,
1000
+ const u32[::1] s, const u32[::1] idx, const u32[::1] rest,
1001
+ const uintptr_t[::1] rows=None):
1002
+ cdef:
1003
+ Py_ssize_t j = 0, n = idx.shape[0], nr = rest.shape[0], m = s.shape[0]
1004
+ const u8 *row = NULL
1005
+
1006
+ if m < 1 or n < 1 or nr < 1 or A.shape[0] != m or C.shape[0] != m:
1007
+ raise ValueError("Invalid split dimensions")
1008
+ if A.shape[1] != (n + 3) // 4 or C.shape[1] != (nr + 3) // 4:
1009
+ raise ValueError("Invalid split row widths")
1010
+ for j in prange(m, nogil=True, schedule="static"):
1011
+ row = packedRow(B, rows, s[j])
1012
+ fm_select_samples(row, &A[j, 0], &idx[0], n)
1013
+ fm_select_samples(row, &C[j, 0], &rest[0], nr)
1014
+
1015
+
968
1016
  ### Count observed alleles in one packed pass
969
1017
  cpdef int countPackedRows(
970
1018
  const u8[:, ::1] B, f64[::1] q_nrm,
@@ -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
@@ -848,7 +848,7 @@ def initializeUnsupervised(G, K, rng, strict=True, run=None, fit=None, limit=Non
848
848
  from fastmixture2 import functions
849
849
 
850
850
  fit = partial(functions.likelihoodRun if gl else functions.sqpRun, subset=True)
851
- _refineSubset(G, P, Q, s, run, fit, limit)
851
+ _refineSubset(G, P, Q, s, run, fit, limit, rng=rng)
852
852
  P0 = P
853
853
  P = _projectP(G, f, Q)
854
854
  P[s] = P0
@@ -929,18 +929,76 @@ def _subsetData(G, s, limit, order=None):
929
929
  return packedGenotypes(X, G["samples"], mapped=mapped)
930
930
 
931
931
 
932
+ ### Split packed samples without expanding calls or exceeding the copy budget
933
+ def _sampleData(G, s, idx, rest, limit):
934
+ a, b = (len(idx) + 3) // 4, (len(rest) + 3) // 4
935
+ m = len(s)
936
+ B, rows = nativeData(G), packedRows(G)
937
+ mapped = m * (a + b) > limit
938
+ if mapped:
939
+ r = max(1, min(m, defaults.SVD_CHUNK_MARKERS, limit // (a + b)))
940
+ A, C = np.empty((r, a), np.uint8), np.empty((r, b), np.uint8)
941
+ with (
942
+ tempfile.TemporaryFile(prefix=".fastmixture2-init-", buffering=0) as out,
943
+ tempfile.TemporaryFile(prefix=".fastmixture2-init-", buffering=0) as other,
944
+ ):
945
+ for j in range(0, m, r):
946
+ e = min(j + r, m)
947
+ x, z = A[: e - j], C[: e - j]
948
+ shared.splitSamples(B, x, z, s[j:e], idx, rest, rows=rows)
949
+ x.tofile(out)
950
+ z.tofile(other)
951
+ del A, C, x, z
952
+ A = np.memmap(out, mode="r", dtype=np.uint8, shape=(m, a))
953
+ C = np.memmap(other, mode="r", dtype=np.uint8, shape=(m, b))
954
+ else:
955
+ A, C = np.empty((m, a), np.uint8), np.empty((m, b), np.uint8)
956
+ shared.splitSamples(B, A, C, s, idx, rest, rows=rows)
957
+ return packedGenotypes(A, len(idx), mapped), packedGenotypes(C, len(rest), mapped)
958
+
959
+
960
+ ### Refine selected individuals and project remaining Q at fixed P
961
+ def _refineSamples(G, P, Q, s, fit, sub, limit, rng):
962
+ N, m = len(Q), len(s)
963
+ n = defaults.INITIALIZATION_SAMPLES
964
+ idx = np.sort(rng.choice(N, n, replace=False)).astype(np.uint32)
965
+ mask = np.ones(N, dtype=bool)
966
+ mask[idx] = False
967
+ rest = np.flatnonzero(mask).astype(np.uint32)
968
+ del mask
969
+ X, Z = _sampleData(G, s, idx, rest, limit)
970
+ nrm = np.full(N, 2.0 * m)
971
+ shared.countPackedRows(X["data"], nrm[:n], n)
972
+ shared.countPackedRows(Z["data"], nrm[n:], N - n)
973
+ if np.min(nrm) == 0:
974
+ return
975
+ q = np.ascontiguousarray(Q[idx])
976
+ res = fit(X, P, q, nrm[:n], None, sub)
977
+ Q[idx] = q
978
+ del X, q
979
+ q = np.ascontiguousarray(Q[rest])
980
+ proj = fit(Z, P, q, nrm[n:], None, sub, fixed=True)
981
+ Q[rest] = q
982
+ status = res["status"]
983
+ if status == "subset handoff" or proj["status"] == "numerical failure":
984
+ status = proj["status"]
985
+ return {
986
+ **res,
987
+ "like": res["like"] + proj["like"],
988
+ "elapsed": res["elapsed"] + proj["elapsed"],
989
+ "conv": res["conv"] and proj["conv"],
990
+ "status": status,
991
+ "samples": n,
992
+ "projection": proj,
993
+ }
994
+
995
+
932
996
  ### Refine subset P/Q with isolated fit settings
933
- def _refineSubset(G, P, Q, s, run, fit, limit=None, order=None):
997
+ def _refineSubset(G, P, Q, s, run, fit, limit=None, order=None, rng=None):
934
998
  from fastmixture2.functions import logInfo
935
999
 
936
1000
  N, m = Q.shape[0], len(s)
937
1001
  limit = defaults.SVD_WORKSPACE_BYTES if limit is None else limit
938
- X = _subsetData(G, s, limit, order=order)
939
- nrm = np.full(N, 2.0 * m)
940
- if not isLikelihood(G):
941
- shared.countPackedRows(X["data"], nrm, N)
942
- if np.min(nrm) == 0:
943
- return
944
1002
  opt = {} if run is None else run
945
1003
  sub = {
946
1004
  "iter": opt.get("iter", 1000),
@@ -949,23 +1007,45 @@ def _refineSubset(G, P, Q, s, run, fit, limit=None, order=None):
949
1007
  "quiet": True,
950
1008
  "gpu": opt.get("gpu", False),
951
1009
  }
952
- y = None
953
- dst = Q
954
- if order is not None:
955
- Q = np.ascontiguousarray(Q[order])
956
- if N > 1:
957
- sub["n_chunk"] = defaults.sqpSampleChunk(N - N // 2, Q.shape[1])
958
- y = Q[N - N // 2 :].copy()
959
- res = fit(X, P, Q, nrm, y, sub)
960
- if order is not None:
961
- dst[order] = Q
962
- del X
1010
+ if (
1011
+ rng is not None
1012
+ and order is None
1013
+ and not isLikelihood(G)
1014
+ and N > defaults.INITIALIZATION_SAMPLES
1015
+ ):
1016
+ if "seed" in opt:
1017
+ # Keep sample selection independent of SVD/ALS draws
1018
+ rng = np.random.default_rng([opt["seed"], N, 0x53414D50, 0])
1019
+ res = _refineSamples(G, P, Q, s, fit, sub, limit, rng)
1020
+ if res is None:
1021
+ return
1022
+ else:
1023
+ X = _subsetData(G, s, limit, order=order)
1024
+ nrm = np.full(N, 2.0 * m)
1025
+ if not isLikelihood(G):
1026
+ shared.countPackedRows(X["data"], nrm, N)
1027
+ if np.min(nrm) == 0:
1028
+ return
1029
+ y = None
1030
+ dst = Q
1031
+ if order is not None:
1032
+ Q = np.ascontiguousarray(Q[order])
1033
+ if N > 1:
1034
+ sub["n_chunk"] = defaults.sqpSampleChunk(N - N // 2, Q.shape[1])
1035
+ y = Q[N - N // 2 :].copy()
1036
+ res = fit(X, P, Q, nrm, y, sub)
1037
+ if order is not None:
1038
+ dst[order] = Q
1039
+ del X
963
1040
  if run is not None:
964
1041
  run["init"] = {**res, "markers": m}
1042
+ msg = f"{res['iter']} SQP iterations"
1043
+ if "projection" in res:
1044
+ msg += (
1045
+ f" + {res['projection']['iter']} Q iterations | {res['samples']}/{N} joint samples"
1046
+ )
965
1047
  logInfo(
966
- run,
967
- f"Subset refinement: {m} SNPs | {res['iter']} SQP iterations | "
968
- f"{res['elapsed']:.1f} s | {res['status']}",
1048
+ run, f"Subset refinement: {m} SNPs | {msg} | {res['elapsed']:.1f} s | {res['status']}"
969
1049
  )
970
1050
  return res
971
1051
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fastmixture2
3
- Version: 2.0.8
3
+ Version: 2.1.0
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
@@ -61,8 +61,7 @@ python -m pip install .
61
61
  ```
62
62
 
63
63
  Source builds need a C compiler with OpenMP. On macOS, install OpenMP with
64
- `brew install libomp`. On HPC, build on the compute-node type used for your
65
- analyses.
64
+ `brew install libomp`.
66
65
 
67
66
  With Conda, the [CPU](https://github.com/MeisnerLab/fastmixture2/blob/main/environment-cpu.yml)
68
67
  and [GPU](https://github.com/MeisnerLab/fastmixture2/blob/main/environment-gpu.yml)
@@ -153,17 +152,19 @@ CUDA keeps input data on the GPU when they fit and streams in blocks otherwise.
153
152
  Small CPU/GPU differences can arise from floating-point arithmetic.
154
153
 
155
154
  At K > 1, unsupervised fits use SVD/ALS on up to 50,000 genome-wide SNPs, with
156
- subset refinement for larger panels. All modes use safeguarded SQP/ZAL with EM/QN
155
+ subset refinement for larger panels. For called genotypes, joint subset refinement
156
+ uses up to 50,000 randomly selected individuals. The remaining Q rows are fitted
157
+ at fixed P before full-data fitting. All modes use safeguarded SQP/ZAL with EM/QN
157
158
  rescue and float64 likelihood checks. CPU fitting uses float64. CUDA uses
158
159
  mixed precision followed by float64 refinement.
159
160
 
160
161
  Processing uses bounded tiles. Total memory still grows with panel size and K.
161
- Initialization subsets use memory-mapped temporary files when needed. Temporary
162
- files use `TMPDIR`. For large panels, point it to disk-backed scratch with
163
- sufficient space.
162
+ Temporary files use `TMPDIR`. For large panels, use disk-backed scratch with
163
+ enough space.
164
164
 
165
165
  The defaults are `--threads 1`, `--seed 42`, `--iter 1000` and `--tole 1e-10`.
166
- `--threads` also controls CPU work during GPU fits.
166
+ `--threads` also controls CPU work during GPU fits. On HPC, use the allocated
167
+ CPU count.
167
168
  The optimizer scales the tolerance by observed genotypes or informative
168
169
  likelihood triplets. `--iter` and `--tole` apply to each refinement stage.
169
170
  Run `fastmixture2 --help` for the full CLI.
@@ -316,22 +317,9 @@ For `--out cohort --K 5 --seed 42`:
316
317
  | `cohort.K5.s42.Q_se` | Q standard errors when bootstrap is requested |
317
318
  | `cohort.K5.s42.log` | Settings, likelihood, convergence and CV/bootstrap summaries |
318
319
 
319
- Rows follow input order and columns correspond to components. Use
320
- `--write-info` for headers and sample or variant IDs, or `--no-freqs` to omit
321
- P. Projection does not write P. For PLINK, P is the frequency of BIM A1.
322
- For Beagle, it is the frequency of allele2.
323
-
324
- Matrices use ten decimal places. Logs retain full-precision likelihoods and
325
- iteration counts, including ALS when used.
326
-
327
- Outputs, checkpoints and caches use standard file permissions controlled by
328
- your umask.
329
-
330
- The log distinguishes convergence, iteration limits, stalled optimization and
331
- numerical failure. Unsuccessful fits retain the best accepted parameters.
332
-
333
- Parallel jobs should use distinct output prefixes. Build each likelihood cache
334
- with one job, then reuse it across fits, or use a separate cache path per job.
320
+ Rows follow input order and columns correspond to components. `--write-info`
321
+ adds headers and IDs. `--no-freqs` omits P, which is also omitted in projection.
322
+ P is the frequency of BIM A1 for PLINK and allele2 for Beagle.
335
323
 
336
324
  ## Authors and license
337
325
 
@@ -56,6 +56,7 @@ tests/test_optimizers.py
56
56
  tests/test_plink_files.py
57
57
  tests/test_q_constraints.py
58
58
  tests/test_restarts.py
59
+ tests/test_sample_subset.py
59
60
  tests/test_sqp_scoring.py
60
61
  tests/test_sqp_solver.py
61
62
  tests/test_subset_modes.py
@@ -38,6 +38,7 @@ def main():
38
38
  "test_genotypes.GenotypesTest.test_packed_svd_decoder_covers_all_bytes_and_sample_tails",
39
39
  "test_genotypes.GenotypesTest.test_packed_svd_decoder_preserves_simd_tails_unaligned_rows_and_zero_signs",
40
40
  "test_genotypes.GenotypesTest.test_packed_float64_decoder_matches_float32_bits_and_tile_offsets",
41
+ "test_sample_subset.SampleStorageTest.test_all_codes_tails_and_partitioned_rows_match_reference",
41
42
  "test_cpu_scaling.CpuScalingTest.test_full_likelihood_em_matches_extended_precision_posteriors",
42
43
  "test_cpu_scaling.BlasTest.test_called_statistics_cover_packed_bytes_offsets_and_scored_tails",
43
44
  "test_cpu_scaling.BlasTest.test_called_statistics_match_float64_algebra_at_clipped_bounds",