qc
Quality control functions for CREDTOOLS data.
cochran_q(locus_set)
¶
Compute Cochran-Q statistic for heterogeneity testing across cohorts.
Parameters¶
locus_set : LocusSet LocusSet object containing multiple loci/cohorts.
Returns¶
pd.DataFrame DataFrame with SNPID as index and columns: - Q: Cochran-Q test statistic - Q_pvalue: p-value from chi-squared test - I_squared: I² heterogeneity statistic (percentage)
Notes¶
The Cochran-Q test assesses heterogeneity in effect sizes across studies:
Q = Σ w_i(β_i - β_pooled)²
where: - w_i = 1/SE_i² (inverse variance weights) - β_i = effect size in study i - β_pooled = weighted average effect size
The I² statistic quantifies the proportion of total variation due to heterogeneity rather than chance:
I² = max(0, (Q - df)/Q × 100%)
Interpretation: - Q p-value < 0.05: significant heterogeneity - I² > 50%: substantial heterogeneity - I² > 75%: considerable heterogeneity
High heterogeneity may indicate: - Population differences - Different LD patterns - Batch effects - Population stratification
Source code in credtools/qc.py
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 |
|
compare_maf(locus)
¶
Compare allele frequencies between summary statistics and LD reference.
Parameters¶
locus : Locus Locus object containing summary statistics and LD matrix.
Returns¶
pd.DataFrame DataFrame containing the comparison results with columns: - SNPID: SNP identifier - MAF_sumstats: MAF from summary statistics - MAF_ld: MAF from LD reference
Returns empty DataFrame if AF2 column is not available in LD matrix.
Warnings¶
If AF2 column is not present in the LD matrix, a warning is logged.
Notes¶
This function compares minor allele frequencies (MAF) between:
- Summary statistics (derived from EAF)
- LD reference panel (from AF2 column)
Large discrepancies may indicate: - Population stratification - Allele frequency differences between studies - Potential data quality issues
MAF is calculated as min(AF, 1-AF) for both sources.
Source code in credtools/qc.py
compute_dentist_s(locus)
¶
Compute Dentist-S statistic and p-value for outlier detection.
Parameters¶
locus : Locus Locus object containing summary statistics and LD matrix.
Returns¶
pd.DataFrame DataFrame containing the results of the Dentist-S test with columns: - SNPID: SNP identifier - t_dentist_s: Dentist-S test statistic - -log10p_dentist_s: -log10 p-value
Notes¶
Reference: https://github.com/mkanai/slalom/blob/854976f8e19e6fad2db3123eb9249e07ba0e1c1b/slalom.py#L254
The Dentist-S statistic tests for outliers by comparing each variant's z-score to what would be expected based on its LD with the lead variant:
t_dentist_s = (z_j - r_jk * z_k)^2 / (1 - r_jk^2)
where: - z_j: z-score for variant j - z_k: z-score for lead variant k - r_jk: LD correlation between variants j and k
TODO: Use ABF to select lead variant, although in most cases the lead variant is the one with the smallest p-value.
Source code in credtools/qc.py
estimate_s_rss(locus, r_tol=1e-08, method='null-mle', eigvens=None, dtype=None)
¶
Estimate s parameter in the susie_rss Model Using Regularized LD.
Parameters¶
locus : Locus Locus object containing summary statistics and LD matrix. r_tol : float, optional Tolerance level for eigenvalue check of positive semidefinite matrix, by default 1e-8. method : str, optional Method to estimate s, by default "null-mle". Options: "null-mle", "null-partialmle", or "null-pseudomle". eigvens : Optional[Dict[str, np.ndarray]], optional Pre-computed eigenvalues and eigenvectors, by default None. dtype : Optional[np.dtype], optional Data type for computation. If None, uses float64. Use np.float32 for reduced memory usage with minimal precision loss.
Returns¶
float Estimated s value between 0 and 1 (or potentially > 1 for "null-partialmle").
Raises¶
ValueError If n <= 1 or if the method is not implemented.
Notes¶
This function estimates the parameter s, which provides information about the consistency between z-scores and the LD matrix. A larger s indicates a strong inconsistency between z-scores and the LD matrix.
The function implements three estimation methods:
- "null-mle": Maximum likelihood estimation under the null model
- "null-partialmle": Partial MLE using null space projection
- "null-pseudomle": Pseudo-likelihood estimation
The z-scores are transformed using the formula: z_transformed = sqrt(sigma2) * z where sigma2 = (n-1) / (z^2 + n-2)
Source code in credtools/qc.py
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 231 232 233 234 235 236 237 238 239 240 |
|
get_eigen(ldmatrix, dtype=None)
¶
Compute eigenvalues and eigenvectors of LD matrix.
Parameters¶
ldmatrix : np.ndarray A p by p symmetric, positive semidefinite correlation matrix. dtype : Optional[np.dtype], optional Data type for computation. If None, uses the input matrix dtype. Use np.float32 for reduced memory usage with minimal precision loss.
Returns¶
Dict[str, np.ndarray] Dictionary containing eigenvalues and eigenvectors with keys: - 'eigvals': eigenvalues array - 'eigvecs': eigenvectors matrix
Notes¶
TODO: accelerate with joblib for large matrices.
This function uses numpy.linalg.eigh which is optimized for symmetric matrices and returns eigenvalues in ascending order.
Source code in credtools/qc.py
kriging_rss(locus, r_tol=1e-08, s=None, eigvens=None, dtype=None)
¶
Compute distribution of z-scores of variant j given other z-scores, and detect possible allele switch issues.
Parameters¶
locus : Locus Locus object containing summary statistics and LD matrix. r_tol : float, optional Tolerance level for eigenvalue check of positive semidefinite matrix, by default 1e-8. s : Optional[float], optional An estimated s parameter from estimate_s_rss function, by default None. If None, s will be estimated automatically. eigvens : Optional[Dict[str, np.ndarray]], optional Pre-computed eigenvalues and eigenvectors, by default None. dtype : Optional[np.dtype], optional Data type for computation. If None, uses float64. Use np.float32 for reduced memory usage with minimal precision loss.
Returns¶
pd.DataFrame DataFrame containing the results of the kriging RSS test with columns: - SNPID: SNP identifier - z: transformed z-score - condmean: conditional mean - condvar: conditional variance - z_std_diff: standardized difference - logLR: log likelihood ratio
Raises¶
ValueError If n <= 1.
Notes¶
Under the null hypothesis, the RSS model with regularized LD matrix assumes: z|R,s ~ N(0, (1-s)R + sI)
This function uses a mixture of normals to model the conditional distribution of z_j given other z-scores. The method can help detect:
- Allele switch issues
- Outlier variants
- LD inconsistencies
The algorithm: 1. Computes conditional means and variances for each variant 2. Fits a Gaussian mixture model to capture heterogeneity 3. Calculates likelihood ratios for allele switch detection
Source code in credtools/qc.py
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 298 299 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 |
|
ld_4th_moment(locus_set)
¶
Compute the 4th moment of the LD matrix as a measure of LD structure.
Parameters¶
locus_set : LocusSet LocusSet object containing multiple loci/cohorts.
Returns¶
pd.DataFrame DataFrame with variants as rows and cohorts as columns, containing the 4th moment values (sum of r^4 - 1 for each variant).
Notes¶
The 4th moment is calculated as: Σ(r_ij^4) - 1 for each variant i
This metric provides information about: - LD structure complexity - Potential issues with LD matrix quality - Differences in LD patterns between populations
Higher values may indicate: - Strong local LD structure - Potential genotyping errors - Population stratification effects
The function intersects variants across all cohorts to ensure fair comparison.
Source code in credtools/qc.py
ld_decay(locus_set)
¶
Compute LD decay patterns across cohorts.
Parameters¶
locus_set : LocusSet LocusSet object containing multiple loci/cohorts.
Returns¶
pd.DataFrame DataFrame containing LD decay information with columns: - distance_kb: distance in kilobases - r2_avg: average r² value at that distance - decay_rate: fitted exponential decay rate parameter - cohort: cohort identifier
Notes¶
This function analyzes LD decay by:
- Computing pairwise distances between all variants
- Binning distances into 1kb windows
- Calculating average r² within each distance bin
- Fitting an exponential decay model: r² = a * exp(-b * distance)
LD decay patterns can reveal: - Population-specific recombination patterns - Effective population size differences - Demographic history effects
Different populations typically show different decay rates due to: - Historical effective population sizes - Admixture patterns - Founder effects
Source code in credtools/qc.py
loci_qc(inputs, out_dir, threads=1)
¶
Perform quality control analysis on multiple loci in parallel.
Parameters¶
inputs : str Path to input file containing locus information. Must be tab-separated with columns including 'locus_id'. out_dir : str Output directory path where results will be saved. threads : int, optional Number of parallel threads to use, by default 1.
Returns¶
Dict[str, Any]
Run summary containing counts of successful and failed loci and error
details. QC result files are written under out_dir
.
Raises¶
ValueError
Raised when threads
is less than 1.
Notes¶
This function processes multiple loci in parallel with the following workflow:
- Reads locus information from input file
- Groups loci by locus_id
- Processes each locus group using multiprocessing
- Displays progress bar for user feedback
- Saves results organized by locus_id
The input file should contain columns: locus_id, prefix, popu, cohort, sample_size.
Output structure: {out_dir}/{locus_id}/{qc_metric}.txt.gz {out_dir}/{locus_id}/qc.txt.gz {out_dir}/qc.txt.gz
Each locus gets its own subdirectory with compressed QC result files. A global QC summary file is also generated at the output directory root.
Source code in credtools/qc.py
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 |
|
locus_qc(locus_set, r_tol=0.001, method='null-mle', out_dir=None, dtype=None, flip_logLR_threshold=2, flip_z_threshold=2, lambda_s_outlier_threshold=3, dentist_s_pvalue_threshold=4, dentist_s_r2_threshold=0.6)
¶
Perform comprehensive quality control analysis for a locus.
Parameters¶
locus_set : LocusSet LocusSet object containing loci to analyze. r_tol : float, optional Tolerance level for eigenvalue check of positive semidefinite matrix, by default 1e-3. method : str, optional Method to estimate s parameter, by default "null-mle". Options: "null-mle", "null-partialmle", or "null-pseudomle". out_dir : Optional[str], optional Output directory to save results, by default None. dtype : Optional[np.dtype], optional Data type for computation. If None, uses float64. Use np.float32 for reduced memory usage with minimal precision loss. flip_logLR_threshold : float, optional LogLR threshold for flip detection, by default 2. flip_z_threshold : float, optional Z-score threshold for flip detection, by default 2. lambda_s_outlier_threshold : float, optional Z_std_diff threshold for lambda-s outlier detection, by default 3. dentist_s_pvalue_threshold : float, optional -log10 p-value threshold for Dentist-S outlier detection, by default 4. dentist_s_r2_threshold : float, optional R² threshold for Dentist-S outlier detection, by default 0.6.
Returns¶
Dict[str, pd.DataFrame] Dictionary of quality control results with keys: - 'expected_z': kriging RSS results - 'dentist_s': Dentist-S test results - 'compare_maf': MAF comparison results - 'ld_4th_moment': 4th moment of LD matrix - 'ld_decay': LD decay analysis - 'cochran_q': heterogeneity test (if multiple cohorts) - 'snp_missingness': missingness analysis (if multiple cohorts)
Notes¶
This function performs comprehensive QC including:
Single-locus analyses: - Kriging RSS for outlier detection - Dentist-S for outlier detection - MAF comparison between sumstats and LD reference - LD matrix 4th moment analysis - LD decay pattern analysis
Multi-locus analyses (when applicable): - Cochran-Q heterogeneity testing - SNP missingness across cohorts
TODO: Add LAVA (Local Analysis of Variant Associations) analysis.
If out_dir is provided, results are saved as tab-separated files.
Source code in credtools/qc.py
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 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 |
|
locus_qc_summary(qc_metrics, flip_logLR_threshold=2, flip_z_threshold=2, lambda_s_outlier_threshold=3, dentist_s_pvalue_threshold=4, dentist_s_r2_threshold=0.6)
¶
Generate summary QC statistics for a locus across all cohorts.
Parameters¶
qc_metrics : Dict[str, pd.DataFrame] Dictionary of QC results from locus_qc function. flip_logLR_threshold : float, optional LogLR threshold for flip detection, by default 2. flip_z_threshold : float, optional Z-score threshold for flip detection, by default 2. lambda_s_outlier_threshold : float, optional Z_std_diff threshold for lambda-s outlier detection, by default 3. dentist_s_pvalue_threshold : float, optional -log10 p-value threshold for Dentist-S outlier detection, by default 4. dentist_s_r2_threshold : float, optional R² threshold for Dentist-S outlier detection, by default 0.6.
Returns¶
pd.DataFrame Summary QC statistics with columns: popu, cohort, n_snps, n_1e-5, n_5e-8, maf_corr, lambda_s, n_flip, n_lambda_s_outlier, n_dentist_s_outlier.
Source code in credtools/qc.py
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 |
|
qc_locus_cli(args)
¶
Quality control for a single locus (command-line interface wrapper).
Parameters¶
args : Tuple[str, pd.DataFrame, str] Tuple containing: - locus_id : str Locus identifier - locus_info : pd.DataFrame DataFrame with locus information - base_out_dir : str Base output directory
Returns¶
Tuple[str, pd.DataFrame] Tuple containing the locus_id that was processed and its summary QC stats.
Notes¶
This function is designed for multiprocessing and:
- Loads the locus set from the provided information
- Performs comprehensive QC analysis
- Creates locus-specific output directory
- Saves all QC results as compressed files
- Generates and saves locus-level summary QC statistics
- Returns the processed locus_id and summary for global aggregation
Output files are saved as: {base_out_dir}/{locus_id}/{qc_metric}.txt.gz {base_out_dir}/{locus_id}/qc.txt.gz
Source code in credtools/qc.py
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 |
|
safe_qc_locus_cli(args)
¶
Wrapper for qc_locus_cli that captures exceptions.
Source code in credtools/qc.py
snp_missingness(locus_set)
¶
Compute the missingness rate of each cohort across variants.
Parameters¶
locus_set : LocusSet LocusSet object containing multiple loci/cohorts.
Returns¶
pd.DataFrame DataFrame with variants as rows and cohorts as columns, where 1 indicates presence and 0 indicates absence of the variant in that cohort.
Warnings¶
If any cohort has a missing rate > 0.1, a warning is logged.
Notes¶
This function:
- Identifies all unique variants across cohorts
- Creates a binary matrix indicating variant presence/absence
- Calculates and logs missing rates for each cohort
- Issues warnings for cohorts with high missing rates (>10%)
High missing rates may indicate: - Different genotyping platforms - Different quality control criteria - Population-specific variants