> ## Documentation Index
> Fetch the complete documentation index at: https://proto.evodesign.org/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# K-mer Frequency

> Evaluate k-mer frequencies or usage deviations with configurable mer length and scoring mode

<div class="page-hero">
  <img class="page-hero-banner" src="https://proto-bio.github.io/proto-assets/images/constraint/kmer-frequency/hero.png" alt="K-mer Frequency" />
</div>

<p class="entity-disclaimer">This constraint is open source. Any third-party models, product names, or trademarks referenced are the property of their respective owners, and Proto is not affiliated with them.</p>

<hr class="entity-rule" />

<div class="tool-tab-bar entity-source-bar"><span class="tool-tab-wrap"><span class="tool-tab badge-source entity-source-tab"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6" /><polyline points="8 6 2 12 8 18" /></svg> Source</span></span></div>

<a href="https://github.com/evo-design/proto-language/blob/d3b7822f74ea64747cc751a3b2ab1aa6b799ac47/proto_language/constraint/sequence_composition/kmer_frequency_constraint.py#L122" target="_blank" class="tab-panel source-panel entity-source-panel">
  <div class="source-info">
    <img noZoom src="https://github.com/evo-design.png?size=40" class="source-avatar" width="36" height="36" />

    <span class="source-path">evo-design/proto-language<span class="source-subpath">/proto\_language/constraint/sequence\_composition/kmer\_frequency\_constraint.py</span></span>
  </div>

  <span class="panel-goto-btn source-goto-btn"><span><svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z" /></svg> View source</span></span>
</a>

<div class="entity-contributors"><span class="entity-contributors-label">Constraint contributors</span><span class="entity-contributors-people"><a class="entity-contributor" href="https://github.com/dguo8412" target="_blank" rel="noopener" title="dguo8412: 3 commits"><img noZoom class="entity-contributor-avatar" src="https://avatars.githubusercontent.com/u/46211285?v=4&s=64" alt="" loading="lazy" /><span class="entity-contributor-login">dguo8412</span></a></span></div>
Evaluate k-mer frequencies or usage deviations with configurable mer length and scoring modes.

This constraint function analyzes k-mer (subsequences of length k) composition
in DNA, RNA, or protein sequences using two possible scoring modes:

1. **Frequency mode**: Evaluates raw k-mer frequencies (observed\_count / total\_kmers).

2. **Usage deviation mode**: Evaluates observed/expected ratios using a zero-order
   Markov model where expected = product of individual nucleotide/amino acid
   frequencies. A ratio of 1.0 indicates observed matches expected composition,
   > 1.0 indicates overrepresentation, \<1.0 indicates underrepresentation.

The penalty is the maximum deviation from the \[min\_value, max\_value] band across
observed k-mers; absent k-mers are not penalized. To target a single specific
k-mer (including penalizing its absence), use specific\_kmer\_constraint instead.

## API Reference

<div class="api-model-section api-model-static api-config-section">
  <div class="api-model-header"><span class="api-model-badge api-config-badge">Config</span><span class="api-model-name">KmerFrequencyConfig</span><a href="https://github.com/evo-design/proto-language/blob/d3b7822f74ea64747cc751a3b2ab1aa6b799ac47/proto_language/constraint/sequence_composition/kmer_frequency_constraint.py#L20" target="_blank" class="func-table-btn func-source-btn api-model-source"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6" /><polyline points="8 6 2 12 8 18" /></svg> Source</a></div>

  Configuration for k-mer frequency constraint.

  This class defines configuration parameters for evaluating k-mer composition
  in DNA, RNA, or protein sequences. K-mers are subsequences of length k, and
  their frequencies can indicate codon bias, tandem repeats, sequence composition
  biases, CpG islands, etc. The constraint supports two scoring modes:
  frequency-based (direct k-mer counts) and usage deviation (observed vs expected
  based on nucleotide/amino acid composition).

  <Note>
    **Frequency mode** evaluates raw k-mer proportions (10/100 CG dinucleotides
    \= 0.1). Only k-mers that occur in the sequence are scored; absent k-mers
    are not penalized.

    **Usage deviation mode** compares observed to expected frequencies under
    a zero-order Markov model. Expected frequency = product of individual
    nucleotide frequencies. For example, if a sequence is 40% G and 60% C,
    the expected CG dinucleotide frequency is 0.4 x 0.6 = 0.24. If observed
    is 0.12, usage\_deviation = 0.12/0.24 = 0.5 (underrepresented).

    The penalty is the maximum deviation across observed k-mers. To evaluate a
    single specific k-mer (including penalizing its absence), use
    specific\_kmer\_constraint instead.
  </Note>

  <ParamField path="k" type="integer" required>
    Length of k-mer to analyze (e.g., 2 for dinucleotide, 3 for trinucleotide).
  </ParamField>

  <ParamField path="scoring_mode" type="enum" default="frequency">
    Scoring metric: 'frequency' uses raw k-mer counts; 'usage\_deviation' uses observed/expected ratios.

    Options: `frequency`, `usage_deviation`
  </ParamField>

  <ParamField path="min_value" type="number" required>
    Minimum acceptable frequency/deviation based on scoring\_mode
  </ParamField>

  <ParamField path="max_value" type="number" required>
    Maximum acceptable frequency/deviation based on scoring\_mode
  </ParamField>
</div>

<div class="api-model-section api-model-static api-output-section">
  <div class="api-model-header"><span class="api-model-badge api-output-badge">Returns</span><span class="api-model-name">ConstraintOutput</span></div>

  One result per sequence. A score of 0.0 indicates
  every observed k-mer is within the acceptable range \[min\_value, max\_value].
  Higher scores indicate the maximum deviation across observed k-mers. The
  penalty scales linearly with deviation distance from the acceptable
  range, capped at 1.0. `metadata` carries (over *observed* k-mers only):

  **For frequency mode:**

  * `{k}mer_frequencies`: Dictionary mapping each observed k-mer to its
    frequency (0.0-1.0). For example, `2mer_frequencies` for dinucleotides.

  **For usage\_deviation mode:**

  * `{k}mer_usage_deviations`: Dictionary mapping each observed k-mer to
    its observed/expected ratio

  **For sequences too short (\<k length) or with no valid k-mers:**

  * `{k}mer_data`: Empty dictionary
</div>

## Usage

Analyzing codon usage (all trinucleotides):

```python python icon="python" theme={null}
>>> coding_seq = Sequence("ATGAAACGTATTGCGTCG", "dna")
>>> config = KmerFrequencyConfig(
...     k=3,
...     scoring_mode="usage_deviation",
...     min_value=0.5,  # Allow some underrepresentation
...     max_value=2.0,  # Allow some overrepresentation
... )
>>> results = kmer_frequency_constraint([(coding_seq,)], config)
>>> deviations = results[0].metadata["3mer_usage_deviations"]
>>> for codon, ratio in sorted(deviations.items(), key=lambda x: x[1], reverse=True):
...     print(f"{codon}: {ratio:.2f}x expected")
```

## Metadata

| Property        | Value                       |
| --------------- | --------------------------- |
| Key             | `kmer-frequency`            |
| Function        | `kmer_frequency_constraint` |
| Category        | `sequence_composition`      |
| Mode            | `discrete`                  |
| Uses GPU        | `False`                     |
| Supported Types | `dna`, `rna`, `protein`     |
