# A quote snapshot
Look for the right-sided search and the subtraction by one. An event exactly on the decision tick belongs to the information set. The graph construction retains both the quote side and the source timestamp, so a later user can audit the transformation.
## Source walkthrough
The excerpt is from research/quote_graph.py in the PhaseWeave implementation.
```
def snapshot_graph(quotes, at):
    import pandas as pd

    if at.tzinfo is None:
        raise ValueError("snapshot time requires an explicit UTC offset")
    at = at.astimezone(timezone.utc)
    nodes = set()
    edges = []
    for pair, frame in sorted(quotes.items()):
        base, counter = pair[:3], pair[3:]
        nodes.update((base, counter))
        position = int(frame.index.searchsorted(pd.Timestamp(at), side="right")) - 1
        if position < 0:
            continue
        timestamp = frame.index[position].to_pydatetime()
        bid, ask = frame.iloc[position][["bid", "ask"]]
        for origin, destination, side, log_rate in (
            (base, counter, "bid", math.log(bid)),
            (counter, base, "inverse_ask", -math.log(ask)),
        ):
            edges.append({
                "origin": origin, "destination": destination, "pair": pair,
                "side": side, "quote_time_utc": timestamp.isoformat(),
                "log_rate": log_rate,
            })
    return {
        "schema": "phaseweave.quote_graph.v1",
        "snapshot_time_utc": at.isoformat(),
        "nodes": [{"id": currency, "type": "currency"} for currency in sorted(nodes)],
        "edges": edges,
    }
```
## Check your interpretation
Change one input quote to occur a microsecond after the decision time. If no earlier quote exists, the pair should have no edges at that tick. Replacing the right-sided search with nearest-neighbor selection could import that future observation.

# An exhaustive triangle verifier
The first stage rejects malformed graphs. A repeated endpoint pair is ambiguous under this schema because there is no venue dimension in the lookup key. The second stage quotients simple directed triangles by rotation. The exact score uses a high-accuracy sum and one cost deduction per leg.
## Source walkthrough
The excerpt is from research/quote_graph.py in the PhaseWeave implementation.
```
def audit_triangles(graph, *, max_age_ms, extra_cost_bps):
    """Enumerate each directed simple triangle modulo cyclic rotation."""
    if not (math.isfinite(max_age_ms) and math.isfinite(extra_cost_bps)):
        raise ValueError("age and cost must be finite")
    if max_age_ms < 0 or extra_cost_bps < 0:
        raise ValueError("age and cost must be nonnegative")
    if graph["schema"] != "phaseweave.quote_graph.v1":
        raise ValueError("unexpected graph schema")
    timestamp = datetime.fromisoformat(graph["snapshot_time_utc"])
    if timestamp.tzinfo is None:
        raise ValueError("snapshot requires an explicit UTC offset")
    nodes = sorted(node["id"] for node in graph["nodes"])
    if len(set(nodes)) != len(nodes):
        raise ValueError("duplicate graph node")
    by_endpoints = {}
    for edge in graph["edges"]:
        start, end = edge["origin"], edge["destination"]
        if start == end or start not in nodes or end not in nodes:
            raise ValueError("edge endpoints must be distinct nodes in the graph")
        if (start, end) in by_endpoints:
            raise ValueError("duplicate directed edge")
        if not math.isfinite(edge["log_rate"]):
            raise ValueError("edge log-rate must be finite")
        quote_time = datetime.fromisoformat(edge["quote_time_utc"])
        if quote_time.tzinfo is None:
            raise ValueError("quote requires an explicit UTC offset")
        age_ms = (timestamp - quote_time).total_seconds() * 1000
        if age_ms < 0:
            raise ValueError("graph contains a future quote")
        by_endpoints[start, end] = (edge, age_ms)

    triangles = []
    for first, second, third in permutations(nodes, 3):
        if first != min(first, second, third):
            continue
        key = [(first, second), (second, third), (third, first)]
        available = [by_endpoints.get(endpoints) for endpoints in key]
        complete = all(item is not None and item[1] <= max_age_ms for item in available)
        margin = None
        if complete:
            margin = 1e4 * math.fsum(item[0]["log_rate"] for item in available) - 3 * extra_cost_bps
        triangles.append({
            "cycle": [first, second, third, first],
            "status": "indicative_quote_margin" if complete else "unavailable_or_stale",
            "net_log_margin_bps": margin,
        })
    return {
        "snapshot_time_utc": timestamp.isoformat(), "extra_log_cost_bps_per_leg": extra_cost_bps,
        "max_quote_age_ms": max_age_ms, "triangles": triangles,
    }
```
## Check your interpretation
On four distinct nodes there are eight directed three-cycles modulo rotation, allowing both orientations. Check the count by choosing three nodes in four ways and two orientations. In a partial graph the verifier still reports the candidate with a missing score.

