ctxawr 0.2.0
CTXAWR 8-Dimensional Semantic Coordinate System
License: Apache-2.0
Requires Python: >=3.10
Keywords: 8d, context, coordinates, embeddings, encoding, retrieval, semantic

# ctxawr

8-Dimensional Semantic Coordinate System for context-aware retrieval.

CTXAWR encodes text into compact 8D coordinates (32 bits / 4 bytes) that capture semantic properties across eight dimensions: Domain, Concept, Intensity, Temporal, Scope, Direction, Valence, and Certainty.

## Installation

```bash
pip install ctxawr
```

For development:

```bash
pip install ctxawr[dev]
```

## Quick Start

```python
from ctxawr import Coordinate8D, encode, pack, unpack

# Encode text into an 8D coordinate
coord = encode("The server crashed with a critical error")
print(coord)  # e.g. Coordinate8D(15900163)

# Pack to 4 bytes for transmission
data = pack(coord)
assert len(data) == 4

# Unpack back
recovered = unpack(data)
assert recovered == coord
```

## Core Concepts

### Coordinate8D

An immutable 8-dimensional coordinate where each dimension is an integer 0-9:

| Dim | Name      | Range | Description                    |
|-----|-----------|-------|--------------------------------|
| D1  | Domain    | 0-9   | Subject area (system, data...) |
| D2  | Concept   | 0-9   | What kind of thing              |
| D3  | Intensity | 0-9   | Severity/importance level       |
| D4  | Temporal  | 0-9   | Time reference (past..future)   |
| D5  | Scope     | 0-9   | Breadth (local..global)         |
| D6  | Direction | 0-9   | Data flow direction             |
| D7  | Valence   | 0-9   | Sentiment (negative..positive)  |
| D8  | Certainty | 0-9   | Confidence level                |

```python
from ctxawr import Coordinate8D

# Create directly
c = Coordinate8D(5, 1, 4, 2, 5, 5, 6, 6)

# From string
c = Coordinate8D.from_string("51425566")

# From tuple
c = Coordinate8D.from_tuple((5, 1, 4, 2, 5, 5, 6, 6))
```

### Encoding

Three encoding modes:

```python
from ctxawr import encode, encode_detailed, encode_llm

# Keyword-based (deterministic, no dependencies)
coord = encode("The server crashed with a fatal error")

# With provenance (shows which method classified each dimension)
result = encode_detailed("The server crashed with a fatal error")
print(result.coordinate)  # Coordinate8D(...)
print(result.methods)     # ('keyword', 'keyword', ..., 'pattern', 'hash')

# LLM-assisted (bring your own classifier)
def my_llm(text: str) -> Coordinate8D:
    # Call your LLM here
    return Coordinate8D(1, 2, 3, 4, 5, 6, 7, 8)

coord = encode_llm("some text", my_llm)
```

### Packing (32-bit Wire Format)

Every coordinate packs into exactly 4 bytes (32 bits), regardless of content:

```python
from ctxawr import pack, unpack

data = pack(coord)       # -> bytes (length 4)
coord = unpack(data)     # -> Coordinate8D
```

### Semantic Delta Sync (SDS)

Transfer semantic state changes in exactly 4 bytes:

```python
from ctxawr import (
    compute_delta, apply_delta, compose_deltas,
    pack_sds_payload, unpack_sds_payload, sds_bandwidth_ratio,
)

# Compute delta between two states
source = encode("System starting up")
target = encode("System running normally")
delta = compute_delta(source, target)

# Apply delta to reconstruct target
reconstructed = apply_delta(source, delta)
assert reconstructed == target

# Compose delta chains: A->B + B->C = A->C
delta_ac = compose_deltas(delta_ab, delta_bc)

# Canonical wire format (lossless, 4 bytes)
payload = pack_sds_payload(target)
received = unpack_sds_payload(payload)

# Bandwidth ratio: 25KB doc synced in 4 bytes = 6,456x compression
ratio = sds_bandwidth_ratio(25_824)
```

### Similarity & Distance

