# Metrics

> A metric is a builder that scores one round of candidates against one query at a time, so an expensive metric can batch, pack or upload its candidates before scoring them all at once.

8122c932

### Writing Metrics

A metric is a builder that scores one round of candidates against one query at a time, so an expensive metric can batch, pack or upload its candidates before scoring them all at once:

- `reset(query)` opens a round for one query; a walk reopens the same query every round, so a metric that prepares its query keeps that work when nothing changed.
- `push(value)` stages one candidate and answers `staged_k`, or `refused_k` once its staging is full, which makes the walk drain before staging more.
- `drain(distances, radius)` scores everything staged, writes the distances in push order, and clears the staging.

A distance within `radius` must be exact, while one above it may be any value above it, so a kernel can stop scoring a candidate the moment it cannot come back under. Every verb runs with no locks held, so a `drain` may take milliseconds without stalling another thread, and the values a round pushed stay valid until its `drain` returns. A metric marked `is_transparent` accepts query forms other than the stored value, such as a `std::string_view` for `std::string` payloads.

```cpp
#include <cmath>  // `std::fabs`
#include <span>   // `std::span`
#include <vector> // `std::vector`

#include <usearch/basic/ram_index.hpp>

namespace us = unum::usearch;

/** Manhattan distance over vectors of any length, scored one staged round at a time. */
struct manhattan_metric_t {
    std::vector<float> const* query_ = nullptr;
    std::vector<std::vector<float> const*> staged_;

    void reset(std::vector<float> const& query) noexcept { query_ = &query, staged_.clear(); }
    us::basic::metric_staging_t push(std::vector<float> const& value) noexcept {
        return staged_.push_back(&value), us::basic::metric_staging_t::staged_k;
    }
    void drain(std::span<double> distances, double) noexcept {
        for (std::size_t i = 0; i != staged_.size(); ++i) {
            double sum = 0;
            for (std::size_t j = 0; j != query_->size(); ++j) sum += std::fabs((*query_)[j] - (*staged_[i])[j]);
            distances[i] = sum;
        }
        staged_.clear();
    }
};
```
