Metadata-Version: 2.4
Name: SSE_for_Py
Version: 0.1.0rc13
Author-email: Peter Simmonds <peter.simmonds@utu.fi>, "Terry C. Jones" <terence.jones@charite.de>
License-Expression: LicenseRef-Academic-NonCommercial
Project-URL: Homepage, https://github.com/psimmond/SSE_for_Py
Project-URL: Repository, https://github.com/psimmond/SSE_for_Py
Project-URL: Issues, https://github.com/psimmond/SSE_for_Py/issues
Keywords: RNA,structure,MFE,bioinformatics,sequence-analysis,scrambling
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: C
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: prseq>=0.0.38
Dynamic: license-file

# PRE-RELEASE

**The code in this repository is under active development and testing
prior to an official release. Until that time, the project should be
considered unstable and liable to change without warning.**

# SSE_for_Py — sequence order scrambling and mutation tools

`SSE_for_Py` provides tools for scrambling the order of bases in a
nucleotide sequence or introducing specific mutations into the
sequence. Both operate under selected constraints— for example,
preserving the sequence of the encoded protein while randomizing codon
usage, or modifying a sequence's dinucleotide composition (e.g., CpG
content) toward a target value while keeping coding and mononucleotide
frequencies constant. In some cases, these operations are used to
build null-model or control sequences for studying compositional
selection pressures in viral and other genomes, or they may be used to
generate sequence that explore the biological consequences of modified
dinucleotide frequencies.

The scrambling and mutation algorithms were originally written in
PowerBasic and distributed within the integrated SSE package PMID:
xxx). The original code was translated into C, and Python bindings
were added on top of the C extension, all written by Claude,
Anthropic's AI coding agent. The C code was checked (via the Python
bindings) for equivalence with the original PowerBasic implementation
(see [Testing](#testing) below).

## Installation

`SSE_for_Py` ships as a compiled Python package (the C code is built
into a Python extension module), with prebuilt binaries for Windows,
Linux, and OS X.

Using pip:

```bash
pip install SSE_for_Py
```

Using [uv](https://docs.astral.sh/uv/):

```bash
uv add SSE_for_Py
```

## Sequence order randomisation

The following sequence randomisation methods are implemented
identically in the PowerBasic original and the C code (for which
Python bindings are provided). They are described here in a
language-independent way; see Implementations below for how to call
them from either language.

All methods operate on a nucleotide sequence (A, C, G, T). Methods
whose description mentions "codons" treat the sequence as a series of
amino acid-encoding triplets with a sequence length that is a multiple
of 3, with a reading framing starting from the first position in the
sequence.

1) NOR: Completely randomises base order within a sequence.

2) NxR: Randomises sequence order while preserving frequencies of
dinucleotides (NDR), trinucleotides (NTR) or tetranucleotides (NQR)
found in the native sequences.

3) NxS: This is the same as NnR, called as NDS, NTS and NQS), except
that randomisation is carried out by swapping of bases between
adjacent matched sites rather than global randomisation.

4) COR: Completely randomises the order of codons

5) CLR: Randomises the order of codons for each of the 20 encoded
amino acid and stop codons. The resulting sequence has the same amino
acid sequence as the original.

6) CLS: The same as CLR except that matching codons are swapped rather
than globally scrambled.

7) CDR Scrambles codon order while preserving dinucleotide frequencies
(that may be biased in the native sequence).

8) CDS As CDR, but where randomisation is limited to swaps between
synonymous codons.

9) CDLR: A scrambling method that both preserves the coding sequence
and dinucleotide frequencies of the native sequence. The Python / C
version has been further optimised and achieves a greater degree of
sequence randomisation than achieved by the CDLR algorithm in SSE.

CLM: Mutates rather than randomises synonymous codons to generate a
sequence that is maximally different from the native sequence while
retaining coding. It does not preserve dinucleotide or mononucleotide
frequencies.

All of the codon-aware methods (CDLR, COR, CLR, CLS) accept a genetic
code number as an additional parameter (1–23, following the NCBI
genetic code tables, default=1), allowing the use of alternative
genetic codes.

### Command-line invocation

Installing `SSE_for_Py` provides a `scramble` command for sequence
order randomisation, with sequences provided as a FASTA file (or from
stdin, or a single sequence given on the command line).

Each scrambling method is its own subcommand (`scramble CDLR ...`,
`scramble NOR ...`, etc.), so `--help` on a given method only shows the
options that actually apply to it.