# Constructing a timestamp stream
The raw source files are immutable. The analysis reads quote rows, checks their digest and aggregates ties before performing time-based joins. The grouping rule is part of the observation model. A later policy using the final row of a tie would define a different source series.
## Source walkthrough
The excerpt is from research/histdata_quality.py in the PhaseWeave implementation.
```
def asof_quotes(path, expected_sha256):
    with path.open("rb") as source:
        digest = hashlib.file_digest(source, "sha256").hexdigest()
    if digest != expected_sha256:
        raise ValueError(f"archive checksum mismatch: {path.name}")
    with ZipFile(path) as archive:
        member, = [name for name in archive.namelist() if name.upper().endswith(".CSV")]
        with archive.open(member) as data:
            table = pd.read_csv(data, names=["stamp", "bid", "ask", "volume"], dtype={"stamp": str})
    # Provider's timestamps use fixed EST throughout the year.
    utc = pd.to_datetime(table.pop("stamp"), format="%Y%m%d %H%M%S%f", utc=True) + pd.Timedelta(hours=5)
    table.index = pd.DatetimeIndex(utc)
    stamps = table.index.as_unit("ns").asi8
    lag = (np.maximum.accumulate(stamps) - stamps) // 1_000_000
    groups = table.groupby(level=0, sort=True)
    quotes = groups.agg(bid=("bid", "min"), ask=("ask", "max"))
    conflicts = groups.agg(
        bid_min=("bid", "min"), bid_max=("bid", "max"), ask_min=("ask", "min"), ask_max=("ask", "max"),
    )
    stats = {
        "max_source_order_lag_ms": int(lag.max()),
        "median_source_order_lag_ms_when_lagged": float(np.median(lag[lag > 0])) if (lag > 0).any() else 0.0,
        "duplicate_timestamp_rows": int(len(table) - len(quotes)),
        "conflicting_timestamp_groups": int(
            ((conflicts.bid_min != conflicts.bid_max) | (conflicts.ask_min != conflicts.ask_max)).sum()
        ),
        "nonzero_volume_rows": int((table.volume != 0).sum()),
    }
    return quotes, stats
```
## Check your interpretation
Consider tied bids 99 and 100 with asks 102 and 101. The conservative envelope is 99/102. This wider pair reduces both directed edge rates relative to 100/101. A two-leg round trip reflects the entire difference.

# Sampling a supported window
The eligibility predicate is a conjunction over all three quote streams at the decision and forecast ticks. A separate condition checks that the future records arrived after the anchor. Sampling follows eligibility. Holding a fixed seed while changing the eligibility definition changes the population sampled.
## Source walkthrough
The excerpt is from research/curate_margin.py in the PhaseWeave implementation.
```
def verify_window(anchor, left, right):
    return (anchor - (LOOKBACK - 1) > left) & (anchor + HORIZON < right - 1)
```
```
def triangle_data(streams, left, right, rng, limit):
    stamps = [stream.index.as_unit("ns").asi8 for stream in streams]
    tick_grid = np.arange(left, right, dtype=np.int64)
    nanoseconds = tick_grid * NS_PER_S
    rows = [np.searchsorted(entry, nanoseconds, side="right") - 1 for entry in stamps]
    observed = np.stack([entry[np.maximum(index, 0)] for entry, index in zip(stamps, rows, strict=True)])
    age = (nanoseconds - observed) / 1_000_000
    valid = (np.stack(rows) >= 0) & (age >= 0) & (age <= AGE_MS)
    eligible = np.zeros(len(tick_grid), dtype=bool)
    eligible[:-HORIZON] = (
        valid[:, :-HORIZON].all(axis=0) & valid[:, HORIZON:].all(axis=0) &
        (observed[:, HORIZON:] > nanoseconds[:-HORIZON]).all(axis=0)
    )
    eligible &= verify_window(tick_grid, left, right)
    selected = np.flatnonzero(eligible)
    if len(selected) > limit:
        selected = np.sort(rng.choice(selected, limit, replace=False))
    if not len(selected):
        raise ValueError("no supported windows in the requested fold")
    offsets = np.arange(-(LOOKBACK-1), 1)
    history = selected[:, None] + offsets
    future = selected + HORIZON

    def rates(indices):
        e01, e12, e02 = [
            np.log(stream.to_numpy()[np.maximum(row[indices], 0)]) * 1e4
            for stream, row in zip(streams, rows, strict=True)
        ]
        l01, l12 = e01[..., 0], e12[..., 0]
        return np.stack((
            np.zeros_like(l01), l01 - e01[..., 1],
            np.zeros_like(l12), l12 - e12[..., 1],
            e02[..., 0] - l01 - l12, l01 + l12 - e02[..., 1],
        ), axis=-1)

    logs = rates(history)
    # An edge can use the chosen unit gauge only when both gauge-tree
    # quotes exist and meet the same age rule at that frame.
    gauge_known = valid[:2, history].all(axis=0)[..., None]
    available = np.moveaxis(np.repeat(valid[:, history], 2, axis=0), 0, -1) & gauge_known
    age_fraction = np.moveaxis(np.repeat(np.clip(age[:, history] / AGE_MS, 0, 1), 2, axis=0), 0, -1)
    features = np.stack((
        np.where(available, logs, 0), np.where(available, age_fraction, 1), available,
    ), axis=-1).astype(np.float32)
    targets = rates(future)
    margins = np.stack((targets[:, 5], targets[:, [1, 3, 4]].sum(axis=1)), axis=-1)
    margins = (margins - 3 * FEES_BPS).astype(np.float32)
    past = logs[:, -1]
    baseline = (np.stack((past[:, 5], past[:, [1, 3, 4]].sum(axis=1)), axis=-1) - 3 * FEES_BPS).astype(np.float32)
    return {"features": features, "margin": margins, "anchor_utc_s": tick_grid[selected], "persistence": baseline}
```
## Check your interpretation
Trace the shapes through the nested rates function. It accepts both a two-dimensional array of history indices and a one-dimensional array of future indices. Summing along the wrong axis can produce plausible numbers of the wrong shape when a batch size happens to equal an edge count.

# Forecast inputs, masks and pooling
One batch dimension is temporarily expanded into batch times history for spatial processing. The edge mask contributes to outgoing counts, token masking and pooling. Unavailable edge logs are zeroed at curation time; the numeric zero alone cannot carry the distinction between an absent edge and a gauge-fixed tree edge.
## Source walkthrough
The excerpt is from research/forecast.py in the PhaseWeave implementation.
```
def forward(self, features, persistence):
    batch, history, edge_count, channels = features.shape
    values = features.reshape(batch * history, edge_count, channels)
    edge_ok = values[..., 2] > .5
    graph_count = batch * history
    counts = edge_ok.to(values.dtype) @ self.outgoing
    log_rates = values[..., 0].clamp(-20, 20) * 0.2
    node_features = torch.stack(((log_rates @ self.outgoing) / counts.clamp_min(1), counts / 2), dim=-1)
    attr = torch.cat([log_rates.unsqueeze(-1), values[..., 1:]], dim=-1)
    graph = self.batch_type(
        node_features=node_features, edge_features=attr,
        edge_index=self.endpoints.unsqueeze(0).expand(graph_count, -1, -1),
        node_mask=torch.ones(graph_count, 3, device=features.device, dtype=torch.bool),
        edge_mask=edge_ok, edge_identity_ids=self.edge_ids.unsqueeze(0).expand(graph_count, -1),
    )
    tokens = self.tokenizer(graph)
    hidden = tokens.tokens
    mask = self.attention_mask(tokens.token_mask)
    for layer in self.spatial:
        hidden = layer(hidden, mask=mask)
    pooled = (hidden * tokens.token_mask.unsqueeze(-1)).sum(dim=1) / tokens.token_mask.sum(dim=1, keepdim=True)
    if self.phase_patch is not None:
        pooled = pooled + self.phase_patch(log_rates)
    temporal = pooled.reshape(batch, history, -1) + self.position[:history]
    for layer in self.temporal:
        temporal = layer(temporal)
    return persistence + self.readout(temporal[:, -1])
```
## Check your interpretation
An isolated valid node token remains in the pooling denominator. Removing invalid edge features without removing them from that denominator changes the scale of the frame vector. Padding-invariance checks therefore need both the aggregation and its normalization.

# Width-scaled projective attention
The imported transformer provides the projections and gates. This wrapper centers every head vector at its largest coordinate and normalizes it. The chosen multiplier acts after this operation. The base and delta models tell the μP library which dimensions change with width.
## Source walkthrough
The excerpt is from research/forecast.py in the PhaseWeave implementation.
```
def width_scaled_attention(width, heads, config):
    from toricgt.tropical_attention import (
        AttentionResult, MultiHeadTropicalAttention, softmax_attention,
        tropical_attention, tropical_ring_attention,
    )

    class WidthScaledProjectiveAttention(MultiHeadTropicalAttention):
        def forward(self, x, mask=None, return_scores=False):
            q, k, v = [self._split_heads(part) for part in self.qkv(x).chunk(3, dim=-1)]
            q = nn.functional.normalize(q - q.amax(dim=-1, keepdim=True), dim=-1)
            k = nn.functional.normalize(k - k.amax(dim=-1, keepdim=True), dim=-1)
            # The L2-normalized projective coordinates supply the inverse-width
            # dot-product normalization. A fixed multiplier avoids an extra sqrt(d).
            kwargs = {"mask": mask, "scale": config["attention_multiplier"],
                      "return_scores": return_scores}
            if self.mode == "tropical_ring":
                result = tropical_ring_attention(q, k, v, block_size=self.ring_block_size, **kwargs)
            else:
                kernel = {"softmax": softmax_attention, "tropical": tropical_attention}[self.mode]
                result = kernel(q, k, v, **kwargs)
            output, scores = result if return_scores else (result, None)
            output = output * torch.sigmoid(self.norm_gate).view(1, self.num_heads, 1, 1)
            return AttentionResult(output=self.out(self.dropout(self._merge_heads(output))), scores=scores)

    return WidthScaledProjectiveAttention(width, heads, mode=config["attention"], ring_block_size=64)
```
```
def parameterize(model, config, modules, *, rescale_params):
    if not config.get("mup"):
        return
    from mup import set_base_shapes

    with torch.random.fork_rng(devices=[]):
        base = Forecast(dict(config, width=64), modules)
        delta = Forecast(dict(config, width=96), modules)
    set_base_shapes(model, base, delta=delta, rescale_params=rescale_params)
```
```
def create_optimizer(model, config):
    if config.get("mup"):
        from mup import MuAdamW
        return MuAdamW(model.parameters(), lr=config["learning_rate"])
    return torch.optim.AdamW(model.parameters(), lr=config["learning_rate"])
```
## Check your interpretation
Consider a head with all coordinates equal. Subtracting its maximum produces zero. A robust normalization returns a finite zero vector through its epsilon convention. Such a head can still have meaningful value vectors. Inspect empty valid masks separately.

