diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml
index 9102898..4811860 100644
--- a/.github/workflows/docs.yml
+++ b/.github/workflows/docs.yml
@@ -10,6 +10,15 @@ on:
- "mkdocs.yml"
- "pyproject.toml"
- ".github/workflows/docs.yml"
+ pull_request:
+ branches:
+ - main
+ paths:
+ - "docs/**"
+ - "wavefactor/**"
+ - "mkdocs.yml"
+ - "pyproject.toml"
+ - ".github/workflows/docs.yml"
permissions:
contents: read
@@ -32,11 +41,8 @@ jobs:
- name: Build site and generate llms.md
run: |
- uv run --extra docs mkdocs build
- for f in $(find docs -name '*.md' | sort); do
- cat "$f"
- echo -e "\n\n---\n"
- done > site/llms.md
+ uv run --extra docs mkdocs build --strict
+ uv run --extra docs python docs/scripts/generate_llms.py
- name: Upload Pages artifact
uses: actions/upload-pages-artifact@v3
@@ -49,6 +55,7 @@ jobs:
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
needs: build
+ if: github.event_name == 'push' && github.ref == 'refs/heads/main'
steps:
- name: Deploy to GitHub Pages
id: deployment
diff --git a/.gitignore b/.gitignore
index b186c94..d0de5c6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -51,6 +51,7 @@ build/
dist/
*.egg-info/
site/
+docs/llms.md
# Not typical practice to include installable libraries; but here kept for sake of ease of reproducibility (hence below commented out)
diff --git a/README.md b/README.md
index c579177..87a52f7 100644
--- a/README.md
+++ b/README.md
@@ -46,7 +46,7 @@ Options:
- `docs/`: Documentation files
- `dev/`: Developer files
- `examples/`: Example scripts
-- `lib`: External libraries
+- `lib/`: External libraries
- `src/`: C++ CAVI engine source files
- `test/`: C++ testing suite
- `tests/`: Python test suite
diff --git a/docs/api.md b/docs/api.md
index 3c2da99..0e3f63a 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -32,16 +32,21 @@ This page contains the automated API reference for WaveFactor. Signatures, type
- factors
- spatial_factor_maps
- loadings
+ - loadings_variance
- gene_pip
- spatial_pip
- precision_t
- precision_tau
- elbo
- elbo_history
- - cpp_time
- - dimensions
+ - n_iter
+ - n_init
+ - grid_x
+ - grid_y
- grid_side_length
- grid_shape
+ - cpp_time
+ - dimensions
- summary
---
diff --git a/docs/getting_started.md b/docs/getting_started.md
index 55177fb..df4b486 100644
--- a/docs/getting_started.md
+++ b/docs/getting_started.md
@@ -16,7 +16,8 @@ import wavefactor as wf
# coords: (N_spots x 2) integer grid coordinates covering [0, L-1] x [0, L-1]
# N_spots = L * L must be an exact power of 4 (e.g. 64, 256, 1024, 4096)
np.random.seed(42)
-coords = np.mgrid[0:32, 0:32].reshape(2, -1).T
+gx, gy = np.meshgrid(np.arange(32), np.arange(32))
+coords = np.column_stack([gx.ravel(), gy.ravel()])
X = np.random.randn(1024, 200)
# 2. Instantiate WaveFactor estimator
@@ -43,9 +44,9 @@ spatial_pips = result.spatial_pip # Multiresolution spatial wavelet PIPs
## Another Example With Simulated Data Based On Gene Program Ground Truths
-WaveFactor includes additionally ready-to-run simulation example with ground truth gene programs, fits the model, and checks the results against the ground truth gene programs.
+Additionally, WaveFactor includes a ready-to-run simulation example that simulates data with ground-truth gene programs, fits the model, and verifies the estimated factors and loadings against the ground truth.
-This example can be ran with the following command.
+This example can be run with the following command:
```bash
python examples/getting_started/run_analysis.py
diff --git a/docs/index.md b/docs/index.md
index af64ba2..36ee246 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -52,4 +52,4 @@ python -c "import wavefactor as wf; print('WaveFactor version:', wf.__version__)
---
-> **LLM Context**: Working with an AI assistant? Use the raw single-file documentation at [llms.md](llms.md).
+> **LLM Context**: Working with an AI assistant? Use the raw single-file documentation at [llms.md](https://shimlab.github.io/WaveFactor/llms.md).
diff --git a/docs/input_output.md b/docs/input_output.md
index 446e475..9e330b6 100644
--- a/docs/input_output.md
+++ b/docs/input_output.md
@@ -40,7 +40,7 @@ result = model.get_result()
| `result.spatial_factor_maps` | `(L, L, K)` | Reconstructed 2D spatial maps of each factor. |
| `result.loadings` | `(K, N_genes)` | How strongly each gene belongs to each factor. |
| `result.gene_pip` | `(K, N_genes)` | Gene inclusion probability ($\approx 1$ = active gene, $\approx 0$ = noise). |
-| `result.spatial_pip` | List of arrays | Wavelet inclusion probabilities across spatial length scales. |
+| `result.spatial_pip` | Nested list | Wavelet coefficient inclusion probabilities per factor, resolution, and directional subband (`List[List[List[np.ndarray]]]`). |
| `result.elbo` | `float` | Final model fit score (higher is better). |
---
diff --git a/docs/scripts/generate_llms.py b/docs/scripts/generate_llms.py
new file mode 100644
index 0000000..daa95ce
--- /dev/null
+++ b/docs/scripts/generate_llms.py
@@ -0,0 +1,258 @@
+#!/usr/bin/env python3
+"""
+Generates llms.md by concatenating documentation pages in mkdocs.yml nav order
+and converting the mkdocstrings-rendered API Reference HTML into clean Markdown.
+"""
+
+from html.parser import HTMLParser
+from pathlib import Path
+import re
+import subprocess
+import sys
+from typing import List, Tuple
+
+import yaml
+
+REPO_ROOT = Path(__file__).resolve().parent.parent.parent
+
+
+class MkdocsHTMLToMarkdown(HTMLParser):
+ """Converts the main article HTML from MkDocs/mkdocstrings into clean Markdown."""
+
+ def __init__(self):
+ super().__init__()
+ self.output = []
+ self.in_pre = False
+ self.in_headerlink = False
+ self.list_depth = 0
+ self.table_row = []
+ self.in_table = False
+ self.in_thead = False
+ self.in_th = False
+ self.in_td = False
+ self.cell_content = []
+
+ def handle_starttag(self, tag, attrs):
+ attr_dict = dict(attrs)
+ classes = attr_dict.get("class", "").split()
+ if "headerlink" in classes or "doc-github-link" in classes or "doc-permalink" in classes:
+ self.in_headerlink = True
+ return
+
+ if self.in_th or self.in_td:
+ if tag == "code":
+ self.cell_content.append("`")
+ elif tag in ["strong", "b"]:
+ self.cell_content.append("**")
+ elif tag in ["em", "i"]:
+ self.cell_content.append("*")
+ return
+
+ if tag in ["h1", "h2", "h3", "h4", "h5", "h6"]:
+ level = int(tag[1])
+ self.output.append("\n\n" + "#" * level + " ")
+ elif tag == "p":
+ self.output.append("\n\n")
+ elif tag == "pre":
+ self.in_pre = True
+ self.output.append("\n\n```python\n")
+ elif tag == "code" and not self.in_pre:
+ self.output.append("`")
+ elif tag in ["strong", "b"]:
+ self.output.append("**")
+ elif tag in ["em", "i"]:
+ self.output.append("*")
+ elif tag == "hr":
+ self.output.append("\n\n---\n\n")
+ elif tag in ["ul", "ol"]:
+ self.list_depth += 1
+ self.output.append("\n")
+ elif tag == "li":
+ indent = " " * (self.list_depth - 1)
+ self.output.append(f"\n{indent}- ")
+ elif tag == "table":
+ self.in_table = True
+ self.output.append("\n\n")
+ elif tag == "thead":
+ self.in_thead = True
+ elif tag == "tr":
+ self.table_row = []
+ elif tag == "th":
+ self.in_th = True
+ self.cell_content = []
+ elif tag == "td":
+ self.in_td = True
+ self.cell_content = []
+
+ def handle_endtag(self, tag):
+ if self.in_headerlink:
+ if tag == "a":
+ self.in_headerlink = False
+ return
+
+ if self.in_th or self.in_td:
+ if tag == "code":
+ self.cell_content.append("`")
+ return
+ elif tag in ["strong", "b"]:
+ self.cell_content.append("**")
+ return
+ elif tag in ["em", "i"]:
+ self.cell_content.append("*")
+ return
+
+ if tag in ["h1", "h2", "h3", "h4", "h5", "h6"]:
+ self.output.append("\n")
+ elif tag == "p":
+ self.output.append("\n")
+ elif tag == "pre":
+ self.in_pre = False
+ self.output.append("\n```\n")
+ elif tag == "code" and not self.in_pre:
+ self.output.append("`")
+ elif tag in ["strong", "b"]:
+ self.output.append("**")
+ elif tag in ["em", "i"]:
+ self.output.append("*")
+ elif tag in ["ul", "ol"]:
+ self.list_depth = max(0, self.list_depth - 1)
+ self.output.append("\n")
+ elif tag in ["th", "td"]:
+ text = "".join(self.cell_content).strip().replace("\n", " ")
+ text = re.sub(r"\s+", " ", text)
+ self.table_row.append(text)
+ self.in_th = False
+ self.in_td = False
+ elif tag == "thead":
+ self.in_thead = False
+ elif tag == "tr":
+ if self.table_row:
+ row_str = "| " + " | ".join(self.table_row) + " |"
+ self.output.append(row_str + "\n")
+ if self.in_thead:
+ sep = "| " + " | ".join(["---"] * len(self.table_row)) + " |"
+ self.output.append(sep + "\n")
+ elif tag == "table":
+ self.in_table = False
+ self.output.append("\n")
+
+ def handle_data(self, data):
+ if self.in_headerlink:
+ return
+ if self.in_th or self.in_td:
+ self.cell_content.append(data)
+ else:
+ self.output.append(data)
+
+
+def clean_markdown_table_spacing(md: str) -> str:
+ """Removes empty lines between table rows to ensure contiguous GitHub-flavored tables."""
+ lines = md.splitlines()
+ cleaned = []
+ in_table = False
+
+ for line in lines:
+ stripped = line.strip()
+ if stripped.startswith("|") and stripped.endswith("|"):
+ in_table = True
+ cleaned.append(stripped)
+ elif in_table and stripped == "":
+ continue # drop blank lines inside markdown table
+ else:
+ in_table = False
+ cleaned.append(line)
+
+ result = "\n".join(cleaned)
+ # Collapse 3+ newlines into 2
+ return re.sub(r"\n{3,}", "\n\n", result).strip()
+
+
+def extract_api_markdown_from_site(site_dir: Path) -> str:
+ """Extracts and converts the rendered API HTML from mkdocs build output."""
+ api_html_path = site_dir / "api" / "index.html"
+ if not api_html_path.is_file():
+ raise FileNotFoundError(
+ f"Rendered API HTML not found at {api_html_path}. Run 'mkdocs build' first."
+ )
+
+ html = api_html_path.read_text(encoding="utf-8")
+ match = re.search(
+ r"]*class=\"[^\"]*md-content__inner[^\"]*\"[^>]*>(.*?)",
+ html,
+ re.DOTALL,
+ )
+ if not match:
+ raise ValueError(f"Could not locate main in {api_html_path}.")
+
+ parser = MkdocsHTMLToMarkdown()
+ parser.feed(match.group(1))
+ raw_md = "".join(parser.output)
+ return clean_markdown_table_spacing(raw_md)
+
+
+def get_nav_files(repo_root: Path) -> List[Tuple[str, str]]:
+ """Reads mkdocs.yml and extracts navigation titles and file paths in order."""
+ mkdocs_path = repo_root / "mkdocs.yml"
+ with open(mkdocs_path, "r", encoding="utf-8") as f:
+ config = yaml.safe_load(f)
+
+ nav = config.get("nav", [])
+ pages = []
+ for item in nav:
+ if isinstance(item, dict):
+ for title, path in item.items():
+ if isinstance(path, str) and path.endswith(".md"):
+ pages.append((title, path))
+ return pages
+
+
+def build_llms_md(repo_root: Path):
+ """Builds docs/llms.md following mkdocs.yml nav order using rendered mkdocs output."""
+ docs_dir = repo_root / "docs"
+ site_dir = repo_root / "site"
+ api_html = site_dir / "api" / "index.html"
+
+ # If site/api/index.html doesn't exist, run mkdocs build
+ if not api_html.is_file():
+ print("[INFO] Building mkdocs site to generate rendered API documentation...")
+ subprocess.run(["mkdocs", "build"], cwd=repo_root, check=True)
+
+ nav_files = get_nav_files(repo_root)
+
+ header = (
+ "# WaveFactor LLM Documentation Reference\n\n"
+ "> Single-file documentation reference optimized for LLM context windows and developer agents."
+ )
+ content_blocks = [header]
+
+ for title, rel_path in nav_files:
+ if rel_path == "api.md":
+ api_md = extract_api_markdown_from_site(site_dir)
+ content_blocks.append(api_md)
+ else:
+ src_file = docs_dir / rel_path
+ if not src_file.is_file():
+ print(f"[WARNING] Nav file not found: {src_file}", file=sys.stderr)
+ continue
+ raw_content = src_file.read_text(encoding="utf-8").strip()
+ # Strip redundant single-file LLM context pointer at bottom of index.md if present
+ if rel_path == "index.md":
+ lines = [
+ l for l in raw_content.splitlines()
+ if not l.startswith("> **LLM Context**:")
+ ]
+ raw_content = "\n".join(lines).rstrip()
+
+ content_blocks.append(raw_content)
+
+ full_text = "\n\n---\n\n".join(content_blocks).rstrip() + "\n"
+
+ # Write to site/llms.md for deployment
+ site_dir.mkdir(parents=True, exist_ok=True)
+ site_llms = site_dir / "llms.md"
+ site_llms.write_text(full_text, encoding="utf-8")
+ print(f"[SUCCESS] Written {site_llms} ({len(full_text):,} bytes).")
+
+
+if __name__ == "__main__":
+ build_llms_md(REPO_ROOT)
diff --git a/examples/getting_started/run_analysis.py b/examples/getting_started/run_analysis.py
index cb96b03..3940522 100644
--- a/examples/getting_started/run_analysis.py
+++ b/examples/getting_started/run_analysis.py
@@ -59,8 +59,8 @@ def simulate_spatial_data(
n_spots = side * side
# 1. 2D regular lattice coordinates (row-major: y = row, x = col)
- x = np.tile(np.arange(side), side)
- y = np.repeat(np.arange(side), side)
+ gx, gy = np.meshgrid(np.arange(side), np.arange(side))
+ x, y = gx.ravel(), gy.ravel()
coords = np.column_stack([x, y])
# 2. Ground-truth spatial factor activities (L in R^(N x K))
diff --git a/mkdocs.yml b/mkdocs.yml
index 926127e..5684921 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -26,7 +26,7 @@ plugins:
show_source: false
show_root_heading: true
show_root_toc_entry: true
- heading_level: 2
+ heading_level: 3
nav:
- Overview: index.md
@@ -41,5 +41,5 @@ extra:
link: https://github.com/shimlab/WaveFactor
name: GitHub Repository
- icon: fontawesome/solid/robot
- link: llms.md
+ link: https://shimlab.github.io/WaveFactor/llms.md
name: LLM-friendly Documentation (llms.md)
diff --git a/wavefactor/model.py b/wavefactor/model.py
index b2a3f8e..c806053 100644
--- a/wavefactor/model.py
+++ b/wavefactor/model.py
@@ -59,9 +59,9 @@ class WaveFactor(BaseEstimator):
beta_t : Optional[np.ndarray], default=None
Rate hyperparameter matrix for factor precision Gamma prior, shape (R, K).
alpha_tau : Optional[np.ndarray], default=None
- Shape hyperparameter matrix for noise precision Gamma prior, shape (R, G).
+ Shape hyperparameter matrix for noise precision Gamma prior, shape (R, G) where G = n_features.
beta_tau : Optional[np.ndarray], default=None
- Rate hyperparameter matrix for noise precision Gamma prior, shape (R, G).
+ Rate hyperparameter matrix for noise precision Gamma prior, shape (R, G) where G = n_features.
max_iter : int, default=1000
Maximum CAVI optimization iterations per start.
tol : float, default=1e-5
diff --git a/wavefactor/results.py b/wavefactor/results.py
index bfe59d0..1dc6fd1 100644
--- a/wavefactor/results.py
+++ b/wavefactor/results.py
@@ -78,12 +78,12 @@ def grid_shape(self) -> Tuple[int, int]:
@property
def grid_x(self) -> Optional[np.ndarray]:
- """1D integer grid x-coordinates (columns in 0..W-1)."""
+ """1D integer grid x-coordinates (columns in 0..L-1)."""
return self.spot_grid_coords[:, 0] if self.spot_grid_coords is not None else None
@property
def grid_y(self) -> Optional[np.ndarray]:
- """1D integer grid y-coordinates (rows in 0..H-1)."""
+ """1D integer grid y-coordinates (rows in 0..L-1)."""
return self.spot_grid_coords[:, 1] if self.spot_grid_coords is not None else None
@property
@@ -124,7 +124,7 @@ def n_resolutions(self) -> int:
@property
def spatial_factor_maps(self) -> np.ndarray:
"""
- 2D Continuous Spatial Factor Activity Maps S in R^(N_y x N_x x K),
+ 2D Continuous Spatial Factor Activity Maps S in R^(L x L x K),
reconstructed via automated 2D Inverse Wavelet Transform (IDWT).
"""
if self._spatial_factor_maps is None: