# COGILES Feature Ideas

> Brainstormed by a panel of three experts: Graph Theory & Algorithms, API Design & Developer Experience, and Domain Applications.

---

## Quick Ideas (Breadth)

### Graph Theory & Algorithms

| # | Idea | Description |
|---|------|-------------|
| 1 | **Color-Induced Subgraph Extraction** | Extract the induced subgraph containing only specific colors (e.g., all red and green nodes with edges between them). |
| 2 | **Color-Aware Isomorphism** | Check if two colored graphs are isomorphic respecting node colors — stricter than fingerprint comparison. |
| 3 | **Motif / Subgraph Pattern Matching** | Find all occurrences of a small COGILES pattern (e.g., `R(G)B`) as a subgraph in a larger graph. |
| 4 | **Connected Component Analysis by Color** | Decompose a graph into components and label them by dominant color or color distribution histogram. |
| 5 | **Degree Distribution by Color** | Report degree statistics grouped by node color (mean/median/max degree per color). |
| 6 | **Random Colored Graph Generator** | Generate random connected colored graphs with configurable degree distribution and color constraints. |
| 7 | **Color Palette Coverage** | Calculate what fraction of the 17-color palette is used and suggest missing colors for diversity. |

### Developer Experience & API Design

| # | Idea | Description |
|---|------|-------------|
| 8 | **Graph Builder API** | Fluent, chainable builder for constructing graphs programmatically without touching NetworkX directly. |
| 9 | **Batch Fingerprinting** | `fingerprint_batch(graphs)` to compute fingerprints for many graphs efficiently with shared state. |
| 10 | **Color Discovery Utilities** | Helpers like `list_colors()`, `get_color_info(symbol)` to explore the palette programmatically. |
| 11 | **COGILES String Validator** | `is_valid(string) -> bool` — check syntax without building a graph, useful for input filtering. |
| 12 | **Similarity Search** | `find_similar(query, candidates, threshold)` to batch-compare one graph against many. |
| 13 | **Export to DOT/GML** | Convert COGILES graphs to standard graph formats for interoperability with Graphviz, yEd, etc. |
| 14 | **Graph Statistics Helper** | `stats(graph)` returning a dict with node/edge counts, density, diameter, components, is_tree, etc. |

### Domain Applications

| # | Idea | Description |
|---|------|-------------|
| 15 | **Graph Constraint Validation** | Declarative rules engine (e.g., "red nodes max degree 2", "no B-Y edges") for puzzle/game validation. |
| 16 | **Wildcard Pattern Matching** | Support wildcard colors (`X`) in pattern strings for flexible subgraph search. |
| 17 | **Custom Color Palettes** | Let users define their own palette beyond the fixed 17 colors for domain-specific applications. |
| 18 | **ASCII/Unicode Visualization** | Terminal-based graph drawing for environments without matplotlib. |
| 19 | **Multigraph / Weighted Edge Support** | Extend notation to support labeled or weighted edges for richer graph representations. |

---

## Detailed Ideas (Depth)

### 1. Color-Aware Structural Isomorphism

**Expert:** Graph Theory & Algorithms

**Description:** Two colored graphs are isomorphic if there exists a node mapping that preserves both edges AND color attributes. This is stricter than Jaccard similarity (which can have false positives) and gives a definitive yes/no answer.

**Use cases:**
- Determine if two COGILES strings represent the same colored structure
- Deduplicate graphs in a collection
- Verify that transformations preserve structure

**API sketch:**
```python
def are_color_isomorphic(G1: nx.Graph, G2: nx.Graph) -> bool:
    """Check if G1 and G2 are isomorphic with matching node colors."""

def find_color_isomorphism(G1: nx.Graph, G2: nx.Graph) -> dict[int, int] | None:
    """Return a color-preserving node mapping if isomorphic, else None."""

# Usage
G1 = cogiles.parse("R(G)(B)")
G2 = cogiles.parse("R(B)(G)")
are_color_isomorphic(G1, G2)  # True — same structure under permutation

G3 = cogiles.parse("R(Y)(B)")
are_color_isomorphic(G1, G3)  # False — different colors
```

**Implementation notes:**
- Wrap NetworkX's `GraphMatcher` with a color-equality constraint on `node_match`
- Pre-filter with color histogram comparison for fast rejection
- Realistic scope: mostly thin wrapper around existing NetworkX machinery

---

### 2. Weighted Color-Topological Distance

**Expert:** Graph Theory & Algorithms

**Description:** A continuous distance metric combining graph edit distance with color dissimilarity. Unlike Jaccard (binary overlap), this produces a value in `[0, ∞)` that captures both structural and chromatic differences. Enables clustering and ranking.

**Use cases:**
- Rank graphs by proximity to a query
- Cluster colored graphs into families
- Quantify how much a transformation changed a graph

**API sketch:**
```python
def color_topological_distance(
    G1: nx.Graph,
    G2: nx.Graph,
    *,
    alpha: float = 0.5,          # 0 = pure color, 1 = pure topology
    color_metric: str = "euclidean",  # or "hamming", "label"
) -> float:
    """Distance in [0, ∞). 0 = identical."""

# Usage
G1 = cogiles.parse("RRR")
G2 = cogiles.parse("RGR")   # same topology, one color changed
G3 = cogiles.parse("RRRR")  # different topology

d12 = color_topological_distance(G1, G2)  # small
d13 = color_topological_distance(G1, G3)  # larger
```

**Implementation notes:**
- Leverage NetworkX's `graph_edit_distance` with custom node substitution costs based on RGB distance
- Normalize topology and color costs before blending with `alpha`
- For large graphs, use heuristic approximation to avoid factorial complexity

---

### 3. Graph Builder API

**Expert:** Developer Experience & API Design

**Description:** A fluent, chainable builder for constructing COGILES graphs programmatically. Eliminates the need to know NetworkX internals or COGILES node attribute conventions (`color`, `symbol`, `color_name`).

**Use cases:**
- Programmatic graph construction in tests and scripts
- Interactive exploration in notebooks/REPL
- Educational settings where learning the string notation is secondary

**API sketch:**
```python
from cogiles import GraphBuilder

# Fluent chain
G = (
    GraphBuilder()
    .add_node("R")              # node 0
    .add_node("G")              # node 1
    .add_node("B")              # node 2
    .add_edge(0, 1)
    .add_edge(0, 2)
    .build()
)
cogiles.encode(G)  # "R(G)(B)"

# Star shortcut
G = (
    GraphBuilder()
    .add_node("R")
    .add_node("G").add_node("G").add_node("G")
    .add_edges(0, [1, 2, 3])
    .build()
)

# From symbols
G = GraphBuilder.from_symbols("RGB").build()  # chain R-G-B
```

**Implementation notes:**
- Validate symbols against `SYMBOL_MAP` on `add_node()` for early error detection
- Store nodes/edges in internal lists, construct `nx.Graph` with proper attributes in `build()`
- Return `self` from mutation methods for chaining; `add_node()` also returns the node ID
- Small, self-contained module — no new dependencies

---

### 4. Graph Introspection & Iteration Utilities

**Expert:** Developer Experience & API Design

**Description:** Convenience functions for querying and traversing colored graphs without requiring NetworkX expertise. Color-centric queries, quick statistics, and efficient iterators.

**API sketch:**
```python
import cogiles

G = cogiles.parse("R(G)(B)(Y).R(P)(T)")

# Quick stats
cogiles.stats(G)
# → {"nodes": 7, "edges": 6, "components": 2, "density": 0.29,
#     "is_tree": False, "is_connected": False, "diameter": None}

# Color queries
cogiles.nodes_by_color(G, "R")           # → [0, 4]
cogiles.color_distribution(G)            # → {"R": 2, "G": 1, "B": 1, ...}
cogiles.neighbors_by_color(G, 0, "G")    # → [1]

# k-nearest neighbors
cogiles.knn(query, candidates, k=5)      # → [(index, similarity), ...]
```

**Implementation notes:**
- Thin wrappers around NetworkX functions with COGILES-attribute awareness
- `stats()` computes common properties in one pass
- `knn()` reuses `FingerprintGenerator` across all candidates for efficiency

---

### 5. Subgraph Pattern Matching

**Expert:** Domain Applications

**Description:** Find all occurrences of a COGILES pattern within a larger graph, with optional wildcard colors. Returns match locations as node ID sets.

**Use cases:**
- Puzzle solving: find and highlight forbidden/winning patterns
- Motif discovery in colored networks
- Educational tools: show where a student's graph contains a specific structure

**API sketch:**
```python
pattern = "R(G)(B)"
matches = cogiles.find_pattern(G, pattern)
for m in matches:
    print(m.nodes, m.subgraph)

# Wildcard colors
matches = cogiles.find_pattern(G, "X(X)(X)")  # any star-3

# Count triangles
triangles = cogiles.find_pattern(G, "R-1RR-1")
```

**Implementation notes:**
- Use NetworkX's VF2 subgraph isomorphism with `node_match` on color
- Wildcard `X` skips the color constraint for that node
- Return match objects with node mapping and induced subgraph
- Cache compiled patterns for repeated queries

---

### 6. Graph Constraint Validation System !!!

**Expert:** Domain Applications

**Description:** A declarative system for defining and enforcing rules on colored graphs. Define constraints like degree limits per color, forbidden edge-color pairs, structural properties (tree, bipartite), and node count bounds. Validate any graph against a constraint set.

**Use cases:**
- Puzzle/game design: enforce valid configurations
- Educational CSP exercises
- Network design rule checking

**API sketch:**
```python
constraints = cogiles.Constraints()
constraints.add_degree_limit("R", max_degree=2)
constraints.add_forbidden_edge("B", "Y")
constraints.add_node_count("G", min_count=1, max_count=3)
constraints.add_property("is_tree")

result = constraints.validate(G)
if not result.valid:
    print(result.violations)  # list of human-readable violation descriptions
```

**Implementation notes:**
- `Constraints` class stores rules as a list of callable predicates
- Each rule returns a `Violation` or `None`
- Leverage NetworkX properties (`nx.is_tree`, `nx.is_bipartite`) for structural checks
- Keep the rule set extensible via `add_custom(predicate_fn)`