# The simulated feature and its control
The shape of the joint tensor is batch by 3 by 3 by 3 by 3. Broadcasted phase terms provide local and nearest-neighbor contributions. Dividing by nine normalizes equal-magnitude amplitudes. Each probability marginal sums over three axes and leaves the measured axis intact.
## Source walkthrough
The excerpt is from research/cyclic_patch.py in the PhaseWeave implementation.
```
class CyclicPatch(nn.Module):
    RADIX = 3
    WIRES = 4

    def __init__(self, width, variant):
        super().__init__()
        if variant not in {"qutrit", "frozen_qutrit", "classical"}:
            raise ValueError("unknown phase ablation")
        self.variant = variant
        self.input = nn.Linear(6, self.WIRES)
        self.coupling = nn.Parameter(torch.full((self.WIRES - 1,), 0.45))
        self.output = nn.Linear(self.WIRES, width)
        if variant == "frozen_qutrit":
            self.input.requires_grad_(False)
            self.coupling.requires_grad_(False)
        values = torch.arange(self.RADIX)
        self.register_buffer("levels", values, persistent=False)
        self.register_buffer("clock_real", torch.cos(values * math.tau / self.RADIX), persistent=False)

    def quantum_measurement(self, angles):
        count = angles.shape[0]
        shape = (count,) + (self.RADIX,) * self.WIRES
        phase = torch.zeros(shape, device=angles.device)
        for wire in range(self.WIRES):
            dimensions = [1] * len(shape)
            dimensions[wire + 1] = self.RADIX
            own_slices = [count] + [1] * self.WIRES
            phase = phase + angles[:, wire].reshape(own_slices) * self.clock_real.reshape(dimensions)
        for wire in range(self.WIRES-1):
            dimensions = [1] * len(shape)
            dimensions[wire+1] = dimensions[wire+2] = self.RADIX
            overlap = (self.levels[:, None] * self.levels[None, :]) * (math.tau / self.RADIX)
            phase = phase + self.coupling[wire] * overlap.reshape(dimensions)
        scaled = torch.exp(1j * phase) / (self.RADIX ** (self.WIRES * 0.5))
        state = torch.fft.ifftn(scaled, dim=tuple(range(1, self.WIRES+1)), norm="ortho")
        probabilities = state.abs().square()
        observables = []
        for wire in range(self.WIRES):
            rest = tuple(axis for axis in range(1, self.WIRES+1) if axis != wire+1)
            measure = probabilities.sum(dim=rest)
            observables.append((measure * self.clock_real).sum(dim=1))
        return torch.stack(observables, dim=-1)

    def forward(self, values):
        angles = math.pi * torch.tanh(self.input(values)).float()
        if self.variant == "classical":
            pair = angles[:, :-1] * angles[:, 1:] * self.coupling
            zero = torch.zeros_like(angles[:, :1])
            features = torch.cos(angles + torch.cat([pair, zero], dim=1) + torch.cat([zero, pair], dim=1))
        else:
            features = self.quantum_measurement(angles)
        return self.output(features)
```
## Check your interpretation
Set the input angles and all couplings to zero for the formula. The joint state is uniform before the orthonormal inverse transform. It concentrates at the all-zero basis vector afterward, giving real clock expectation one on every wire. The output projection can change the projected result.