#### Examples

  ```bash
  # Scramble a FASTA file using the CDLR method, with genetic code 1
  scramble CDLR input.fasta --genetic-code 1 --output scrambled.fasta

  # Scramble a single sequence using NOR, with a given random seed
  scramble NOR --sequence ACGTACGTACGT --seed 42

  # Read from stdin, scramble with NTR to preserve trinucleotide sequences
  scramble NTR < input.fasta > scrambled.fasta
  ```

#### All options

Use `scramble --help` to list the methods, and `scramble METHOD --help`
for a given method's own options and their defaults:

```bash
scramble --help
usage: scramble [-h] {CDLR,CLM,CLR,CLS,COR,NDR,NTR,NQR,NDS,NTS,NQS,NOR} ...

Scramble DNA sequences using various methods.

positional arguments:
  {CDLR,CLM,CLR,CLS,COR,NDR,NTR,NQR,NDS,NTS,NQS,NOR}
                        The sequence scrambling method to use.
    CDLR                Preserve coding and dinucleotide frequencies of the
                        sequence.
    CLM                 Mutate (not scramble) synonymous codons for maximal
                        divergence; preserves coding only.
    CLR                 Randomize the order of synonymous codons; preserves
                        coding only.
    CLS                 Swap pairs of synonymous codons; preserves coding
                        only.
    COR                 Completely randomize the order of codons.
    NDR                 Randomize bases while preserving dinucleotide
                        frequencies.
    NTR                 Randomize bases while preserving trinucleotide
                        frequencies.
    NQR                 Randomize bases while preserving tetranucleotide
                        frequencies.
    NDS                 Swap bases to preserve dinucleotide frequencies.
    NTS                 Swap bases to preserve trinucleotide frequencies.
    NQS                 Swap bases to preserve tetranucleotide frequencies.
    NOR                 Completely randomize base order.

options:
  -h, --help            show this help message and exit
```

The 12 methods fall into four groups of identical options (beyond the
common ones shown for `NOR` below): `CDLR` on its own; `CLS` and `COR`
(same as `CDLR` but without `--max-retries`/`--min-swap-fraction`); `NDR`,
`NTR`, `NQR`, `NDS`, `NTS`, and `NQS` (identical to each other); and
`CLM`, `CLR`, and `NOR` (no extra options beyond the common ones).

```bash
scramble CDLR --help
usage: scramble CDLR [-h] [--output output.fasta] [--sequence ACGT....]
                     [--seed N] [--wrap N] [--repeat N] [--offset N]
                     [--seed-each-sequence] [--genetic-code N]
                     [--max-retries N] [--min-swap-fraction N]
                     [seqs.fasta]

positional arguments:
  seqs.fasta            Input FASTA file (default is standard input).
                        (default: None)

options:
  -h, --help            show this help message and exit
  --output, -o output.fasta
                        Output file (default is standard output). (default:
                        None)
  --sequence ACGT....   Process a nucleotide sequence directly from the
                        command line instead of reading FASTA from a file or
                        standard input. (default: None)
  --seed N              Random seed. (default: None)
  --wrap N              The line length to wrap output sequences. Use -1 for
                        no wrapping. (default: -1)
  --repeat N            The number of times to operate on each input sequence.
                        (default: 1)
  --offset N            Number of leading bases to leave untouched, and to use
                        as the start of the reading frame for codon-aware
                        methods. (default: 0)
  --seed-each-sequence  Re-seed the random number generator (with the
                        identical seed) before each sequence is processed. By
                        default, the RNG is seeded once at the start of a run.
                        (default: False)
  --genetic-code N      Genetic code (1-23). (default: 1)
  --max-retries N       Maximum attempts per swap to find a valid pick before
                        giving up on that swap. -1 uses the built-in default.
                        (default: 10000)
  --min-swap-fraction N
                        Minimum required fraction (0.0-1.0) of swap attempts
                        that must succeed, else a ScrambleError is raised.
                        (default: 0.0)
```

```bash
scramble COR --help
usage: scramble COR [-h] [--output output.fasta] [--sequence ACGT....]
                    [--seed N] [--wrap N] [--repeat N] [--offset N]
                    [--seed-each-sequence] [--genetic-code N]
                    [seqs.fasta]

positional arguments:
  seqs.fasta            Input FASTA file (default is standard input).
                        (default: None)

options:
  -h, --help            show this help message and exit
  --output, -o output.fasta
                        Output file (default is standard output). (default:
                        None)
  --sequence ACGT....   Process a nucleotide sequence directly from the
                        command line instead of reading FASTA from a file or
                        standard input. (default: None)
  --seed N              Random seed. (default: None)
  --wrap N              The line length to wrap output sequences. Use -1 for
                        no wrapping. (default: -1)
  --repeat N            The number of times to operate on each input sequence.
                        (default: 1)
  --offset N            Number of leading bases to leave untouched, and to use
                        as the start of the reading frame for codon-aware
                        methods. (default: 0)
  --seed-each-sequence  Re-seed the random number generator (with the
                        identical seed) before each sequence is processed. By
                        default, the RNG is seeded once at the start of a run.
                        (default: False)
  --genetic-code N      Genetic code (1-23). (default: 1)
```

