Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions .github/workflows/docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 7 additions & 2 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

---
Expand Down
7 changes: 4 additions & 3 deletions docs/getting_started.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
2 changes: 1 addition & 1 deletion docs/input_output.md
Original file line number Diff line number Diff line change
Expand Up @@ -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). |

---
Expand Down
258 changes: 258 additions & 0 deletions docs/scripts/generate_llms.py
Original file line number Diff line number Diff line change
@@ -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"<article[^>]*class=\"[^\"]*md-content__inner[^\"]*\"[^>]*>(.*?)</article>",
html,
re.DOTALL,
)
if not match:
raise ValueError(f"Could not locate main <article> 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)
4 changes: 2 additions & 2 deletions examples/getting_started/run_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
Loading
Loading