# A finite coordinate check
At fixed rows, seed and selected nominal multipliers the hook records the absolute mean output of the last temporal block. Each iteration's logged residual belongs to the forward pass preceding the optimizer update. The initial zero residual follows from the zero-initialized prediction head.
## Source walkthrough
The excerpt is from research/campaign.py in the PhaseWeave implementation.
```
def coordinate_check(config, source, modules):
    root_manifest = json.loads((source / "manifest.json").read_text())
    x, y, previous = dataset(source, root_manifest, "train", "cuda", limit=64)
    rows = []
    for width in (64, 128, 200, 448, 832):
        torch.manual_seed(SEEDS[0])
        settings = dict(config, width=width, learning_rate=RATES[1],
                        readout_multiplier=1.0, attention_multiplier=1.0)
        model = Forecast(settings, modules)
        parameterize(model, settings, modules, rescale_params=True)
        model.cuda()
        optimizer = create_optimizer(model, settings)
        measures = []
        observed = {}
        def capture(_module, _inputs, output):
            observed["activation_mean_abs"] = output.detach().float().abs().mean().item()
        hook = model.temporal[-1].register_forward_hook(capture)
        for index in range(4):
            optimizer.zero_grad(set_to_none=True)
            prediction = model(x, previous)
            loss = torch.nn.functional.smooth_l1_loss(prediction, y, beta=.25)
            loss.backward()
            optimizer.step()
            measures.append({
                "step": index, "activation_mean_abs": observed["activation_mean_abs"],
                "mean_abs_residual_bps": (prediction.detach() - previous).abs().mean().item(),
            })
        hook.remove()
        rows.append({"width": width, "points": measures,
                     "parameters": sum(p.numel() for p in model.parameters())})
    readings = [row["points"][-1]["activation_mean_abs"] for row in rows]
    changes = [row["points"][-1]["mean_abs_residual_bps"] for row in rows]
    for values in (readings, changes):
        if min(values) <= 0 or max(values)/min(values) > 20:
            raise ValueError("coordinate check exceeded the finite-width stability envelope")
    return rows
```
## Check your interpretation
A factor-of-twenty envelope detects catastrophic width dependence at these five widths. Smooth variation inside that envelope cannot by itself validate gradient scaling or long-run generalization. The reported table supplies the final finite readings.

# A reproducible proxy choice
The roster product places the two seeds adjacent for each setting. The minimum pair uses its index as a deterministic tie breaker. The transfer configuration inherits the first seed in the winning pair. A validation-only selection keeps subsequent holdout comparisons interpretable.
## Source walkthrough
The excerpt is from research/campaign.py in the PhaseWeave implementation.
```
def launch(config, name, args, modules):
    path = args.output / (name + ".yaml")
    with path.open("x") as destination:
        yaml.safe_dump(config, destination, sort_keys=True)
    output = args.output / name
    train(Namespace(config=path, dataset=args.dataset, output=output), modules)
    result = json.loads((output / "metrics.json").read_text())
    return {"run": name, "config": config, "parameters": result["parameters"],
            "best_validation": min(v["validation"]["mae_bps"] for v in result["validation"]),
            "checkpoint_sha256": result["best_checkpoint_sha256"]}
```
```
def main():
    parser = ArgumentParser(description=__doc__)
    parser.add_argument("--predecessor", required=True, type=Path)
    parser.add_argument("--dataset", required=True, type=Path)
    parser.add_argument("--config", required=True, type=Path)
    parser.add_argument("--output", required=True, type=Path)
    args = parser.parse_args()
    config = yaml.safe_load(args.config.read_text())
    modules = source_modules(args.predecessor)
    args.output.mkdir(parents=True, exist_ok=False)
    torch.set_num_threads(4)
    torch.set_float32_matmul_precision("high")
    torch.cuda.set_per_process_memory_fraction(0.55)
    save_json(args.output / "coordinates.json", coordinate_check(config, args.dataset, modules))
    roster = [
        dict(config, learning_rate=lr, readout_multiplier=out, attention_multiplier=attn, seed=seed)
        for lr, out, attn, seed in product(RATES, READOUTS, ATTENTION, SEEDS)
    ]
    save_json(args.output / "roster.json", roster)
    results = []
    for number, settings in enumerate(roster, 1):
        print(f"Proxy {number:02d}/24", flush=True)
        result = launch(settings, f"proxy-{number:02d}", args, modules)
        with (args.output / "completed.jsonl").open("a", encoding="utf-8") as journal:
            journal.write(json.dumps(result, allow_nan=False) + "\n")
        results.append(result)
    ranking = []
    for index in range(0, len(results), len(SEEDS)):
        group = results[index:index+len(SEEDS)]
        ranking.append((sum(row["best_validation"] for row in group) / len(group), index))
    _, winner = min(ranking)
    chosen = results[winner]["config"]
    save_json(args.output / "selection.json", {"selected": chosen, "group_scores": sorted(ranking)})
    for width in WIDTHS:
        print(f"Transfer width {width}", flush=True)
        result = launch(dict(chosen, width=width), f"transfer-{width}", args, modules)
        with (args.output / "completed.jsonl").open("a", encoding="utf-8") as journal:
            journal.write(json.dumps(result, allow_nan=False) + "\n")
```
## Check your interpretation
If each seed were ranked separately, a noisier hyperparameter group would get extra opportunities to win. The two-seed average reduces this selection effect, though two draws still provide limited information. Repeating the same seed at larger width tests width transfer under one optimization draw.

