# Causal Discovery

Orxaq discovers causal structure from data using multiple algorithms and a consensus voting mechanism.

## Algorithms

**PC Algorithm** (constraint-based) — Starts with a fully connected graph and removes edges that fail conditional independence tests. Then orients remaining edges using Meek's rules: collider detection and acyclicity enforcement.

**GES Algorithm** (score-based) — Starts with an empty graph and greedily adds edges that improve the BIC score (forward phase), then removes edges that don't help (backward phase).

**Consensus** — Runs both algorithms and includes edges where a configurable threshold of algorithms agree. This reduces false positives from any single algorithm.

## CLI Usage

Run PC algorithm only:

```bash
orxaq discover --variables unemployment_rate,income,credit_score
```

Run multi-algorithm consensus:

```bash
orxaq discover --consensus --variables unemployment_rate,income,credit_score
```

## Validation

After discovery, validate the learned DAG against the data using d-separation tests:

```bash
orxaq validate
```

This tests every conditional independence implied by the DAG. Violations (where the DAG implies independence but the data shows dependence) are reported with p-values.

## Try It: Discovery Pipeline

```python
from orxaq.intelligence import ConsensusEngine
from orxaq.credit.ontology import build_credit_ontology
from orxaq.credit.synthetic import CreditDataGenerator

dag = build_credit_ontology()
gen = CreditDataGenerator(dag)
data = gen.generate(n=500, seed=42)

# Convert to variable -> values mapping
variables = list(data[0].keys())[:3]
var_data = {v: [row[v] for row in data] for v in variables}

engine = ConsensusEngine()
result = engine.discover(var_data, variables)

for edge in result.edges:
    print(f"{edge.source} -> {edge.target} (support: {edge.support_count})")
```

## Refutation

Validate discovered causal effects with refutation tests:

- **Placebo test** — Permute the treatment variable and re-estimate the effect. A genuine causal effect should vanish under permutation.
- **Subset stability** — Re-estimate the effect on random subsets of the data. Stable effects produce consistent estimates across subsets.
