[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EBNX0J893VQ8KXNGJYWFS0":3,"skill-same:01M7EBNX0J893VQ8KXNGJYWFS0":68},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":30,"commitSha":31,"skillDirectory":32,"forksCount":14,"repositoryHtmlUrl":33,"repositoryHomepageUrl":33,"ownerHtmlUrl":34,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":35,"install":36,"resources":49},"01M7EBNX0J893VQ8KXNGJYWFS0","bio-causal-genomics-genomic-sem",null,"Fits structural equation models to GWAS summary statistics using GenomicSEM (Grotzinger 2019), including common-factor models, confirmatory factor models, ESEM, common-factor GWAS with Q_SNP heterogeneity, multivariate Wald tests, and stratified GenomicSEM partitioned heritability. Reconciles results against MTAG multi-trait analysis. Handles sample overlap via the LDSC sampling-covariance matrix, identifies and resolves Heywood cases, and verifies model fit with CFI \u002F RMSEA. Use when modeling latent genetic architecture across correlated traits, running multivariate GWAS on a shared factor, distinguishing factor-mediated from trait-specific SNP effects, or comparing GenomicSEM common-factor results against MTAG when both depend on accurate sampling covariance.","Mr-Nobody-Anonymous\u002FAll-skills","Mr-Nobody-Anonymous","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F184253119?v=4","01M7AEXFJHKTYQW5R0ZCQQTWFV","anonymous","01M7C00M3GQR4QKP9GZA42GFAK",0,"MIT","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-causal-genomics-genomic-sem\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-causal-genomics-genomic-sem\ndescription: Fits structural equation models to GWAS summary statistics using GenomicSEM (Grotzinger 2019), including common-factor models, confirmatory factor models, ESEM, common-factor GWAS with Q_SNP heterogeneity, multivariate Wald tests, and stratified GenomicSEM partitioned heritability. Reconciles results against MTAG multi-trait analysis. Handles sample overlap via the LDSC sampling-covariance matrix, identifies and resolves Heywood cases, and verifies model fit with CFI \u002F RMSEA. Use when modeling latent genetic architecture across correlated traits, running multivariate GWAS on a shared factor, distinguishing factor-mediated from trait-specific SNP effects, or comparing GenomicSEM common-factor results against MTAG when both depend on accurate sampling covariance.\ntool_type: r\nprimary_tool: GenomicSEM\nsource: \"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills\"\nsource_repository: \"GPTomics\u002FbioSkills\"\nsource_path: \"causal-genomics\u002Fgenomic-sem\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n\n## Version Compatibility\n\nReference examples tested with: GenomicSEM 0.0.5+ (GitHub `GenomicSEM\u002FGenomicSEM`), lavaan 0.6-17+, LDSC v1.0.1+ (Python 3; prefer `abdenlab\u002Fldsc-python3` v2.0.0 -- `belowlab\u002Fldsc` v3.0.1 README states the CLI is broken; Docker `jtb114\u002Fldsc:latest` is the belowlab fallback), baselineLD_v2.2 annotations (alkesgroup.broadinstitute.org\u002FLDSCORE), MTAG 1.0.8+ (Python; `JonJala\u002Fmtag`), R 4.4+.\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- R: `packageVersion('GenomicSEM')` then `?ldsc`, `?commonfactor`, `?usermodel`, `?commonfactorGWAS`\n- Python (LDSC, MTAG): `\u003Ctool>.py -h` and inspect the source under `ldsc\u002F` or `mtag\u002F`\n\nGenomicSEM is GitHub-only (never on CRAN). If `ldsc()` or `usermodel()` throws an error about lavaan syntax or non-positive-definite covariance, introspect the installed API (`getMethod('ldsc')`) and adapt rather than retrying.\n\n# Genomic SEM\n\n**\"Model the latent genetic architecture across several correlated GWAS\"** -> Treat each GWAS as a measured indicator of one or more latent genetic factors and fit a structural equation model to the LDSC-derived genetic covariance matrix S and its sampling covariance V (Grotzinger 2019 Nat Hum Behav 3:513). The framework extends naturally to a multivariate GWAS in which a SNP is regressed on a latent factor (common-factor GWAS), with Q_SNP testing whether the SNP effect is homogeneous across factor loadings. Sample overlap between input GWAS is absorbed by the off-diagonals of V; ignoring V inflates Type-I.\n\n- R: `GenomicSEM::ldsc()` produces the (S, V) covariance pair from munged sumstats\n- R: `GenomicSEM::commonfactor()` fits a single-factor CFA across all traits in S\n- R: `GenomicSEM::usermodel()` fits an arbitrary lavaan-syntax model\n- R: `GenomicSEM::commonfactorGWAS()` runs SNP -> factor multivariate GWAS with Q_SNP\n- R: `GenomicSEM::userGWAS()` runs arbitrary multivariate SNP regression with per-path Q_SNP\n- Python (alternative): `mtag.py --sumstats t1,t2,t3 --out mtag_out` (multi-trait power boost on individual traits)\n\n## Statistical Model Taxonomy\n\n| Method | Latent structure | Min traits | SNP-level test | Strength | Fails when |\n|--------|------------------|-----------|----------------|----------|------------|\n| Common-factor CFA (Grotzinger 2019) | Single F loading all traits | 3 | None (model-fit only) | Tests whether shared variance is unidimensional | Heterogeneous architecture; CFI \u003C 0.9; near-zero loadings |\n| User-specified CFA (`usermodel`) | Pre-specified lavaan syntax | 3 | None | Confirmatory; arbitrary structure | Misspecified model; identification under-determined |\n| ESEM | Exploratory rotation; cross-loadings allowed | 6+ | None | When factor count and structure unknown | Few traits; collinear traits; rotation arbitrary |\n| Common-factor GWAS (`commonfactorGWAS`) | SNP -> F -> trait1..k | 3 | Wald on F + Q_SNP heterogeneity | Discovers SNPs acting via the common factor; flags Q_SNP outliers | Q_SNP-significant SNPs not interpretable as factor SNPs |\n| User GWAS (`userGWAS`) | Arbitrary SNP-path lavaan | 3 | Wald per path + Q_SNP | Tests SNP on any specified path | Highly parameterized models lose power |\n| Multivariate Wald test | Joint test across SNP -> trait paths | 2+ | Joint chi-square | Boost power when SNP affects multiple traits | Heterogeneous SNP effects collapse joint test |\n| Stratified GenomicSEM (Grotzinger AD et al 2022 Nat Genet 54:548) | Factor model with sLDSC-partitioned annotations | 3 | Per-annotation factor tau | Localizes heritability of the factor to functional categories | Same sLDSC failure modes (small annotation, collinearity) |\n| MTAG (Turley 2018 Nat Genet 50:229) | Empirical-Bayes shrinkage across correlated traits | 2 | Per-trait shrunk z-score | Boosts marginal power for any input trait | MaxFDR > 5% indicates heterogeneity violates MTAG assumption |\n\nMethodology evolves; verify the current Grotzinger 2023+ tutorials at `github.com\u002FGenomicSEM\u002FGenomicSEM\u002Fwiki` before locking a method. ESEM rotation choice (geomin vs target rotation) is an active area; report sensitivity to rotation.\n\n## MTAG vs GenomicSEM Common-Factor GWAS\n\nBoth methods exploit genetic correlation among input GWAS, but their goals and outputs differ.\n\n| Property | MTAG | GenomicSEM commonfactorGWAS |\n|----------|------|------------------------------|\n| Output | Per-trait shrunk z-scores | SNP effect on latent factor |\n| Sample-overlap handling | Bivariate LDSC intercept | Full LDSC sampling-covariance matrix V |\n| Heterogeneity diagnostic | MaxFDR (Turley 2018) | Q_SNP (Grotzinger 2019) |\n| Interpretation | \"Boosted power for trait k\" | \"Effect on what the traits share\" |\n| Min traits | 2 | 3 (otherwise factor not identified) |\n| Best when | Power-boost an individual trait | Common factor hypothesized |\n\nBoth depend on accurate sampling covariance. MTAG fails (MaxFDR > 5%) under the same heterogeneity that produces large Q_SNP in GenomicSEM. The two methods should be reported together when the prior on a common factor is non-trivial; agreement increases confidence, disagreement points to architecture-specific SNPs.\n\n## Decision Tree by Scenario\n\n| Scenario | Recommended | Why |\n|----------|-------------|-----|\n| Multi-trait GWAS power boost for one focal trait | MTAG | Optimized for per-trait marginal power |\n| Common-factor architecture hypothesized | GenomicSEM `commonfactorGWAS` | Tests SNP -> factor; reports Q_SNP heterogeneity |\n| Heterogeneous architecture (>1 latent factor) | ESEM, then confirmatory `usermodel` | Exploratory first, then confirm |\n| Confirming a pre-specified factor structure | `usermodel` with lavaan syntax | Confirmatory factor analysis |\n| Partition heritability of factor across annotations | Stratified GenomicSEM | Combines sLDSC + factor model |\n| Mediation in a SEM framework | `usermodel` with indirect path | Path coefficients + delta-method SE |\n| Sample overlap unknown or any-overlap suspected | Always use `ldsc()` output as input | V matrix off-diagonals absorb overlap |\n| Cross-ancestry common-factor analysis | Run per-ancestry, compare loadings; no published cross-ancestry SEM as of 2026 | Method not yet validated for mixed-ancestry V |\n| Single biobank for all traits (e.g., UKB only) | GenomicSEM with `ldsc()`; the V matrix will reflect overlap | Equivalent to one-sample MR -- the V matrix is the correction |\n| Comparing GenomicSEM and MTAG on the same traits | Run both; compare top hits + heterogeneity | Concordance increases confidence; divergence flags heterogeneity |\n\n## Per-Method Failure Modes\n\n### Heywood case (negative residual variance)\n\n**Trigger:** A residual variance estimate is \u003C 0, or a standardized loading exceeds 1.\n\n**Mechanism:** Empirical underidentification; the genetic covariance matrix S is near-singular OR a trait has near-zero specific variance under the model. The maximum-likelihood \u002F DWLS estimator runs past the boundary of the parameter space.\n\n**Symptom:** `lavaan` warning \"some estimated lv variances are negative\" or \"covariance matrix is not positive definite\"; standardized loading > 1; non-convergence.\n\n**Fix:** First, inspect the LDSC S matrix for genetic correlations near 1 (multicollinearity). Drop or merge near-identical traits. Second, constrain the offending residual variance to be non-negative in the lavaan syntax (`trait1 ~~ a*trait1; a > 0`). Third, verify the V matrix is positive definite via `chol(V_LD)`; if not, the bivariate LDSC inputs disagree on intercept signs and need re-munging. Never re-fit without diagnosing the cause.\n\n### Sample overlap mis-specified\n\n**Trigger:** Using LDSC intercept manually or supplying covariance from non-`ldsc()` source.\n\n**Mechanism:** GenomicSEM's `ldsc()` function returns a list with `S` (genetic covariance) AND `V` (sampling covariance of the lower-triangle of S). The V off-diagonals capture sample overlap via cross-trait LDSC intercept. Skipping V and supplying only S treats all inputs as independent samples; Type-I error inflates because the sampling distribution under H0 is wrong.\n\n**Symptom:** SE on factor loadings far too small; many SNPs significant in common-factor GWAS that don't replicate; comparison to MTAG shows disagreement consistent with overlap.\n\n**Fix:** Always pass the full output of `ldsc()` -- both S and V -- to `commonfactor()`, `usermodel()`, and `commonfactorGWAS()`. Never construct S manually from rg estimates.\n\n### Q_SNP not reported in commonfactorGWAS\n\n**Trigger:** Running `commonfactorGWAS()` and reporting only the factor p-value per SNP.\n\n**Mechanism:** Q_SNP tests heterogeneity of the SNP's effect across factor loadings (Grotzinger 2019 supplement). A SNP with significant Q_SNP violates the common-factor assumption: its effect is NOT mediated by the factor, and the factor estimate is meaningless for that SNP.\n\n**Symptom:** Top \"common-factor SNPs\" are dominated by trait-specific effects; replication in independent cohorts is poor for SNPs with high Q_SNP.\n\n**Fix:** Always report Q_SNP p-value alongside the factor p-value. Flag SNPs with Q_SNP p \u003C 5e-8 \u002F N_factor_SNPs (Bonferroni for the discovered set) as architecture-violating and exclude from \"common-factor SNP\" claims. Re-fit those SNPs in `userGWAS()` with separate paths to each trait.\n\n### Trait inclusion under heterogeneous factor structure\n\n**Trigger:** Forcing a common-factor model on traits that don't share a single latent factor.\n\n**Mechanism:** When two or more traits load on a different factor than the rest, the single-factor model misfits. lavaan still returns parameter estimates but model fit is poor.\n\n**Symptom:** CFI \u003C 0.9; RMSEA > 0.08; some standardized loadings near 0 while others near 1; chi-square highly significant even after accounting for N.\n\n**Fix:** Run ESEM first (`commonfactor` then `usermodel` with cross-loadings allowed) to discover structure. If two factors emerge, fit a two-factor `usermodel`. Drop traits with near-zero loadings on all factors. Document the model search.\n\n### MTAG MaxFDR > 5%\n\n**Trigger:** Running MTAG on traits with low pairwise genetic correlation or with one trait that has a very different architecture.\n\n**Mechanism:** MTAG assumes a homogeneous variance-covariance structure across SNPs. When heterogeneity dominates, the empirical-Bayes shrinkage can over-claim SNPs in the focal trait. Turley 2018 defines MaxFDR as the maximum estimated false discovery rate under worst-case heterogeneity; > 5% invalidates the published trait-specific summary statistics.\n\n**Symptom:** MTAG output file reports `maxFDR` > 0.05; per-trait MTAG hits don't replicate in independent cohorts.\n\n**Fix:** Check pairwise rg via LDSC; if any pair is \u003C 0.7, MTAG is risky. Drop the most heterogeneous trait and re-run. Alternatively, switch to GenomicSEM's `commonfactorGWAS` which models heterogeneity explicitly via Q_SNP.\n\n### Non-positive-definite V_LD matrix\n\n**Trigger:** LDSC inputs from different ancestry GWAS, or one trait with very low mean chi-square (\u003C 1.02).\n\n**Mechanism:** V is the sampling covariance of vech(S); when individual entries of S have huge SE relative to off-diagonal covariance, the resulting V is not positive definite (negative eigenvalues).\n\n**Symptom:** `commonfactor()` errors with \"matrix is not positive definite\" before fitting; `eigen(LDSCoutput$V)$values` shows negative values.\n\n**Fix:** Verify per-trait mean chi-square via `ldsc()` log; below 1.02, exclude that trait. Verify all GWAS are EUR ancestry (or match ancestry of LD scores). Apply nearest-PD smoothing via `Matrix::nearPD(V)$mat` ONLY as a last resort and document the approximation in methods.\n\n## Model Fit Diagnostics\n\n| Index | Acceptable | Good | Source |\n|-------|-----------|------|--------|\n| CFI | >= 0.90 | >= 0.95 | Hu & Bentler 1999 Struct Equ Model 6:1 |\n| TLI \u002F NNFI | >= 0.90 | >= 0.95 | Hu & Bentler 1999 |\n| RMSEA | \u003C= 0.08 | \u003C= 0.05 | Hu & Bentler 1999 |\n| SRMR | \u003C= 0.08 | \u003C= 0.05 | Hu & Bentler 1999 |\n| chi-square p-value | (less informative at large N) | n\u002Fa | Penalize for N inflation |\n\nAIC \u002F BIC are used for nested-model comparison (lower is better); only compare nested models fit on the same S.\n\n## Quantitative Thresholds\n\n| Threshold | Source | Rationale |\n|-----------|--------|-----------|\n| CFI >= 0.95 | Hu & Bentler 1999 | Conventional good fit; SEM literature default |\n| RMSEA \u003C= 0.05 | Hu & Bentler 1999 | Conventional good fit |\n| RMSEA 0.05 - 0.08 | Hu & Bentler 1999 | Acceptable; flag as \"adequate\" not \"good\" |\n| Q_SNP p \u003C 0.05 \u002F N_SNP_factor | Grotzinger 2019 Nat Hum Behav 3:513 | Bonferroni for heterogeneity among factor-significant SNPs |\n| MTAG MaxFDR \u003C 5% | Turley 2018 Nat Genet 50:229 | Above this, MTAG marginal trait results invalid |\n| Per-trait LDSC mean chi-square > 1.02 | LDSC documentation | Below this, V entries too noisy; factor SE inflated |\n| Standardized loading 0.3 - 0.9 typical | SEM conventions | \u003C 0.3 trait loads weakly; > 0.95 may indicate over-fit \u002F collinearity |\n| Min 3 traits for common factor | SEM identification | Single factor with k traits has k(k+1)\u002F2 moments; needs k>=3 to identify |\n\n## Standard Workflow\n\n**Goal:** Fit a common-factor model across correlated GWAS and run a multivariate GWAS on the factor with Q_SNP.\n\n**Approach:** Munge sumstats -> LDSC for (S, V) -> common-factor CFA -> inspect fit -> prepare SNPs -> common-factor GWAS -> report factor effects with Q_SNP flags.\n\n```r\nlibrary(GenomicSEM)\n\n# Step 1: Munge sumstats (one-time; produces .sumstats.gz files)\nfiles \u003C- c('raw\u002Ftrait1.txt', 'raw\u002Ftrait2.txt', 'raw\u002Ftrait3.txt')\nhm3 \u003C- 'w_hm3.snplist'  # HapMap3 SNP list\ntrait_names \u003C- c('trait1', 'trait2', 'trait3')\nN \u003C- c(150000, 200000, 175000)\nmunge(files = files, hm3 = hm3, trait.names = trait_names, N = N)\n\n# Step 2: LDSC produces both S (genetic covariance) and V (sampling covariance)\ntraits \u003C- c('trait1.sumstats.gz', 'trait2.sumstats.gz', 'trait3.sumstats.gz')\nldsc_results \u003C- ldsc(\n    traits = traits,\n    sample.prev = c(0.5, 0.5, NA),    # case prevalence; NA for continuous\n    population.prev = c(0.05, 0.05, NA),\n    ld = 'eur_w_ld_chr\u002F',\n    wld = 'eur_w_ld_chr\u002F',\n    trait.names = trait_names\n)\n# ldsc_results$S = genetic covariance; ldsc_results$V = sampling covariance\n\n# Step 3a: Common-factor CFA via DWLS\ncf_fit \u003C- commonfactor(covstruc = ldsc_results, estimation = 'DWLS')\nprint(cf_fit$modelfit)  # CFI, RMSEA, SRMR, chi-square\nprint(cf_fit$results)   # loadings + SEs\n\n# Step 3b: Alternative -- user-specified two-factor model (>=3 indicators per factor)\n# Identification rule: each factor needs >= 3 indicators OR one anchor loading fixed\n# to 1 plus factor variance free. A factor with a single indicator is NOT identified.\nmodel_syntax \u003C- '\n    F1 =~ NA*trait1 + trait2 + trait3\n    F2 =~ NA*trait4 + trait5 + trait6\n    F1 ~~ 1*F1\n    F2 ~~ 1*F2\n    F1 ~~ F2\n'\nuser_fit \u003C- usermodel(covstruc = ldsc_results, model = model_syntax, estimation = 'DWLS')\n```\n\n`estimation = 'DWLS'` (diagonally weighted least squares) is the default and is required when V is large; `'ML'` is faster but assumes a known V and can produce wrong SE under sample overlap.\n\n### ESEM (Exploratory Factor Structure)\n\nWhen the factor structure is unknown, fit `usermodel()` with all loadings free across all factors, then apply a rotation post-fit. Rotation choices: **geomin oblique** (default; allows factor correlation), **target rotation** (Browne 2001 Multivariate Behav Res 36:111; uses a hypothesized loading template), **quartimin** (orthogonal; assumes factors are uncorrelated).\n\n```r\nmodel_esem \u003C- '\n    F1 =~ NA*trait1 + trait2 + trait3 + trait4\n    F2 =~ NA*trait1 + trait2 + trait3 + trait4\n    F1 ~~ 1*F1\n    F2 ~~ 1*F2\n    F1 ~~ F2\n'\nesem_fit \u003C- usermodel(covstruc = ldsc_results, model = model_esem, estimation = 'DWLS')\n# Rotate post-fit via GPArotation::GPForth\u002FGPFoblq or lavaan::rotate()\n```\n\n**Decision:** ESEM for K-factor exploration when structure is unknown; CFA via `usermodel()` once a structure is confirmed. Report rotation sensitivity (geomin vs target vs quartimin) and treat as exploratory.\n\n**Cross-loadings.** Cross-loadings (one trait loads on > 1 factor) are common in psychiatric and behavioral GWAS. Brown 2015 *Confirmatory Factor Analysis for Applied Research* recommends allowing cross-loadings first and using modification indices to guide simplification. Allow a cross-loading when constraining residual variance otherwise forces a Heywood case. Constrain when CFI \u003C 0.9 and modification indices instead suggest a correlated residual between two indicators (which is the more parsimonious fix).\n\n### userGWAS for Custom Path Models\n\n`userGWAS()` fits arbitrary lavaan-syntax SNP regressions and is the right tool when the SNP needs to be tested on multiple paths simultaneously (e.g. factor-mediated effect AND a direct effect on one indicator).\n\n```r\n# Test SNP -> F path + SNP -> trait1 direct path simultaneously\nmodel \u003C- '\n    F =~ NA*trait1 + trait2 + trait3\n    F ~~ 1*F\n    F ~ SNP\n    trait1 ~ SNP    # direct effect on trait1, partialed out of F\n'\nuser_results \u003C- userGWAS(covstruc = ldsc_results,\n                         SNPs = ss,\n                         estimation = 'DWLS',\n                         model = model,\n                         sub = c('F~SNP', 'trait1~SNP'),\n                         parallel = TRUE,\n                         cores = 8)\n# Output columns include: lhs, op, rhs, est, SE, Z, Pvalue, Q_pval, Q_df.\n# Q_pval per SNP measures heterogeneity across loadings AFTER conditioning on\n# the direct path; remaining Q_SNP signal indicates a third path is needed.\n```\n\n### Higher-Order \u002F Bifactor \u002F p-Factor Models\n\nUse case: psychiatric genetics p-factor (Caspi 2014 Clin Psychol Sci 2:119; Grotzinger 2022 Nat Genet 54:548 cross-disorder), cognitive g-factor (de la Fuente 2021 Nat Hum Behav 5:49).\n\nHierarchical template -- first-order factors load on a single second-order p-factor:\n\n```r\nmodel_pfactor \u003C- '\n    # First-order factors\n    INT =~ NA*trait_anx + trait_dep + trait_neuro       # internalizing\n    EXT =~ NA*trait_adhd + trait_alc + trait_subst       # externalizing\n    THT =~ NA*trait_scz + trait_bp                       # thought-disorder\n    # Second-order p-factor\n    p =~ NA*INT + EXT + THT\n    INT ~~ 1*INT\n    EXT ~~ 1*EXT\n    THT ~~ 1*THT\n    p ~~ 1*p\n'\n```\n\nBifactor alternative: `p =~` all traits directly, with `INT`\u002F`EXT`\u002F`THT` as orthogonal residual factors. Bifactor typically gives tighter CFI\u002FRMSEA but the substantive interpretation of the residual factors is harder; bifactor is also prone to over-fitting at modest trait counts (Bonifay W & Cai L 2017 Multivariate Behav Res 52:465). Cite Grotzinger 2022 Nat Genet 54:548 and Karlsson Linner R, Mallard TT et al 2021 Nat Neurosci 24:1367 for the canonical psychiatric implementations.\n\n## Common-Factor GWAS with Q_SNP\n\n**Goal:** Identify SNPs that affect the latent factor and flag SNPs whose effect is heterogeneous across loadings.\n\n**Approach:** Build SNP-by-trait effect-and-SE matrix via `sumstats()`, then fit the SNP-augmented model genome-wide via `commonfactorGWAS()`. Report both factor p-value and Q_SNP p-value per SNP.\n\n`sumstats()` flips effect signs based on the reference panel A1\u002FA2 to enforce consistent allele coding across input GWAS. Required input columns (case-sensitive) are `SNP, A1, A2, BETA\u002FZ\u002FOR, SE, P, N, MAF`; some are conditional on `se.logit` \u002F `OLS`. Silent failures are almost always column-name mismatches (e.g. `EA`\u002F`NEA` instead of `A1`\u002F`A2` -> 0% SNPs retained) or a missing `N` column -> SNPs dropped. Always run `head(read.table(file, header=TRUE, nrow=2))` per input before the `sumstats()` call.\n\n```r\n# Prepare per-SNP betas and SEs across all input GWAS\nss \u003C- sumstats(\n    files = c('raw\u002Ftrait1.txt', 'raw\u002Ftrait2.txt', 'raw\u002Ftrait3.txt'),\n    ref = 'reference.1000G.maf.0.005.txt',\n    trait.names = trait_names,\n    se.logit = c(TRUE, TRUE, FALSE),     # TRUE if trait is logistic-scale (case-control); FALSE if continuous\n    OLS = c(FALSE, FALSE, TRUE),\n    linprob = c(FALSE, FALSE, FALSE),\n    N = N,\n    info.filter = 0.9,                   # standard imputation INFO threshold\n    maf.filter = 0.01\n)\n\n# GenomicSEM internally detects the OS via Sys.info()[['sysname']] and chooses\n# PSOCK (Windows) vs FORK (Linux\u002FMac) clusters automatically; there is no user\n# `Operating=` argument. MPI=TRUE switches to an mpirun-based strategy for\n# cluster job submission. parallel=TRUE is the default.\ncfgwas \u003C- commonfactorGWAS(\n    covstruc = ldsc_results,\n    SNPs = ss,\n    estimation = 'DWLS',\n    parallel = TRUE,\n    cores = 8,\n    MPI = FALSE\n)\n\n# cfgwas columns include rsID\u002Fchr\u002FBP\u002FMAF\u002FA1\u002FA2\u002Fest\u002Fse_c\u002FZ_Estimate\u002FPval_Estimate (factor effect)\n# plus heterogeneity columns Q \u002F Q_df \u002F Q_pval. Q_pval IS the per-SNP heterogeneity\n# test (often referred to as Q_SNP in the literature; the column name in the data.frame is Q_pval).\ncfgwas$factor_sig \u003C- cfgwas$Pval_Estimate \u003C 5e-08\ncfgwas$qsnp_sig \u003C- cfgwas$Q_pval \u003C (0.05 \u002F sum(cfgwas$factor_sig))\ncfgwas$factor_only \u003C- cfgwas$factor_sig & !cfgwas$qsnp_sig\n```\n\nThe \"factor-only\" subset (factor-significant AND Q_SNP non-significant) is the publication-grade set of common-factor SNPs.\n\n## MTAG Comparison\n\n**Goal:** Cross-check GenomicSEM common-factor results against MTAG per-trait shrunk z-scores.\n\n**Approach:** Run MTAG CLI on the same input sumstats; compare top hits with GenomicSEM factor hits. Report MaxFDR.\n\n```bash\n# MTAG CLI (Python)\npython mtag.py \\\n    --sumstats trait1.txt,trait2.txt,trait3.txt \\\n    --n_min 0 \\\n    --out mtag_results\n# MTAG uses the signed Z by default; --use_beta_se was disabled upstream (raises a\n# RuntimeError since Dec 2021 due to beta-se bugs), so supply a Z column and omit it.\n\n# Check MaxFDR per trait\ngrep -iE 'max ?fdr' mtag_results.log   # matches both the section header and the 'Max FDR of Trait' value lines\n# Each per-trait MTAG file: mtag_results_trait_\u003Ck>.txt\n```\n\nIf MaxFDR > 0.05 for any trait, MTAG results for that trait are unreliable; GenomicSEM with Q_SNP filtering is the more defensible report.\n\n## Stratified GenomicSEM (Partitioned Heritability of Factor)\n\nFor partitioning the heritability of the latent factor across functional annotations, use `s_ldsc()` (stratified LDSC inside GenomicSEM) and pass the multi-annotation output to a stratified model fit.\n\n```r\n# Stratified LDSC across baseline + custom annotations\ns_results \u003C- s_ldsc(\n    traits = traits,\n    sample.prev = c(0.5, 0.5, NA),\n    population.prev = c(0.05, 0.05, NA),\n    ld = 'baselineLD_v2.2.',\n    wld = 'weights.hm3_noMHC.',\n    frq = '1000G.EUR.QC.',\n    trait.names = trait_names\n)\n\n# enrich() inventory:\n#   params: lavaan syntax of the parameter under enrichment (loading, residual var, or F~~F latent var)\n#   fix='regressions': hold regression paths fixed at the genome-wide estimate during stratified fit\n#   std.lv=FALSE: do not standardize the latent variance\n#   rm_flank=TRUE: drop flanking-window contributions (default)\n#   tau=FALSE: use the baseline-annotation S\u002FV matrices (TRUE switches to the V_Tau\u002FS_Tau tau parametrization)\n#   base=TRUE: include baseline annotation contributions in the partition\n#   toler=NULL: matrix-inversion tolerance (let GenomicSEM choose; supply a small value when S is near-singular)\nstrat_factor \u003C- enrich(s_covstruc = s_results,\n                       model = '',\n                       params = 'F =~ trait1',\n                       fix = 'regressions',\n                       std.lv = FALSE,\n                       rm_flank = TRUE,\n                       tau = FALSE,\n                       base = TRUE,\n                       toler = NULL)\n```\n\nThe output gives per-annotation enrichment of the factor h2 -- the analog of cell-type S-LDSC for the latent factor (Grotzinger AD et al 2022 Nat Genet 54:548).\n\n## Computational Footprint\n\n| Step | Runtime | Hardware |\n|------|---------|----------|\n| `ldsc()` multi-trait sampling covariance | minutes | laptop |\n| `commonfactor()` \u002F `usermodel()` (no SNP loop) | seconds | laptop |\n| `commonfactorGWAS()` over 6-8M SNPs | 4-24h depending on cores | cluster recommended |\n| `userGWAS()` over 6-8M SNPs with complex path model | 8-48h | cluster recommended |\n| Stratified GenomicSEM with 50+ annotations | 1-3 days | cluster |\n| MTAG over 6-8M SNPs | 1-2h | laptop or cluster |\n\nCluster runs of `commonfactorGWAS()` \u002F `userGWAS()` should use `MPI=TRUE` when submitting via mpirun; GenomicSEM detects the OS internally (via `Sys.info()[['sysname']]`) and selects FORK (Linux\u002FMac) vs PSOCK (Windows) cluster types automatically -- there is no `Operating=` user argument. On a Mac\u002FWindows workstation, reduce `cores` to the physical-core count to avoid PSOCK fork failures.\n\n## Reconciliation: When GenomicSEM and MTAG Disagree\n\n| Pattern | Likely cause | Action |\n|---------|--------------|--------|\n| GenomicSEM factor SNP sig, MTAG sig for all traits | Genuine common-factor SNP | Report; high confidence |\n| GenomicSEM factor SNP sig, MTAG sig in only 1 trait | Q_SNP heterogeneity likely; one-trait-dominant | Check Q_SNP; if sig, this is NOT a factor SNP |\n| MTAG sig, GenomicSEM factor null, Q_SNP sig | Trait-specific SNP captured by MTAG shrinkage | Report as trait-specific, not common-factor |\n| Both null but per-trait univariate sig | Power loss from multivariate parameterization | Re-check sample overlap V matrix |\n| GenomicSEM and MTAG both sig but opposite direction | Sample-overlap mis-specification OR sign error in munging | Re-munge with same allele convention; re-run `ldsc()` |\n| MTAG MaxFDR > 5%, GenomicSEM with Q_SNP works | MTAG assumption violated | Prefer GenomicSEM as primary |\n| One-trait GWAS sig but common-factor not | Trait-specific architecture | Don't force into common-factor frame |\n\n**Operational rule for publication:** A common-factor SNP claim requires (1) factor p \u003C 5e-8, (2) Q_SNP p > 0.05 \u002F N_factor_SNPs (non-heterogeneous), and (3) replication in an independent set of traits or cohorts. Trait-specific SNPs from MTAG require MaxFDR \u003C 5% for the trait. Reporting only the factor effect without Q_SNP is the most common reviewer-flagged error.\n\n## Common Errors\n\n| Error \u002F symptom | Cause | Solution |\n|-----------------|-------|----------|\n| `commonfactor()` complains \"S not positive definite\" | Genetic correlations near +\u002F-1 among inputs | Drop redundant traits; verify rg \u003C 0.95 pairwise |\n| Standardized loading > 1 | Heywood case; under-identification | Constrain residual variance >= 0; inspect S for collinearity |\n| Factor p-value reported, Q_SNP not reported | Default focus is on factor effect | Always report Q_SNP from `commonfactorGWAS` output |\n| `ldsc()` fails with \"category not found\" | Wrong LD score column names (legacy format) | Use Python 3 LDSC fork; download `eur_w_ld_chr\u002F` from alkesgroup |\n| `lavaan` says \"model not identified\" | Too few traits for too many parameters | Need >= 3 traits per factor; constrain factor variance to 1 |\n| MTAG `MaxFDR` not in log | Older MTAG version (\u003C 1.0.7) | Update MTAG; MaxFDR reporting added late 2019 |\n| Singular V matrix on smooth `nearPD` | One trait has near-zero h2 or mean chi-square \u003C 1.02 | Drop the trait; do not smooth as a fix |\n| `usermodel()` slow or fails | Complex syntax + many traits | Simplify model; estimate with `estimation = 'DWLS'`, not `'ML'`, when V is informative |\n| Sumstats output has zero overlap with reference | Allele coding mismatch in `sumstats()` | Check `se.logit` and `OLS` settings per trait; align A1\u002FA2 |\n| GenomicSEM and TwoSampleMR give different rg | TwoSampleMR uses bivariate LDSC; GenomicSEM uses the same S | Match the underlying LDSC reference panel and weights |\n\n## Anticipated Reviewer Pushback\n\n| Pushback | Standard response |\n|----------|-------------------|\n| \"Q_SNP reported?\" | `Q_pval` column reported alongside SNP->factor effect; Bonferroni threshold 5e-8 \u002F N_factor_SNPs applied |\n| \"MaxFDR > 5%?\" | MTAG `maxFDR` reported per trait; > 5% invalidates MTAG for that trait -> GenomicSEM common-factor used instead |\n| \"Sample overlap absorbed?\" | Full V matrix from `ldsc()` is the input to all model fits; S is never constructed manually from pairwise rg estimates |\n| \"Model fit?\" | CFI >= 0.95, RMSEA \u003C= 0.08, SRMR \u003C= 0.08 reported; AIC \u002F BIC for nested comparison; chi-square reported but treated as inflated at large N |\n| \"Why a factor model and not MTAG?\" | Factor structure tested first; if traits load on a common factor with CFI > 0.95, common-factor GWAS preferred -- explicitly models heterogeneity via Q_SNP |\n| \"Heywood case?\" | Negative residual variance constrained >= 0; OR the offending indicator dropped and the model re-specified; the choice is documented in methods |\n| \"Cross-ancestry?\" | Run per-ancestry; no validated cross-ancestry V matrix as of 2026; loadings compared qualitatively |\n| \"Why DWLS and not ML?\" | ML assumes V is known; DWLS uses the empirical V from `ldsc()` and is the appropriate estimator under sample overlap |\n\n## Tool Installation\n\n```r\n# GenomicSEM is GitHub-only\nremotes::install_github('GenomicSEM\u002FGenomicSEM')\n\n# Dependencies\ninstall.packages(c('lavaan', 'Matrix', 'gdata'))\n\n# Optional companions\nremotes::install_github('MRCIEU\u002FTwoSampleMR')  # for downstream MR using factor GWAS as exposure\n```\n\nFor Python tools:\n\n```bash\n# LDSC python3 fork (GenomicSEM input format). belowlab\u002Fldsc v3.0.1 broke the\n# --h2\u002F--rg\u002F--h2-cts CLI per its README; use abdenlab\u002Fldsc-python3 (v2.0.0)\n# for a working CLI. Docker jtb114\u002Fldsc:latest is the belowlab fallback.\ngit clone https:\u002F\u002Fgithub.com\u002Fabdenlab\u002Fldsc-python3.git\ncd ldsc-python3 && pip install .   # Poetry project (pyproject.toml); no requirements.txt\n\n# MTAG\ngit clone https:\u002F\u002Fgithub.com\u002FJonJala\u002Fmtag.git\ncd mtag && pip install -r requirements.txt\n```\n\nPre-downloaded reference files: `eur_w_ld_chr\u002F`, `baselineLD_v2.2.*`, `w_hm3.snplist`, and 1000G allele-frequency files are hosted at `alkesgroup.broadinstitute.org\u002FLDSCORE\u002F`.\n\n## References\n\n- Grotzinger AD et al 2019 Nat Hum Behav 3:513 (GenomicSEM, common-factor GWAS, Q_SNP)\n- Grotzinger AD et al 2022 Nat Genet 54:548 (Stratified GenomicSEM)\n- Turley P et al 2018 Nat Genet 50:229 (MTAG; MaxFDR)\n- Bulik-Sullivan B et al 2015 Nat Genet 47:291 (LDSC for genetic covariance)\n- Bulik-Sullivan B et al 2015 Nat Genet 47:1236 (bivariate LDSC, sample overlap)\n- Rosseel Y 2012 J Stat Softw 48:1-36 (lavaan package)\n- Hu LT & Bentler PM 1999 Struct Equ Model 6:1 (CFI \u002F RMSEA cutoffs)\n- Asparouhov T & Muthen B 2009 Struct Equ Model 16:397 (ESEM framework)\n- Finucane HK et al 2015 Nat Genet 47:1228 (S-LDSC, foundation for stratified GenomicSEM)\n- Gazal S et al 2017 Nat Genet 49:1421 (baseline-LD annotations)\n- Demange PA et al 2021 Nat Genet 53:35 (GenomicSEM GWAS-by-subtraction for noncognitive skills; Q_SNP in practice)\n- Karlsson Linner R, Mallard TT et al 2021 Nat Neurosci 24:1367 (multivariate externalizing GWAS via GenomicSEM)\n- de la Fuente J et al 2021 Nat Hum Behav 5:49 (GenomicSEM for cognitive g factor)\n- Skrivankova VW et al 2021 JAMA 326:1614 (STROBE-MR; relevant when downstream MR uses factor GWAS)\n\n## Related Skills\n\n- causal-genomics\u002Fmendelian-randomization - Use factor-GWAS effect sizes as MR exposure\n- causal-genomics\u002Fgenetic-correlation - Bivariate LDSC produces the off-diagonals of the S matrix; GenomicSEM is the multi-trait extension\n- causal-genomics\u002Fheritability-partitioning - LDSC and S-LDSC foundations for stratified GenomicSEM\n- causal-genomics\u002Fcolocalization-analysis - Cross-trait colocalization at common-factor loci\n- causal-genomics\u002Fpleiotropy-detection - Q_SNP is a per-SNP pleiotropy diagnostic; sibling concept\n- causal-genomics\u002Ffine-mapping - Resolve factor-significant loci to credible sets\n- causal-genomics\u002Fmediation-analysis - SEM mediation paths overlap with `usermodel` indirect effects\n- causal-genomics\u002Ftranscriptome-wide-association - TWAS on factor sumstats from `commonfactorGWAS`\n- population-genetics\u002Fassociation-testing - GWAS sumstats are the input format\n","## Version Compatibility\n\nReference examples tested with: GenomicSEM 0.0.5+ (GitHub `GenomicSEM\u002FGenomicSEM`), lavaan 0.6-17+, LDSC v1.0.1+ (Python 3; prefer `abdenlab\u002Fldsc-python3` v2.0.0 -- `belowlab\u002Fldsc` v3.0.1 README states the CLI is broken; Docker `jtb114\u002Fldsc:latest` is the belowlab fallback), baselineLD_v2.2 annotations (alkesgroup.broadinstitute.org\u002FLDSCORE), MTAG 1.0.8+ (Python; `JonJala\u002Fmtag`), R 4.4+.\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- R: `packageVersion('GenomicSEM')` then `?ldsc`, `?commonfactor`, `?usermodel`, `?commonfactorGWAS`\n- Python (LDSC, MTAG): `\u003Ctool>.py -h` and inspect the source under `ldsc\u002F` or `mtag\u002F`\n\nGenomicSEM is GitHub-only (never on CRAN). If `ldsc()` or `usermodel()` throws an error about lavaan syntax or non-positive-definite covariance, introspect the installed API (`getMethod('ldsc')`) and adapt rather than retrying.\n\n# Genomic SEM\n\n**\"Model the latent genetic architecture across several correlated GWAS\"** -> Treat each GWAS as a measured indicator of one or more latent genetic factors and fit a structural equation model to the LDSC-derived genetic covariance matrix S and its sampling covariance V (Grotzinger 2019 Nat Hum Behav 3:513). The framework extends naturally to a multivariate GWAS in which a SNP is regressed on a latent factor (common-factor GWAS), with Q_SNP testing whether the SNP effect is homogeneous across factor loadings. Sample overlap between input GWAS is absorbed by the off-diagonals of V; ignoring V inflates Type-I.\n\n- R: `GenomicSEM::ldsc()` produces the (S, V) covariance pair from munged sumstats\n- R: `GenomicSEM::commonfactor()` fits a single-factor CFA across all traits in S\n- R: `GenomicSEM::usermodel()` fits an arbitrary lavaan-syntax model\n- R: `GenomicSEM::commonfactorGWAS()` runs SNP -> factor multivariate GWAS with Q_SNP\n- R: `GenomicSEM::userGWAS()` runs arbitrary multivariate SNP regression with per-path Q_SNP\n- Python (alternative): `mtag.py --sumstats t1,t2,t3 --out mtag_out` (multi-trait power boost on individual traits)\n\n## Statistical Model Taxonomy\n\n| Method | Latent structure | Min traits | SNP-level test | Strength | Fails when |\n|--------|------------------|-----------|----------------|----------|------------|\n| Common-factor CFA (Grotzinger 2019) | Single F loading all traits | 3 | None (model-fit only) | Tests whether shared variance is unidimensional | Heterogeneous architecture; CFI \u003C 0.9; near-zero loadings |\n| User-specified CFA (`usermodel`) | Pre-specified lavaan syntax | 3 | None | Confirmatory; arbitrary structure | Misspecified model; identification under-determined |\n| ESEM | Exploratory rotation; cross-loadings allowed | 6+ | None | When factor count and structure unknown | Few traits; collinear traits; rotation arbitrary |\n| Common-factor GWAS (`commonfactorGWAS`) | SNP -> F -> trait1..k | 3 | Wald on F + Q_SNP heterogeneity | Discovers SNPs acting via the common factor; flags Q_SNP outliers | Q_SNP-significant SNPs not interpretable as factor SNPs |\n| User GWAS (`userGWAS`) | Arbitrary SNP-path lavaan | 3 | Wald per path + Q_SNP | Tests SNP on any specified path | Highly parameterized models lose power |\n| Multivariate Wald test | Joint test across SNP -> trait paths | 2+ | Joint chi-square | Boost power when SNP affects multiple traits | Heterogeneous SNP effects collapse joint test |\n| Stratified GenomicSEM (Grotzinger AD et al 2022 Nat Genet 54:548) | Factor model with sLDSC-partitioned annotations | 3 | Per-annotation factor tau | Localizes heritability of the factor to functional categories | Same sLDSC failure modes (small annotation, collinearity) |\n| MTAG (Turley 2018 Nat Genet 50:229) | Empirical-Bayes shrinkage across correlated traits | 2 | Per-trait shrunk z-score | Boosts marginal power for any input trait | MaxFDR > 5% indicates heterogeneity violates MTAG assumption |\n\nMethodology evolves; verify the current Grotzinger 2023+ tutorials at `github.com\u002FGenomicSEM\u002FGenomicSEM\u002Fwiki` before locking a method. ESEM rotation choice (geomin vs target rotation) is an active area; report sensitivity to rotation.\n\n## MTAG vs GenomicSEM Common-Factor GWAS\n\nBoth methods exploit genetic correlation among input GWAS, but their goals and outputs differ.\n\n| Property | MTAG | GenomicSEM commonfactorGWAS |\n|----------|------|------------------------------|\n| Output | Per-trait shrunk z-scores | SNP effect on latent factor |\n| Sample-overlap handling | Bivariate LDSC intercept | Full LDSC sampling-covariance matrix V |\n| Heterogeneity diagnostic | MaxFDR (Turley 2018) | Q_SNP (Grotzinger 2019) |\n| Interpretation | \"Boosted power for trait k\" | \"Effect on what the traits share\" |\n| Min traits | 2 | 3 (otherwise factor not identified) |\n| Best when | Power-boost an individual trait | Common factor hypothesized |\n\nBoth depend on accurate sampling covariance. MTAG fails (MaxFDR > 5%) under the same heterogeneity that produces large Q_SNP in GenomicSEM. The two methods should be reported together when the prior on a common factor is non-trivial; agreement increases confidence, disagreement points to architecture-specific SNPs.\n\n## Decision Tree by Scenario\n\n| Scenario | Recommended | Why |\n|----------|-------------|-----|\n| Multi-trait GWAS power boost for one focal trait | MTAG | Optimized for per-trait marginal power |\n| Common-factor architecture hypothesized | GenomicSEM `commonfactorGWAS` | Tests SNP -> factor; reports Q_SNP heterogeneity |\n| Heterogeneous architecture (>1 latent factor) | ESEM, then confirmatory `usermodel` | Exploratory first, then confirm |\n| Confirming a pre-specified factor structure | `usermodel` with lavaan syntax | Confirmatory factor analysis |\n| Partition heritability of factor across annotations | Stratified GenomicSEM | Combines sLDSC + factor model |\n| Mediation in a SEM framework | `usermodel` with indirect path | Path coefficients + delta-method SE |\n| Sample overlap unknown or any-overlap suspected | Always use `ldsc()` output as input | V matrix off-diagonals absorb overlap |\n| Cross-ancestry common-factor analysis | Run per-ancestry, compare loadings; no published cross-ancestry SEM as of 2026 | Method not yet validated for mixed-ancestry V |\n| Single biobank for all traits (e.g., UKB only) | GenomicSEM with `ldsc()`; the V matrix will reflect overlap | Equivalent to one-sample MR -- the V matrix is the correction |\n| Comparing GenomicSEM and MTAG on the same traits | Run both; compare top hits + heterogeneity | Concordance increases confidence; divergence flags heterogeneity |\n\n## Per-Method Failure Modes\n\n### Heywood case (negative residual variance)\n\n**Trigger:** A residual variance estimate is \u003C 0, or a standardized loading exceeds 1.\n\n**Mechanism:** Empirical underidentification; the genetic covariance matrix S is near-singular OR a trait has near-zero specific variance under the model. The maximum-likelihood \u002F DWLS estimator runs past the boundary of the parameter space.\n\n**Symptom:** `lavaan` warning \"some estimated lv variances are negative\" or \"covariance matrix is not positive definite\"; standardized loading > 1; non-convergence.\n\n**Fix:** First, inspect the LDSC S matrix for genetic correlations near 1 (multicollinearity). Drop or merge near-identical traits. Second, constrain the offending residual variance to be non-negative in the lavaan syntax (`trait1 ~~ a*trait1; a > 0`). Third, verify the V matrix is positive definite via `chol(V_LD)`; if not, the bivariate LDSC inputs disagree on intercept signs and need re-munging. Never re-fit without diagnosing the cause.\n\n### Sample overlap mis-specified\n\n**Trigger:** Using LDSC intercept manually or supplying covariance from non-`ldsc()` source.\n\n**Mechanism:** GenomicSEM's `ldsc()` function returns a list with `S` (genetic covariance) AND `V` (sampling covariance of the lower-triangle of S). The V off-diagonals capture sample overlap via cross-trait LDSC intercept. Skipping V and supplying only S treats all inputs as independent samples; Type-I error inflates because the sampling distribution under H0 is wrong.\n\n**Symptom:** SE on factor loadings far too small; many SNPs significant in common-factor GWAS that don't replicate; comparison to MTAG shows disagreement consistent with overlap.\n\n**Fix:** Always pass the full output of `ldsc()` -- both S and V -- to `commonfactor()`, `usermodel()`, and `commonfactorGWAS()`. Never construct S manually from rg estimates.\n\n### Q_SNP not reported in commonfactorGWAS\n\n**Trigger:** Running `commonfactorGWAS()` and reporting only the factor p-value per SNP.\n\n**Mechanism:** Q_SNP tests heterogeneity of the SNP's effect across factor loadings (Grotzinger 2019 supplement). A SNP with significant Q_SNP violates the common-factor assumption: its effect is NOT mediated by the factor, and the factor estimate is meaningless for that SNP.\n\n**Symptom:** Top \"common-factor SNPs\" are dominated by trait-specific effects; replication in independent cohorts is poor for SNPs with high Q_SNP.\n\n**Fix:** Always report Q_SNP p-value alongside the factor p-value. Flag SNPs with Q_SNP p \u003C 5e-8 \u002F N_factor_SNPs (Bonferroni for the discovered set) as architecture-violating and exclude from \"common-factor SNP\" claims. Re-fit those SNPs in `userGWAS()` with separate paths to each trait.\n\n### Trait inclusion under heterogeneous factor structure\n\n**Trigger:** Forcing a common-factor model on traits that don't share a single latent factor.\n\n**Mechanism:** When two or more traits load on a different factor than the rest, the single-factor model misfits. lavaan still returns parameter estimates but model fit is poor.\n\n**Symptom:** CFI \u003C 0.9; RMSEA > 0.08; some standardized loadings near 0 while others near 1; chi-square highly significant even after accounting for N.\n\n**Fix:** Run ESEM first (`commonfactor` then `usermodel` with cross-loadings allowed) to discover structure. If two factors emerge, fit a two-factor `usermodel`. Drop traits with near-zero loadings on all factors. Document the model search.\n\n### MTAG MaxFDR > 5%\n\n**Trigger:** Running MTAG on traits with low pairwise genetic correlation or with one trait that has a very different architecture.\n\n**Mechanism:** MTAG assumes a homogeneous variance-covariance structure across SNPs. When heterogeneity dominates, the empirical-Bayes shrinkage can over-claim SNPs in the focal trait. Turley 2018 defines MaxFDR as the maximum estimated false discovery rate under worst-case heterogeneity; > 5% invalidates the published trait-specific summary statistics.\n\n**Symptom:** MTAG output file reports `maxFDR` > 0.05; per-trait MTAG hits don't replicate in independent cohorts.\n\n**Fix:** Check pairwise rg via LDSC; if any pair is \u003C 0.7, MTAG is risky. Drop the most heterogeneous trait and re-run. Alternatively, switch to GenomicSEM's `commonfactorGWAS` which models heterogeneity explicitly via Q_SNP.\n\n### Non-positive-definite V_LD matrix\n\n**Trigger:** LDSC inputs from different ancestry GWAS, or one trait with very low mean chi-square (\u003C 1.02).\n\n**Mechanism:** V is the sampling covariance of vech(S); when individual entries of S have huge SE relative to off-diagonal covariance, the resulting V is not positive definite (negative eigenvalues).\n\n**Symptom:** `commonfactor()` errors with \"matrix is not positive definite\" before fitting; `eigen(LDSCoutput$V)$values` shows negative values.\n\n**Fix:** Verify per-trait mean chi-square via `ldsc()` log; below 1.02, exclude that trait. Verify all GWAS are EUR ancestry (or match ancestry of LD scores). Apply nearest-PD smoothing via `Matrix::nearPD(V)$mat` ONLY as a last resort and document the approximation in methods.\n\n## Model Fit Diagnostics\n\n| Index | Acceptable | Good | Source |\n|-------|-----------|------|--------|\n| CFI | >= 0.90 | >= 0.95 | Hu & Bentler 1999 Struct Equ Model 6:1 |\n| TLI \u002F NNFI | >= 0.90 | >= 0.95 | Hu & Bentler 1999 |\n| RMSEA | \u003C= 0.08 | \u003C= 0.05 | Hu & Bentler 1999 |\n| SRMR | \u003C= 0.08 | \u003C= 0.05 | Hu & Bentler 1999 |\n| chi-square p-value | (less informative at large N) | n\u002Fa | Penalize for N inflation |\n\nAIC \u002F BIC are used for nested-model comparison (lower is better); only compare nested models fit on the same S.\n\n## Quantitative Thresholds\n\n| Threshold | Source | Rationale |\n|-----------|--------|-----------|\n| CFI >= 0.95 | Hu & Bentler 1999 | Conventional good fit; SEM literature default |\n| RMSEA \u003C= 0.05 | Hu & Bentler 1999 | Conventional good fit |\n| RMSEA 0.05 - 0.08 | Hu & Bentler 1999 | Acceptable; flag as \"adequate\" not \"good\" |\n| Q_SNP p \u003C 0.05 \u002F N_SNP_factor | Grotzinger 2019 Nat Hum Behav 3:513 | Bonferroni for heterogeneity among factor-significant SNPs |\n| MTAG MaxFDR \u003C 5% | Turley 2018 Nat Genet 50:229 | Above this, MTAG marginal trait results invalid |\n| Per-trait LDSC mean chi-square > 1.02 | LDSC documentation | Below this, V entries too noisy; factor SE inflated |\n| Standardized loading 0.3 - 0.9 typical | SEM conventions | \u003C 0.3 trait loads weakly; > 0.95 may indicate over-fit \u002F collinearity |\n| Min 3 traits for common factor | SEM identification | Single factor with k traits has k(k+1)\u002F2 moments; needs k>=3 to identify |\n\n## Standard Workflow\n\n**Goal:** Fit a common-factor model across correlated GWAS and run a multivariate GWAS on the factor with Q_SNP.\n\n**Approach:** Munge sumstats -> LDSC for (S, V) -> common-factor CFA -> inspect fit -> prepare SNPs -> common-factor GWAS -> report factor effects with Q_SNP flags.\n\n```r\nlibrary(GenomicSEM)\n\n# Step 1: Munge sumstats (one-time; produces .sumstats.gz files)\nfiles \u003C- c('raw\u002Ftrait1.txt', 'raw\u002Ftrait2.txt', 'raw\u002Ftrait3.txt')\nhm3 \u003C- 'w_hm3.snplist'  # HapMap3 SNP list\ntrait_names \u003C- c('trait1', 'trait2', 'trait3')\nN \u003C- c(150000, 200000, 175000)\nmunge(files = files, hm3 = hm3, trait.names = trait_names, N = N)\n\n# Step 2: LDSC produces both S (genetic covariance) and V (sampling covariance)\ntraits \u003C- c('trait1.sumstats.gz', 'trait2.sumstats.gz', 'trait3.sumstats.gz')\nldsc_results \u003C- ldsc(\n    traits = traits,\n    sample.prev = c(0.5, 0.5, NA),    # case prevalence; NA for continuous\n    population.prev = c(0.05, 0.05, NA),\n    ld = 'eur_w_ld_chr\u002F',\n    wld = 'eur_w_ld_chr\u002F',\n    trait.names = trait_names\n)\n# ldsc_results$S = genetic covariance; ldsc_results$V = sampling covariance\n\n# Step 3a: Common-factor CFA via DWLS\ncf_fit \u003C- commonfactor(covstruc = ldsc_results, estimation = 'DWLS')\nprint(cf_fit$modelfit)  # CFI, RMSEA, SRMR, chi-square\nprint(cf_fit$results)   # loadings + SEs\n\n# Step 3b: Alternative -- user-specified two-factor model (>=3 indicators per factor)\n# Identification rule: each factor needs >= 3 indicators OR one anchor loading fixed\n# to 1 plus factor variance free. A factor with a single indicator is NOT identified.\nmodel_syntax \u003C- '\n    F1 =~ NA*trait1 + trait2 + trait3\n    F2 =~ NA*trait4 + trait5 + trait6\n    F1 ~~ 1*F1\n    F2 ~~ 1*F2\n    F1 ~~ F2\n'\nuser_fit \u003C- usermodel(covstruc = ldsc_results, model = model_syntax, estimation = 'DWLS')\n```\n\n`estimation = 'DWLS'` (diagonally weighted least squares) is the default and is required when V is large; `'ML'` is faster but assumes a known V and can produce wrong SE under sample overlap.\n\n### ESEM (Exploratory Factor Structure)\n\nWhen the factor structure is unknown, fit `usermodel()` with all loadings free across all factors, then apply a rotation post-fit. Rotation choices: **geomin oblique** (default; allows factor correlation), **target rotation** (Browne 2001 Multivariate Behav Res 36:111; uses a hypothesized loading template), **quartimin** (orthogonal; assumes factors are uncorrelated).\n\n```r\nmodel_esem \u003C- '\n    F1 =~ NA*trait1 + trait2 + trait3 + trait4\n    F2 =~ NA*trait1 + trait2 + trait3 + trait4\n    F1 ~~ 1*F1\n    F2 ~~ 1*F2\n    F1 ~~ F2\n'\nesem_fit \u003C- usermodel(covstruc = ldsc_results, model = model_esem, estimation = 'DWLS')\n# Rotate post-fit via GPArotation::GPForth\u002FGPFoblq or lavaan::rotate()\n```\n\n**Decision:** ESEM for K-factor exploration when structure is unknown; CFA via `usermodel()` once a structure is confirmed. Report rotation sensitivity (geomin vs target vs quartimin) and treat as exploratory.\n\n**Cross-loadings.** Cross-loadings (one trait loads on > 1 factor) are common in psychiatric and behavioral GWAS. Brown 2015 *Confirmatory Factor Analysis for Applied Research* recommends allowing cross-loadings first and using modification indices to guide simplification. Allow a cross-loading when constraining residual variance otherwise forces a Heywood case. Constrain when CFI \u003C 0.9 and modification indices instead suggest a correlated residual between two indicators (which is the more parsimonious fix).\n\n### userGWAS for Custom Path Models\n\n`userGWAS()` fits arbitrary lavaan-syntax SNP regressions and is the right tool when the SNP needs to be tested on multiple paths simultaneously (e.g. factor-mediated effect AND a direct effect on one indicator).\n\n```r\n# Test SNP -> F path + SNP -> trait1 direct path simultaneously\nmodel \u003C- '\n    F =~ NA*trait1 + trait2 + trait3\n    F ~~ 1*F\n    F ~ SNP\n    trait1 ~ SNP    # direct effect on trait1, partialed out of F\n'\nuser_results \u003C- userGWAS(covstruc = ldsc_results,\n                         SNPs = ss,\n                         estimation = 'DWLS',\n                         model = model,\n                         sub = c('F~SNP', 'trait1~SNP'),\n                         parallel = TRUE,\n                         cores = 8)\n# Output columns include: lhs, op, rhs, est, SE, Z, Pvalue, Q_pval, Q_df.\n# Q_pval per SNP measures heterogeneity across loadings AFTER conditioning on\n# the direct path; remaining Q_SNP signal indicates a third path is needed.\n```\n\n### Higher-Order \u002F Bifactor \u002F p-Factor Models\n\nUse case: psychiatric genetics p-factor (Caspi 2014 Clin Psychol Sci 2:119; Grotzinger 2022 Nat Genet 54:548 cross-disorder), cognitive g-factor (de la Fuente 2021 Nat Hum Behav 5:49).\n\nHierarchical template -- first-order factors load on a single second-order p-factor:\n\n```r\nmodel_pfactor \u003C- '\n    # First-order factors\n    INT =~ NA*trait_anx + trait_dep + trait_neuro       # internalizing\n    EXT =~ NA*trait_adhd + trait_alc + trait_subst       # externalizing\n    THT =~ NA*trait_scz + trait_bp                       # thought-disorder\n    # Second-order p-factor\n    p =~ NA*INT + EXT + THT\n    INT ~~ 1*INT\n    EXT ~~ 1*EXT\n    THT ~~ 1*THT\n    p ~~ 1*p\n'\n```\n\nBifactor alternative: `p =~` all traits directly, with `INT`\u002F`EXT`\u002F`THT` as orthogonal residual factors. Bifactor typically gives tighter CFI\u002FRMSEA but the substantive interpretation of the residual factors is harder; bifactor is also prone to over-fitting at modest trait counts (Bonifay W & Cai L 2017 Multivariate Behav Res 52:465). Cite Grotzinger 2022 Nat Genet 54:548 and Karlsson Linner R, Mallard TT et al 2021 Nat Neurosci 24:1367 for the canonical psychiatric implementations.\n\n## Common-Factor GWAS with Q_SNP\n\n**Goal:** Identify SNPs that affect the latent factor and flag SNPs whose effect is heterogeneous across loadings.\n\n**Approach:** Build SNP-by-trait effect-and-SE matrix via `sumstats()`, then fit the SNP-augmented model genome-wide via `commonfactorGWAS()`. Report both factor p-value and Q_SNP p-value per SNP.\n\n`sumstats()` flips effect signs based on the reference panel A1\u002FA2 to enforce consistent allele coding across input GWAS. Required input columns (case-sensitive) are `SNP, A1, A2, BETA\u002FZ\u002FOR, SE, P, N, MAF`; some are conditional on `se.logit` \u002F `OLS`. Silent failures are almost always column-name mismatches (e.g. `EA`\u002F`NEA` instead of `A1`\u002F`A2` -> 0% SNPs retained) or a missing `N` column -> SNPs dropped. Always run `head(read.table(file, header=TRUE, nrow=2))` per input before the `sumstats()` call.\n\n```r\n# Prepare per-SNP betas and SEs across all input GWAS\nss \u003C- sumstats(\n    files = c('raw\u002Ftrait1.txt', 'raw\u002Ftrait2.txt', 'raw\u002Ftrait3.txt'),\n    ref = 'reference.1000G.maf.0.005.txt',\n    trait.names = trait_names,\n    se.logit = c(TRUE, TRUE, FALSE),     # TRUE if trait is logistic-scale (case-control); FALSE if continuous\n    OLS = c(FALSE, FALSE, TRUE),\n    linprob = c(FALSE, FALSE, FALSE),\n    N = N,\n    info.filter = 0.9,                   # standard imputation INFO threshold\n    maf.filter = 0.01\n)\n\n# GenomicSEM internally detects the OS via Sys.info()[['sysname']] and chooses\n# PSOCK (Windows) vs FORK (Linux\u002FMac) clusters automatically; there is no user\n# `Operating=` argument. MPI=TRUE switches to an mpirun-based strategy for\n# cluster job submission. parallel=TRUE is the default.\ncfgwas \u003C- commonfactorGWAS(\n    covstruc = ldsc_results,\n    SNPs = ss,\n    estimation = 'DWLS',\n    parallel = TRUE,\n    cores = 8,\n    MPI = FALSE\n)\n\n# cfgwas columns include rsID\u002Fchr\u002FBP\u002FMAF\u002FA1\u002FA2\u002Fest\u002Fse_c\u002FZ_Estimate\u002FPval_Estimate (factor effect)\n# plus heterogeneity columns Q \u002F Q_df \u002F Q_pval. Q_pval IS the per-SNP heterogeneity\n# test (often referred to as Q_SNP in the literature; the column name in the data.frame is Q_pval).\ncfgwas$factor_sig \u003C- cfgwas$Pval_Estimate \u003C 5e-08\ncfgwas$qsnp_sig \u003C- cfgwas$Q_pval \u003C (0.05 \u002F sum(cfgwas$factor_sig))\ncfgwas$factor_only \u003C- cfgwas$factor_sig & !cfgwas$qsnp_sig\n```\n\nThe \"factor-only\" subset (factor-significant AND Q_SNP non-significant) is the publication-grade set of common-factor SNPs.\n\n## MTAG Comparison\n\n**Goal:** Cross-check GenomicSEM common-factor results against MTAG per-trait shrunk z-scores.\n\n**Approach:** Run MTAG CLI on the same input sumstats; compare top hits with GenomicSEM factor hits. Report MaxFDR.\n\n```bash\n# MTAG CLI (Python)\npython mtag.py \\\n    --sumstats trait1.txt,trait2.txt,trait3.txt \\\n    --n_min 0 \\\n    --out mtag_results\n# MTAG uses the signed Z by default; --use_beta_se was disabled upstream (raises a\n# RuntimeError since Dec 2021 due to beta-se bugs), so supply a Z column and omit it.\n\n# Check MaxFDR per trait\ngrep -iE 'max ?fdr' mtag_results.log   # matches both the section header and the 'Max FDR of Trait' value lines\n# Each per-trait MTAG file: mtag_results_trait_\u003Ck>.txt\n```\n\nIf MaxFDR > 0.05 for any trait, MTAG results for that trait are unreliable; GenomicSEM with Q_SNP filtering is the more defensible report.\n\n## Stratified GenomicSEM (Partitioned Heritability of Factor)\n\nFor partitioning the heritability of the latent factor across functional annotations, use `s_ldsc()` (stratified LDSC inside GenomicSEM) and pass the multi-annotation output to a stratified model fit.\n\n```r\n# Stratified LDSC across baseline + custom annotations\ns_results \u003C- s_ldsc(\n    traits = traits,\n    sample.prev = c(0.5, 0.5, NA),\n    population.prev = c(0.05, 0.05, NA),\n    ld = 'baselineLD_v2.2.',\n    wld = 'weights.hm3_noMHC.',\n    frq = '1000G.EUR.QC.',\n    trait.names = trait_names\n)\n\n# enrich() inventory:\n#   params: lavaan syntax of the parameter under enrichment (loading, residual var, or F~~F latent var)\n#   fix='regressions': hold regression paths fixed at the genome-wide estimate during stratified fit\n#   std.lv=FALSE: do not standardize the latent variance\n#   rm_flank=TRUE: drop flanking-window contributions (default)\n#   tau=FALSE: use the baseline-annotation S\u002FV matrices (TRUE switches to the V_Tau\u002FS_Tau tau parametrization)\n#   base=TRUE: include baseline annotation contributions in the partition\n#   toler=NULL: matrix-inversion tolerance (let GenomicSEM choose; supply a small value when S is near-singular)\nstrat_factor \u003C- enrich(s_covstruc = s_results,\n                       model = '',\n                       params = 'F =~ trait1',\n                       fix = 'regressions',\n                       std.lv = FALSE,\n                       rm_flank = TRUE,\n                       tau = FALSE,\n                       base = TRUE,\n                       toler = NULL)\n```\n\nThe output gives per-annotation enrichment of the factor h2 -- the analog of cell-type S-LDSC for the latent factor (Grotzinger AD et al 2022 Nat Genet 54:548).\n\n## Computational Footprint\n\n| Step | Runtime | Hardware |\n|------|---------|----------|\n| `ldsc()` multi-trait sampling covariance | minutes | laptop |\n| `commonfactor()` \u002F `usermodel()` (no SNP loop) | seconds | laptop |\n| `commonfactorGWAS()` over 6-8M SNPs | 4-24h depending on cores | cluster recommended |\n| `userGWAS()` over 6-8M SNPs with complex path model | 8-48h | cluster recommended |\n| Stratified GenomicSEM with 50+ annotations | 1-3 days | cluster |\n| MTAG over 6-8M SNPs | 1-2h | laptop or cluster |\n\nCluster runs of `commonfactorGWAS()` \u002F `userGWAS()` should use `MPI=TRUE` when submitting via mpirun; GenomicSEM detects the OS internally (via `Sys.info()[['sysname']]`) and selects FORK (Linux\u002FMac) vs PSOCK (Windows) cluster types automatically -- there is no `Operating=` user argument. On a Mac\u002FWindows workstation, reduce `cores` to the physical-core count to avoid PSOCK fork failures.\n\n## Reconciliation: When GenomicSEM and MTAG Disagree\n\n| Pattern | Likely cause | Action |\n|---------|--------------|--------|\n| GenomicSEM factor SNP sig, MTAG sig for all traits | Genuine common-factor SNP | Report; high confidence |\n| GenomicSEM factor SNP sig, MTAG sig in only 1 trait | Q_SNP heterogeneity likely; one-trait-dominant | Check Q_SNP; if sig, this is NOT a factor SNP |\n| MTAG sig, GenomicSEM factor null, Q_SNP sig | Trait-specific SNP captured by MTAG shrinkage | Report as trait-specific, not common-factor |\n| Both null but per-trait univariate sig | Power loss from multivariate parameterization | Re-check sample overlap V matrix |\n| GenomicSEM and MTAG both sig but opposite direction | Sample-overlap mis-specification OR sign error in munging | Re-munge with same allele convention; re-run `ldsc()` |\n| MTAG MaxFDR > 5%, GenomicSEM with Q_SNP works | MTAG assumption violated | Prefer GenomicSEM as primary |\n| One-trait GWAS sig but common-factor not | Trait-specific architecture | Don't force into common-factor frame |\n\n**Operational rule for publication:** A common-factor SNP claim requires (1) factor p \u003C 5e-8, (2) Q_SNP p > 0.05 \u002F N_factor_SNPs (non-heterogeneous), and (3) replication in an independent set of traits or cohorts. Trait-specific SNPs from MTAG require MaxFDR \u003C 5% for the trait. Reporting only the factor effect without Q_SNP is the most common reviewer-flagged error.\n\n## Common Errors\n\n| Error \u002F symptom | Cause | Solution |\n|-----------------|-------|----------|\n| `commonfactor()` complains \"S not positive definite\" | Genetic correlations near +\u002F-1 among inputs | Drop redundant traits; verify rg \u003C 0.95 pairwise |\n| Standardized loading > 1 | Heywood case; under-identification | Constrain residual variance >= 0; inspect S for collinearity |\n| Factor p-value reported, Q_SNP not reported | Default focus is on factor effect | Always report Q_SNP from `commonfactorGWAS` output |\n| `ldsc()` fails with \"category not found\" | Wrong LD score column names (legacy format) | Use Python 3 LDSC fork; download `eur_w_ld_chr\u002F` from alkesgroup |\n| `lavaan` says \"model not identified\" | Too few traits for too many parameters | Need >= 3 traits per factor; constrain factor variance to 1 |\n| MTAG `MaxFDR` not in log | Older MTAG version (\u003C 1.0.7) | Update MTAG; MaxFDR reporting added late 2019 |\n| Singular V matrix on smooth `nearPD` | One trait has near-zero h2 or mean chi-square \u003C 1.02 | Drop the trait; do not smooth as a fix |\n| `usermodel()` slow or fails | Complex syntax + many traits | Simplify model; estimate with `estimation = 'DWLS'`, not `'ML'`, when V is informative |\n| Sumstats output has zero overlap with reference | Allele coding mismatch in `sumstats()` | Check `se.logit` and `OLS` settings per trait; align A1\u002FA2 |\n| GenomicSEM and TwoSampleMR give different rg | TwoSampleMR uses bivariate LDSC; GenomicSEM uses the same S | Match the underlying LDSC reference panel and weights |\n\n## Anticipated Reviewer Pushback\n\n| Pushback | Standard response |\n|----------|-------------------|\n| \"Q_SNP reported?\" | `Q_pval` column reported alongside SNP->factor effect; Bonferroni threshold 5e-8 \u002F N_factor_SNPs applied |\n| \"MaxFDR > 5%?\" | MTAG `maxFDR` reported per trait; > 5% invalidates MTAG for that trait -> GenomicSEM common-factor used instead |\n| \"Sample overlap absorbed?\" | Full V matrix from `ldsc()` is the input to all model fits; S is never constructed manually from pairwise rg estimates |\n| \"Model fit?\" | CFI >= 0.95, RMSEA \u003C= 0.08, SRMR \u003C= 0.08 reported; AIC \u002F BIC for nested comparison; chi-square reported but treated as inflated at large N |\n| \"Why a factor model and not MTAG?\" | Factor structure tested first; if traits load on a common factor with CFI > 0.95, common-factor GWAS preferred -- explicitly models heterogeneity via Q_SNP |\n| \"Heywood case?\" | Negative residual variance constrained >= 0; OR the offending indicator dropped and the model re-specified; the choice is documented in methods |\n| \"Cross-ancestry?\" | Run per-ancestry; no validated cross-ancestry V matrix as of 2026; loadings compared qualitatively |\n| \"Why DWLS and not ML?\" | ML assumes V is known; DWLS uses the empirical V from `ldsc()` and is the appropriate estimator under sample overlap |\n\n## Tool Installation\n\n```r\n# GenomicSEM is GitHub-only\nremotes::install_github('GenomicSEM\u002FGenomicSEM')\n\n# Dependencies\ninstall.packages(c('lavaan', 'Matrix', 'gdata'))\n\n# Optional companions\nremotes::install_github('MRCIEU\u002FTwoSampleMR')  # for downstream MR using factor GWAS as exposure\n```\n\nFor Python tools:\n\n```bash\n# LDSC python3 fork (GenomicSEM input format). belowlab\u002Fldsc v3.0.1 broke the\n# --h2\u002F--rg\u002F--h2-cts CLI per its README; use abdenlab\u002Fldsc-python3 (v2.0.0)\n# for a working CLI. Docker jtb114\u002Fldsc:latest is the belowlab fallback.\ngit clone https:\u002F\u002Fgithub.com\u002Fabdenlab\u002Fldsc-python3.git\ncd ldsc-python3 && pip install .   # Poetry project (pyproject.toml); no requirements.txt\n\n# MTAG\ngit clone https:\u002F\u002Fgithub.com\u002FJonJala\u002Fmtag.git\ncd mtag && pip install -r requirements.txt\n```\n\nPre-downloaded reference files: `eur_w_ld_chr\u002F`, `baselineLD_v2.2.*`, `w_hm3.snplist`, and 1000G allele-frequency files are hosted at `alkesgroup.broadinstitute.org\u002FLDSCORE\u002F`.\n\n## References\n\n- Grotzinger AD et al 2019 Nat Hum Behav 3:513 (GenomicSEM, common-factor GWAS, Q_SNP)\n- Grotzinger AD et al 2022 Nat Genet 54:548 (Stratified GenomicSEM)\n- Turley P et al 2018 Nat Genet 50:229 (MTAG; MaxFDR)\n- Bulik-Sullivan B et al 2015 Nat Genet 47:291 (LDSC for genetic covariance)\n- Bulik-Sullivan B et al 2015 Nat Genet 47:1236 (bivariate LDSC, sample overlap)\n- Rosseel Y 2012 J Stat Softw 48:1-36 (lavaan package)\n- Hu LT & Bentler PM 1999 Struct Equ Model 6:1 (CFI \u002F RMSEA cutoffs)\n- Asparouhov T & Muthen B 2009 Struct Equ Model 16:397 (ESEM framework)\n- Finucane HK et al 2015 Nat Genet 47:1228 (S-LDSC, foundation for stratified GenomicSEM)\n- Gazal S et al 2017 Nat Genet 49:1421 (baseline-LD annotations)\n- Demange PA et al 2021 Nat Genet 53:35 (GenomicSEM GWAS-by-subtraction for noncognitive skills; Q_SNP in practice)\n- Karlsson Linner R, Mallard TT et al 2021 Nat Neurosci 24:1367 (multivariate externalizing GWAS via GenomicSEM)\n- de la Fuente J et al 2021 Nat Hum Behav 5:49 (GenomicSEM for cognitive g factor)\n- Skrivankova VW et al 2021 JAMA 326:1614 (STROBE-MR; relevant when downstream MR uses factor GWAS)\n\n## Related Skills\n\n- causal-genomics\u002Fmendelian-randomization - Use factor-GWAS effect sizes as MR exposure\n- causal-genomics\u002Fgenetic-correlation - Bivariate LDSC produces the off-diagonals of the S matrix; GenomicSEM is the multi-trait extension\n- causal-genomics\u002Fheritability-partitioning - LDSC and S-LDSC foundations for stratified GenomicSEM\n- causal-genomics\u002Fcolocalization-analysis - Cross-trait colocalization at common-factor loci\n- causal-genomics\u002Fpleiotropy-detection - Q_SNP is a per-SNP pleiotropy diagnostic; sibling concept\n- causal-genomics\u002Ffine-mapping - Resolve factor-significant loci to credible sets\n- causal-genomics\u002Fmediation-analysis - SEM mediation paths overlap with `usermodel` indirect effects\n- causal-genomics\u002Ftranscriptome-wide-association - TWAS on factor sumstats from `commonfactorGWAS`\n- population-genetics\u002Fassociation-testing - GWAS sumstats are the input format\n",{"name":5,"source":24,"license":15,"tool_type":25,"description":7,"imported_at":26,"source_path":27,"primary_tool":28,"source_repository":29},"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills","r","2026-09-20","causal-genomics\u002Fgenomic-sem\u002FSKILL.md","GenomicSEM","GPTomics\u002FbioSkills","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fbiology\u002Fbio-causal-genomics-genomic-sem","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous","2026-11-09 11:45:36",{"source":8,"skillName":5,"commands":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-causal-genomics-genomic-sem",{"tool":42,"command":43},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-causal-genomics-genomic-sem",{"tool":45,"command":46},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-causal-genomics-genomic-sem","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-causal-genomics-genomic-sem\u002FSKILL.md",true,[50,56,62],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"examples\u002Fgenomic_sem_commonfactor.R","OTHER","其他",4770,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-causal-genomics-genomic-sem\u002Fexamples\u002Fgenomic_sem_commonfactor.R",{"path":57,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":61},"examples\u002Fmtag_pipeline.sh","SCRIPT","脚本",2624,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-causal-genomics-genomic-sem\u002Fexamples\u002Fmtag_pipeline.sh",{"path":63,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":66,"sourceHtmlUrl":67},"usage-guide.md","REFERENCE","参考文档",8944,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-causal-genomics-genomic-sem\u002Fusage-guide.md",[69,77,84,91,98,105],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":76},"01M7FFFZPC2025JQQHPHDX154J","dei-assessment","Assess diversity, equity, and inclusion with metrics. TRIGGERS - Use when user needs help with dei-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-assessment\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":76},"01M7FFFWN8H4WA7A6Y398QKB6J","dei-action-plan","Create DEI action plans with goals and initiatives. TRIGGERS - Use when user needs help with dei-action-plan related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-action-plan\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":76},"01M7FFFSHTM0QZRVZ2NRJTJ0PY","culture-fit-assessment","Design culture add assessment processes. TRIGGERS - Use when user needs help with culture-fit-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fculture-fit-assessment\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":76},"01M7FFFMA12RKEQA38KHJSXXPS","cowork-to-code-bridge","Use an already-installed, independently verified cowork-to-code bridge to run narrowly approved actions on the user's own macOS, Linux, or WSL2 machine through a local file queue.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcowork-to-code-bridge\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":76},"01M7FFFH1F6M8YRGW5V487GH1K","counter-offer-response","Draft counter-offer responses for retention. TRIGGERS - Use when user needs help with counter-offer-response related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcounter-offer-response\u002FSKILL.md",[],[],{"skillNo":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":76},"01M7FFFDGEHV8Y7J9N40HZXW52","continuous-feedback-system","Design continuous feedback systems. TRIGGERS - Use when user needs help with continuous-feedback-system related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcontinuous-feedback-system\u002FSKILL.md",[],[]]