# Computing population scores
One action per row is chosen from the larger predicted margin if that margin is positive. A hit depends on the realized margin of precisely that route. The quantile of all directional absolute errors and the event hit counts summarize different parts of the output.
## Source walkthrough
The excerpt is from research/campaign_report.py in the PhaseWeave implementation.
```
def selected_records(entries, selection):
    chosen = selection["selected"]
    keys = ("learning_rate", "readout_multiplier", "attention_multiplier")
    return [
        item for item in entries if item["run"].startswith("transfer-") or
        all(item["config"][key] == chosen[key] for key in keys)
    ]
```
```
def aligned_prediction(model, data, batch_size):
    features, targets, persistence = data
    with torch.inference_mode():
        predicted = torch.cat([
            model(x, base).float().cpu()
            for x, base in zip(features.split(batch_size), persistence.split(batch_size), strict=True)
        ])
    return predicted.numpy(), targets.cpu().numpy(), persistence.cpu().numpy()
```
```
def margin_scores(predicted, observed):
    absolute = np.abs(predicted - observed)
    scores = predicted.max(axis=1)
    chosen = predicted.argmax(axis=1)
    act = scores > 0
    scored = observed[np.arange(len(observed)), chosen]
    hit = int((act & (scored > 0)).sum())
    positive_any = int((observed.max(axis=1) > 0).sum())
    return {
        "mae_bps": float(absolute.mean()),
        "rmse_bps": float(np.mean((predicted - observed) ** 2) ** 0.5),
        "p95_absolute_error_bps": float(np.quantile(absolute, 0.95)),
        "positive_windows": positive_any, "positive_proposals": int(act.sum()),
        "positive_route_hits": hit,
        "positive_proposal_precision": float(hit / int(act.sum())) if act.any() else None,
        "positive_window_recall": float(hit / positive_any) if positive_any else None,
    }
```
```
def block_interval(delta, timestamps, seed):
    day_groups = np.unique(timestamps // 86400, return_inverse=True)[1]
    counts = np.bincount(day_groups)
    totals = np.bincount(day_groups, weights=delta)
    rng = np.random.default_rng(seed)
    resample = rng.integers(len(counts), size=(2500, len(counts)))
    draws = np.sum(totals[resample], axis=1) / np.sum(counts[resample], axis=1)
    return {
        "utc_day_blocks": len(counts),
        "lower_95": float(np.quantile(draws, 0.025)),
        "upper_95": float(np.quantile(draws, 0.975)),
    }
```
## Check your interpretation
Suppose actual margins are (0.1, −0.1) and predicted margins are (−0.1, 0.1). The row has a positive opportunity and a positive proposal, yet the chosen route misses. Evaluating only whether each row contains some positive value would incorrectly count a success.