```bash
scramble NDR --help
usage: scramble NDR [-h] [--output output.fasta] [--sequence ACGT....]
                    [--seed N] [--wrap N] [--repeat N] [--offset N]
                    [--seed-each-sequence] [--no-swaps N] [--max-retries N]
                    [--min-swap-fraction N]
                    [seqs.fasta]

positional arguments:
  seqs.fasta            Input FASTA file (default is standard input).
                        (default: None)

options:
  -h, --help            show this help message and exit
  --output, -o output.fasta
                        Output file (default is standard output). (default:
                        None)
  --sequence ACGT....   Process a nucleotide sequence directly from the
                        command line instead of reading FASTA from a file or
                        standard input. (default: None)
  --seed N              Random seed. (default: None)
  --wrap N              The line length to wrap output sequences. Use -1 for
                        no wrapping. (default: -1)
  --repeat N            The number of times to operate on each input sequence.
                        (default: 1)
  --offset N            Number of leading bases to leave untouched, and to use
                        as the start of the reading frame for codon-aware
                        methods. (default: 0)
  --seed-each-sequence  Re-seed the random number generator (with the
                        identical seed) before each sequence is processed. By
                        default, the RNG is seeded once at the start of a run.
                        (default: False)
  --no-swaps N          Number of swaps to perform (default is the length of
                        the sequence). (default: None)
  --max-retries N       Maximum attempts per swap to find a valid pick before
                        giving up on that swap. -1 uses the built-in default.
                        (default: 10000)
  --min-swap-fraction N
                        Minimum required fraction (0.0-1.0) of swap attempts
                        that must succeed, else a ScrambleError is raised.
                        (default: 0.0)
```

```bash
scramble NOR --help
usage: scramble NOR [-h] [--output output.fasta] [--sequence ACGT....]
                    [--seed N] [--wrap N] [--repeat N] [--offset N]
                    [--seed-each-sequence]
                    [seqs.fasta]

positional arguments:
  seqs.fasta            Input FASTA file (default is standard input).
                        (default: None)

options:
  -h, --help            show this help message and exit
  --output, -o output.fasta
                        Output file (default is standard output). (default:
                        None)
  --sequence ACGT....   Process a nucleotide sequence directly from the
                        command line instead of reading FASTA from a file or
                        standard input. (default: None)
  --seed N              Random seed. (default: None)
  --wrap N              The line length to wrap output sequences. Use -1 for
                        no wrapping. (default: -1)
  --repeat N            The number of times to operate on each input sequence.
                        (default: 1)
  --offset N            Number of leading bases to leave untouched, and to use
                        as the start of the reading frame for codon-aware
                        methods. (default: 0)
  --seed-each-sequence  Re-seed the random number generator (with the
                        identical seed) before each sequence is processed. By
                        default, the RNG is seeded once at the start of a run.
                        (default: False)
```

## Sequence mutation

Two algorithms to mutate sequences under specified constraints
provided in SSE have been translated as standalone Python / C programs.

1) MUT: modifying dinucleotide frequencies. This mutates sequences to
achieve a specified target frequency of an individual dinucleotide.
This mutational process can also be performed under several
constraints, including retaining protein coding, native mononucleotide
frequencies and the option to fix frequencies of other dinucleotides.
Dinucleotide frequency targets are expressed as observed/expected
ratios, indicating the degree of over- or under-representation of a
dinucleotide relative to that expected from monocucleotide
frequencies.

2) CPB: modifying codon pair bias. This allows the generation of
sequences with a specified codon pair bias (CPB) score or the minimum
or maximum possible values. CPB is a composite metric that describes
the over-representation or under-representation of codon pairs
compared with frequencies based on the frequencies of individual codon
and amino acid pairs in a reference organism (Gutman & Hatfield,
1989).  By default, standard codon pair usage is based on sequencies
recorded from in human mRNA sequences and encoded in the supplied
table in the file "CPB_Bias.TXT" that is required for running the
program and supplied in the repo. Mutating a sequence to achieve a
specified CPB score retains the protein coding of the sequence.
Optionally, the mutational process can be constrained so as to
preserve frequencies of one or more dinucleotides in the sequence.

