[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EGXHHC74P02FDAHKZVKHPC":3,"skill-same:01M7EGXHHC74P02FDAHKZVKHPC":83},{"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":46,"commitSha":47,"skillDirectory":48,"forksCount":14,"repositoryHtmlUrl":49,"repositoryHomepageUrl":49,"ownerHtmlUrl":50,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":51,"install":52,"resources":64},"01M7EGXHHC74P02FDAHKZVKHPC","bio-workflows-timecourse-pipeline",null,"End-to-end bulk time-course analysis from an expression matrix to temporal gene modules and per-cluster pathway enrichment. Orchestrates temporal DE (limma splines or DESeq2 LRT), Mfuzz\u002Ftslearn soft clustering of expression-profile shapes, GAM trajectory fitting, per-cluster GO enrichment against a temporal-gene background, and an OPTIONAL circadian rhythm-detection branch (MetaCycle\u002FCosinorPy) that runs only when the design covers >=2 full cycles with >=6-8 evenly spaced samples per cycle. Use when analyzing a bulk time-series expression experiment from any omics platform and deciding limma-splines vs DESeq2-LRT for temporal DE, soft vs hard clustering, whether the sampling design even licenses rhythm detection, and which background to use for enrichment. Not for single-cell pseudotime (see temporal-genomics\u002Ftrajectory-modeling for the bulk-vs-pseudotime boundary) or unknown-period discovery (see temporal-genomics\u002Fperiodicity-detection).","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-workflows-timecourse-pipeline\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-workflows-timecourse-pipeline\ndescription: End-to-end bulk time-course analysis from an expression matrix to temporal gene modules and per-cluster pathway enrichment. Orchestrates temporal DE (limma splines or DESeq2 LRT), Mfuzz\u002Ftslearn soft clustering of expression-profile shapes, GAM trajectory fitting, per-cluster GO enrichment against a temporal-gene background, and an OPTIONAL circadian rhythm-detection branch (MetaCycle\u002FCosinorPy) that runs only when the design covers >=2 full cycles with >=6-8 evenly spaced samples per cycle. Use when analyzing a bulk time-series expression experiment from any omics platform and deciding limma-splines vs DESeq2-LRT for temporal DE, soft vs hard clustering, whether the sampling design even licenses rhythm detection, and which background to use for enrichment. Not for single-cell pseudotime (see temporal-genomics\u002Ftrajectory-modeling for the bulk-vs-pseudotime boundary) or unknown-period discovery (see temporal-genomics\u002Fperiodicity-detection).\ntool_type: mixed\nprimary_tool: Mfuzz\ngoal_approach_exempt: true\nworkflow: true\ndepends_on:\n  - differential-expression\u002Ftimeseries-de\n  - temporal-genomics\u002Ftemporal-clustering\n  - temporal-genomics\u002Fcircadian-rhythms\n  - temporal-genomics\u002Ftrajectory-modeling\n  - pathway-analysis\u002Fgo-enrichment\nqc_checkpoints:\n  - after_de: \"Significant temporal genes >100 at FDR \u003C0.05; model-fit residuals reasonable\"\n  - after_clustering: \"Membership >0.5 for soft clustering; no empty clusters; k validated by silhouette\u002Fgap or bootstrap stability (typical 4-20)\"\n  - before_rhythm_detection: \"GATE: design covers >=2 full cycles AND >=6-8 samples\u002Fcycle at ~even spacing AND collection order was randomized; else SKIP rhythm detection\"\n  - after_enrichment: \"At least 3 clusters with significant GO terms at FDR \u003C0.05; background = temporal genes, not the genome\"\nsource: \"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills\"\nsource_repository: \"GPTomics\u002FbioSkills\"\nsource_path: \"workflows\u002Ftimecourse-pipeline\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n\n## Version Compatibility\n\nReference examples tested with: DESeq2 1.42+, limma 3.58+, splines (R base), Mfuzz 2.62+, MetaCycle 1.2+, mgcv 1.9+, clusterProfiler 4.10+, CosinorPy 3.1+, tslearn 0.6+, pygam 0.9+, gseapy 1.2+, statsmodels 0.14+, patsy 1.0+, scikit-learn 1.4+\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show \u003Cpackage>` then `help(module.function)` to check signatures\n- R: `packageVersion('\u003Cpkg>')` then `?function_name` to verify parameters\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\nNote: the whole pipeline is dominated by the SAMPLING DESIGN, not the algorithm. Temporal DE, clustering, and trajectory fitting need genes pre-selected for temporal change and enough timepoints to resolve a shape; rhythm detection additionally requires >=2 full cycles and >=6-8 evenly spaced samples per cycle. A small p-value on 6 timepoints over a single cycle is not evidence of a rhythm.\n\n# Time-Course Analysis Pipeline\n\n**\"Analyze my bulk time-course expression data end-to-end\"** -> Orchestrate temporal differential expression, soft clustering of expression-profile shapes, GAM trajectory fitting, per-cluster pathway enrichment, and (only under a circadian sampling design) rhythm detection.\n- Python: statsmodels\u002Fpatsy spline F-test -> tslearn TimeSeriesKMeans -> pygam LinearGAM -> gseapy; CosinorPy for the optional rhythm branch\n- R: limma splines or DESeq2 LRT -> Mfuzz -> mgcv -> clusterProfiler; MetaCycle for the optional rhythm branch\n\n## Pipeline principles (read before running)\n\n- Clustering, GAM fitting, and enrichment are DESCRIPTIVE steps DOWNSTREAM of the temporal-DE gene selection; they add no inference of their own. Cluster only the temporally variable genes, never the full matrix, or every method returns confident-looking clusters of noise.\n- Do NOT test the clusters for the temporal signal used to select the genes (circular \u002F double-dipping). Enrichment is valid only against an INDEPENDENT annotation (GO\u002FKEGG), with the temporal genes as background.\n- Rhythm detection is an OPTIONAL branch, not a routine default. It is licensed only by a circadian sampling design (>=2 full cycles, >=6-8 samples\u002Fcycle, roughly even spacing, randomized collection order). Under any other design it is SKIPPED, not run with a warning.\n- Cluster number k and Mfuzz fuzzifier m are analyst CHOICES, not results; sweep and report the criterion.\n\n## Pipeline Overview\n\n```\nExpression matrix + time metadata\n    |\n    v\n[1. Temporal DE] ---------> limma splines \u002F DESeq2 LRT \u002F statsmodels spline F-test\n    |                            (selects temporally variable genes; FDR \u003C0.05)\n    v\n[2. Filter] --------------> Significant temporal genes only (clustering input)\n    |\n    v\n[3. Soft Clustering] -----> Mfuzz (R) \u002F tslearn TimeSeriesKMeans (Python) on z-scored profiles\n    |                            +---> QC: membership >0.5, no empty clusters, sweep k\n    |\n    v\n[4b. GAM Trajectory] -----> mgcv \u002F pygam GAM on standardized cluster-mean profiles\n    |\n    v\n[5. Pathway Enrichment] --> clusterProfiler \u002F gseapy per cluster\n    |                            background = temporal genes (NOT the genome)\n    v\nTemporal gene modules + enriched pathways + trajectory fits\n\n    OPTIONAL branch, gated (NOT on the default path):\n    IF design covers >=2 full cycles AND >=6-8 samples\u002Fcycle (even spacing)\n       AND collection order was randomized:\n        [4a. Rhythm Detection] --> MetaCycle meta2d \u002F CosinorPy fit_group\n                                   period\u002Fphase\u002Famplitude + BH q across genes\n    ELSE: SKIP (design does not license a rhythm test)\n```\n\n## Step 1: Temporal Differential Expression\n\n### R (limma splines)\n\n```r\nlibrary(limma)\nlibrary(splines)\n\nexpr \u003C- as.matrix(read.csv('counts_normalized.csv', row.names = 1))\nmeta \u003C- read.csv('metadata.csv')\n\n# Natural cubic spline on time; df=3 is enough for most courses, raise to 4-5 for >10 timepoints\ndesign \u003C- model.matrix(~ ns(meta$time, df = 3))\nfit \u003C- lmFit(expr, design)\nfit \u003C- eBayes(fit)\n\n# Joint F-test on all spline coefficients = \"expression changes over time\"\ntemporal_results \u003C- topTable(fit, coef = 2:ncol(design), number = Inf, sort.by = 'F')\n# topTable already returns adj.P.Val (BH-corrected); use it directly (not $FDR, which does not exist)\n```\n\n### R (DESeq2 LRT)\n\n```r\nlibrary(DESeq2)\n\ncounts \u003C- as.matrix(read.csv('raw_counts.csv', row.names = 1))\nmeta \u003C- read.csv('metadata.csv')\nmeta$time \u003C- factor(meta$time)\n\n# LRT: full model (time as factor) vs reduced (intercept) = any between-timepoint change\ndds \u003C- DESeqDataSetFromMatrix(counts, colData = meta, design = ~ time)\ndds \u003C- DESeq(dds, test = 'LRT', reduced = ~ 1)\nres \u003C- results(dds)   # BH-adjusted padj\n```\n\nChoose limma-splines when the time axis is continuous and a smooth trend is expected (normalized\u002Fvoom or vst input); choose DESeq2-LRT for raw counts and few, discrete timepoints treated as a factor.\n\n### Python (statsmodels spline F-test)\n\n```python\nimport pandas as pd\nimport numpy as np\nfrom statsmodels.stats.multitest import multipletests\nfrom patsy import dmatrix\nfrom scipy import stats\n\nexpr = pd.read_csv('counts_normalized.csv', index_col=0)\nmeta = pd.read_csv('metadata.csv')\n\nspline_basis = dmatrix('bs(time, df=3)', data=meta, return_type='dataframe')\n# patsy already includes an Intercept column; do NOT prepend another np.ones (that duplicates the\n# intercept, inflates model df, and miscalibrates the F-test -> wrong temporal-DE FDR). Use it directly.\ndesign_full = spline_basis.values                          # [Intercept, bs1, bs2, bs3] = 4 cols\ndesign_reduced = np.ones((len(meta), 1))\ndf_diff = design_full.shape[1] - design_reduced.shape[1]   # 4 - 1 = 3\ndf_resid = len(meta) - design_full.shape[1]                # n - 4\n\npvals = []\nfor gene in expr.index:\n    y = expr.loc[gene].values\n    ss_full = np.sum((y - design_full @ np.linalg.lstsq(design_full, y, rcond=None)[0]) ** 2)\n    ss_red = np.sum((y - design_reduced @ np.linalg.lstsq(design_reduced, y, rcond=None)[0]) ** 2)\n    f_stat = ((ss_red - ss_full) \u002F df_diff) \u002F (ss_full \u002F df_resid)\n    pvals.append(1 - stats.f.cdf(f_stat, df_diff, df_resid))\n\n# multipletests default is Holm-Sidak; force BH explicitly\n_, fdr, _, _ = multipletests(pvals, method='fdr_bh')\ntemporal_genes = expr.index[fdr \u003C 0.05].tolist()\n```\n\n### QC Checkpoint: Temporal DE\n\n```r\nsig_genes \u003C- temporal_results[temporal_results$adj.P.Val \u003C 0.05, ]\nn_sig \u003C- nrow(sig_genes)\nmessage(sprintf('Significant temporal genes: %d', n_sig))\n# \u003C100: underpowered clustering; >10000: check batch\u002Fnormalization before proceeding\nif (n_sig \u003C 100) message('WARNING: Few temporal genes. Check timepoint spacing or relax FDR.')\nif (n_sig > 10000) message('WARNING: Many temporal genes. Inspect batch effects \u002F normalization.')\n```\n\n## Step 2: Filter Significant Genes\n\n```r\n# FDR \u003C0.05 standard; 0.1 acceptable for exploratory clustering only\nsig_genes \u003C- rownames(temporal_results[temporal_results$adj.P.Val \u003C 0.05, ])\nexpr_sig \u003C- expr[sig_genes, ]\nmessage(sprintf('Genes passing FDR \u003C0.05: %d', length(sig_genes)))\n```\n\n## Step 3: Soft Clustering (of expression-profile shapes)\n\nClustering groups genes by SHAPE, not magnitude, so profiles are z-scored per gene first; otherwise abundance dominates and high-expression genes cluster together regardless of dynamics. Cluster only `expr_sig` (the temporal genes), never the full matrix.\n\n### R (Mfuzz)\n\n```r\nlibrary(Mfuzz)\n\neset \u003C- ExpressionSet(assayData = as.matrix(expr_sig))\neset \u003C- standardise(eset)   # per-gene mean 0, sd 1: makes distance shape-based, not magnitude-based\n\n# mestimate() implements Schwaemmle & Jensen (2010): the smallest m that stops fuzzy c-means\n# from clustering RANDOMIZED data. It is dominated by the number of timepoints; inspect the\n# returned value and the membership distribution rather than trusting it blindly (or hardcoding m=2).\nm \u003C- mestimate(eset)\nmessage(sprintf('Estimated fuzzifier m = %.2f', m))\n\n# k is a resolution CHOICE, not a result: start ~sqrt(n_genes\u002F2), then sweep and validate (below)\nn_clusters \u003C- 8\ncl \u003C- mfuzz(eset, c = n_clusters, m = m)\n\n# Membership >0.5 = core (confident) genes; lower to 0.3 only for exploratory overlap\ncore_genes \u003C- acore(eset, cl, min.acore = 0.5)\n```\n\n### Python (tslearn)\n\n```python\nfrom tslearn.clustering import TimeSeriesKMeans\n\n# Row-wise z-score: normalize each gene across its own timepoints (shape, not level)\nexpr_scaled = (expr_sig.values - expr_sig.values.mean(axis=1, keepdims=True)) \u002F expr_sig.values.std(axis=1, keepdims=True)\n\n# soft-DTW tolerates phase-shifted profiles Euclidean would split; gamma smooths the DTW geometry.\n# Use plain 'euclidean' when absolute phase is biologically meaningful (morning vs evening genes).\nmodel = TimeSeriesKMeans(n_clusters=8, metric='softdtw', metric_params={'gamma': 0.01},\n                         max_iter=50, random_state=42)\nlabels = model.fit_predict(expr_scaled.reshape(expr_scaled.shape[0], expr_scaled.shape[1], 1))\n```\n\n### QC Checkpoint: Clustering\n\n```r\nlibrary(cluster)\ncluster_sizes \u003C- table(cl$cluster)\nprint(cluster_sizes)\nif (any(cluster_sizes == 0)) message('WARNING: Empty clusters. Reduce n_clusters.')\n\nfor (i in seq_along(core_genes)) {\n    message(sprintf('Cluster %d: %d core genes (membership >0.5)', i, nrow(core_genes[[i]])))\n}\n\n# Silhouette on the z-scored profiles; triangulate k with a sweep, do not crown one index\nsil \u003C- silhouette(cl$cluster, dist(exprs(eset)))\nmessage(sprintf('Mean silhouette: %.3f', mean(sil[, 3])))\n```\n\n## Step 4a: Rhythm Detection (OPTIONAL branch - GATED)\n\n**This branch runs only when the sampling design licenses a rhythm test. Otherwise it is SKIPPED, not run with a warning.** Rhythm detection is not a routine step in a general time-course pipeline.\n\nHard precondition (all must hold), a design gate, not a soft aside:\n- **>=2 full cycles** of the target period (48h+ for a 24h circadian rhythm). One cycle cannot distinguish an oscillation from a monotone trend or a single transient bump.\n- **>=6-8 samples per cycle at roughly even spacing** (a lenient practical convention; Hughes 2017 recommends denser -- every 2h \u002F >=12 per cycle -- and calls 4h intervals underpowered). Nyquist's 2\u002Fcycle is a mathematical floor with zero robustness to noise, no phase, no amplitude, no waveform shape.\n- **Collection order randomized.** Harvest\u002Fcollection order aliases directly onto circadian time: any drift (reagent lot, RIN, lane) is perfectly confounded with the rhythm axis and CANNOT be removed analytically. The only fix is design (randomize processing order).\n\nEven when the gate passes, a rhythm found under a light-dark (LD) cycle may be light\u002Ffeeding-DRIVEN masking, not endogenous clock output: diurnal != circadian. Endogeneity requires persistence under constant conditions (constant darkness, DD). Report ZT for entrained (LD) data, CT for free-running (DD) data.\n\n```python\nCIRCADIAN_DESIGN = False  # the un-computable precondition (circadian design + randomized order); set True only if it holds\n\nn_cycles = (meta['time'].max() - meta['time'].min()) \u002F 24.0\nsamples_per_cycle = meta['time'].nunique() \u002F max(n_cycles, 1e-9)\ngate_design = n_cycles >= 2 and samples_per_cycle >= 6   # the COMPUTABLE part of the gate\nif CIRCADIAN_DESIGN and gate_design:\n    pass  # run rhythm detection (CosinorPy\u002FMetaCycle below)\nelif not gate_design:\n    print(f'Rhythm detection SKIPPED: inadequate design ({n_cycles:.1f} cycles, {samples_per_cycle:.1f}\u002Fcycle; need >=2 and >=6-8).')\nelse:\n    print('Rhythm detection SKIPPED: design meets the cycle\u002Fsampling floor but CIRCADIAN_DESIGN is not set (randomized-order \u002F circadian precondition unconfirmed).')\n```\n\n### R (MetaCycle)\n\n```r\nlibrary(MetaCycle)\nexpr_for_meta \u003C- expr_sig\ncolnames(expr_for_meta) \u003C- meta$time\nwrite.csv(expr_for_meta, 'expr_for_metacycle.csv')\n\n# Circadian search window 20-28h; ARS\u002FJTK require EVEN integer sampling and drop out silently\n# (analysisStrategy='auto') on uneven\u002Freplicated data, leaving LS only.\nmeta2d('expr_for_metacycle.csv', filestyle = 'csv',\n       minper = 20, maxper = 28,\n       timepoints = sort(unique(meta$time)),\n       outdir = 'metacycle_results')\n# Filter on meta2d_BH.Q (BH FDR) AND meta2d_rAMP (relative amplitude); significance alone over-detects.\n```\n\n### Python (CosinorPy)\n\n```python\nfrom CosinorPy import cosinor   # note: import name is capitalized CosinorPy, not cosinorpy\n\n# fit_group expects long-format columns 'x' (time), 'y' (expression), 'test' (gene id).\n# period=24 for circadian; n_components=2 adds the 12h harmonic for non-sinusoidal shapes.\nresults = cosinor.fit_group(expr_long, period=24, n_components=1)\n\n# fit_group ALREADY returns a BH-adjusted 'q' column across the fitted group; use it, do NOT\n# threshold the raw per-gene 'p'. Add a RELATIVE-amplitude filter (fit_group has no rAMP column,\n# so compute rAMP = amplitude\u002Fmesor): significance alone over-detects rhythms. rAMP>0.1 = >=10% of baseline.\nresults['rAMP'] = results['amplitude'] \u002F results['mesor']\nrhythmic = results[(results['q'] \u003C 0.05) & (results['rAMP'] > 0.1)]\n```\n\n## Step 4b: GAM Trajectory Fitting\n\nGAMs here summarize each cluster's temporal shape by fitting a penalized smooth to the STANDARDIZED cluster-mean profile. Because the input is a z-scored mean (not raw counts), a Gaussian family is appropriate; NB-family\u002Foffsets are needed only when fitting raw counts directly (see temporal-genomics\u002Ftrajectory-modeling).\n\n### R (mgcv)\n\n```r\nlibrary(mgcv)\n\ncluster_trajectories \u003C- list()\nfor (cl_id in 1:n_clusters) {\n    cl_genes \u003C- names(cl$cluster[cl$cluster == cl_id])\n    mean_profile \u003C- colMeans(expr_sig[cl_genes, ])\n    df_gam \u003C- data.frame(time = meta$time, expr = mean_profile)\n\n    # k is a flexibility CEILING (max basis dimension), NOT the number of knots\u002Fbends to fit.\n    # REML (not GCV) then picks the wiggliness penalty; realized complexity is reported as edf.\n    # Keep k \u003C number of unique timepoints (identifiability); k=5 suits >=6-8 timepoints.\n    gam_fit \u003C- gam(expr ~ s(time, k = 5), data = df_gam, method = 'REML')\n\n    cluster_trajectories[[cl_id]] \u003C- list(fit = gam_fit,\n                                          r_squared = summary(gam_fit)$r.sq,\n                                          edf = summary(gam_fit)$edf)\n    message(sprintf('Cluster %d: R^2 = %.3f, EDF = %.2f (edf~1 => linear; edf~k-1 => highly non-linear)',\n                    cl_id, summary(gam_fit)$r.sq, summary(gam_fit)$edf))\n}\n```\n\n### Python (pygam)\n\n```python\nfrom pygam import LinearGAM, s\n\nfor cl_id in range(n_clusters):\n    mean_profile = expr_scaled[labels == cl_id].mean(axis=0)\n    # n_splines is the basis-dimension ceiling (like mgcv k); the penalty picks realized wiggliness.\n    gam = LinearGAM(s(0, n_splines=5)).fit(meta['time'].values.reshape(-1, 1), mean_profile)\n    print(f'Cluster {cl_id}: GCV = {gam.statistics_[\"GCV\"]:.4f}, edof = {gam.statistics_[\"edof\"]:.2f}')\n```\n\n## Step 5: Per-Cluster Pathway Enrichment\n\nThe enrichment BACKGROUND (universe) must be the temporal genes that were clustered, NOT the whole genome. Genome background re-detects the generic biology of being a dynamic gene (the selection step), so every cluster lights up; temporal-gene background isolates what makes THIS shape distinct.\n\n### R (clusterProfiler)\n\n```r\nlibrary(clusterProfiler)\nlibrary(org.Hs.eg.db)\n\nall_temporal_entrez \u003C- bitr(rownames(expr_sig), fromType = 'SYMBOL', toType = 'ENTREZID',\n                            OrgDb = org.Hs.eg.db)\n\nenrichment_results \u003C- list()\nfor (i in seq_along(core_genes)) {\n    entrez \u003C- bitr(core_genes[[i]]$NAME, fromType = 'SYMBOL', toType = 'ENTREZID', OrgDb = org.Hs.eg.db)\n    ego \u003C- enrichGO(gene = entrez$ENTREZID,\n                    universe = all_temporal_entrez$ENTREZID,   # background = temporal genes\n                    OrgDb = org.Hs.eg.db, ont = 'BP', pAdjustMethod = 'BH',\n                    pvalueCutoff = 0.05, qvalueCutoff = 0.05, readable = TRUE)\n    if (nrow(as.data.frame(ego)) > 0) {\n        ego \u003C- simplify(ego, cutoff = 0.7, by = 'p.adjust')   # collapse redundant parent-child GO terms\n    }\n    enrichment_results[[i]] \u003C- ego\n    message(sprintf('Cluster %d: %d significant GO terms', i, nrow(as.data.frame(ego))))\n}\n```\n\n### Python (gseapy)\n\n```python\nimport gseapy as gp\n\nall_temporal_genes = list(expr_sig.index)   # background = temporal genes, not the genome\n\nfor cl_id in range(n_clusters):\n    cl_genes = [g for g, l in zip(expr_sig.index, labels) if l == cl_id]\n    # enrichr hits the Enrichr web API; pass background=temporal genes and outdir=None (no files).\n    # For a strictly offline hypergeometric test with a custom background, gp.enrich(gene_sets=\u003Cgmt\u002Fdict>,\n    # background=all_temporal_genes) computes it locally instead.\n    enr = gp.enrichr(gene_list=cl_genes, gene_sets='GO_Biological_Process_2023',\n                     organism='human', background=all_temporal_genes, outdir=None)\n    sig_terms = enr.results[enr.results['Adjusted P-value'] \u003C 0.05]\n    print(f'Cluster {cl_id}: {len(sig_terms)} significant GO terms')\n```\n\n### QC Checkpoint: Enrichment\n\n```r\nclusters_with_terms \u003C- sum(sapply(enrichment_results, function(x) nrow(as.data.frame(x)) > 0))\nmessage(sprintf('Clusters with significant GO terms: %d \u002F %d', clusters_with_terms, length(enrichment_results)))\nif (clusters_with_terms \u003C 3) message('WARNING: Few clusters enriched. Check gene ID mapping or thresholds.')\n```\n\n## Parameter Recommendations\n\n| Step | Parameter | Recommendation |\n|------|-----------|----------------|\n| Temporal DE | Spline df | 3 (default); 4-5 for >10 timepoints |\n| Temporal DE | FDR | 0.05 (standard); 0.1 exploratory clustering only |\n| Clustering | fuzzifier m | Use mestimate(); inspect returned value + membership distribution |\n| Clustering | n_clusters (k) | 4-20; a CHOICE, not a result; sweep + validate (silhouette\u002Fgap\u002Fbootstrap) |\n| Clustering | min membership | 0.5 (core); 0.3 (exploratory) |\n| Rhythm (gated) | design gate | >=2 cycles AND >=6-8 samples\u002Fcycle AND randomized order; else skip |\n| Rhythm (gated) | period window | 20-28h circadian; filter on BH q AND rAMP |\n| GAM | k (basis ceiling) | 5 for >=6-8 timepoints; keep k \u003C #unique timepoints; REML picks the penalty |\n| Enrichment | background | temporal genes (NOT genome); pvalueCutoff 0.05 |\n\n## Common Errors\n\n| Symptom | Cause | Fix |\n|---------|-------|-----|\n| Clusters look clean but mean nothing | Clustered the full matrix \u002F did not z-score | Cluster only temporal-DE hits; standardise per gene first |\n| Cluster enrichment lights up everywhere with generic terms | Genome used as enrichment background | Use temporal genes as universe\u002Fbackground |\n| \"Rhythmic\" hits on a short\u002F1-cycle design | Rhythm test run without the design gate | Enforce >=2 cycles + >=6-8 samples\u002Fcycle; else skip the branch |\n| A 24h rhythm appears at ~12h or ~36h | Aliasing from sub-Nyquist sampling | Sample >=2x per target period; report the interval |\n| Implausibly many rhythmic genes | Significance-only threshold; undetrended trend | Filter on rAMP\u002Famplitude too; require >=2 cycles |\n| CosinorPy import fails | Wrong import name | `from CosinorPy import cosinor` (capitalized) |\n| MetaCycle \"wrote files but read.csv fails\" | Output is under `outdir\u002F` as `meta2d_\u003Cinfile>` | Read the actual emitted path; ARS\u002FJTK silently drop on uneven sampling |\n| gam.check k-index \u003C 1 | Basis ceiling k too low (or residual autocorrelation) | Double k and refit; if edf barely moves, suspect autocorrelation, not k |\n| GAM p=1e-30 over-trusted | Smooth-term p-values are approximate | Treat as categorical significant\u002Fnot; apply BH across genes |\n\n## Related Skills\n\n- differential-expression\u002Ftimeseries-de - Temporal DE methods (limma splines, DESeq2 LRT, maSigPro)\n- temporal-genomics\u002Ftemporal-clustering - Soft\u002Fhard clustering, k selection, DTW details\n- temporal-genomics\u002Fcircadian-rhythms - Single-condition rhythm detection, sampling design, phase\u002Famplitude\n- temporal-genomics\u002Fdifferential-rhythmicity - Comparing rhythms between conditions (gain\u002Floss\u002Fphase\u002Famplitude)\n- temporal-genomics\u002Ftrajectory-modeling - GAM fitting, k-vs-edf, bulk-vs-pseudotime boundary\n- temporal-genomics\u002Fperiodicity-detection - Unknown-period discovery (Lomb-Scargle, wavelets)\n- pathway-analysis\u002Fgo-enrichment - Enrichment, background choice, GO term simplification\n\n## References\n\n- Hughes ME, Abruzzi KC, Allada R, et al. 2017. Guidelines for Genome-Scale Analysis of Biological Rhythms. *J Biol Rhythms* 32(5):380-393. doi:10.1177\u002F0748730417728663. (Recommends >=2 cycles and dense sampling -- at least every 2 h \u002F >=12 timepoints per cycle, explicitly calling 4 h intervals underpowered -- plus biological replicates. The lenient 6-8\u002Fcycle floor used above is a stated practical convention, denser is better.)\n- Wu G, Anafi RC, Hughes ME, Kornacker K, Hogenesch JB. 2016. MetaCycle: an integrated R package to evaluate periodicity in large scale data. *Bioinformatics* 32(21):3351-3353. doi:10.1093\u002Fbioinformatics\u002Fbtw405. (meta2d integrating ARS\u002FJTK\u002FLS; output columns.)\n- Moškon M. 2020. CosinorPy: a python package for cosinor-based rhythmometry. *BMC Bioinformatics* 21(1):485. doi:10.1186\u002Fs12859-020-03830-w. (fit_group \u002F cosinor rhythmometry.)\n- Futschik ME, Carlisle B. 2005. Noise-robust soft clustering of gene expression time-course data. *J Bioinform Comput Biol* 3(4):965-988. doi:10.1142\u002FS0219720005001375. (Fuzzy c-means noise-robustness rationale for Mfuzz.)\n- Schwämmle V, Jensen ON. 2010. A simple and fast method to determine the parameters for fuzzy c-means cluster analysis. *Bioinformatics* 26(22):2841-2848. doi:10.1093\u002Fbioinformatics\u002Fbtq534. (The mestimate() fuzzifier estimator.)\n- Wood SN. 2011. Fast stable restricted maximum likelihood and marginal likelihood estimation of semiparametric generalized linear models. *J R Stat Soc B* 73(1):3-36. doi:10.1111\u002Fj.1467-9868.2010.00749.x. (Why REML over GCV for the smoothing penalty.)\n- Laloum D, Robinson-Rechavi M. 2020. Methods detecting rhythmic gene expression are biologically relevant only for strong signal. *PLoS Comput Biol* 16(3):e1007666. doi:10.1371\u002Fjournal.pcbi.1007666. (Amplitude filtering; significance alone over-detects rhythms.)\n","## Version Compatibility\n\nReference examples tested with: DESeq2 1.42+, limma 3.58+, splines (R base), Mfuzz 2.62+, MetaCycle 1.2+, mgcv 1.9+, clusterProfiler 4.10+, CosinorPy 3.1+, tslearn 0.6+, pygam 0.9+, gseapy 1.2+, statsmodels 0.14+, patsy 1.0+, scikit-learn 1.4+\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show \u003Cpackage>` then `help(module.function)` to check signatures\n- R: `packageVersion('\u003Cpkg>')` then `?function_name` to verify parameters\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\nNote: the whole pipeline is dominated by the SAMPLING DESIGN, not the algorithm. Temporal DE, clustering, and trajectory fitting need genes pre-selected for temporal change and enough timepoints to resolve a shape; rhythm detection additionally requires >=2 full cycles and >=6-8 evenly spaced samples per cycle. A small p-value on 6 timepoints over a single cycle is not evidence of a rhythm.\n\n# Time-Course Analysis Pipeline\n\n**\"Analyze my bulk time-course expression data end-to-end\"** -> Orchestrate temporal differential expression, soft clustering of expression-profile shapes, GAM trajectory fitting, per-cluster pathway enrichment, and (only under a circadian sampling design) rhythm detection.\n- Python: statsmodels\u002Fpatsy spline F-test -> tslearn TimeSeriesKMeans -> pygam LinearGAM -> gseapy; CosinorPy for the optional rhythm branch\n- R: limma splines or DESeq2 LRT -> Mfuzz -> mgcv -> clusterProfiler; MetaCycle for the optional rhythm branch\n\n## Pipeline principles (read before running)\n\n- Clustering, GAM fitting, and enrichment are DESCRIPTIVE steps DOWNSTREAM of the temporal-DE gene selection; they add no inference of their own. Cluster only the temporally variable genes, never the full matrix, or every method returns confident-looking clusters of noise.\n- Do NOT test the clusters for the temporal signal used to select the genes (circular \u002F double-dipping). Enrichment is valid only against an INDEPENDENT annotation (GO\u002FKEGG), with the temporal genes as background.\n- Rhythm detection is an OPTIONAL branch, not a routine default. It is licensed only by a circadian sampling design (>=2 full cycles, >=6-8 samples\u002Fcycle, roughly even spacing, randomized collection order). Under any other design it is SKIPPED, not run with a warning.\n- Cluster number k and Mfuzz fuzzifier m are analyst CHOICES, not results; sweep and report the criterion.\n\n## Pipeline Overview\n\n```\nExpression matrix + time metadata\n    |\n    v\n[1. Temporal DE] ---------> limma splines \u002F DESeq2 LRT \u002F statsmodels spline F-test\n    |                            (selects temporally variable genes; FDR \u003C0.05)\n    v\n[2. Filter] --------------> Significant temporal genes only (clustering input)\n    |\n    v\n[3. Soft Clustering] -----> Mfuzz (R) \u002F tslearn TimeSeriesKMeans (Python) on z-scored profiles\n    |                            +---> QC: membership >0.5, no empty clusters, sweep k\n    |\n    v\n[4b. GAM Trajectory] -----> mgcv \u002F pygam GAM on standardized cluster-mean profiles\n    |\n    v\n[5. Pathway Enrichment] --> clusterProfiler \u002F gseapy per cluster\n    |                            background = temporal genes (NOT the genome)\n    v\nTemporal gene modules + enriched pathways + trajectory fits\n\n    OPTIONAL branch, gated (NOT on the default path):\n    IF design covers >=2 full cycles AND >=6-8 samples\u002Fcycle (even spacing)\n       AND collection order was randomized:\n        [4a. Rhythm Detection] --> MetaCycle meta2d \u002F CosinorPy fit_group\n                                   period\u002Fphase\u002Famplitude + BH q across genes\n    ELSE: SKIP (design does not license a rhythm test)\n```\n\n## Step 1: Temporal Differential Expression\n\n### R (limma splines)\n\n```r\nlibrary(limma)\nlibrary(splines)\n\nexpr \u003C- as.matrix(read.csv('counts_normalized.csv', row.names = 1))\nmeta \u003C- read.csv('metadata.csv')\n\n# Natural cubic spline on time; df=3 is enough for most courses, raise to 4-5 for >10 timepoints\ndesign \u003C- model.matrix(~ ns(meta$time, df = 3))\nfit \u003C- lmFit(expr, design)\nfit \u003C- eBayes(fit)\n\n# Joint F-test on all spline coefficients = \"expression changes over time\"\ntemporal_results \u003C- topTable(fit, coef = 2:ncol(design), number = Inf, sort.by = 'F')\n# topTable already returns adj.P.Val (BH-corrected); use it directly (not $FDR, which does not exist)\n```\n\n### R (DESeq2 LRT)\n\n```r\nlibrary(DESeq2)\n\ncounts \u003C- as.matrix(read.csv('raw_counts.csv', row.names = 1))\nmeta \u003C- read.csv('metadata.csv')\nmeta$time \u003C- factor(meta$time)\n\n# LRT: full model (time as factor) vs reduced (intercept) = any between-timepoint change\ndds \u003C- DESeqDataSetFromMatrix(counts, colData = meta, design = ~ time)\ndds \u003C- DESeq(dds, test = 'LRT', reduced = ~ 1)\nres \u003C- results(dds)   # BH-adjusted padj\n```\n\nChoose limma-splines when the time axis is continuous and a smooth trend is expected (normalized\u002Fvoom or vst input); choose DESeq2-LRT for raw counts and few, discrete timepoints treated as a factor.\n\n### Python (statsmodels spline F-test)\n\n```python\nimport pandas as pd\nimport numpy as np\nfrom statsmodels.stats.multitest import multipletests\nfrom patsy import dmatrix\nfrom scipy import stats\n\nexpr = pd.read_csv('counts_normalized.csv', index_col=0)\nmeta = pd.read_csv('metadata.csv')\n\nspline_basis = dmatrix('bs(time, df=3)', data=meta, return_type='dataframe')\n# patsy already includes an Intercept column; do NOT prepend another np.ones (that duplicates the\n# intercept, inflates model df, and miscalibrates the F-test -> wrong temporal-DE FDR). Use it directly.\ndesign_full = spline_basis.values                          # [Intercept, bs1, bs2, bs3] = 4 cols\ndesign_reduced = np.ones((len(meta), 1))\ndf_diff = design_full.shape[1] - design_reduced.shape[1]   # 4 - 1 = 3\ndf_resid = len(meta) - design_full.shape[1]                # n - 4\n\npvals = []\nfor gene in expr.index:\n    y = expr.loc[gene].values\n    ss_full = np.sum((y - design_full @ np.linalg.lstsq(design_full, y, rcond=None)[0]) ** 2)\n    ss_red = np.sum((y - design_reduced @ np.linalg.lstsq(design_reduced, y, rcond=None)[0]) ** 2)\n    f_stat = ((ss_red - ss_full) \u002F df_diff) \u002F (ss_full \u002F df_resid)\n    pvals.append(1 - stats.f.cdf(f_stat, df_diff, df_resid))\n\n# multipletests default is Holm-Sidak; force BH explicitly\n_, fdr, _, _ = multipletests(pvals, method='fdr_bh')\ntemporal_genes = expr.index[fdr \u003C 0.05].tolist()\n```\n\n### QC Checkpoint: Temporal DE\n\n```r\nsig_genes \u003C- temporal_results[temporal_results$adj.P.Val \u003C 0.05, ]\nn_sig \u003C- nrow(sig_genes)\nmessage(sprintf('Significant temporal genes: %d', n_sig))\n# \u003C100: underpowered clustering; >10000: check batch\u002Fnormalization before proceeding\nif (n_sig \u003C 100) message('WARNING: Few temporal genes. Check timepoint spacing or relax FDR.')\nif (n_sig > 10000) message('WARNING: Many temporal genes. Inspect batch effects \u002F normalization.')\n```\n\n## Step 2: Filter Significant Genes\n\n```r\n# FDR \u003C0.05 standard; 0.1 acceptable for exploratory clustering only\nsig_genes \u003C- rownames(temporal_results[temporal_results$adj.P.Val \u003C 0.05, ])\nexpr_sig \u003C- expr[sig_genes, ]\nmessage(sprintf('Genes passing FDR \u003C0.05: %d', length(sig_genes)))\n```\n\n## Step 3: Soft Clustering (of expression-profile shapes)\n\nClustering groups genes by SHAPE, not magnitude, so profiles are z-scored per gene first; otherwise abundance dominates and high-expression genes cluster together regardless of dynamics. Cluster only `expr_sig` (the temporal genes), never the full matrix.\n\n### R (Mfuzz)\n\n```r\nlibrary(Mfuzz)\n\neset \u003C- ExpressionSet(assayData = as.matrix(expr_sig))\neset \u003C- standardise(eset)   # per-gene mean 0, sd 1: makes distance shape-based, not magnitude-based\n\n# mestimate() implements Schwaemmle & Jensen (2010): the smallest m that stops fuzzy c-means\n# from clustering RANDOMIZED data. It is dominated by the number of timepoints; inspect the\n# returned value and the membership distribution rather than trusting it blindly (or hardcoding m=2).\nm \u003C- mestimate(eset)\nmessage(sprintf('Estimated fuzzifier m = %.2f', m))\n\n# k is a resolution CHOICE, not a result: start ~sqrt(n_genes\u002F2), then sweep and validate (below)\nn_clusters \u003C- 8\ncl \u003C- mfuzz(eset, c = n_clusters, m = m)\n\n# Membership >0.5 = core (confident) genes; lower to 0.3 only for exploratory overlap\ncore_genes \u003C- acore(eset, cl, min.acore = 0.5)\n```\n\n### Python (tslearn)\n\n```python\nfrom tslearn.clustering import TimeSeriesKMeans\n\n# Row-wise z-score: normalize each gene across its own timepoints (shape, not level)\nexpr_scaled = (expr_sig.values - expr_sig.values.mean(axis=1, keepdims=True)) \u002F expr_sig.values.std(axis=1, keepdims=True)\n\n# soft-DTW tolerates phase-shifted profiles Euclidean would split; gamma smooths the DTW geometry.\n# Use plain 'euclidean' when absolute phase is biologically meaningful (morning vs evening genes).\nmodel = TimeSeriesKMeans(n_clusters=8, metric='softdtw', metric_params={'gamma': 0.01},\n                         max_iter=50, random_state=42)\nlabels = model.fit_predict(expr_scaled.reshape(expr_scaled.shape[0], expr_scaled.shape[1], 1))\n```\n\n### QC Checkpoint: Clustering\n\n```r\nlibrary(cluster)\ncluster_sizes \u003C- table(cl$cluster)\nprint(cluster_sizes)\nif (any(cluster_sizes == 0)) message('WARNING: Empty clusters. Reduce n_clusters.')\n\nfor (i in seq_along(core_genes)) {\n    message(sprintf('Cluster %d: %d core genes (membership >0.5)', i, nrow(core_genes[[i]])))\n}\n\n# Silhouette on the z-scored profiles; triangulate k with a sweep, do not crown one index\nsil \u003C- silhouette(cl$cluster, dist(exprs(eset)))\nmessage(sprintf('Mean silhouette: %.3f', mean(sil[, 3])))\n```\n\n## Step 4a: Rhythm Detection (OPTIONAL branch - GATED)\n\n**This branch runs only when the sampling design licenses a rhythm test. Otherwise it is SKIPPED, not run with a warning.** Rhythm detection is not a routine step in a general time-course pipeline.\n\nHard precondition (all must hold), a design gate, not a soft aside:\n- **>=2 full cycles** of the target period (48h+ for a 24h circadian rhythm). One cycle cannot distinguish an oscillation from a monotone trend or a single transient bump.\n- **>=6-8 samples per cycle at roughly even spacing** (a lenient practical convention; Hughes 2017 recommends denser -- every 2h \u002F >=12 per cycle -- and calls 4h intervals underpowered). Nyquist's 2\u002Fcycle is a mathematical floor with zero robustness to noise, no phase, no amplitude, no waveform shape.\n- **Collection order randomized.** Harvest\u002Fcollection order aliases directly onto circadian time: any drift (reagent lot, RIN, lane) is perfectly confounded with the rhythm axis and CANNOT be removed analytically. The only fix is design (randomize processing order).\n\nEven when the gate passes, a rhythm found under a light-dark (LD) cycle may be light\u002Ffeeding-DRIVEN masking, not endogenous clock output: diurnal != circadian. Endogeneity requires persistence under constant conditions (constant darkness, DD). Report ZT for entrained (LD) data, CT for free-running (DD) data.\n\n```python\nCIRCADIAN_DESIGN = False  # the un-computable precondition (circadian design + randomized order); set True only if it holds\n\nn_cycles = (meta['time'].max() - meta['time'].min()) \u002F 24.0\nsamples_per_cycle = meta['time'].nunique() \u002F max(n_cycles, 1e-9)\ngate_design = n_cycles >= 2 and samples_per_cycle >= 6   # the COMPUTABLE part of the gate\nif CIRCADIAN_DESIGN and gate_design:\n    pass  # run rhythm detection (CosinorPy\u002FMetaCycle below)\nelif not gate_design:\n    print(f'Rhythm detection SKIPPED: inadequate design ({n_cycles:.1f} cycles, {samples_per_cycle:.1f}\u002Fcycle; need >=2 and >=6-8).')\nelse:\n    print('Rhythm detection SKIPPED: design meets the cycle\u002Fsampling floor but CIRCADIAN_DESIGN is not set (randomized-order \u002F circadian precondition unconfirmed).')\n```\n\n### R (MetaCycle)\n\n```r\nlibrary(MetaCycle)\nexpr_for_meta \u003C- expr_sig\ncolnames(expr_for_meta) \u003C- meta$time\nwrite.csv(expr_for_meta, 'expr_for_metacycle.csv')\n\n# Circadian search window 20-28h; ARS\u002FJTK require EVEN integer sampling and drop out silently\n# (analysisStrategy='auto') on uneven\u002Freplicated data, leaving LS only.\nmeta2d('expr_for_metacycle.csv', filestyle = 'csv',\n       minper = 20, maxper = 28,\n       timepoints = sort(unique(meta$time)),\n       outdir = 'metacycle_results')\n# Filter on meta2d_BH.Q (BH FDR) AND meta2d_rAMP (relative amplitude); significance alone over-detects.\n```\n\n### Python (CosinorPy)\n\n```python\nfrom CosinorPy import cosinor   # note: import name is capitalized CosinorPy, not cosinorpy\n\n# fit_group expects long-format columns 'x' (time), 'y' (expression), 'test' (gene id).\n# period=24 for circadian; n_components=2 adds the 12h harmonic for non-sinusoidal shapes.\nresults = cosinor.fit_group(expr_long, period=24, n_components=1)\n\n# fit_group ALREADY returns a BH-adjusted 'q' column across the fitted group; use it, do NOT\n# threshold the raw per-gene 'p'. Add a RELATIVE-amplitude filter (fit_group has no rAMP column,\n# so compute rAMP = amplitude\u002Fmesor): significance alone over-detects rhythms. rAMP>0.1 = >=10% of baseline.\nresults['rAMP'] = results['amplitude'] \u002F results['mesor']\nrhythmic = results[(results['q'] \u003C 0.05) & (results['rAMP'] > 0.1)]\n```\n\n## Step 4b: GAM Trajectory Fitting\n\nGAMs here summarize each cluster's temporal shape by fitting a penalized smooth to the STANDARDIZED cluster-mean profile. Because the input is a z-scored mean (not raw counts), a Gaussian family is appropriate; NB-family\u002Foffsets are needed only when fitting raw counts directly (see temporal-genomics\u002Ftrajectory-modeling).\n\n### R (mgcv)\n\n```r\nlibrary(mgcv)\n\ncluster_trajectories \u003C- list()\nfor (cl_id in 1:n_clusters) {\n    cl_genes \u003C- names(cl$cluster[cl$cluster == cl_id])\n    mean_profile \u003C- colMeans(expr_sig[cl_genes, ])\n    df_gam \u003C- data.frame(time = meta$time, expr = mean_profile)\n\n    # k is a flexibility CEILING (max basis dimension), NOT the number of knots\u002Fbends to fit.\n    # REML (not GCV) then picks the wiggliness penalty; realized complexity is reported as edf.\n    # Keep k \u003C number of unique timepoints (identifiability); k=5 suits >=6-8 timepoints.\n    gam_fit \u003C- gam(expr ~ s(time, k = 5), data = df_gam, method = 'REML')\n\n    cluster_trajectories[[cl_id]] \u003C- list(fit = gam_fit,\n                                          r_squared = summary(gam_fit)$r.sq,\n                                          edf = summary(gam_fit)$edf)\n    message(sprintf('Cluster %d: R^2 = %.3f, EDF = %.2f (edf~1 => linear; edf~k-1 => highly non-linear)',\n                    cl_id, summary(gam_fit)$r.sq, summary(gam_fit)$edf))\n}\n```\n\n### Python (pygam)\n\n```python\nfrom pygam import LinearGAM, s\n\nfor cl_id in range(n_clusters):\n    mean_profile = expr_scaled[labels == cl_id].mean(axis=0)\n    # n_splines is the basis-dimension ceiling (like mgcv k); the penalty picks realized wiggliness.\n    gam = LinearGAM(s(0, n_splines=5)).fit(meta['time'].values.reshape(-1, 1), mean_profile)\n    print(f'Cluster {cl_id}: GCV = {gam.statistics_[\"GCV\"]:.4f}, edof = {gam.statistics_[\"edof\"]:.2f}')\n```\n\n## Step 5: Per-Cluster Pathway Enrichment\n\nThe enrichment BACKGROUND (universe) must be the temporal genes that were clustered, NOT the whole genome. Genome background re-detects the generic biology of being a dynamic gene (the selection step), so every cluster lights up; temporal-gene background isolates what makes THIS shape distinct.\n\n### R (clusterProfiler)\n\n```r\nlibrary(clusterProfiler)\nlibrary(org.Hs.eg.db)\n\nall_temporal_entrez \u003C- bitr(rownames(expr_sig), fromType = 'SYMBOL', toType = 'ENTREZID',\n                            OrgDb = org.Hs.eg.db)\n\nenrichment_results \u003C- list()\nfor (i in seq_along(core_genes)) {\n    entrez \u003C- bitr(core_genes[[i]]$NAME, fromType = 'SYMBOL', toType = 'ENTREZID', OrgDb = org.Hs.eg.db)\n    ego \u003C- enrichGO(gene = entrez$ENTREZID,\n                    universe = all_temporal_entrez$ENTREZID,   # background = temporal genes\n                    OrgDb = org.Hs.eg.db, ont = 'BP', pAdjustMethod = 'BH',\n                    pvalueCutoff = 0.05, qvalueCutoff = 0.05, readable = TRUE)\n    if (nrow(as.data.frame(ego)) > 0) {\n        ego \u003C- simplify(ego, cutoff = 0.7, by = 'p.adjust')   # collapse redundant parent-child GO terms\n    }\n    enrichment_results[[i]] \u003C- ego\n    message(sprintf('Cluster %d: %d significant GO terms', i, nrow(as.data.frame(ego))))\n}\n```\n\n### Python (gseapy)\n\n```python\nimport gseapy as gp\n\nall_temporal_genes = list(expr_sig.index)   # background = temporal genes, not the genome\n\nfor cl_id in range(n_clusters):\n    cl_genes = [g for g, l in zip(expr_sig.index, labels) if l == cl_id]\n    # enrichr hits the Enrichr web API; pass background=temporal genes and outdir=None (no files).\n    # For a strictly offline hypergeometric test with a custom background, gp.enrich(gene_sets=\u003Cgmt\u002Fdict>,\n    # background=all_temporal_genes) computes it locally instead.\n    enr = gp.enrichr(gene_list=cl_genes, gene_sets='GO_Biological_Process_2023',\n                     organism='human', background=all_temporal_genes, outdir=None)\n    sig_terms = enr.results[enr.results['Adjusted P-value'] \u003C 0.05]\n    print(f'Cluster {cl_id}: {len(sig_terms)} significant GO terms')\n```\n\n### QC Checkpoint: Enrichment\n\n```r\nclusters_with_terms \u003C- sum(sapply(enrichment_results, function(x) nrow(as.data.frame(x)) > 0))\nmessage(sprintf('Clusters with significant GO terms: %d \u002F %d', clusters_with_terms, length(enrichment_results)))\nif (clusters_with_terms \u003C 3) message('WARNING: Few clusters enriched. Check gene ID mapping or thresholds.')\n```\n\n## Parameter Recommendations\n\n| Step | Parameter | Recommendation |\n|------|-----------|----------------|\n| Temporal DE | Spline df | 3 (default); 4-5 for >10 timepoints |\n| Temporal DE | FDR | 0.05 (standard); 0.1 exploratory clustering only |\n| Clustering | fuzzifier m | Use mestimate(); inspect returned value + membership distribution |\n| Clustering | n_clusters (k) | 4-20; a CHOICE, not a result; sweep + validate (silhouette\u002Fgap\u002Fbootstrap) |\n| Clustering | min membership | 0.5 (core); 0.3 (exploratory) |\n| Rhythm (gated) | design gate | >=2 cycles AND >=6-8 samples\u002Fcycle AND randomized order; else skip |\n| Rhythm (gated) | period window | 20-28h circadian; filter on BH q AND rAMP |\n| GAM | k (basis ceiling) | 5 for >=6-8 timepoints; keep k \u003C #unique timepoints; REML picks the penalty |\n| Enrichment | background | temporal genes (NOT genome); pvalueCutoff 0.05 |\n\n## Common Errors\n\n| Symptom | Cause | Fix |\n|---------|-------|-----|\n| Clusters look clean but mean nothing | Clustered the full matrix \u002F did not z-score | Cluster only temporal-DE hits; standardise per gene first |\n| Cluster enrichment lights up everywhere with generic terms | Genome used as enrichment background | Use temporal genes as universe\u002Fbackground |\n| \"Rhythmic\" hits on a short\u002F1-cycle design | Rhythm test run without the design gate | Enforce >=2 cycles + >=6-8 samples\u002Fcycle; else skip the branch |\n| A 24h rhythm appears at ~12h or ~36h | Aliasing from sub-Nyquist sampling | Sample >=2x per target period; report the interval |\n| Implausibly many rhythmic genes | Significance-only threshold; undetrended trend | Filter on rAMP\u002Famplitude too; require >=2 cycles |\n| CosinorPy import fails | Wrong import name | `from CosinorPy import cosinor` (capitalized) |\n| MetaCycle \"wrote files but read.csv fails\" | Output is under `outdir\u002F` as `meta2d_\u003Cinfile>` | Read the actual emitted path; ARS\u002FJTK silently drop on uneven sampling |\n| gam.check k-index \u003C 1 | Basis ceiling k too low (or residual autocorrelation) | Double k and refit; if edf barely moves, suspect autocorrelation, not k |\n| GAM p=1e-30 over-trusted | Smooth-term p-values are approximate | Treat as categorical significant\u002Fnot; apply BH across genes |\n\n## Related Skills\n\n- differential-expression\u002Ftimeseries-de - Temporal DE methods (limma splines, DESeq2 LRT, maSigPro)\n- temporal-genomics\u002Ftemporal-clustering - Soft\u002Fhard clustering, k selection, DTW details\n- temporal-genomics\u002Fcircadian-rhythms - Single-condition rhythm detection, sampling design, phase\u002Famplitude\n- temporal-genomics\u002Fdifferential-rhythmicity - Comparing rhythms between conditions (gain\u002Floss\u002Fphase\u002Famplitude)\n- temporal-genomics\u002Ftrajectory-modeling - GAM fitting, k-vs-edf, bulk-vs-pseudotime boundary\n- temporal-genomics\u002Fperiodicity-detection - Unknown-period discovery (Lomb-Scargle, wavelets)\n- pathway-analysis\u002Fgo-enrichment - Enrichment, background choice, GO term simplification\n\n## References\n\n- Hughes ME, Abruzzi KC, Allada R, et al. 2017. Guidelines for Genome-Scale Analysis of Biological Rhythms. *J Biol Rhythms* 32(5):380-393. doi:10.1177\u002F0748730417728663. (Recommends >=2 cycles and dense sampling -- at least every 2 h \u002F >=12 timepoints per cycle, explicitly calling 4 h intervals underpowered -- plus biological replicates. The lenient 6-8\u002Fcycle floor used above is a stated practical convention, denser is better.)\n- Wu G, Anafi RC, Hughes ME, Kornacker K, Hogenesch JB. 2016. MetaCycle: an integrated R package to evaluate periodicity in large scale data. *Bioinformatics* 32(21):3351-3353. doi:10.1093\u002Fbioinformatics\u002Fbtw405. (meta2d integrating ARS\u002FJTK\u002FLS; output columns.)\n- Moškon M. 2020. CosinorPy: a python package for cosinor-based rhythmometry. *BMC Bioinformatics* 21(1):485. doi:10.1186\u002Fs12859-020-03830-w. (fit_group \u002F cosinor rhythmometry.)\n- Futschik ME, Carlisle B. 2005. Noise-robust soft clustering of gene expression time-course data. *J Bioinform Comput Biol* 3(4):965-988. doi:10.1142\u002FS0219720005001375. (Fuzzy c-means noise-robustness rationale for Mfuzz.)\n- Schwämmle V, Jensen ON. 2010. A simple and fast method to determine the parameters for fuzzy c-means cluster analysis. *Bioinformatics* 26(22):2841-2848. doi:10.1093\u002Fbioinformatics\u002Fbtq534. (The mestimate() fuzzifier estimator.)\n- Wood SN. 2011. Fast stable restricted maximum likelihood and marginal likelihood estimation of semiparametric generalized linear models. *J R Stat Soc B* 73(1):3-36. doi:10.1111\u002Fj.1467-9868.2010.00749.x. (Why REML over GCV for the smoothing penalty.)\n- Laloum D, Robinson-Rechavi M. 2020. Methods detecting rhythmic gene expression are biologically relevant only for strong signal. *PLoS Comput Biol* 16(3):e1007666. doi:10.1371\u002Fjournal.pcbi.1007666. (Amplitude filtering; significance alone over-detects rhythms.)\n",{"name":5,"source":24,"license":15,"workflow":25,"tool_type":26,"depends_on":27,"description":7,"imported_at":33,"source_path":34,"primary_tool":35,"qc_checkpoints":36,"source_repository":45,"goal_approach_exempt":25},"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills",true,"mixed",[28,29,30,31,32],"differential-expression\u002Ftimeseries-de","temporal-genomics\u002Ftemporal-clustering","temporal-genomics\u002Fcircadian-rhythms","temporal-genomics\u002Ftrajectory-modeling","pathway-analysis\u002Fgo-enrichment","2026-09-20","workflows\u002Ftimecourse-pipeline\u002FSKILL.md","Mfuzz",[37,39,41,43],{"after_de":38},"Significant temporal genes >100 at FDR \u003C0.05; model-fit residuals reasonable",{"after_clustering":40},"Membership >0.5 for soft clustering; no empty clusters; k validated by silhouette\u002Fgap or bootstrap stability (typical 4-20)",{"before_rhythm_detection":42},"GATE: design covers >=2 full cycles AND >=6-8 samples\u002Fcycle at ~even spacing AND collection order was randomized; else SKIP rhythm detection",{"after_enrichment":44},"At least 3 clusters with significant GO terms at FDR \u003C0.05; background = temporal genes, not the genome","GPTomics\u002FbioSkills","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fbiology\u002Fbio-workflows-timecourse-pipeline","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":53,"prompt":63,"zipAvailable":25},[54,57,60],{"tool":55,"command":56},"npx","npx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-workflows-timecourse-pipeline",{"tool":58,"command":59},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-workflows-timecourse-pipeline",{"tool":61,"command":62},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-workflows-timecourse-pipeline","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-workflows-timecourse-pipeline\u002FSKILL.md",[65,71,77],{"path":66,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":69,"sourceHtmlUrl":70},"examples\u002Ftimecourse_pipeline.py","SCRIPT","脚本",9089,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-workflows-timecourse-pipeline\u002Fexamples\u002Ftimecourse_pipeline.py",{"path":72,"resourceType":73,"resourceTypeDesc":74,"sizeBytes":75,"sourceHtmlUrl":76},"examples\u002Ftimecourse_pipeline.R","OTHER","其他",7532,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-workflows-timecourse-pipeline\u002Fexamples\u002Ftimecourse_pipeline.R",{"path":78,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":81,"sourceHtmlUrl":82},"usage-guide.md","REFERENCE","参考文档",6207,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-workflows-timecourse-pipeline\u002Fusage-guide.md",[84,92,99,106,113,120],{"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":91},"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":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":91},"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":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":91},"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":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":91},"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":114,"name":115,"nameZh":6,"description":116,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":117,"categories":118,"keywords":119,"publishedAt":91},"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":121,"name":122,"nameZh":6,"description":123,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":124,"categories":125,"keywords":126,"publishedAt":91},"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",[],[]]