[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EDBJPC0YGZ8W95VRDV4067":3,"skill-same:01M7EDBJPC0YGZ8W95VRDV4067":66},{"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},"01M7EDBJPC0YGZ8W95VRDV4067","bio-gene-regulatory-networks-coexpression-networks",null,"Build weighted gene co-expression networks to identify modules of co-regulated genes, relate them to phenotypes, and find hub genes using WGCNA, hdWGCNA, MEGENA, CEMiTool, and Gaussian graphical models. Covers signed-network choice, soft-threshold selection, module preservation, and the marginal-vs-partial-correlation distinction. Use when finding co-expression modules, identifying hub genes, relating gene networks to clinical or experimental traits, or building single-cell co-expression networks. For directed TF-target inference see scenic-regulons and grn-inference; for condition rewiring see differential-networks.","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-gene-regulatory-networks-coexpression-networks\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-gene-regulatory-networks-coexpression-networks\ndescription: Build weighted gene co-expression networks to identify modules of co-regulated genes, relate them to phenotypes, and find hub genes using WGCNA, hdWGCNA, MEGENA, CEMiTool, and Gaussian graphical models. Covers signed-network choice, soft-threshold selection, module preservation, and the marginal-vs-partial-correlation distinction. Use when finding co-expression modules, identifying hub genes, relating gene networks to clinical or experimental traits, or building single-cell co-expression networks. For directed TF-target inference see scenic-regulons and grn-inference; for condition rewiring see differential-networks.\ntool_type: r\nprimary_tool: WGCNA\nsource: \"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills\"\nsource_repository: \"GPTomics\u002FbioSkills\"\nsource_path: \"gene-regulatory-networks\u002Fcoexpression-networks\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n\n## Version Compatibility\n\nReference examples tested with: WGCNA 1.72+, hdWGCNA 0.3+, CEMiTool 1.26+, GENIE3-adjacent GGM via GeneNet 1.2.16+.\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- R: `packageVersion('\u003Cpkg>')` then `?function_name` to verify parameters\n- Python: `pip show \u003Cpackage>` then `help(module.function)` to check signatures\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\nWGCNA argument defaults differ by entry point: `pickSoftThreshold()` and `blockwiseModules()` default to `networkType='unsigned'`. The signed-network choice (below) must be set identically at every step or the soft power and modules silently mismatch.\n\n# Co-expression Networks\n\n**\"Find co-expression modules and hub genes from my expression data\"** -> Build a weighted gene co-expression network, detect modules of co-regulated genes by clustering a topological-overlap dissimilarity, summarize each module by its eigengene, and relate modules to sample traits.\n- R: `WGCNA::blockwiseModules()` for network construction + module detection (bulk)\n- R: `hdWGCNA` metacell workflow for single-cell expression\n- R: `GeneNet`\u002Fgraphical lasso when direct (not indirect) edges are required\n\n## The Single Most Important Modern Insight -- Co-expression Is Marginal Correlation; Regulation Is Conditional Dependence\n\nA WGCNA edge between genes B and C exists whenever a common driver A correlates with both -- even if B and C never interact. If A regulates B and C, then B and C are conditionally independent given A, yet a co-expression network still draws a strong B-C edge. **A co-expression module is a descriptive object (\"these genes vary together\"), not a regulatory network, even when its hub is a transcription factor.** The dividing line is marginal vs partial correlation: WGCNA, MEGENA, and CEMiTool measure **marginal** correlation (direct + indirect edges mixed together), while Gaussian graphical models (GeneNet, graphical lasso) estimate **partial** correlation (conditional dependence, i.e. direct edges only). Decide which object the biological question needs before choosing a tool. Causal\u002Fregulatory language (\"module X is driven by hub TF Y\") from a marginal co-expression edge is the single most common over-claim in this domain.\n\nA secondary, load-bearing caveat: the **scale-free topology assumption underpinning soft-threshold selection is empirically weak**. Broido & Clauset 2019 (*Nat Commun* 10:1017) found scale-free structure in only ~4% of ~1000 real networks; Khanin & Wit 2006 (*J Comput Biol* 13:810) found none of 10 biological networks fit a pure power law. The scale-free R^2 >= 0.8 rule is a heuristic for picking the power where the connectivity curve flattens, **not** a hypothesis test confirming the biology is scale-free -- so it does not license \"the network is scale-free, therefore hubs are master regulators.\"\n\n## Co-expression Method Taxonomy\n\n| Method | Edge type | Strength | Use \u002F fails when |\n|--------|-----------|----------|------------------|\n| WGCNA (Langfelder & Horvath 2008) | marginal, soft-threshold + TOM | de facto standard; eigengenes; preservation | bulk, n>=15-20; fails on raw scRNA-seq |\n| hdWGCNA (Morabito 2023) | marginal, on metacells | flattens dropout\u002Fzero-inflation | single-cell; fails if metacells overlap (pseudo-replication) |\n| MEGENA (Song & Zhang 2015) | marginal, planar filtered network | principled sparsification; multiscale\u002Fnested modules | hierarchical biology; nested output breaks WGCNA-style one-module-per-gene code |\n| CEMiTool (Russo 2018) | marginal, auto-beta | fast first pass + GSEA\u002FORA + HTML report | exploratory; S4 object (accessors, not `$`); silently variance-filters genes |\n| GeneNet \u002F graphical lasso | **partial** (direct edges) | distinguishes direct from indirect | when \"who regulates whom directly\" matters; collapses at small n \u002F large p |\n\nRule of thumb: module discovery and trait association -> WGCNA (signed); single-cell -> hdWGCNA; \"is this edge direct or indirect?\" -> a Gaussian graphical model.\n\n## Decision Tree by Scenario\n\n| Scenario | Recommended | Why |\n|----------|-------------|-----|\n| Bulk RNA-seq, >=15-20 samples, want modules + trait links | WGCNA signed, bicor | stable marginal modules; eigengene-trait correlation |\n| Single-cell \u002F sparse counts | hdWGCNA on metacells | naive WGCNA fails on zero-inflation; metacells flatten dropout |\n| Need direct vs indirect edges | GeneNet \u002F graphical lasso | partial correlation removes confounded indirect edges |\n| Hierarchical \u002F multiscale structure expected | MEGENA | nested modules at multiple resolutions |\n| Want directed TF -> target regulons | -> scenic-regulons (single-cell) \u002F grn-inference (bulk) | co-expression is undirected; motif\u002Fregression priors add direction |\n| Compare networks across conditions | -> differential-networks | rewiring is a different question from module discovery |\n| \u003C15 samples | none reliable | correlation estimates too noisy; report this, do not force WGCNA |\n\n## WGCNA: Build a Signed Network\n\n**Goal:** Detect robust co-expression modules from a bulk expression matrix and choose network parameters defensibly.\n\n**Approach:** Use a **signed** network with **biweight midcorrelation (bicor)** so activators and repressors are not merged into one module and outliers are down-weighted; pick the soft power on the SAME network type used for construction; set `maxBlockSize` above the gene count to avoid the block artifact.\n\n```r\nlibrary(WGCNA)\noptions(stringsAsFactors = FALSE)\nallowWGCNAThreads()\n\n# WGCNA convention: genes as columns, samples as rows\nexpr \u003C- t(as.matrix(read.csv('normalized_counts.csv', row.names = 1)))\ngsg \u003C- goodSamplesGenes(expr, verbose = 0)\nexpr \u003C- expr[gsg$goodSamples, gsg$goodGenes]\n\n# Soft power on the SIGNED fit (must match construction below)\npowers \u003C- 1:20\nsft \u003C- pickSoftThreshold(expr, powerVector = powers, networkType = 'signed', verbose = 0)\nsoft_power \u003C- sft$powerEstimate            # signed networks usually land near 12\n\n# Signed network, bicor with maxPOutliers to avoid spurious outlier flags at modest n.\n# maxBlockSize >= n_genes keeps everything in one block (no cross-block blindness).\nnet \u003C- blockwiseModules(\n    expr, power = soft_power,\n    networkType = 'signed', TOMType = 'signed',\n    corType = 'bicor', maxPOutliers = 0.05,\n    minModuleSize = 30, mergeCutHeight = 0.25, deepSplit = 2,\n    maxBlockSize = ncol(expr) + 1,\n    numericLabels = TRUE, pamRespectsDendro = FALSE, verbose = 0\n)\nmodule_colors \u003C- labels2colors(net$colors)\ntable(module_colors)                       # large 'grey' fraction = poor fit, not a module\n```\n\n## WGCNA: Eigengenes, Hubs, and Trait Relationships\n\n**Goal:** Relate modules to sample traits and identify defensible hub genes.\n\n**Approach:** Summarize each module by its eigengene (first PC), correlate eigengenes with traits, and define hubs by **module membership kME** (signed, bounded, comparable across modules) rather than raw connectivity.\n\n```r\n# Recompute eigengenes from the COLOR labels so ME\u002FkME columns are MEturquoise\u002FkMEturquoise.\n# (net$MEs uses numeric names ME0\u002FME1... under numericLabels=TRUE and won't match colors.)\nMEs \u003C- orderMEs(moduleEigengenes(expr, module_colors)$eigengenes)\ntraits \u003C- read.csv('sample_traits.csv', row.names = 1)\n\nmodule_trait_cor  \u003C- cor(MEs, traits, use = 'p')\nmodule_trait_pval \u003C- corPvalueStudent(module_trait_cor, nrow(expr))\n\n# Hub = high module membership (kME), the WGCNA-preferred definition.\n# kME is signed and bounded [-1,1] with a p-value; prefer it over kWithin connectivity.\nkME \u003C- signedKME(expr, MEs)\nmoi \u003C- 'turquoise'\nmoi_genes \u003C- colnames(expr)[module_colors == moi]\nhubs \u003C- sort(kME[moi_genes, paste0('kME', moi)], decreasing = TRUE)\nhead(hubs, 20)\n```\n\n## WGCNA: Module Preservation (the step that makes a module real)\n\n**Goal:** Test whether discovered modules reproduce in an independent dataset -- the scientific claim, not module detection itself.\n\n**Approach:** Run `modulePreservation()` with the discovery network as reference and an independent cohort as test; read Zsummary and medianRank.\n\n```r\n# multiData\u002FmultiColor hold reference + test expression and the reference module labels\nmp \u003C- modulePreservation(\n    multiData, multiColor,\n    referenceNetworks = 1, nPermutations = 200,\n    randomSeed = 1, verbose = 0\n)\nstats \u003C- mp$preservation$Z$ref.reference$inColumnsAlsoPresentIn.test\nstats[, c('moduleSize', 'Zsummary.pres')]\n# Zsummary > 10 strong preservation; 2-10 weak\u002Fmoderate; \u003C 2 no evidence (Langfelder 2011).\n# medianRank (mp$preservation$observed) compares modules to each other, size-independent.\n```\n\n## hdWGCNA: Single-Cell Co-expression\n\n**Goal:** Build co-expression networks from scRNA-seq without dropout-driven spurious correlation.\n\n**Approach:** Aggregate transcriptionally similar cells into metacells (pseudobulk) to flatten zero-inflation; cap metacell sharing to avoid pseudo-replication; then run standard WGCNA on the metacells.\n\n```r\nlibrary(hdWGCNA); library(Seurat)\nseurat_obj \u003C- readRDS('clustered.rds')\nseurat_obj \u003C- SetupForWGCNA(seurat_obj, gene_select = 'fraction', fraction = 0.05,\n                            wgcna_name = 'hdwgcna')\n\n# Build metacells WITHIN cell types; max_shared caps how many cells two metacells share.\n# Heavy overlap inflates downstream correlations (pseudo-replication) -- keep it low.\nseurat_obj \u003C- MetacellsByGroups(seurat_obj, group.by = 'cell_type',\n                                k = 25, max_shared = 10, ident.group = 'cell_type')\nseurat_obj \u003C- NormalizeMetacells(seurat_obj)\n\nseurat_obj \u003C- SetDatExpr(seurat_obj, group.by = 'cell_type', group_name = 'all')\nseurat_obj \u003C- TestSoftPowers(seurat_obj, networkType = 'signed')\nseurat_obj \u003C- ConstructNetwork(seurat_obj, setDatExpr = FALSE, tom_name = 'hdwgcna')\nseurat_obj \u003C- ModuleEigengenes(seurat_obj)\nseurat_obj \u003C- ModuleConnectivity(seurat_obj)   # kME per module\n```\n\n## Direct vs Indirect Edges: Gaussian Graphical Model\n\n**Goal:** Recover edges that survive conditioning on all other genes (direct dependence), not marginal co-expression.\n\n**Approach:** Estimate a shrinkage partial-correlation matrix (n \u003C\u003C p safe) and test edges by local FDR.\n\n```r\nlibrary(GeneNet)\n# expr: samples x genes\npcor   \u003C- ggm.estimate.pcor(expr)              # shrinkage partial correlations\nedges  \u003C- network.test.edges(pcor, direct = FALSE, plot = FALSE)\nnet_gg \u003C- extract.network(edges, method.ggm = 'prob', cutoff.ggm = 0.9)\n# Far sparser than WGCNA -- that is the point: indirect edges have been removed.\n```\n\nCEMiTool (`cemitool(expr, annot)`) returns an **S4 object** -- use accessors (`module_genes()`, `get_hubs()`, `generate_report()`), never `$` -- and silently variance-filters genes with `filter=TRUE`. MEGENA returns nested modules; do not feed them to one-module-per-gene WGCNA code.\n\n## Per-Method Failure Modes\n\n### Unsigned-by-default network\n**Trigger:** leaving `networkType='unsigned'` (the default) then interpreting modules as co-regulated programs. **Mechanism:** unsigned uses |cor|, so a gene and its strong anti-correlate land in the same module. **Symptom:** modules mixing clearly opposing programs (e.g. proliferation and quiescence). **Fix:** use `networkType='signed'` (and `TOMType='signed'`) at pickSoftThreshold AND blockwiseModules.\n\n### Soft power chosen on the wrong network type\n**Trigger:** `pickSoftThreshold()` run unsigned, then `blockwiseModules(networkType='signed')`. **Mechanism:** the scale-free fit and chosen power differ by network type. **Symptom:** near-disconnected network or one giant module. **Fix:** set `networkType` identically in both calls (signed power is roughly double unsigned).\n\n### blockwiseModules block artifact\n**Trigger:** n_genes > `maxBlockSize` (historical default 5000) with no mention of blocking. **Mechanism:** TOM is computed within each block only; cross-block co-expression is invisible and assignments shift with block size\u002FRAM. **Symptom:** module membership changes when rerun on a different machine. **Fix:** set `maxBlockSize >= n_genes`, or report the block size.\n\n### Naive WGCNA on raw scRNA-seq\n**Trigger:** running WGCNA on sparse single-cell counts. **Mechanism:** zero-inflation creates a spike of zero correlations and dropout-driven spurious correlation. **Symptom:** a pathological correlation distribution and unstable modules. **Fix:** use hdWGCNA metacells (and cap `max_shared`).\n\n### Detection without preservation\n**Trigger:** reporting modules from one cohort with no replication test. **Mechanism:** any dendrogram can be cut into modules. **Symptom:** modules that do not reproduce in independent data. **Fix:** run `modulePreservation()`; report Zsummary\u002FmedianRank.\n\n## Quantitative Thresholds\n\n| Threshold | Source | Rationale |\n|-----------|--------|-----------|\n| Samples >= 15 (ideally >= 20) | Horvath\u002FLangfelder WGCNA FAQ | correlation estimates too noisy below 15; modules become random |\n| Scale-free R^2 >= 0.8 (0.8-0.9) | WGCNA convention | heuristic for power where connectivity flattens -- NOT proof of scale-free biology |\n| Signed soft power ~12 (vs ~6 unsigned) | WGCNA FAQ table | signed adjacency = ((1+cor)\u002F2)^power needs higher power for the same connectivity |\n| maxPOutliers = 0.05-0.10 | Langfelder & Horvath 2012 | prevents bicor flagging legitimate observations as outliers at modest n |\n| minModuleSize = 30 (default); mergeCutHeight = 0.25 (chosen; default is 0.15) | WGCNA | smaller modules are usually noise; 0.25 merges eigengenes correlating > 0.75 |\n| Zsummary > 10 \u002F 2-10 \u002F \u003C 2 | Langfelder 2011 | strong \u002F weak-moderate \u002F no preservation evidence |\n\n## Common Errors\n\n| Error \u002F symptom | Cause | Solution |\n|-----------------|-------|----------|\n| One giant module + large grey | power too low or wrong network type | re-pick power on the correct `networkType` |\n| `cemitool` results via `$` return NULL | CEMiTool returns an S4 object | use accessors `module_genes()`, `get_hubs()` |\n| hub list dominated by housekeeping genes | hubness tracking mean expression | define hubs by kME, control for expression level |\n| top module is the sequencing batch | batch correlates with many genes | correct batch before network construction (-> differential-expression\u002Fbatch-correction) |\n| modules irreproducible across reruns | block artifact | set `maxBlockSize >= n_genes` |\n\n## References\n\n- Langfelder P, Horvath S. 2008. WGCNA: an R package for weighted correlation network analysis. *BMC Bioinformatics* 9:559.\n- Langfelder P, Horvath S. 2012. Fast R functions for robust correlations and hierarchical clustering. *J Stat Softw* 46(11):1-17. -- bicor \u002F maxPOutliers.\n- Langfelder P, Luo R, Oldham MC, Horvath S. 2011. Is my network module preserved and reproducible? *PLoS Comput Biol* 7(1):e1001057.\n- Broido AD, Clauset A. 2019. Scale-free networks are rare. *Nat Commun* 10:1017. -- soft-threshold caveat.\n- Khanin R, Wit E. 2006. How scale-free are biological networks? *J Comput Biol* 13(3):810-818.\n- Song WM, Zhang B. 2015. Multiscale embedded gene co-expression network analysis (MEGENA). *PLoS Comput Biol* 11(11):e1004574.\n- Russo PST, et al. 2018. CEMiTool. *BMC Bioinformatics* 19:56.\n- Morabito S, Reese F, Rahimzadeh N, Miyoshi E, Swarup V. 2023. hdWGCNA. *Cell Rep Methods* 3(6):100498.\n\n## Related Skills\n\n- differential-networks - compare co-expression structure between conditions (rewiring)\n- scenic-regulons - directed TF regulons from single-cell data (motif-pruned)\n- grn-inference - bulk directed GRN inference and TF protein-activity (VIPER)\n- differential-expression\u002Fbatch-correction - remove batch effects before network construction\n- single-cell\u002Fpreprocessing - QC and normalization for single-cell inputs to hdWGCNA\n- pathway-analysis\u002Fgo-enrichment - functional enrichment of co-expression modules\n","## Version Compatibility\n\nReference examples tested with: WGCNA 1.72+, hdWGCNA 0.3+, CEMiTool 1.26+, GENIE3-adjacent GGM via GeneNet 1.2.16+.\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- R: `packageVersion('\u003Cpkg>')` then `?function_name` to verify parameters\n- Python: `pip show \u003Cpackage>` then `help(module.function)` to check signatures\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\nWGCNA argument defaults differ by entry point: `pickSoftThreshold()` and `blockwiseModules()` default to `networkType='unsigned'`. The signed-network choice (below) must be set identically at every step or the soft power and modules silently mismatch.\n\n# Co-expression Networks\n\n**\"Find co-expression modules and hub genes from my expression data\"** -> Build a weighted gene co-expression network, detect modules of co-regulated genes by clustering a topological-overlap dissimilarity, summarize each module by its eigengene, and relate modules to sample traits.\n- R: `WGCNA::blockwiseModules()` for network construction + module detection (bulk)\n- R: `hdWGCNA` metacell workflow for single-cell expression\n- R: `GeneNet`\u002Fgraphical lasso when direct (not indirect) edges are required\n\n## The Single Most Important Modern Insight -- Co-expression Is Marginal Correlation; Regulation Is Conditional Dependence\n\nA WGCNA edge between genes B and C exists whenever a common driver A correlates with both -- even if B and C never interact. If A regulates B and C, then B and C are conditionally independent given A, yet a co-expression network still draws a strong B-C edge. **A co-expression module is a descriptive object (\"these genes vary together\"), not a regulatory network, even when its hub is a transcription factor.** The dividing line is marginal vs partial correlation: WGCNA, MEGENA, and CEMiTool measure **marginal** correlation (direct + indirect edges mixed together), while Gaussian graphical models (GeneNet, graphical lasso) estimate **partial** correlation (conditional dependence, i.e. direct edges only). Decide which object the biological question needs before choosing a tool. Causal\u002Fregulatory language (\"module X is driven by hub TF Y\") from a marginal co-expression edge is the single most common over-claim in this domain.\n\nA secondary, load-bearing caveat: the **scale-free topology assumption underpinning soft-threshold selection is empirically weak**. Broido & Clauset 2019 (*Nat Commun* 10:1017) found scale-free structure in only ~4% of ~1000 real networks; Khanin & Wit 2006 (*J Comput Biol* 13:810) found none of 10 biological networks fit a pure power law. The scale-free R^2 >= 0.8 rule is a heuristic for picking the power where the connectivity curve flattens, **not** a hypothesis test confirming the biology is scale-free -- so it does not license \"the network is scale-free, therefore hubs are master regulators.\"\n\n## Co-expression Method Taxonomy\n\n| Method | Edge type | Strength | Use \u002F fails when |\n|--------|-----------|----------|------------------|\n| WGCNA (Langfelder & Horvath 2008) | marginal, soft-threshold + TOM | de facto standard; eigengenes; preservation | bulk, n>=15-20; fails on raw scRNA-seq |\n| hdWGCNA (Morabito 2023) | marginal, on metacells | flattens dropout\u002Fzero-inflation | single-cell; fails if metacells overlap (pseudo-replication) |\n| MEGENA (Song & Zhang 2015) | marginal, planar filtered network | principled sparsification; multiscale\u002Fnested modules | hierarchical biology; nested output breaks WGCNA-style one-module-per-gene code |\n| CEMiTool (Russo 2018) | marginal, auto-beta | fast first pass + GSEA\u002FORA + HTML report | exploratory; S4 object (accessors, not `$`); silently variance-filters genes |\n| GeneNet \u002F graphical lasso | **partial** (direct edges) | distinguishes direct from indirect | when \"who regulates whom directly\" matters; collapses at small n \u002F large p |\n\nRule of thumb: module discovery and trait association -> WGCNA (signed); single-cell -> hdWGCNA; \"is this edge direct or indirect?\" -> a Gaussian graphical model.\n\n## Decision Tree by Scenario\n\n| Scenario | Recommended | Why |\n|----------|-------------|-----|\n| Bulk RNA-seq, >=15-20 samples, want modules + trait links | WGCNA signed, bicor | stable marginal modules; eigengene-trait correlation |\n| Single-cell \u002F sparse counts | hdWGCNA on metacells | naive WGCNA fails on zero-inflation; metacells flatten dropout |\n| Need direct vs indirect edges | GeneNet \u002F graphical lasso | partial correlation removes confounded indirect edges |\n| Hierarchical \u002F multiscale structure expected | MEGENA | nested modules at multiple resolutions |\n| Want directed TF -> target regulons | -> scenic-regulons (single-cell) \u002F grn-inference (bulk) | co-expression is undirected; motif\u002Fregression priors add direction |\n| Compare networks across conditions | -> differential-networks | rewiring is a different question from module discovery |\n| \u003C15 samples | none reliable | correlation estimates too noisy; report this, do not force WGCNA |\n\n## WGCNA: Build a Signed Network\n\n**Goal:** Detect robust co-expression modules from a bulk expression matrix and choose network parameters defensibly.\n\n**Approach:** Use a **signed** network with **biweight midcorrelation (bicor)** so activators and repressors are not merged into one module and outliers are down-weighted; pick the soft power on the SAME network type used for construction; set `maxBlockSize` above the gene count to avoid the block artifact.\n\n```r\nlibrary(WGCNA)\noptions(stringsAsFactors = FALSE)\nallowWGCNAThreads()\n\n# WGCNA convention: genes as columns, samples as rows\nexpr \u003C- t(as.matrix(read.csv('normalized_counts.csv', row.names = 1)))\ngsg \u003C- goodSamplesGenes(expr, verbose = 0)\nexpr \u003C- expr[gsg$goodSamples, gsg$goodGenes]\n\n# Soft power on the SIGNED fit (must match construction below)\npowers \u003C- 1:20\nsft \u003C- pickSoftThreshold(expr, powerVector = powers, networkType = 'signed', verbose = 0)\nsoft_power \u003C- sft$powerEstimate            # signed networks usually land near 12\n\n# Signed network, bicor with maxPOutliers to avoid spurious outlier flags at modest n.\n# maxBlockSize >= n_genes keeps everything in one block (no cross-block blindness).\nnet \u003C- blockwiseModules(\n    expr, power = soft_power,\n    networkType = 'signed', TOMType = 'signed',\n    corType = 'bicor', maxPOutliers = 0.05,\n    minModuleSize = 30, mergeCutHeight = 0.25, deepSplit = 2,\n    maxBlockSize = ncol(expr) + 1,\n    numericLabels = TRUE, pamRespectsDendro = FALSE, verbose = 0\n)\nmodule_colors \u003C- labels2colors(net$colors)\ntable(module_colors)                       # large 'grey' fraction = poor fit, not a module\n```\n\n## WGCNA: Eigengenes, Hubs, and Trait Relationships\n\n**Goal:** Relate modules to sample traits and identify defensible hub genes.\n\n**Approach:** Summarize each module by its eigengene (first PC), correlate eigengenes with traits, and define hubs by **module membership kME** (signed, bounded, comparable across modules) rather than raw connectivity.\n\n```r\n# Recompute eigengenes from the COLOR labels so ME\u002FkME columns are MEturquoise\u002FkMEturquoise.\n# (net$MEs uses numeric names ME0\u002FME1... under numericLabels=TRUE and won't match colors.)\nMEs \u003C- orderMEs(moduleEigengenes(expr, module_colors)$eigengenes)\ntraits \u003C- read.csv('sample_traits.csv', row.names = 1)\n\nmodule_trait_cor  \u003C- cor(MEs, traits, use = 'p')\nmodule_trait_pval \u003C- corPvalueStudent(module_trait_cor, nrow(expr))\n\n# Hub = high module membership (kME), the WGCNA-preferred definition.\n# kME is signed and bounded [-1,1] with a p-value; prefer it over kWithin connectivity.\nkME \u003C- signedKME(expr, MEs)\nmoi \u003C- 'turquoise'\nmoi_genes \u003C- colnames(expr)[module_colors == moi]\nhubs \u003C- sort(kME[moi_genes, paste0('kME', moi)], decreasing = TRUE)\nhead(hubs, 20)\n```\n\n## WGCNA: Module Preservation (the step that makes a module real)\n\n**Goal:** Test whether discovered modules reproduce in an independent dataset -- the scientific claim, not module detection itself.\n\n**Approach:** Run `modulePreservation()` with the discovery network as reference and an independent cohort as test; read Zsummary and medianRank.\n\n```r\n# multiData\u002FmultiColor hold reference + test expression and the reference module labels\nmp \u003C- modulePreservation(\n    multiData, multiColor,\n    referenceNetworks = 1, nPermutations = 200,\n    randomSeed = 1, verbose = 0\n)\nstats \u003C- mp$preservation$Z$ref.reference$inColumnsAlsoPresentIn.test\nstats[, c('moduleSize', 'Zsummary.pres')]\n# Zsummary > 10 strong preservation; 2-10 weak\u002Fmoderate; \u003C 2 no evidence (Langfelder 2011).\n# medianRank (mp$preservation$observed) compares modules to each other, size-independent.\n```\n\n## hdWGCNA: Single-Cell Co-expression\n\n**Goal:** Build co-expression networks from scRNA-seq without dropout-driven spurious correlation.\n\n**Approach:** Aggregate transcriptionally similar cells into metacells (pseudobulk) to flatten zero-inflation; cap metacell sharing to avoid pseudo-replication; then run standard WGCNA on the metacells.\n\n```r\nlibrary(hdWGCNA); library(Seurat)\nseurat_obj \u003C- readRDS('clustered.rds')\nseurat_obj \u003C- SetupForWGCNA(seurat_obj, gene_select = 'fraction', fraction = 0.05,\n                            wgcna_name = 'hdwgcna')\n\n# Build metacells WITHIN cell types; max_shared caps how many cells two metacells share.\n# Heavy overlap inflates downstream correlations (pseudo-replication) -- keep it low.\nseurat_obj \u003C- MetacellsByGroups(seurat_obj, group.by = 'cell_type',\n                                k = 25, max_shared = 10, ident.group = 'cell_type')\nseurat_obj \u003C- NormalizeMetacells(seurat_obj)\n\nseurat_obj \u003C- SetDatExpr(seurat_obj, group.by = 'cell_type', group_name = 'all')\nseurat_obj \u003C- TestSoftPowers(seurat_obj, networkType = 'signed')\nseurat_obj \u003C- ConstructNetwork(seurat_obj, setDatExpr = FALSE, tom_name = 'hdwgcna')\nseurat_obj \u003C- ModuleEigengenes(seurat_obj)\nseurat_obj \u003C- ModuleConnectivity(seurat_obj)   # kME per module\n```\n\n## Direct vs Indirect Edges: Gaussian Graphical Model\n\n**Goal:** Recover edges that survive conditioning on all other genes (direct dependence), not marginal co-expression.\n\n**Approach:** Estimate a shrinkage partial-correlation matrix (n \u003C\u003C p safe) and test edges by local FDR.\n\n```r\nlibrary(GeneNet)\n# expr: samples x genes\npcor   \u003C- ggm.estimate.pcor(expr)              # shrinkage partial correlations\nedges  \u003C- network.test.edges(pcor, direct = FALSE, plot = FALSE)\nnet_gg \u003C- extract.network(edges, method.ggm = 'prob', cutoff.ggm = 0.9)\n# Far sparser than WGCNA -- that is the point: indirect edges have been removed.\n```\n\nCEMiTool (`cemitool(expr, annot)`) returns an **S4 object** -- use accessors (`module_genes()`, `get_hubs()`, `generate_report()`), never `$` -- and silently variance-filters genes with `filter=TRUE`. MEGENA returns nested modules; do not feed them to one-module-per-gene WGCNA code.\n\n## Per-Method Failure Modes\n\n### Unsigned-by-default network\n**Trigger:** leaving `networkType='unsigned'` (the default) then interpreting modules as co-regulated programs. **Mechanism:** unsigned uses |cor|, so a gene and its strong anti-correlate land in the same module. **Symptom:** modules mixing clearly opposing programs (e.g. proliferation and quiescence). **Fix:** use `networkType='signed'` (and `TOMType='signed'`) at pickSoftThreshold AND blockwiseModules.\n\n### Soft power chosen on the wrong network type\n**Trigger:** `pickSoftThreshold()` run unsigned, then `blockwiseModules(networkType='signed')`. **Mechanism:** the scale-free fit and chosen power differ by network type. **Symptom:** near-disconnected network or one giant module. **Fix:** set `networkType` identically in both calls (signed power is roughly double unsigned).\n\n### blockwiseModules block artifact\n**Trigger:** n_genes > `maxBlockSize` (historical default 5000) with no mention of blocking. **Mechanism:** TOM is computed within each block only; cross-block co-expression is invisible and assignments shift with block size\u002FRAM. **Symptom:** module membership changes when rerun on a different machine. **Fix:** set `maxBlockSize >= n_genes`, or report the block size.\n\n### Naive WGCNA on raw scRNA-seq\n**Trigger:** running WGCNA on sparse single-cell counts. **Mechanism:** zero-inflation creates a spike of zero correlations and dropout-driven spurious correlation. **Symptom:** a pathological correlation distribution and unstable modules. **Fix:** use hdWGCNA metacells (and cap `max_shared`).\n\n### Detection without preservation\n**Trigger:** reporting modules from one cohort with no replication test. **Mechanism:** any dendrogram can be cut into modules. **Symptom:** modules that do not reproduce in independent data. **Fix:** run `modulePreservation()`; report Zsummary\u002FmedianRank.\n\n## Quantitative Thresholds\n\n| Threshold | Source | Rationale |\n|-----------|--------|-----------|\n| Samples >= 15 (ideally >= 20) | Horvath\u002FLangfelder WGCNA FAQ | correlation estimates too noisy below 15; modules become random |\n| Scale-free R^2 >= 0.8 (0.8-0.9) | WGCNA convention | heuristic for power where connectivity flattens -- NOT proof of scale-free biology |\n| Signed soft power ~12 (vs ~6 unsigned) | WGCNA FAQ table | signed adjacency = ((1+cor)\u002F2)^power needs higher power for the same connectivity |\n| maxPOutliers = 0.05-0.10 | Langfelder & Horvath 2012 | prevents bicor flagging legitimate observations as outliers at modest n |\n| minModuleSize = 30 (default); mergeCutHeight = 0.25 (chosen; default is 0.15) | WGCNA | smaller modules are usually noise; 0.25 merges eigengenes correlating > 0.75 |\n| Zsummary > 10 \u002F 2-10 \u002F \u003C 2 | Langfelder 2011 | strong \u002F weak-moderate \u002F no preservation evidence |\n\n## Common Errors\n\n| Error \u002F symptom | Cause | Solution |\n|-----------------|-------|----------|\n| One giant module + large grey | power too low or wrong network type | re-pick power on the correct `networkType` |\n| `cemitool` results via `$` return NULL | CEMiTool returns an S4 object | use accessors `module_genes()`, `get_hubs()` |\n| hub list dominated by housekeeping genes | hubness tracking mean expression | define hubs by kME, control for expression level |\n| top module is the sequencing batch | batch correlates with many genes | correct batch before network construction (-> differential-expression\u002Fbatch-correction) |\n| modules irreproducible across reruns | block artifact | set `maxBlockSize >= n_genes` |\n\n## References\n\n- Langfelder P, Horvath S. 2008. WGCNA: an R package for weighted correlation network analysis. *BMC Bioinformatics* 9:559.\n- Langfelder P, Horvath S. 2012. Fast R functions for robust correlations and hierarchical clustering. *J Stat Softw* 46(11):1-17. -- bicor \u002F maxPOutliers.\n- Langfelder P, Luo R, Oldham MC, Horvath S. 2011. Is my network module preserved and reproducible? *PLoS Comput Biol* 7(1):e1001057.\n- Broido AD, Clauset A. 2019. Scale-free networks are rare. *Nat Commun* 10:1017. -- soft-threshold caveat.\n- Khanin R, Wit E. 2006. How scale-free are biological networks? *J Comput Biol* 13(3):810-818.\n- Song WM, Zhang B. 2015. Multiscale embedded gene co-expression network analysis (MEGENA). *PLoS Comput Biol* 11(11):e1004574.\n- Russo PST, et al. 2018. CEMiTool. *BMC Bioinformatics* 19:56.\n- Morabito S, Reese F, Rahimzadeh N, Miyoshi E, Swarup V. 2023. hdWGCNA. *Cell Rep Methods* 3(6):100498.\n\n## Related Skills\n\n- differential-networks - compare co-expression structure between conditions (rewiring)\n- scenic-regulons - directed TF regulons from single-cell data (motif-pruned)\n- grn-inference - bulk directed GRN inference and TF protein-activity (VIPER)\n- differential-expression\u002Fbatch-correction - remove batch effects before network construction\n- single-cell\u002Fpreprocessing - QC and normalization for single-cell inputs to hdWGCNA\n- pathway-analysis\u002Fgo-enrichment - functional enrichment of co-expression modules\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","gene-regulatory-networks\u002Fcoexpression-networks\u002FSKILL.md","WGCNA","GPTomics\u002FbioSkills","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fbiology\u002Fbio-gene-regulatory-networks-coexpression-networks","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-gene-regulatory-networks-coexpression-networks",{"tool":42,"command":43},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-gene-regulatory-networks-coexpression-networks",{"tool":45,"command":46},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-gene-regulatory-networks-coexpression-networks","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-gene-regulatory-networks-coexpression-networks\u002FSKILL.md",true,[50,56,60],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"examples\u002Fcemitool_quick.R","OTHER","其他",888,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-gene-regulatory-networks-coexpression-networks\u002Fexamples\u002Fcemitool_quick.R",{"path":57,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":58,"sourceHtmlUrl":59},"examples\u002Fwgcna_analysis.R",4272,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-gene-regulatory-networks-coexpression-networks\u002Fexamples\u002Fwgcna_analysis.R",{"path":61,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":64,"sourceHtmlUrl":65},"usage-guide.md","REFERENCE","参考文档",4524,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-gene-regulatory-networks-coexpression-networks\u002Fusage-guide.md",[67,75,82,89,96,103],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":74},"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":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":74},"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":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":74},"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":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":74},"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":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":74},"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":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":74},"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",[],[]]