The dinucleotide-frequency method is invoked via the `dinuc` subcommand,
and codon-pair bias via the `CPB` subcommand.

### Command-line examples

  ```bash
  # Modify UpA frequencies in a sequence, keep CpG and UpU invariant, use a fixed seed:
  mutate dinuc input.fasta --dinuc-mutate UpA --invariant 'CpG|UpU' --diverge 1.5 --seed 123

  # Remove all CpG dinucleotides, retain coding and mononucleotide frequencies (composition):
  mutate dinuc input.fasta --output mutated.fasta --dinuc-mutate CpG --diverge 0 --coding --compensate

  # Shift codon-pair bias towards -5.0 while keeping CpG frequencies fixed at codon-pair boundaries:
  mutate CPB input.fasta --output mutated.fasta --exclude CpG --target-cp -5
  ```

#### All options

```
mutate --help
usage: mutate [-h] {dinuc,CPB} ...

Mutate DNA sequences using various methods.

positional arguments:
  {dinuc,CPB}  The mutation method to use.
    dinuc      Mutate a sequence to achieve a target dinucleotide frequency.
    CPB        Mutate a coding sequence to shift its codon-pair bias.

options:
  -h, --help   show this help message and exit
```

```
mutate dinuc --help
usage: mutate dinuc [-h] [--output output.fasta] [--sequence ACGT....]
                    [--seed N] [--wrap N] [--repeat N] [--offset N]
                    [--seed-each-sequence] [--dinuc-mutate DINUC_MUTATE]
                    [--diverge DIVERGE] [--tolerance TOLERANCE]
                    [--coding | --no-coding] [--compensate]
                    [--invariant DINUC_INVARIANT]
                    [seqs.fasta]

positional arguments:
  seqs.fasta            Input FASTA file (default is standard input).
                        (default: None)

options:
  -h, --help            show this help message and exit
  --output, -o output.fasta
                        Output file (default is standard output). (default:
                        None)
  --sequence ACGT....   Process a nucleotide sequence directly from the
                        command line instead of reading FASTA from a file or
                        standard input. (default: None)
  --seed N              Random seed. (default: None)
  --wrap N              The line length to wrap output sequences. Use -1 for
                        no wrapping. (default: -1)
  --repeat N            The number of times to operate on each input sequence.
                        (default: 1)
  --offset N            Number of leading bases to leave untouched, and to use
                        as the start of the reading frame for codon-aware
                        methods. (default: 0)
  --seed-each-sequence  Re-seed the random number generator (with the
                        identical seed) before each sequence is processed. By
                        default, the RNG is seeded once at the start of a run.
                        (default: False)
  --dinuc-mutate DINUC_MUTATE
                        Target dinucleotide (e.g., CpG, ApT). (default: CpG)
  --diverge DIVERGE     Target frequency ratio. (default: 2.0)
  --tolerance TOLERANCE
                        Acceptable tolerance for target frequency. (default:
                        0.0)
  --coding, --no-coding
                        Preserve coding. (default: True)
  --compensate          Preserve mononucleotide frequencies (default:
                        disabled). (default: False)
  --invariant DINUC_INVARIANT
                        Dinucleotides to keep constant (e.g., UpA or ApA|CpG).
                        (default: UpA)
```

```
mutate CPB --help
usage: mutate CPB [-h] [--output output.fasta] [--sequence ACGT....]
                  [--seed N] [--wrap N] [--repeat N] [--offset N]
                  [--seed-each-sequence] --target-cp TARGET_CP
                  [--exclude DINUC_EXCLUDE] [--genetic-code N]
                  [--CPB-table PATH]
                  [seqs.fasta]

positional arguments:
  seqs.fasta            Input FASTA file (default is standard input).
                        (default: None)

options:
  -h, --help            show this help message and exit
  --output, -o output.fasta
                        Output file (default is standard output). (default:
                        None)
  --sequence ACGT....   Process a nucleotide sequence directly from the
                        command line instead of reading FASTA from a file or
                        standard input. (default: None)
  --seed N              Random seed. (default: None)
  --wrap N              The line length to wrap output sequences. Use -1 for
                        no wrapping. (default: -1)
  --repeat N            The number of times to operate on each input sequence.
                        (default: 1)
  --offset N            Number of leading bases to leave untouched, and to use
                        as the start of the reading frame for codon-aware
                        methods. (default: 0)
  --seed-each-sequence  Re-seed the random number generator (with the
                        identical seed) before each sequence is processed. By
                        default, the RNG is seeded once at the start of a run.
                        (default: False)
  --target-cp TARGET_CP
                        Target codon-pair bias score. (default: None)
  --exclude DINUC_EXCLUDE
                        Dinucleotide(s) to keep fixed at codon-pair boundaries
                        (e.g., CpG or UpA|CpA). (default: CpG)
  --genetic-code N      Genetic code (1-23). (default: 1)
  --CPB-table PATH      Path to a codon-pair-bias TSV table (default: the
                        table bundled with this package). (default: None)
```