# Converting displayed book size
A positive bid size is already denominated in the input asset of the forward edge. A positive ask size is multiplied by the ask to obtain the reverse edge's input capacity. The adapter uses the provider update time and reports fetch failures separately before invoking the graph verifier.
## Source walkthrough
The excerpt is from research/workbench.py in the PhaseWeave implementation.
```
def gate_edges(pair):
    query = urlencode({"limit": 1, "currency_pair": pair})
    quote = request_json(GATE + "?" + query)
    if not quote.get("bids") or not quote.get("asks"):
        raise ValueError("empty order book")
    bid, bid_size = map(float, quote["bids"][0])
    ask, ask_size = map(float, quote["asks"][0])
    if not all(math.isfinite(item) and item > 0 for item in (bid, ask, bid_size, ask_size)) or bid > ask:
        raise ValueError("invalid order book")
    updated = datetime.fromtimestamp(int(quote["update"]) / 1e3, tz=timezone.utc).isoformat()
    base, counter = pair.split("_")
    return [
        {"origin": base, "destination": counter, "quote_time_utc": updated,
         "log_rate": math.log(bid), "displayed_input_cap": bid_size},
        {"origin": counter, "destination": base, "quote_time_utc": updated,
         "log_rate": -math.log(ask), "displayed_input_cap": ask * ask_size},
    ]
```
```
def feed_report():
    with ThreadPoolExecutor(max_workers=len(PAIRS)) as pool:
        futures = {pair: pool.submit(gate_edges, pair) for pair in PAIRS}
        edges = []
        failures = {}
        for pair, pending in futures.items():
            try:
                edges.extend(pending.result())
            except (OSError, ValueError, KeyError) as error:
                failures[pair] = type(error).__name__
    now = datetime.now(timezone.utc)
    future = {e["origin"] + "→" + e["destination"] for e in edges if datetime.fromisoformat(e["quote_time_utc"]) > now}
    clean = [e for e in edges if e["origin"] + "→" + e["destination"] not in future]
    graph = make_graph(now, ("ETH", "BTC", "USDT"), clean)
    return {
        "source": "Gate public top of book", "graph": graph, "provider_errors": failures,
        "future_quote_edges": sorted(future), "audit": audit_triangles(graph, **MARGIN_OPTIONS),
    }
```
## Check your interpretation
If a provider sends a timestamp later than local time, the workbench excludes the affected edges and records that symptom. A sound diagnosis would compare clocks and units before treating the sample as evidence about the market.

# Replay decisions and denominators
The archive adapter reconstructs absolute quote times from stored ages relative to a frame. Replay evaluates the same chosen orientation in the immediately following recorded frame and records a missing outcome when that frame lacks usable quotes. Attempt counts and observed later outcomes can differ.
## Source walkthrough
The excerpt is from research/workbench.py in the PhaseWeave implementation.
```
def archive_graph(frame):
    now = datetime.fromisoformat(frame["utc"])
    edges = []
    for item in frame["edges"]:
        age = timedelta(milliseconds=item["age"])
        edges.append({
            "origin": item["from"], "destination": item["to"],
            "quote_time_utc": (now - age).isoformat(), "log_rate": item["bps"] / 1e4,
        })
    return make_graph(now, ("EUR", "USD", "JPY"), edges)
```
```
def policy_report(example):
    audits = [audit_triangles(archive_graph(frame), **MARGIN_OPTIONS) for frame in example["frames"]]
    margins = [[item["net_log_margin_bps"] for item in audit["triangles"]] for audit in audits]
    candidates = {"abstain": [], "current_positive": [], "two_observations": []}
    attempted = {name: 0 for name in candidates}
    unavailable = {name: 0 for name in candidates}
    for index, (current, later) in enumerate(zip(margins, margins[1:])):
        past = margins[index-1] if index else [None] * len(current)
        for name in ("current_positive", "two_observations"):
            allowed = [j for j, score in enumerate(current) if score is not None and score > 0 and
                       (name == "current_positive" or past[j] is not None and past[j] > 0)]
            if not allowed:
                continue
            direction = max(allowed, key=lambda j: current[j])
            attempted[name] += 1
            if later[direction] is None:
                unavailable[name] += 1
            else:
                candidates[name].append(later[direction])
    return {
        "example": example["label"], "source": example["source"], "frame_count": len(audits),
        "first_snapshot": audits[0],
        "policies": [{
            "policy": name, "attempts": attempted[name], "unavailable_next_quote": unavailable[name],
            "scorable_next_quote_events": len(values),
            "mean_next_indicative_log_bps": sum(values)/len(values) if values else None,
        } for name, values in candidates.items()],
    }
```
## Check your interpretation
Walk the code with a current positive quote followed by an unavailable future margin. The policy can record an attempted action even though it lacks a realized quote target. Replacing the missing outcome with zero would understate uncertainty and change the denominator.