```python
from ctxawr import (
    l2_distance, l1_distance, chebyshev_distance,
    cosine_similarity, cosine_distance,
    dimension_match, get_metric,
)

a = encode("The server crashed")
b = encode("The system failed")

# Distance metrics
l2_distance(a, b)       # Euclidean distance
l1_distance(a, b)       # Manhattan distance
chebyshev_distance(a, b)  # Max dimension difference
cosine_similarity(a, b)   # Cosine similarity [-1, 1]

# Check if specific dimensions match
dimension_match(a, b, dimensions=(1, 7))            # D1 and D7 exact match
dimension_match(a, b, dimensions=(1,), tolerance=1)  # D1 within +/-1

# Get metric by name
metric = get_metric("l2")  # Returns l2_distance function
```

### Search

```python
from ctxawr import (
    range_filter, nearest_neighbors, radius_search,
    two_stage_search, batch_nearest_neighbors, hybrid_search,
)

corpus = [encode(text) for text in my_texts]
query = encode("Find security-related errors")

# k-NN search
results = nearest_neighbors(query, corpus, k=5)
# Returns: [(index, distance), ...]

# Range filter by dimension constraints
indices = range_filter(corpus, {1: (4, 4), 7: (0, 2)})
# D1=4 (security) AND D7<=2 (negative valence)

# Two-stage Vector+ search: pre-filter then refine
results = two_stage_search(
    query, corpus,
    constraints={1: (3, 5)},  # Stage 1: D1 in [3,5]
    k=10,                      # Stage 2: top-10 by L2
)

# Weighted hybrid search
results = hybrid_search(
    query, corpus,
    dimension_weights={1: 3.0, 7: 2.0},  # Emphasize Domain and Valence
    k=5,
)
```

## API Reference

### Types

- `Coordinate8D(d1, d2, d3, d4, d5, d6, d7, d8)` - Immutable 8D coordinate
- `EncodingResult` - Encoding result with `.coordinate` and `.methods`
- `NUM_DIMENSIONS` = 8
- `DIMENSION_NAMES` - Tuple of dimension name strings

### Encoding

| Function | Description |
|----------|-------------|
| `encode(text, *, context_id=None)` | Text to Coordinate8D (keyword + hash) |
| `encode_detailed(text, *, context_id=None)` | Text to EncodingResult with provenance |
| `encode_llm(text, llm_fn)` | Text to Coordinate8D via LLM callback |

### Packing

| Function | Description |
|----------|-------------|
| `pack(coord)` | Coordinate8D to 4 bytes |
| `unpack(data)` | 4 bytes to Coordinate8D |

### Delta Sync

| Function | Description |
|----------|-------------|
| `compute_delta(source, target)` | Signed delta vector |
| `apply_delta(source, delta)` | Apply delta to get target |
| `compose_deltas(delta_ab, delta_bc)` | Chain deltas: A->C |
| `pack_delta(delta)` | Delta to 4 bytes (clamped) |
| `unpack_delta(data)` | 4 bytes to delta vector |
| `pack_sds_payload(coord)` | Lossless coordinate payload |
| `unpack_sds_payload(data)` | Unpack lossless payload |
| `sds_bandwidth_ratio(content_bytes)` | Compression ratio |

### Similarity

| Function | Description |
|----------|-------------|
| `l2_distance(a, b)` | Euclidean distance |
| `l1_distance(a, b)` | Manhattan distance |
| `chebyshev_distance(a, b)` | Max-dimension distance |
| `cosine_similarity(a, b)` | Cosine similarity |
| `cosine_distance(a, b)` | 1 - cosine_similarity |
| `dimension_match(a, b, *, dimensions, tolerance)` | Dimension-wise match |
| `get_metric(name)` | Get metric function by name |

### Search

| Function | Description |
|----------|-------------|
| `range_filter(coords, constraints)` | Filter by dimension ranges |
| `nearest_neighbors(query, candidates, k)` | k-NN search |
| `radius_search(query, candidates, radius)` | Radius search |
| `two_stage_search(query, coords, *, constraints, k)` | Vector+ dual-mode |
| `batch_nearest_neighbors(queries, candidates, k)` | Batch k-NN |
| `hybrid_search(query, coords, *, dimension_weights, k)` | Weighted search |

## Requirements

- Python >= 3.10
- Zero runtime dependencies

## License

Apache License 2.0 — see [LICENSE](LICENSE) for details.