## Python library functions

You can import the various scrambling and mutation functions described
above into your own Python programs. The recommended entry points are
`SSE_for_Py.scramble.get_scrambler`/`SSE_for_Py.scramble.scramble_FASTA`
and `SSE_for_Py.mutate.get_mutator`:

```python
from SSE_for_Py.scramble import get_scrambler, scramble_FASTA

# Scramble a single sequence with CDLR:
cdlr = get_scrambler("CDLR")
scrambled = cdlr("ATGCGTAAATAG")

# Scramble every sequence in a FASTA file, using NTR:
ntr = get_scrambler("NTR")
for record in scramble_FASTA(ntr, "input.fasta"):
    print(f">{record.id}\n{record.sequence}")

# Scramble every sequence in an already-opened FASTA file, using NTR:
ntr = get_scrambler("NTR")
with open("input.fasta", "rb") as fp:
    for record in scramble_FASTA(ntr, fp):
        print(f">{record.id}\n{record.sequence}")
```

```python
from SSE_for_Py.mutate import get_mutator

dinuc = get_mutator("dinuc", dinuc_mutate="CpG", dinuc_diverge=2.0)
result = dinuc("ATGCGTAAATAG")
```

Each scrambling method is also available directly as its own function,
if you don't want to go through the `scramble` dispatcher:

```python
from SSE_for_Py.scramble_NDR import scramble_NDR
from SSE_for_Py.scramble_CDLR import scramble_CDLR
from SSE_for_Py.scramble_NOR import scramble_NOR
from SSE_for_Py.scramble_COR import scramble_COR
from SSE_for_Py.scramble_CLR import scramble_CLR
from SSE_for_Py.scramble_CLS import scramble_CLS
from SSE_for_Py.scramble_CLM import scramble_CLM

scramble_NDR("ACGTACGTACGT", s_method=2, no_swaps=10, n_tuple=3)
scramble_CDLR("ATGCGTAAATAG", genetic_code=1)
scramble_NOR("ATGCGTAAATAG")
scramble_COR("ATGCGTAAATAG", genetic_code=1)
scramble_CLR("ATGCGTAAATAG", genetic_code=1)
scramble_CLS("ATGCGTAAATAG", genetic_code=1)
scramble_CLM("ATGCGTAAATAG")
```

Invalid arguments raise `ValueError`. Failures in the underlying C
code, or a scramble that could not make enough progress to be
considered meaningful (see the `min_swap_fraction` argument on
`scramble_NDR` and `scramble_CDLR`), raise
`SSE_for_Py.exceptions.ScrambleError`.

### C library

The underlying functions are in a small, dependency-free C library
under `src/c/`, with one source file per scramble method
(`scramble_NDR.c`, etc.), `mutate_dinuc.c` for mutation, and
`lib.c`/`lib.h` with shared utilities (codon table setup and
translation, RNG seeding).

All of that is compiled into a single Python extension module,
`SSE_for_Py._combined`, built from `combined_module.c` plus the files above.
Everything is built as one extension, rather than one per method, so
that every method shares a single C-level RNG state — important for
reproducibility when a script calls more than one scrambling method with
the same seed.

The C code has no dependencies beyond the C standard library and `libm`,
and can also be compiled and used standalone, outside of Python — see the
`benchmark-bin` target in the `Makefile` for an example of linking it into
a plain C binary.

## Testing

Clone the repository and install the development dependencies with
[uv](https://docs.astral.sh/uv/):

```bash
uv sync
```

Run the test suite:

```bash
make test
```

which is equivalent to `uv run pytest`. To run the tests across every
supported Python version (currently 3.10 through 3.14), use:

```bash
make nox
```

The default testing does not test the checksums produced by the PB. To
do this, run `make build-with-rng-checksum` and then `make test`. This
will rebuild the code with the simplistic linear congruential (random
number) generator. There should be no need to do this under normal
circumstances, given the the equivalence between the C and PB is
alredy established.

### Benchmarking

See [docs/benchmark.md](docs/benchmark.md) for benchmarking results.
