Model utils
build_snp_harmonization_plan(snp_ids, reference, alleles=None, allele_reference=None, allele_target=None)
¶
Build one positional alignment plan for several variant data sources.
The function operates only on arrays that have already been loaded. It finds
the shared variants once, orders them according to reference, and returns
a positional indexer for every source. Optionally, it also removes variants
with incompatible alleles and reports which target alleles need flipping.
Missing identifiers and identifiers duplicated within any source are excluded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
snp_ids
|
Mapping from source name to its one-dimensional variant ID array or pandas Index. Composite identifiers may be represented by a pandas MultiIndex. |
required | |
reference
|
Source whose SNP order defines the final canonical order. |
required | |
alleles
|
Optional mapping from source name to an |
None
|
|
allele_reference
|
Source defining the canonical allele orientation. |
None
|
|
allele_target
|
Source whose alleles are checked against the reference. |
None
|
Returns:
| Type | Description |
|---|---|
|
A dictionary with |
Source code in magenpy/utils/model_utils.py
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 | |
dequantize(ints, float_dtype=np.float32)
¶
Dequantize integers to the specified floating point type. NOTE: Assumes original floats are in the range [-1, 1].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ints
|
A numpy array of integers |
required | |
float_dtype
|
The floating point data type to dequantize the integers to. |
float32
|
Source code in magenpy/utils/model_utils.py
flip_allele_statistics(table, flip, signed_statistics=('BETA', 'STD_BETA', 'Z'))
¶
Update allele-dependent statistics in place for selected positional rows.
Negate each available signed statistic and replace effect-allele frequency
MAF with 1 - MAF where flip is true. Other rows and columns are
unchanged. This function neither matches variants nor changes allele labels:
callers determine flips and assign reference A1/A2 after alignment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table
|
DataFrame whose rows are already aligned with the reference. |
required | |
flip
|
One-dimensional boolean mask in table row order, independent of the DataFrame index labels. |
required | |
signed_statistics
|
Signed statistic column names, or a single name. |
('BETA', 'STD_BETA', 'Z')
|
Returns:
| Type | Description |
|---|---|
|
The same DataFrame, updated in place without a full-table copy. |
Source code in magenpy/utils/model_utils.py
get_shared_distance_matrix(tree, tips=None)
¶
This function takes a Biopython tree and returns the shared distance matrix, i.e. for a pair of clades or populations, time to most recent common ancestor of the pair minus the time of the most recent common ancestor (MRCA).
identify_mismatched_snps(gdl, chrom=None, n_iter=10, G=100, p_dentist_threshold=5e-08, p_gwas_threshold=0.01, rsq_threshold=0.95, max_removed_per_iter=0.005)
¶
This function implements a simple quality control procedures that checks that the GWAS summary statistics (Z-scores) are consistent with the LD reference panel. This is done using a simplified version of the framework outlined in the DENTIST paper:
Improved analyses of GWAS summary statistics by reducing data heterogeneity and errors Chen et al. 2021
Compared to DENTIST, the simplifications we make are:
- For each SNP, we sample one neighboring SNP at a time and compute the T statistic
using that neighbor's information. The benefit of this is that we don't need to
invert any matrices, so it's a fast operation to run.
- To arrive at a more robust estimate, we sample up to k neighbors and average
the T-statistic across those k neighbors.
NOTE: May need to re-implement this to apply some of the constraints genome-wide rather than on a per-chromosome basis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gdl
|
A |
required | |
chrom
|
Perform checking only on chromosome |
None
|
|
n_iter
|
Number of iterations |
10
|
|
G
|
The number of neighboring SNPs to sample (default: 100) |
100
|
|
p_dentist_threshold
|
The Bonferroni-corrected P-value threshold (default: 5e-8) |
5e-08
|
|
p_gwas_threshold
|
The nominal GWAS P-value threshold for partitioning variants (default: 1e-2) |
0.01
|
|
rsq_threshold
|
The R^2 threshold to select neighbors (neighbor's squared correlation coefficient must be less than specified threshold). |
0.95
|
|
max_removed_per_iter
|
The maximum proportion of variants removed in each iteration |
0.005
|
Source code in magenpy/utils/model_utils.py
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 | |
is_identity_indexer(indexer, size=None, chunk_size=65536)
¶
Return whether an integer indexer selects every row in its current order.
Contiguous int32 and int64 arrays use a one-pass native implementation. The comparison is chunked as a fallback when the extension is unavailable or the input has another representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
indexer
|
One-dimensional positional indexer. |
required | |
size
|
Expected source size. Defaults to the indexer length. |
None
|
|
chunk_size
|
Maximum number of expected positions allocated per check. |
65536
|
Source code in magenpy/utils/model_utils.py
map_variants_to_genomic_blocks(variant_table, block_table, variant_pos_col='POS', block_boundary_cols=('block_start', 'block_end'), filter_unmatched=False)
¶
Merge a variant table with a genomic block table. This function assumes that the
variant table includes a column with the positions of the variants POS and the block table
contains the start and end positions of each block.
!!! warning This function assumes that the tables contains data for a single chromosome only.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
variant_table
|
A pandas dataframe with variant information |
required | |
block_table
|
A pandas dataframe with block information |
required | |
variant_pos_col
|
The name of the column in the variant table that contains the positions. By default,
this is set to |
'POS'
|
|
block_boundary_cols
|
A tuple of two strings specifying the column names in the block table that contain
the start and end positions of the blocks. By default, this is set to |
('block_start', 'block_end')
|
|
filter_unmatched
|
If True, filter out variants that were not matched to a block. |
False
|
Source code in magenpy/utils/model_utils.py
match_chromosomes(chrom_1, chrom_2, check_patterns=('chr_', 'chr:', 'chr'), return_both=False)
¶
Given two lists of chromosome IDs, this function returns the
chromosomes that are common to both lists. By default, the returned chromosomes
follow the data type and order of the first list. If return_both is set to True,
the function returns the common chromosomes in both lists.
The function also accounts for common ways to encode chromosomes, such as chr18, chr_18, 18, etc.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chrom_1
|
A list or numpy array of chromosome IDs |
required | |
chrom_2
|
A list or numpy array of chromosome IDs |
required | |
check_patterns
|
Additional leading prefixes to strip before standard normalization. |
('chr_', 'chr:', 'chr')
|
|
return_both
|
If True, return the common chromosomes in both lists |
False
|
Source code in magenpy/utils/model_utils.py
merge_snp_tables(ref_table, alt_table, how='inner', on='auto', signed_statistics=('BETA', 'STD_BETA', 'Z'), drop_duplicates=True, correct_flips=True, return_ref_indices=False, return_alt_indices=False)
¶
This function takes a reference SNP table with at least 3 columns ('SNP', 'A1', A2)
and matches it with an alternative table that also has these 3 columns defined. In the most recent
implementation, we allow users to merge on any set of columns that they wish by specifying the on
parameter. For example, instead of SNP, the user can join the SNP tables on CHR and POS, the
chromosome number and base pair position of the SNP.
The manner in which the join operation takes place depends on the how argument.
Currently, the function supports inner and left joins.
The function removes duplicates if drop_duplicates parameter is set to True
If correct_flips is set to True, the function will correct summary statistics in
the alternative table alt_table (e.g. BETA, MAF) based whether the A1 alleles agree between the two tables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ref_table
|
The reference table (pandas dataframe). |
required | |
alt_table
|
The alternative table (pandas dataframe) |
required | |
how
|
|
'inner'
|
|
on
|
Which columns to use as anchors when merging. By default, we
use |
'auto'
|
|
signed_statistics
|
The columns with signed statistics to flip if |
('BETA', 'STD_BETA', 'Z')
|
|
drop_duplicates
|
Drop duplicate SNPs |
True
|
|
correct_flips
|
Correct SNP summary statistics that depend on status of alternative allele |
True
|
|
return_ref_indices
|
Return the indices of the remaining entries in the reference table before merging. |
False
|
|
return_alt_indices
|
Return the indices of the remaining entries in the alternative table before merging. |
False
|
Source code in magenpy/utils/model_utils.py
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 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | |
multinomial_rvs(n, p)
¶
Copied from Warren Weckesser: https://stackoverflow.com/a/55830796
Sample from the multinomial distribution with multiple p vectors.
- n must be a scalar.
- p must an n-dimensional numpy array, n >= 1. The last axis of p holds the sequence of probabilities for a multinomial distribution.
The return value has the same shape as p.
Source code in magenpy/utils/model_utils.py
normalize_genome_build(genome_build)
¶
Normalize common names for human genome assemblies.
Source code in magenpy/utils/model_utils.py
prepare_harmonization_plan(chromosome, data_sources)
¶
Read chromosome metadata and plan alignment without changing sources.
Collect table metadata and only the LD fields needed for matching. Prefer CHR/POS identifiers, falling back to SNP IDs consistently across sources. Choose variant-order and allele references separately, then delegate intersection and allele compatibility to build_snp_harmonization_plan.
Return the plan and current LD rows in stored coordinates. The latter is None when no LD source is initialized.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chromosome
|
Chromosome label used to construct LD CHR/POS identifiers. |
required | |
data_sources
|
Mapping of source names (genotype, sumstats, ld, annotation) to data objects for this chromosome. Absent sources can be omitted or set to None. Inputs are read without copying full tables. |
required |
Returns:
| Type | Description |
|---|---|
|
Alignment plan and current LD row indices in stored coordinates. |
Source code in magenpy/utils/model_utils.py
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 | |
quantize(floats, int_dtype=np.int8)
¶
Quantize floating point numbers to the specified integer type. NOTE: Assumes that the floats are in the range [-1, 1].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
floats
|
A numpy array of floats |
required | |
int_dtype
|
The integer type to quantize to. |
int8
|
Source code in magenpy/utils/model_utils.py
sumstats_train_test_split(gdl, prop_train=0.9, **kwargs)
¶
Perform a train-test split on the GWAS summary statistics data. This function implemented the PUMAS procedure described in
Zhao, Z., Yi, Y., Song, J. et al. PUMAS: fine-tuning polygenic risk scores with GWAS summary statistics. Genome Biol 22, 257 (2021). https://doi.org/10.1186/s13059-021-02479-9
Specifically, the function takes harmonized LD and summary statistics data (in the form of a
GWADataLoader object) and samples the marginal beta values for the training set, conditional
on the LD matrix and the proportion of training data specified by prop_train.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gdl
|
A |
required | |
prop_train
|
The proportion of training data to sample. |
0.9
|
|
kwargs
|
Additional keyword arguments to pass to the
|
{}
|
Returns:
| Type | Description |
|---|---|
|
A dictionary with the sampled beta values for the training and test sets. |
Source code in magenpy/utils/model_utils.py
tqdm(*args, **kwargs)
¶
tree_to_rho(tree, min_corr)
¶
This function takes a Biopython tree and a minimum correlation parameter and returns the correlation matrix for the effect sizes across populations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree
|
a Biopython Phylo object |
required | |
min_corr
|
minimum correlation |
required |
Returns:
| Type | Description |
|---|---|
|
|
Source code in magenpy/utils/model_utils.py
validate_harmonization_builds(data_sources)
¶
Reject conflicting known assemblies; allow sources with unknown builds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_sources
|
Mapping from source name to a chromosome-to-data mapping. Objects may expose genome_build; missing or unknown builds are ignored. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If known builds disagree within or across sources. |