Skip to content

API reference

sioff

siOFF: siRNA off-target discovery pipeline.

The package exposes four in-memory functions, re-exported from sioff.api: off_targets (intersect RIsearch predictions with a transcriptome, add accessibility penalties and compute off-target probabilities), accessibility (per-chromosome opening-energy profiles), index (build a RIsearch index) and search (run RIsearch and return the hits). They return Polars DataFrames (or a Path for index), write no files and raise ordinary Python exceptions; the sioff command line is a file-writing wrapper over the same core. __version__ reports the installed distribution version.

accessibility

accessibility(
    genome: Union[str, Path],
    window_size: int = 80,
    max_span: int = 40,
    unpaired_prob: int = 30,
    temperature: float = 37.0,
    strand: str = "both",
) -> dict[str, pl.DataFrame]

Compute per-chromosome accessibility profiles in memory.

Folds every sequence in genome with ViennaRNA (local folding, both strands unless strand="+") and returns the opening-energy profiles in the same schema the sioff accessibility command streams to {chrom}.accessibility.parquet. Writes no files. The result is the accessibility argument of off_targets. Every profile stays resident at once, so for genome-scale inputs the CLI's streaming path (then accessibility_dir) is the cheaper route.

Parameters:

Name Type Description Default
genome str or Path

Genome or transcriptome FASTA; one profile is produced per record. CLI: -f/--fasta.

required
window_size int

Local-folding window size W. CLI: -W/--window.

80
max_span int

Maximum base-pair span L. CLI: -L/--span.

40
unpaired_prob int

Length u of the unpaired stretch for which opening energies are computed; sets the number of u columns. CLI: -u/--unpaired.

30
temperature float

Folding temperature in degrees Celsius. CLI: -T/--temperature.

37.0
strand (both, '+')

"+" folds each sequence as given only, skipping its reverse complement: for a transcriptome FASTA, whose records are already sense. Hits on - then have no profile, so pair it with off_targets(sense_only=True). CLI: --strand.

"both"

Returns:

Type Description
dict[str, DataFrame]

Chromosome (FASTA record ID) to profile, in file order. Each frame has the columns position (1-based), strand ("+" or "-") and u1..u{unpaired_prob} (opening energies in kcal/mol), with all + rows followed by all - rows (none with strand="+").

Raises:

Type Description
FileNotFoundError

When genome does not exist.

AccessibilityError

sioff.services.accessibility.AccessibilityError, when ViennaRNA fails to fold a sequence or strand is not "both" or "+".

See Also

off_targets : Consumes the returned dict through its accessibility argument.

Examples:

>>> import sioff
>>> profiles = sioff.accessibility("genome.fa", unpaired_prob=30)
>>> profiles["chr1"].columns[:4]
['position', 'strand', 'u1', 'u2']
>>> df = sioff.off_targets(risearch_file="predictions.tsv", accessibility=profiles)
Source code in src/sioff/api.py
def accessibility(
    genome: Union[str, Path],
    window_size: int = 80,
    max_span: int = 40,
    unpaired_prob: int = 30,
    temperature: float = 37.0,
    strand: str = "both",
) -> dict[str, pl.DataFrame]:
    """Compute per-chromosome accessibility profiles in memory.

    Folds every sequence in *genome* with ViennaRNA (local folding, both
    strands unless ``strand="+"``) and returns the opening-energy profiles in the same schema the
    ``sioff accessibility`` command streams to ``{chrom}.accessibility.parquet``.
    Writes no files. The result is the ``accessibility`` argument of
    [`off_targets`][sioff.off_targets]. Every profile stays resident at once, so for
    genome-scale inputs the CLI's streaming path (then ``accessibility_dir``) is
    the cheaper route.

    Parameters
    ----------
    genome : str or pathlib.Path
        Genome or transcriptome FASTA; one profile is produced per record.
        CLI: ``-f/--fasta``.
    window_size : int, default 80
        Local-folding window size ``W``. CLI: ``-W/--window``.
    max_span : int, default 40
        Maximum base-pair span ``L``. CLI: ``-L/--span``.
    unpaired_prob : int, default 30
        Length ``u`` of the unpaired stretch for which opening energies are
        computed; sets the number of ``u`` columns. CLI: ``-u/--unpaired``.
    temperature : float, default 37.0
        Folding temperature in degrees Celsius. CLI: ``-T/--temperature``.
    strand : {"both", "+"}, default "both"
        ``"+"`` folds each sequence as given only, skipping its reverse
        complement: for a transcriptome FASTA, whose records are already
        sense. Hits on ``-`` then have no profile, so pair it with
        ``off_targets(sense_only=True)``. CLI: ``--strand``.

    Returns
    -------
    dict[str, polars.DataFrame]
        Chromosome (FASTA record ID) to profile, in file order. Each frame has
        the columns ``position`` (1-based), ``strand`` (``"+"`` or ``"-"``) and
        ``u1..u{unpaired_prob}`` (opening energies in kcal/mol), with all
        ``+`` rows followed by all ``-`` rows (none with ``strand="+"``).

    Raises
    ------
    FileNotFoundError
        When *genome* does not exist.
    AccessibilityError
        `sioff.services.accessibility.AccessibilityError`, when
        ViennaRNA fails to fold a sequence or ``strand`` is not ``"both"``
        or ``"+"``.

    See Also
    --------
    off_targets : Consumes the returned dict through its ``accessibility`` argument.

    Examples
    --------
    >>> import sioff
    >>> profiles = sioff.accessibility("genome.fa", unpaired_prob=30)
    >>> profiles["chr1"].columns[:4]
    ['position', 'strand', 'u1', 'u2']
    >>> df = sioff.off_targets(risearch_file="predictions.tsv", accessibility=profiles)
    """
    return _accessibility.compute_accessibility(
        cast(Path, _p(genome)),  # genome is required, so _p never returns None
        window_size=window_size,
        max_span=max_span,
        unpaired_prob=unpaired_prob,
        temperature=temperature,
        strand=strand,
    )

index

index(
    target: Union[str, Path],
    output: Optional[Union[str, Path]] = None,
) -> Path

Build (or reuse) a RIsearch index for a target FASTA.

Runs the in-process risearch indexer and returns the index location. An existing index that is newer than target is reused as is; an outdated one is rebuilt. The function returns a Path rather than data because a RIsearch index is a binary on-disk artifact consumed by search. Mirrors the sioff index command and, like it, requires the external risearch package.

Parameters:

Name Type Description Default
target str or Path

Target FASTA file to index. CLI: the TARGET argument.

required
output str or Path

Index path. Defaults to <target>.idx next to the target file. CLI: -o/--output.

None

Returns:

Type Description
Path

Path of the (new or reused) index file.

Raises:

Type Description
FileNotFoundError

When target does not exist.

RIsearchError

sioff.services.risearch_service.RIsearchError, when indexing fails, including when the risearch package is not installed.

See Also

search : Query the returned index.

Examples:

>>> import sioff
>>> idx = sioff.index("target.fa")
>>> idx.name
'target.idx'
>>> hits = sioff.search("sirnas.fa", idx, target="target.fa")
Source code in src/sioff/api.py
def index(
    target: Union[str, Path],
    output: Optional[Union[str, Path]] = None,
) -> Path:
    """Build (or reuse) a RIsearch index for a target FASTA.

    Runs the in-process ``risearch`` indexer and returns the index location. An
    existing index that is newer than *target* is reused as is; an outdated one
    is rebuilt. The function returns a `Path` rather than data
    because a RIsearch index is a binary on-disk artifact consumed by
    [`search`][sioff.search]. Mirrors the ``sioff index`` command and, like it, requires
    the external ``risearch`` package.

    Parameters
    ----------
    target : str or pathlib.Path
        Target FASTA file to index. CLI: the ``TARGET`` argument.
    output : str or pathlib.Path, optional
        Index path. Defaults to ``<target>.idx`` next to the target file. CLI:
        ``-o/--output``.

    Returns
    -------
    pathlib.Path
        Path of the (new or reused) index file.

    Raises
    ------
    FileNotFoundError
        When *target* does not exist.
    RIsearchError
        `sioff.services.risearch_service.RIsearchError`, when indexing
        fails, including when the ``risearch`` package is not installed.

    See Also
    --------
    search : Query the returned index.

    Examples
    --------
    >>> import sioff
    >>> idx = sioff.index("target.fa")
    >>> idx.name
    'target.idx'
    >>> hits = sioff.search("sirnas.fa", idx, target="target.fa")
    """
    return _risearch.build_index(cast(Path, _p(target)), _p(output))

off_targets

off_targets(
    risearch_file: Optional[Union[str, Path]] = None,
    predictions: Optional[DataFrame] = None,
    sirna_fasta: Optional[Union[str, Path]] = None,
    target_fasta: Optional[Union[str, Path]] = None,
    target_index: Optional[Union[str, Path]] = None,
    gtf_file: Optional[Union[str, Path]] = None,
    feature_type: Optional[str] = None,
    expression_metric: str = "RPKM",
    transcriptome_format: str = "auto",
    accessibility: Optional[Mapping[str, DataFrame]] = None,
    accessibility_dir: Optional[Union[str, Path]] = None,
    accessibility_cache_dir: Optional[
        Union[str, Path]
    ] = None,
    genome_file: Optional[Union[str, Path]] = None,
    window_size: int = 80,
    max_span: int = 40,
    unpaired_prob: int = 30,
    temperature: float = 37.0,
    matrix: Union[str, Path] = "t04",
    sirna_table: Optional[Union[str, Path]] = None,
    alpha: str = "1.0",
    gamma: str = "1.0",
    theta: str = "",
    sense_only: bool = False,
    predictions_type: str = "gw",
    n_workers: int = 1,
    detailed_report: bool = False,
    stream: bool = False,
) -> Union[pl.DataFrame, Iterator[pl.DataFrame]]

Analyse siRNA off-target predictions, returning results in memory.

Intersects RIsearch predictions with a transcriptome annotation, adds an accessibility (opening-energy) penalty, and computes partition-function off-target probabilities. This is the in-memory counterpart of the sioff off-targets command; the defaults reproduce its behaviour, and each parameter below names its CLI flag.

Predictions come from exactly one of:

  • risearch_file: a predictions file, or a directory of them. Each file may hold one siRNA or many.
  • predictions: an in-memory polars.DataFrame in the search schema (sirna_id, chrom, start, end, strand, energy), typically the value returned by search.
  • sirna_fasta + target_fasta: run RIsearch in-process first (requires the risearch package).

Every form takes the same path: the predictions are split into one part per siRNA, and each siRNA is scored on its own, in n_workers processes. The result is one DataFrame, or with stream=True one DataFrame per siRNA as each is scored.

The siRNA table (sirna_table) gives each siRNA its on-target and its guide sequence. E_min, the reference energy of the alpha/gamma clamp, is the lower of the siRNA's perfect-match energy (its sequence searched against itself with matrix) and its strongest hit left after sense_only and the intersection. Every alpha/gamma pair other than (1, 1) needs it, so every siRNA with predictions then needs a table row.

Accessibility profiles come from at most one of accessibility (the dict[chrom -> DataFrame] returned by accessibility), accessibility_dir (the packed cache or per-chromosome Parquet files) or genome_file (fold during the call). Without any profile source the probabilities are computed from hybridisation energy alone.

Writes no output files and prints nothing. The in-process search builds the index <target>.idx next to target_fasta when target_index is omitted, and accessibility_dir gets its packed cache; temporary files are removed before the call returns (with stream=True, when the stream is exhausted or closed).

Parameters:

Name Type Description Default
risearch_file str or Path

Pre-computed predictions: a file, or a directory of files. Read are RIsearch2 output (plain or .gz), sioff search -o TSV and Parquet; from a directory every *.gz, *.tsv, *.out and *.parquet. A sirna_id found in two files is an error. A target name is cut at its first whitespace: the risearch command line writes the whole FASTA header, while the annotation and the accessibility profiles are keyed by its first word. CLI: -r/--risearch-file.

None
predictions DataFrame

In-memory predictions in the search schema. The columns sirna_id, chrom, start, end, strand, energy are required, with start and end counted from 1 and inclusive; extra columns are dropped and dtypes are cast to the schema (Utf8 ids and strand, Int32 coordinates, Float32 energy), so a frame that went through Parquet or your own manipulation still works. chrom is cut at its first whitespace, as for risearch_file. Mutually exclusive with risearch_file. No CLI equivalent.

None
sirna_fasta str or Path

siRNA FASTA with one or more sequences and unique IDs, searched in-process against target_fasta. It is only the search query: it cannot be combined with risearch_file or predictions, and the perfect-match energies come from sirna_table. CLI: -s/--sirna-fasta.

None
target_fasta str or Path

Target FASTA (genome or transcriptome) for the in-process RIsearch run; required together with sirna_fasta and refused with risearch_file or predictions. CLI: --target-fasta (alias --genome).

None
target_index str or Path

Pre-built RIsearch index of target_fasta, to skip indexing on repeated runs; refused with risearch_file or predictions. When omitted the index is built (or reused) next to target_fasta with an .idx suffix. CLI: -idx/--target-index.

None
gtf_file str or Path

Transcriptome annotation (GTF or GFF3). Predictions are intersected with its features, which adds transcript_id, gene_id and the expression column exp_value; features with expression <= 0 are dropped first. Without it no intersection is performed and every prediction is kept with unit expression. CLI: -t/--transcriptome.

None
feature_type str

Feature type (column 3) of the annotation rows to use. Default: "exon" for genome-wide predictions and "transcript" for transcriptome-wide ones (predictions_type="tw"). A type that no row of the file has is an error. CLI: --feature.

None
expression_metric str

Annotation attribute used as the expression score (exp_value). It must be each transcript's own abundance: every transcript containing a site adds its value, so a gene-level value copied onto every transcript counts the gene once per isoform. CLI: --expression-metric.

"RPKM"
transcriptome_format str

One of "auto", "gtf" or "gff3"; BED is rejected. "auto" detects the format from the file, telling GTF from GFF3 by the attribute column. CLI: --transcriptome-format.

"auto"
accessibility dict[str, DataFrame]

In-memory accessibility profiles keyed by chromosome, each frame with columns position, strand, u1..uN and both strands stacked, as returned by accessibility. They are written to a temporary directory and packed into the same cache accessibility_dir uses, so the opening energies match that path. Each key becomes a file name, so it cannot be empty, . or .., or hold /; nor whitespace, since a target is matched by the first word of its name. Mutually exclusive with accessibility_dir. No CLI equivalent.

None
accessibility_dir str or Path

The packed npy cache from sioff accessibility or per-chromosome Parquet files. Parquet is packed into the cache in accessibility_cache_dir before scoring starts, and rebuilt when the Parquet changes. CLI: -a/--accessibility-dir.

None
accessibility_cache_dir str or Path

Where the cache of accessibility_dir is read from and built; default accessibility_dir. Created if absent; use it when accessibility_dir is read-only or to stage the cache on local disk. It may also hold a complete cache without any Parquet. Refused without accessibility_dir. CLI: --accessibility-cache-dir.

None
genome_file str or Path

Genome FASTA to fold during the call; the profiles go to a temporary directory that is removed when the run ends. Refused with accessibility or accessibility_dir. CLI: -f/--fasta.

None
window_size int

Local-folding window size W for genome_file. CLI: -W/--window.

80
max_span int

Maximum base-pair span L for genome_file. CLI: -L/--span.

40
unpaired_prob int

Length u of the unpaired stretch for which opening energies are computed (profile columns u1..u{unpaired_prob}). CLI: -u/--unpaired.

30
temperature float

Temperature in degrees Celsius of everything this run computes: the RT term of the partition function, the genome_file fold, the in-process search of sirna_fasta and the perfect-match energy of E_min. The last two are RIsearch energies, which take whole degrees from 0 to 50. Inputs computed earlier keep their own temperature: fold the accessibility / accessibility_dir profiles and search the risearch_file / predictions hits at this temperature too. CLI: -T/--temperature.

37.0
matrix str or Path

Energy parameter set for the in-process search and for the perfect-match energies of E_min: a bundled id or the path of a DSM TSV table. Use the set the predictions were searched with; E_min is the reference energy of the alpha/gamma clamp. CLI: -z/--matrix.

"t04"
sirna_table str or Path

Tab-separated siRNA table with a header row: sirna_id, on_target_id (the transcript or gene the siRNA is designed against; may be empty) and sequence (the guide strand, ACGU or ACGT). Predictions of a siRNA that fall on its on-target are tagged is_on_target and contribute the on-target weight instead of counting as off-targets; this needs gtf_file, so that transcript_id exists. The sequence gives the perfect-match energy of E_min. Required when an alpha/gamma pair other than (1, 1) is computed; optional otherwise. CLI: --sirna-table.

None
alpha str

Alpha clamping parameter(s) as semicolon-separated floats, e.g. "0.8;1.0". For every (alpha, gamma) pair with alpha <= gamma, predictions whose energy < alpha * E_min have their energy replaced by gamma * E_min. The baseline (1.0, 1.0) is always computed and every other pair adds a P_off_target:alpha=X,gamma=Y column. CLI: --alpha.

"1.0"
gamma str

Gamma clamping parameter(s), same format as alpha; the two lists are combined as a Cartesian product. CLI: --gamma.

"1.0"
theta str

Theta scaling parameter(s) as semicolon-separated floats, e.g. "0.5;0.7"; the empty string disables the sweep. Each value rescales energies as theta * (energy + 10) - 10 and adds a P_off_target:theta=T column. CLI: --theta.

""
sense_only bool

Keep only sense-strand (+) predictions and drop antisense ones. CLI: --sense-only.

False
predictions_type str

"gw" for genome-wide predictions (interval overlap with annotation features) or "tw" for transcriptome-wide predictions, where chrom holds a transcript ID that is joined on transcript_id. CLI: --type.

"gw"
n_workers int

Worker processes that split the inputs and score the siRNAs, one siRNA per task, for every input form. A pool is started only when more than one task can run at once. CLI: -j/--workers, whose default is the CPU count.

1
detailed_report bool

Keep the raw boltzmann_weight*, Z_sirna* and E_min columns for every interaction in the output; by default they are dropped. E_min follows the rule above for a siRNA with a sirna_table row; for one without (no table, or a baseline run's missing row) it is the strongest hit left. CLI: --detailed-report.

False
stream bool

Return a generator of one DataFrame per siRNA, in the order they are scored, instead of one DataFrame. The worker pool and the temporary files live as long as the generator: consume it fully, or close it (contextlib.closing), for prompt cleanup. The generator is lazy, so the argument errors under Raises come from the first next(), not from this call. No CLI equivalent; the CLI always streams to its output file.

False

Returns:

Type Description
DataFrame or Iterator[DataFrame]

One DataFrame holding every siRNA's rows (an empty DataFrame with no columns when nothing was scored), or with stream=True a generator yielding one DataFrame per siRNA. Each row is one prediction with the input columns sirna_id, chrom, start, end, strand, energy; the annotation columns trans_start, trans_end, gene_id, transcript_id when gtf_file is given; exp_value (1.0 without gtf_file); opening_energy (the accessibility penalty, kcal/mol; 0.0 without a profile source); dG_total (energy + opening_energy); is_on_target; P_off_target (baseline alpha=gamma=theta=1); and energy, dG_total and P_off_target again with a :alpha=X,gamma=Y or :theta=T suffix per extra parameter value. With detailed_report the E_min, boltzmann_weight* and Z_sirna* intermediates are kept too. The weights and Z are Float64; every P_off_target* column is Float32.

Raises:

Type Description
ValueError

When no predictions source is given; when an argument would go unused: predictions with risearch_file; sirna_fasta, target_fasta or target_index with risearch_file or predictions; accessibility with accessibility_dir; genome_file with accessibility or accessibility_dir; accessibility_cache_dir without accessibility_dir. Also when accessibility is empty or has a key that cannot be a file name; when sirna_fasta is given without target_fasta; when predictions lacks one of its required columns; when sirna_fasta contains duplicate IDs; when sirna_table cannot be read; when a sirna_id occurs in two input files; and when an alpha/gamma pair other than (1, 1) is computed and a siRNA with predictions has no row in sirna_table (or there is no table).

FileNotFoundError

When risearch_file, gtf_file, genome_file, sirna_fasta, sirna_table, target_fasta or target_index does not exist, or a directory risearch_file contains no prediction files.

RIsearchError

sioff.services.risearch_service.RIsearchError, when the in-process RIsearch run (sirna_fasta form) fails, including when the risearch package is not installed.

AccessibilityError

sioff.services.accessibility.AccessibilityError, when folding genome_file fails, an accessibility profile is missing or malformed, accessibility_dir holds no profile, or the cache cannot be written.

WorkerFailureError

sioff.core.off_targets.WorkerFailureError, when an input file could not be split or a siRNA could not be scored. With stream=True it is raised after the last siRNA that succeeded; with stream=False nothing is returned, so the frames already scored are discarded.

See Also

search : Produce a predictions frame in the schema this function accepts. accessibility : Produce the in-memory accessibility profiles.

Examples:

A predictions file with annotation, pre-computed accessibility, a siRNA table and an alpha sweep:

>>> import sioff
>>> df = sioff.off_targets(
...     risearch_file="predictions.tsv",
...     gtf_file="annotation.gtf",
...     accessibility_dir="accessibility/",
...     sirna_table="sirna_table.tsv",
...     alpha="0.8;1.0",
...     gamma="1.0",
... )
>>> df.select("sirna_id", "transcript_id", "P_off_target").head()

A directory of per-siRNA files, consumed as a stream and torn down promptly:

>>> import contextlib
>>> gen = sioff.off_targets(risearch_file="predictions/", n_workers=8, stream=True)
>>> with contextlib.closing(gen) as frames:
...     for frame in frames:
...         print(frame["sirna_id"][0], frame.height)
Source code in src/sioff/api.py
def off_targets(
    risearch_file: Optional[Union[str, Path]] = None,
    predictions: Optional[pl.DataFrame] = None,
    sirna_fasta: Optional[Union[str, Path]] = None,
    target_fasta: Optional[Union[str, Path]] = None,
    target_index: Optional[Union[str, Path]] = None,
    gtf_file: Optional[Union[str, Path]] = None,
    feature_type: Optional[str] = None,
    expression_metric: str = "RPKM",
    transcriptome_format: str = "auto",
    accessibility: Optional[Mapping[str, pl.DataFrame]] = None,
    accessibility_dir: Optional[Union[str, Path]] = None,
    accessibility_cache_dir: Optional[Union[str, Path]] = None,
    genome_file: Optional[Union[str, Path]] = None,
    window_size: int = 80,
    max_span: int = 40,
    unpaired_prob: int = 30,
    temperature: float = 37.0,
    matrix: Union[str, Path] = "t04",
    sirna_table: Optional[Union[str, Path]] = None,
    alpha: str = "1.0",
    gamma: str = "1.0",
    theta: str = "",
    sense_only: bool = False,
    predictions_type: str = "gw",
    n_workers: int = 1,
    detailed_report: bool = False,
    stream: bool = False,
) -> Union[pl.DataFrame, Iterator[pl.DataFrame]]:
    """Analyse siRNA off-target predictions, returning results in memory.

    Intersects RIsearch predictions with a transcriptome annotation, adds an
    accessibility (opening-energy) penalty, and computes partition-function
    off-target probabilities. This is the in-memory counterpart of the
    ``sioff off-targets`` command; the defaults reproduce its behaviour, and each
    parameter below names its CLI flag.

    Predictions come from exactly one of:

    - ``risearch_file``: a predictions file, or a directory of them. Each file
      may hold one siRNA or many.
    - ``predictions``: an in-memory `polars.DataFrame` in the
      [`search`][sioff.search] schema (``sirna_id, chrom, start, end, strand, energy``),
      typically the value returned by [`search`][sioff.search].
    - ``sirna_fasta`` + ``target_fasta``: run RIsearch in-process first
      (requires the ``risearch`` package).

    Every form takes the same path: the predictions are split into one part
    per siRNA, and each siRNA is scored on its own, in ``n_workers``
    processes. The result is one DataFrame, or with ``stream=True`` one
    DataFrame per siRNA as each is scored.

    **The siRNA table** (``sirna_table``) gives each siRNA its on-target and
    its guide sequence. **E_min**, the reference energy of the alpha/gamma
    clamp, is the lower of the siRNA's perfect-match energy (its sequence
    searched against itself with ``matrix``) and its strongest hit left after
    ``sense_only`` and the intersection. Every alpha/gamma pair other than
    (1, 1) needs it, so every siRNA with predictions then needs a table row.

    Accessibility profiles come from at most one of ``accessibility`` (the
    ``dict[chrom -> DataFrame]`` returned by [`accessibility`][sioff.accessibility]),
    ``accessibility_dir`` (the packed cache or per-chromosome Parquet files)
    or ``genome_file`` (fold during the call). Without any profile source the
    probabilities are computed from hybridisation energy alone.

    Writes no output files and prints nothing. The in-process search builds
    the index ``<target>.idx`` next to ``target_fasta`` when ``target_index``
    is omitted, and ``accessibility_dir`` gets its packed cache; temporary
    files are removed before the call returns (with ``stream=True``, when the
    stream is exhausted or closed).

    Parameters
    ----------
    risearch_file : str or pathlib.Path, optional
        Pre-computed predictions: a file, or a directory of files. Read are
        RIsearch2 output (plain or ``.gz``), ``sioff search -o`` TSV and
        Parquet; from a directory every ``*.gz``, ``*.tsv``, ``*.out`` and
        ``*.parquet``. A ``sirna_id`` found in two files is an error. A
        target name is cut at its first whitespace: the ``risearch`` command
        line writes the whole FASTA header, while the annotation and the
        accessibility profiles are keyed by its first word. CLI:
        ``-r/--risearch-file``.
    predictions : polars.DataFrame, optional
        In-memory predictions in the [`search`][sioff.search] schema. The columns
        ``sirna_id, chrom, start, end, strand, energy`` are required, with
        ``start`` and ``end`` counted from 1 and inclusive; extra
        columns are dropped and dtypes are cast to the schema (``Utf8`` ids and
        strand, ``Int32`` coordinates, ``Float32`` energy), so a frame that went
        through Parquet or your own manipulation still works. ``chrom`` is
        cut at its first whitespace, as for ``risearch_file``. Mutually
        exclusive with ``risearch_file``. No CLI equivalent.
    sirna_fasta : str or pathlib.Path, optional
        siRNA FASTA with one or more sequences and unique IDs, searched
        in-process against ``target_fasta``. It is only the search query: it
        cannot be combined with ``risearch_file`` or ``predictions``, and the
        perfect-match energies come from ``sirna_table``. CLI:
        ``-s/--sirna-fasta``.
    target_fasta : str or pathlib.Path, optional
        Target FASTA (genome or transcriptome) for the in-process RIsearch
        run; required together with ``sirna_fasta`` and refused with
        ``risearch_file`` or ``predictions``. CLI: ``--target-fasta`` (alias
        ``--genome``).
    target_index : str or pathlib.Path, optional
        Pre-built RIsearch index of ``target_fasta``, to skip indexing on
        repeated runs; refused with ``risearch_file`` or ``predictions``. When
        omitted the index is built (or reused) next to ``target_fasta`` with an
        ``.idx`` suffix. CLI: ``-idx/--target-index``.
    gtf_file : str or pathlib.Path, optional
        Transcriptome annotation (GTF or GFF3). Predictions are
        intersected with its features, which adds ``transcript_id``,
        ``gene_id`` and the expression column ``exp_value``; features with
        expression <= 0 are dropped first. Without it no intersection is
        performed and every prediction is kept with unit expression. CLI:
        ``-t/--transcriptome``.
    feature_type : str, optional
        Feature type (column 3) of the annotation rows to use. Default:
        ``"exon"`` for genome-wide predictions and ``"transcript"`` for
        transcriptome-wide ones (``predictions_type="tw"``). A type that no
        row of the file has is an error. CLI: ``--feature``.
    expression_metric : str, default "RPKM"
        Annotation attribute used as the expression score (``exp_value``).
        It must be each transcript's own abundance: every transcript
        containing a site adds its value, so a gene-level value copied onto
        every transcript counts the gene once per isoform. CLI:
        ``--expression-metric``.
    transcriptome_format : str, default "auto"
        One of ``"auto"``, ``"gtf"`` or ``"gff3"``; BED is rejected.
        ``"auto"`` detects the format from the file, telling GTF from GFF3 by
        the attribute column. CLI: ``--transcriptome-format``.
    accessibility : dict[str, polars.DataFrame], optional
        In-memory accessibility profiles keyed by chromosome, each frame with
        columns ``position, strand, u1..uN`` and both strands stacked, as
        returned by [`accessibility`][sioff.accessibility]. They are written to a
        temporary directory and packed into the same cache
        ``accessibility_dir`` uses, so the opening energies match that path.
        Each key becomes a file name, so it cannot be empty, ``.`` or ``..``,
        or hold ``/``; nor whitespace, since a target is matched by the
        first word of its name. Mutually exclusive with
        ``accessibility_dir``. No CLI equivalent.
    accessibility_dir : str or pathlib.Path, optional
        The packed npy cache from ``sioff accessibility`` or per-chromosome
        Parquet files. Parquet is packed into the cache in
        ``accessibility_cache_dir`` before scoring starts, and rebuilt when
        the Parquet changes. CLI: ``-a/--accessibility-dir``.
    accessibility_cache_dir : str or pathlib.Path, optional
        Where the cache of ``accessibility_dir`` is read from and built;
        default ``accessibility_dir``. Created if absent; use it when
        ``accessibility_dir`` is read-only or to stage the cache on local
        disk. It may also hold a complete cache without any Parquet. Refused
        without ``accessibility_dir``. CLI: ``--accessibility-cache-dir``.
    genome_file : str or pathlib.Path, optional
        Genome FASTA to fold during the call; the profiles go to a temporary
        directory that is removed when the run ends. Refused with
        ``accessibility`` or ``accessibility_dir``. CLI: ``-f/--fasta``.
    window_size : int, default 80
        Local-folding window size ``W`` for ``genome_file``. CLI:
        ``-W/--window``.
    max_span : int, default 40
        Maximum base-pair span ``L`` for ``genome_file``. CLI:
        ``-L/--span``.
    unpaired_prob : int, default 30
        Length ``u`` of the unpaired stretch for which opening energies are
        computed (profile columns ``u1..u{unpaired_prob}``). CLI:
        ``-u/--unpaired``.
    temperature : float, default 37.0
        Temperature in degrees Celsius of everything this run computes: the
        ``RT`` term of the partition function, the ``genome_file`` fold, the
        in-process search of ``sirna_fasta`` and the perfect-match energy of
        E_min. The last two are RIsearch energies, which take whole degrees
        from 0 to 50. Inputs computed earlier keep their own temperature:
        fold the ``accessibility`` / ``accessibility_dir`` profiles and
        search the ``risearch_file`` / ``predictions`` hits at this
        temperature too. CLI: ``-T/--temperature``.
    matrix : str or pathlib.Path, default "t04"
        Energy parameter set for the in-process search and for the
        perfect-match energies of E_min: a bundled id or the path of a DSM
        TSV table. Use the set the predictions were searched with; E_min is
        the reference energy of the alpha/gamma clamp. CLI: ``-z/--matrix``.
    sirna_table : str or pathlib.Path, optional
        Tab-separated siRNA table with a header row: ``sirna_id``,
        ``on_target_id`` (the transcript or gene the siRNA is designed
        against; may be empty) and ``sequence`` (the guide strand, ACGU or
        ACGT). Predictions of a siRNA that fall on its on-target are tagged
        ``is_on_target`` and contribute the on-target weight instead of
        counting as off-targets; this needs ``gtf_file``, so that
        ``transcript_id`` exists. The sequence gives the perfect-match energy
        of E_min. Required when an alpha/gamma pair other than (1, 1) is
        computed; optional otherwise. CLI: ``--sirna-table``.
    alpha : str, default "1.0"
        Alpha clamping parameter(s) as semicolon-separated floats, e.g.
        ``"0.8;1.0"``. For every ``(alpha, gamma)`` pair with
        ``alpha <= gamma``, predictions whose ``energy < alpha * E_min`` have
        their energy replaced by ``gamma * E_min``. The baseline ``(1.0, 1.0)``
        is always computed and every other pair adds a
        ``P_off_target:alpha=X,gamma=Y`` column. CLI: ``--alpha``.
    gamma : str, default "1.0"
        Gamma clamping parameter(s), same format as ``alpha``; the two lists
        are combined as a Cartesian product. CLI: ``--gamma``.
    theta : str, default ""
        Theta scaling parameter(s) as semicolon-separated floats, e.g.
        ``"0.5;0.7"``; the empty string disables the sweep. Each value rescales
        energies as ``theta * (energy + 10) - 10`` and adds a
        ``P_off_target:theta=T`` column. CLI: ``--theta``.
    sense_only : bool, default False
        Keep only sense-strand (``+``) predictions and drop antisense ones.
        CLI: ``--sense-only``.
    predictions_type : str, default "gw"
        ``"gw"`` for genome-wide predictions (interval overlap with annotation
        features) or ``"tw"`` for transcriptome-wide predictions, where
        ``chrom`` holds a transcript ID that is joined on ``transcript_id``.
        CLI: ``--type``.
    n_workers : int, default 1
        Worker processes that split the inputs and score the siRNAs, one
        siRNA per task, for every input form. A pool is started only when
        more than one task can run at once. CLI: ``-j/--workers``, whose
        default is the CPU count.
    detailed_report : bool, default False
        Keep the raw ``boltzmann_weight*``, ``Z_sirna*`` and ``E_min`` columns
        for every interaction in the output; by default they are dropped.
        ``E_min`` follows the rule above for a siRNA with a ``sirna_table``
        row; for one without (no table, or a baseline run's missing row) it
        is the strongest hit left. CLI: ``--detailed-report``.
    stream : bool, default False
        Return a generator of one DataFrame per siRNA, in the order they are
        scored, instead of one DataFrame. The worker pool and the temporary
        files live as long as the generator: consume it fully, or close it
        (``contextlib.closing``), for prompt cleanup. The generator is lazy,
        so the argument errors under Raises come from the first ``next()``,
        not from this call. No CLI equivalent; the CLI always streams to its
        output file.

    Returns
    -------
    polars.DataFrame or Iterator[polars.DataFrame]
        One DataFrame holding every siRNA's rows (an empty DataFrame with no
        columns when nothing was scored), or with ``stream=True`` a generator
        yielding one DataFrame per siRNA. Each row is one prediction with the input columns
        ``sirna_id, chrom, start, end, strand, energy``; the annotation
        columns ``trans_start, trans_end, gene_id, transcript_id`` when
        ``gtf_file`` is given; ``exp_value`` (1.0 without ``gtf_file``);
        ``opening_energy`` (the accessibility penalty, kcal/mol; 0.0 without
        a profile source); ``dG_total`` (``energy + opening_energy``);
        ``is_on_target``; ``P_off_target`` (baseline alpha=gamma=theta=1);
        and ``energy``, ``dG_total`` and ``P_off_target`` again with a
        ``:alpha=X,gamma=Y`` or ``:theta=T`` suffix per extra parameter
        value. With ``detailed_report`` the ``E_min``, ``boltzmann_weight*``
        and ``Z_sirna*`` intermediates are kept too. The weights and Z are
        Float64; every ``P_off_target*`` column is Float32.

    Raises
    ------
    ValueError
        When no predictions source is given; when an argument would go
        unused: ``predictions`` with ``risearch_file``; ``sirna_fasta``,
        ``target_fasta`` or ``target_index`` with ``risearch_file`` or
        ``predictions``; ``accessibility`` with ``accessibility_dir``;
        ``genome_file`` with ``accessibility`` or ``accessibility_dir``;
        ``accessibility_cache_dir`` without ``accessibility_dir``. Also when
        ``accessibility`` is empty or has a key that cannot be a file name;
        when ``sirna_fasta`` is given without ``target_fasta``; when
        ``predictions`` lacks one of its required columns; when
        ``sirna_fasta`` contains duplicate IDs; when ``sirna_table`` cannot
        be read; when a ``sirna_id`` occurs in two input files; and when an
        alpha/gamma pair other than (1, 1) is computed and a siRNA with
        predictions has no row in ``sirna_table`` (or there is no table).
    FileNotFoundError
        When ``risearch_file``, ``gtf_file``, ``genome_file``, ``sirna_fasta``,
        ``sirna_table``, ``target_fasta`` or ``target_index`` does not exist,
        or a directory ``risearch_file`` contains no prediction files.
    RIsearchError
        `sioff.services.risearch_service.RIsearchError`, when the
        in-process RIsearch run (``sirna_fasta`` form) fails, including when the
        ``risearch`` package is not installed.
    AccessibilityError
        `sioff.services.accessibility.AccessibilityError`, when folding
        ``genome_file`` fails, an accessibility profile is missing or
        malformed, ``accessibility_dir`` holds no profile, or the cache
        cannot be written.
    WorkerFailureError
        `sioff.core.off_targets.WorkerFailureError`, when an input file
        could not be split or a siRNA could not be scored. With
        ``stream=True`` it is raised after the last siRNA that succeeded; with
        ``stream=False`` nothing is returned, so the frames already scored are
        discarded.

    See Also
    --------
    search : Produce a ``predictions`` frame in the schema this function accepts.
    accessibility : Produce the in-memory ``accessibility`` profiles.

    Examples
    --------
    A predictions file with annotation, pre-computed accessibility, a siRNA
    table and an alpha sweep:

    >>> import sioff
    >>> df = sioff.off_targets(
    ...     risearch_file="predictions.tsv",
    ...     gtf_file="annotation.gtf",
    ...     accessibility_dir="accessibility/",
    ...     sirna_table="sirna_table.tsv",
    ...     alpha="0.8;1.0",
    ...     gamma="1.0",
    ... )
    >>> df.select("sirna_id", "transcript_id", "P_off_target").head()

    A directory of per-siRNA files, consumed as a stream and torn down promptly:

    >>> import contextlib
    >>> gen = sioff.off_targets(risearch_file="predictions/", n_workers=8, stream=True)
    >>> with contextlib.closing(gen) as frames:
    ...     for frame in frames:
    ...         print(frame["sirna_id"][0], frame.height)
    """
    core_gen = _off_targets.compute_off_targets(
        predictions=predictions,
        risearch_file=_p(risearch_file),
        sirna_fasta=_p(sirna_fasta),
        target_fasta=_p(target_fasta),
        target_index=_p(target_index),
        gtf_file=_p(gtf_file),
        feature_type=feature_type,
        expression_metric=expression_metric,
        transcriptome_format=transcriptome_format,
        accessibility=accessibility,
        accessibility_dir=_p(accessibility_dir),
        accessibility_cache_dir=_p(accessibility_cache_dir),
        genome_file=_p(genome_file),
        window_size=window_size,
        max_span=max_span,
        unpaired_prob=unpaired_prob,
        temperature=temperature,
        matrix=matrix,
        sirna_table=_p(sirna_table),
        alpha=alpha,
        gamma=gamma,
        theta=theta,
        sense_only=sense_only,
        predictions_type=predictions_type,
        n_workers=n_workers,
        detailed_report=detailed_report,
    )
    if stream:
        return _frames(core_gen)
    frames = [frame for frame, _meta in core_gen]
    return pl.concat(frames, how="vertical_relaxed") if frames else pl.DataFrame()

search

search(
    query: Union[str, Path],
    index: Union[str, Path],
    target: Optional[Union[str, Path]] = None,
    seed_length: int = 6,
    max_extension: int = 20,
    energy_threshold: float = -10.0,
    seed_start: Optional[int] = None,
    seed_end: Optional[int] = None,
    seed_wobble: bool = True,
    matrix: Union[str, Path] = "t04",
    mismatches: int = 0,
    mismatch_prefix: int = 1,
    mismatch_suffix: int = 0,
    temperature: int = 37,
    penalty: float = 0.0,
    seed_energy: float = 0.0,
    no_max_prune: bool = False,
    no_dedup: bool = False,
    alignment: bool = False,
    threads: Optional[int] = None,
    sense_only: bool = False,
) -> pl.DataFrame

Run a RIsearch search and return the hits as a DataFrame.

Searches every sequence in query against a RIsearch index in-process (no subprocess, no intermediate file) and returns the hits in the schema off_targets accepts through its predictions argument. Mirrors the sioff search command; the defaults reproduce its behaviour, and the function requires the external risearch package.

seed_start / seed_end / seed_length are the RIsearch2 -s n:m/l seed specification and seed_wobble=False is --noGUseed; both affect where seeds may be placed, not the energy model. matrix (-z) selects the nearest-neighbour parameter set: a bundled id (see sioff.services.risearch_service.VALID_DSM_IDS for the models risearch ships) or, given a path, a custom long-form DSM TSV table. Every other risearch.search option is passed through too, each with siOFF's own default, so an upstream default change cannot move the results.

Parameters:

Name Type Description Default
query str or Path

Query siRNA FASTA. CLI: the QUERY argument.

required
index str or Path

RIsearch index built by index or sioff index. CLI: the INDEX argument.

required
target str or Path

FASTA the index was built from, used to map RIsearch's integer target indices back to sequence names. Optional in the signature, but required in practice through this function: the name registry that could resolve it lives in a service instance this call does not keep, so omitting it raises RIsearchError. CLI: -t/--target.

None
seed_length int

Seed length l in nucleotides. With seed_start / seed_end it must not exceed the window seed_end - seed_start + 1. CLI: the l part of -s/--seed.

6
max_extension int

Maximum extension length on each side of the seed. CLI: -e/--max-extension.

20
energy_threshold float

Energy threshold in kcal/mol; only hits with energy below this value are kept. CLI: -E/--energy.

-10.0
seed_start int

First 1-based query position the seed may occupy (n in -s n:m/l). Must be given together with seed_end; both None constrains the seed by length only, RIsearch's default. CLI: the n part of -s/--seed.

None
seed_end int

Last 1-based query position the seed may occupy (m in -s n:m/l), inclusive and not below seed_start. CLI: the m part of -s/--seed.

None
seed_wobble bool

Allow G:U wobble pairs inside the seed. False is RIsearch2's --noGUseed: a candidate-generation filter that changes seed placement, not scoring. CLI: --no-gu-seed sets it to False.

True
matrix str or Path

Nearest-neighbour energy parameter set: one of the bundled ids "t04" (Turner 2004, RNA-RNA), "slh04" (SantaLucia-Hicks 2004, DNA-DNA), "s95-rna-dna" or "s95-dna-rna" (Sugimoto 1995, RNA/DNA hybrids), or the path of a custom long-form DSM TSV table with columns q1 q2 t1 t2 delta_g_kcal_per_mol. CLI: -z/--matrix.

"t04"
mismatches int

Mismatches allowed inside a seed (RIsearch's --mismatch-max). A mismatched seed that holds an uninterrupted run of the full seed length is dropped, as the perfect seed covers it. CLI: --mismatches.

0
mismatch_prefix int

Matches required at the seed's 5' end before any mismatch. CLI: --mismatch-prefix.

1
mismatch_suffix int

Matches required at the seed's 3' end after any mismatch. CLI: --mismatch-suffix.

0
temperature int

Energy-model temperature in °C, 0 to 50; a custom DSM table ignores it. CLI: -T/--temperature.

37
penalty float

kcal/mol added per extended nucleotide, included in the reported energy. RIsearch2's C -d took dacal/mol: its recommended 30 is 0.3 here. CLI: -d/--penalty.

0.0
seed_energy float

Accepted by risearch for compatibility; it has no effect in risearch 3.0.0a4/a5. CLI: --seed-energy.

0.0
no_max_prune bool

Also extend non-maximal seeds, which gives redundant hits. CLI: --no-max-prune.

False
no_dedup bool

Report every seed's hit instead of one best hit per duplex. CLI: --no-dedup.

False
alignment bool

Add the columns q_start, q_end (first and last paired query nucleotide, counted from 1 like start/end) and alignment (pairing string, query 5' to 3': P pair, W G:U, U mismatch, T / Q extra target / query base). CLI: --alignment.

False
threads int

Worker threads; None uses RAYON_NUM_THREADS, else every core. CLI: -j/--threads.

None
sense_only bool

Keep only +-strand hits, for a target whose records are already in sense orientation, such as a transcriptome. A siOFF filter, not a risearch option: risearch indexes and searches both strands, so this shrinks the returned frame but not the search's time or memory. CLI: --sense-only.

False

Returns:

Type Description
DataFrame

One row per hit with the columns sirna_id (query record ID), chrom (target sequence name), start, end, strand and energy (hybridisation energy, kcal/mol), followed by q_start, q_end and alignment when alignment is set. start and end are the first and last target nucleotide of the site, counted from 1 along the target as written, for hits on either strand: the RIsearch2 convention, and the one off_targets reads. (The risearch package itself counts from 0.)

Raises:

Type Description
FileNotFoundError

When query or index does not exist.

RIsearchError

sioff.services.risearch_service.RIsearchError, when target cannot be resolved, matrix is neither a bundled id nor an existing file, the seed specification is inconsistent (seed_start without seed_end, seed_start < 1, seed_end < seed_start, or a seed longer than its window), a mismatch count is negative, temperature is outside 0-50 °C, threads is below 1, or the search itself fails, including when the risearch package is not installed.

See Also

index : Build the index this function queries. off_targets : Accepts the returned frame as predictions.

Examples:

>>> import sioff
>>> idx = sioff.index("target.fa")
>>> hits = sioff.search(
...     "sirnas.fa",
...     idx,
...     target="target.fa",
...     seed_start=2,
...     seed_end=8,
...     seed_length=7,
...     seed_wobble=False,
...     energy_threshold=-15.0,
... )
>>> hits.columns
['sirna_id', 'chrom', 'start', 'end', 'strand', 'energy']
>>> df = sioff.off_targets(predictions=hits, gtf_file="annotation.gtf")
Source code in src/sioff/api.py
def search(
    query: Union[str, Path],
    index: Union[str, Path],
    target: Optional[Union[str, Path]] = None,
    seed_length: int = 6,
    max_extension: int = 20,
    energy_threshold: float = -10.0,
    seed_start: Optional[int] = None,
    seed_end: Optional[int] = None,
    seed_wobble: bool = True,
    matrix: Union[str, Path] = "t04",
    mismatches: int = 0,
    mismatch_prefix: int = 1,
    mismatch_suffix: int = 0,
    temperature: int = 37,
    penalty: float = 0.0,
    seed_energy: float = 0.0,
    no_max_prune: bool = False,
    no_dedup: bool = False,
    alignment: bool = False,
    threads: Optional[int] = None,
    sense_only: bool = False,
) -> pl.DataFrame:
    """Run a RIsearch search and return the hits as a DataFrame.

    Searches every sequence in *query* against a RIsearch *index* in-process
    (no subprocess, no intermediate file) and returns the hits in the schema
    [`off_targets`][sioff.off_targets] accepts through its ``predictions`` argument. Mirrors
    the ``sioff search`` command; the defaults reproduce its behaviour, and the
    function requires the external ``risearch`` package.

    ``seed_start`` / ``seed_end`` / ``seed_length`` are the RIsearch2
    ``-s n:m/l`` seed specification and ``seed_wobble=False`` is
    ``--noGUseed``; both affect where seeds may be placed, not the energy
    model. ``matrix`` (``-z``) selects the nearest-neighbour parameter set: a
    bundled id (see `sioff.services.risearch_service.VALID_DSM_IDS` for
    the models risearch ships) or, given a path, a custom long-form DSM TSV
    table. Every other ``risearch.search`` option is passed through too, each
    with siOFF's own default, so an upstream default change cannot move the
    results.

    Parameters
    ----------
    query : str or pathlib.Path
        Query siRNA FASTA. CLI: the ``QUERY`` argument.
    index : str or pathlib.Path
        RIsearch index built by [`index`][sioff.index] or ``sioff index``. CLI: the
        ``INDEX`` argument.
    target : str or pathlib.Path, optional
        FASTA the index was built from, used to map RIsearch's integer target
        indices back to sequence names. Optional in the signature, but required
        in practice through this function: the name registry that could resolve
        it lives in a service instance this call does not keep, so omitting it
        raises ``RIsearchError``. CLI: ``-t/--target``.
    seed_length : int, default 6
        Seed length ``l`` in nucleotides. With ``seed_start`` / ``seed_end`` it
        must not exceed the window ``seed_end - seed_start + 1``. CLI: the
        ``l`` part of ``-s/--seed``.
    max_extension : int, default 20
        Maximum extension length on each side of the seed. CLI:
        ``-e/--max-extension``.
    energy_threshold : float, default -10.0
        Energy threshold in kcal/mol; only hits with energy below this value
        are kept. CLI: ``-E/--energy``.
    seed_start : int, optional
        First 1-based query position the seed may occupy (``n`` in
        ``-s n:m/l``). Must be given together with ``seed_end``; both ``None``
        constrains the seed by length only, RIsearch's default. CLI: the ``n``
        part of ``-s/--seed``.
    seed_end : int, optional
        Last 1-based query position the seed may occupy (``m`` in
        ``-s n:m/l``), inclusive and not below ``seed_start``. CLI: the ``m``
        part of ``-s/--seed``.
    seed_wobble : bool, default True
        Allow G:U wobble pairs inside the seed. ``False`` is RIsearch2's
        ``--noGUseed``: a candidate-generation filter that changes seed
        placement, not scoring. CLI: ``--no-gu-seed`` sets it to ``False``.
    matrix : str or pathlib.Path, default "t04"
        Nearest-neighbour energy parameter set: one of the bundled ids
        ``"t04"`` (Turner 2004, RNA-RNA), ``"slh04"`` (SantaLucia-Hicks 2004,
        DNA-DNA), ``"s95-rna-dna"`` or ``"s95-dna-rna"`` (Sugimoto 1995,
        RNA/DNA hybrids), or the path of a custom long-form DSM TSV table with
        columns ``q1 q2 t1 t2 delta_g_kcal_per_mol``. CLI: ``-z/--matrix``.
    mismatches : int, default 0
        Mismatches allowed inside a seed (RIsearch's ``--mismatch-max``). A
        mismatched seed that holds an uninterrupted run of the full seed length
        is dropped, as the perfect seed covers it. CLI: ``--mismatches``.
    mismatch_prefix : int, default 1
        Matches required at the seed's 5' end before any mismatch. CLI:
        ``--mismatch-prefix``.
    mismatch_suffix : int, default 0
        Matches required at the seed's 3' end after any mismatch. CLI:
        ``--mismatch-suffix``.
    temperature : int, default 37
        Energy-model temperature in °C, 0 to 50; a custom DSM table ignores it.
        CLI: ``-T/--temperature``.
    penalty : float, default 0.0
        kcal/mol added per extended nucleotide, included in the reported
        energy. RIsearch2's C ``-d`` took dacal/mol: its recommended 30 is 0.3
        here. CLI: ``-d/--penalty``.
    seed_energy : float, default 0.0
        Accepted by risearch for compatibility; it has no effect in risearch
        3.0.0a4/a5. CLI: ``--seed-energy``.
    no_max_prune : bool, default False
        Also extend non-maximal seeds, which gives redundant hits. CLI:
        ``--no-max-prune``.
    no_dedup : bool, default False
        Report every seed's hit instead of one best hit per duplex. CLI:
        ``--no-dedup``.
    alignment : bool, default False
        Add the columns ``q_start``, ``q_end`` (first and last paired query
        nucleotide, counted from 1 like ``start``/``end``) and ``alignment``
        (pairing string,
        query 5' to 3': ``P`` pair, ``W`` G:U, ``U`` mismatch, ``T`` / ``Q``
        extra target / query base). CLI: ``--alignment``.
    threads : int, optional
        Worker threads; ``None`` uses ``RAYON_NUM_THREADS``, else every core.
        CLI: ``-j/--threads``.
    sense_only : bool, default False
        Keep only ``+``-strand hits, for a target whose records are already in
        sense orientation, such as a transcriptome. A siOFF filter, not a
        risearch option: risearch indexes and searches both strands, so this
        shrinks the returned frame but not the search's time or memory. CLI:
        ``--sense-only``.

    Returns
    -------
    polars.DataFrame
        One row per hit with the columns ``sirna_id`` (query record ID),
        ``chrom`` (target sequence name), ``start``, ``end``, ``strand`` and
        ``energy`` (hybridisation energy, kcal/mol), followed by ``q_start``,
        ``q_end`` and ``alignment`` when *alignment* is set. ``start`` and
        ``end`` are the first and last target nucleotide of the site, counted
        from 1 along the target as written, for hits on either strand: the
        RIsearch2 convention, and the one [`off_targets`][sioff.off_targets]
        reads. (The ``risearch`` package itself counts from 0.)

    Raises
    ------
    FileNotFoundError
        When *query* or *index* does not exist.
    RIsearchError
        `sioff.services.risearch_service.RIsearchError`, when *target*
        cannot be resolved, *matrix* is neither a bundled id nor an existing
        file, the seed specification is inconsistent (``seed_start`` without
        ``seed_end``, ``seed_start < 1``, ``seed_end < seed_start``, or a seed
        longer than its window), a mismatch count is negative, *temperature*
        is outside 0-50 °C, *threads* is below 1, or the search itself fails,
        including when the ``risearch`` package is not installed.

    See Also
    --------
    index : Build the index this function queries.
    off_targets : Accepts the returned frame as ``predictions``.

    Examples
    --------
    >>> import sioff
    >>> idx = sioff.index("target.fa")
    >>> hits = sioff.search(
    ...     "sirnas.fa",
    ...     idx,
    ...     target="target.fa",
    ...     seed_start=2,
    ...     seed_end=8,
    ...     seed_length=7,
    ...     seed_wobble=False,
    ...     energy_threshold=-15.0,
    ... )
    >>> hits.columns
    ['sirna_id', 'chrom', 'start', 'end', 'strand', 'energy']
    >>> df = sioff.off_targets(predictions=hits, gtf_file="annotation.gtf")
    """
    return _risearch.run_search(
        query=cast(Path, _p(query)),
        index=cast(Path, _p(index)),
        target=_p(target),
        seed_length=seed_length,
        max_extension=max_extension,
        energy_threshold=energy_threshold,
        seed_start=seed_start,
        seed_end=seed_end,
        seed_wobble=seed_wobble,
        matrix=matrix,
        mismatches=mismatches,
        mismatch_prefix=mismatch_prefix,
        mismatch_suffix=mismatch_suffix,
        temperature=temperature,
        penalty=penalty,
        seed_energy=seed_energy,
        no_max_prune=no_max_prune,
        no_dedup=no_dedup,
        alignment=alignment,
        threads=threads,
        sense_only=sense_only,
    )

Core layer

The pure, file-free core that sioff.off_targets, sioff.accessibility, sioff.index and sioff.search wrap. Functions here take and return in-memory objects (Polars DataFrames, dicts, generators) and raise plain Python exceptions.

sioff.core.off_targets

Pure core for off-target analysis.

The entry point is free of CLI concerns (no stdout, no Typer/Click exceptions): compute_off_targets is the one engine. A predictions file, a folder of them, an in-memory frame or the hits of an in-process search is split into one part per siRNA, and every siRNA is scored as its own task; it is a generator yielding (pl.DataFrame, meta) per siRNA.

The core writes no output files, with two exceptions. The in-process search builds the RIsearch index <target>.idx next to target_fasta when no target_index is given (and reuses it later). And there are temporary files: the Arrow-IPC copy of the transcriptome that every task memory-maps, the per-siRNA split parts (none for a Parquet input that already holds one siRNA), and accessibility profiles spilled to disk so workers can memory-map them. They live inside the generator's try/finally and are removed when the run ends, on error too, so callers should consume the generator fully (or close it) for deterministic cleanup. The accessibility cache built next to -a profiles is kept: it is reused by later runs.

meta carries the partition-function state downstream formatters need: z_per_sirna and on_target_weights.

The public wrapper sioff.off_targets adds path coercion and the choice between one DataFrame and a stream on top of this layer; sioff.accessibility, sioff.index and sioff.search wrap the other core modules.

WorkerFailureError

Bases: RuntimeError

Raised by compute_off_targets when worker tasks failed.

Successful siRNAs are still yielded first; the error is raised once every task has been attempted. failures holds (task_name, error_message) pairs in completion order: in compute_off_targets a task is an input file that could not be split (named by its file name) or a siRNA that could not be scored (named by its sirna_id).

Source code in src/sioff/core/off_targets.py
class WorkerFailureError(RuntimeError):
    """Raised by `compute_off_targets` when worker tasks failed.

    Successful siRNAs are still yielded first; the error is raised once every
    task has been attempted. ``failures`` holds
    ``(task_name, error_message)`` pairs in completion order: in
    `compute_off_targets` a task is an input file that could not be split
    (named by its file name) or a siRNA that could not be scored (named by its
    ``sirna_id``).
    """

    def __init__(self, stage: str, failures: list[tuple[str, str]], n_total: int):
        self.stage = stage
        self.failures = failures
        self.n_total = n_total
        name, msg = failures[0]
        super().__init__(
            f"{len(failures)}/{n_total} tasks failed (input files or siRNAs) in "
            f"{stage}; first error: {name}: {msg}"
        )

    @property
    def n_failed(self) -> int:
        """Number of tasks that failed."""
        return len(self.failures)

    @property
    def failed_names(self) -> list[str]:
        """Names (input files or siRNAs) of the failed tasks, in completion order."""
        return [name for name, _ in self.failures]

failed_names property

failed_names: list[str]

Names (input files or siRNAs) of the failed tasks, in completion order.

n_failed property

n_failed: int

Number of tasks that failed.

compute_off_targets

compute_off_targets(
    *,
    predictions: Optional[DataFrame] = None,
    risearch_file: Optional[Path] = None,
    sirna_fasta: Optional[Path] = None,
    target_fasta: Optional[Path] = None,
    target_index: Optional[Path] = None,
    gtf_file: Optional[Path] = None,
    feature_type: Optional[str] = None,
    expression_metric: str = "RPKM",
    transcriptome_format: str = "auto",
    accessibility: Optional[Mapping[str, DataFrame]] = None,
    accessibility_dir: Optional[Path] = None,
    accessibility_cache_dir: Optional[Path] = None,
    genome_file: Optional[Path] = None,
    window_size: int = 80,
    max_span: int = 40,
    unpaired_prob: int = 30,
    temperature: float = 37.0,
    matrix: Union[str, Path] = "t04",
    sirna_table: Optional[Path] = None,
    alpha: str = "1.0",
    gamma: str = "1.0",
    theta: str = "",
    sense_only: bool = False,
    predictions_type: str = "gw",
    n_workers: int = 1,
    summary_only: bool = False,
    detailed_report: bool = False,
    worker_log_level: str = "WARNING",
    on_split: Optional[Callable[[int], None]] = None,
    accessibility_progress_callback=None,
) -> Generator[tuple[pl.DataFrame, dict], None, None]

Compute off-target probabilities, one siRNA at a time.

A generator yielding (df, meta) per siRNA, in completion order. Every input takes the same path: a file is treated as a folder holding one file, and every input file is split into one Parquet part per sirna_id. A single sioff search TSV holding every siRNA and a folder of per-siRNA files therefore run the same way, and so do the predictions frame and the hits of the in-process search, which are split in this process. A sirna_id found in two input files is an error. Each siRNA is then scored as its own task: its part is loaded, filtered to the sense strand with sense_only, intersected with the transcriptome and scored with the per-siRNA partition function. siRNAs with no predictions left after filtering and intersection are skipped.

E_min (the reference of the alpha/gamma clamp) follows the legacy rule: the lower of the siRNA's perfect-match energy, computed from its sirna_table sequence with matrix, and the strongest hit left after sense_only and the intersection. The perfect-match energies are computed when an alpha/gamma pair other than (1, 1) is, and every siRNA with predictions then needs a table row, or with detailed_report. The clamp alone uses E_min, and never at the baseline.

Tasks run in a pool of spawned worker processes (spawn rather than fork avoids Rayon/Polars thread-pool deadlocks), started only when more than one task can run at once. Otherwise they run in this process. Splitting the input files and scoring the siRNAs share the pool. A failed task is logged and skipped; once every successful siRNA has been yielded, a WorkerFailureError summarising the failures is raised, so a run where tasks failed never looks like an empty success.

Checks and warnings are made in this process, before any siRNA is scored: a siRNA missing from the table (an error when E_min is needed, a warning otherwise), table rows without predictions (an info line), and on-target IDs without gtf_file (a warning). After the last siRNA, the siRNAs whose on-target matched no row are named in one warning.

Default opening energies: a hit on a sequence without a profile, or outside its sequence's profile, keeps the default 10.0 kcal/mol, which all but removes it from the partition function. After the last siRNA one warning per kind gives the number of such hits and up to ten sequence names; if no hit of the run has a profile, an AccessibilityError is raised instead.

Accessibility reaches the workers as a memory-mapped packed cache, whatever its source: the cache of accessibility_dir, the accessibility profiles written to a temporary directory and packed there, or genome_file folded into one. Without any of them, opening energies are treated as zero.

Temporary files: the transcriptome is written once to an Arrow IPC file that every task memory-maps, the split parts go to another temporary directory, and so do the packed accessibility profiles or the genome_file fold. All of them are removed in a finally, on error too. Consume the generator fully, call .close() on it, or wrap it in contextlib.closing for deterministic teardown.

Parameters:

Name Type Description Default
predictions DataFrame

In-memory predictions, typically the value returned by sioff.search. Must contain the columns sirna_id, chrom, start, end, strand, energy; extra columns are dropped and compatible dtypes are cast to the RIsearch schema. chrom is cut at its first whitespace, as for risearch_file.

None
risearch_file Path

A predictions file, or a directory of them (CLI -r/--risearch-file): RIsearch2 output (plain or .gz), a sioff search TSV, or Parquet. From a directory every *.gz, *.tsv, *.out and *.parquet is read, each holding one siRNA or many. A target is named by the first word of its FASTA header, as in the annotation and the accessibility profiles: the risearch command line writes the whole header, which is cut at its first whitespace.

None
sirna_fasta Path

Query FASTA for an in-process RIsearch run against target_fasta (CLI -s/--sirna-fasta), searched with matrix; duplicate sequence IDs are rejected. It is only the query: it cannot be combined with risearch_file or predictions, and the perfect-match energies come from sirna_table.

None
target_fasta Path

Target FASTA (genome or transcriptome) for the in-process search (CLI --target-fasta/--genome); required with sirna_fasta and refused with risearch_file or predictions.

None
target_index Path

Pre-built RIsearch index for target_fasta (CLI -idx/--target-index); refused with risearch_file or predictions. When omitted the index is built (or reused) next to target_fasta.

None
gtf_file Path

Transcriptome annotation, GTF or GFF3 (CLI -t/--transcriptome). Rows with expression <= 0 are dropped; predictions are intersected with the rest and annotated with transcript_id, gene_id and exp_value. Read before genome_file is folded.

None
feature_type str

Feature type (column 3) of the annotation rows to use (CLI --feature). Default: "exon" for genome-wide predictions, where a site has to lie in an exon, and "transcript" for transcriptome-wide ones, where a hit names its transcript. A type that no row of the file has is an error.

None
expression_metric str

Annotation attribute used as the expression score (CLI --expression-metric). It must be each transcript's own abundance: every transcript containing a site adds its value, so a gene-level value copied onto every transcript counts the gene once per isoform.

"RPKM"
transcriptome_format str

Annotation format: "auto", "gtf" or "gff3"; BED is rejected (CLI --transcriptome-format).

"auto"
accessibility Mapping[str, DataFrame]

In-memory accessibility profiles, dict[chrom -> DataFrame] with the columns position, strand, u1..uN and both strands stacked, as returned by sioff.accessibility. They are written to a temporary directory, one <chrom>.accessibility.parquet per key, and packed there, so a key cannot be empty, . or .., or hold /, the path separator, a NUL or whitespace (a target is matched by the first word of its name). Mutually exclusive with accessibility_dir.

None
accessibility_dir Path

The npy cache from sioff accessibility or per-chromosome Parquet files (CLI -a/--accessibility-dir). For Parquet the cache is built (or rebuilt, when older than its Parquet) in accessibility_cache_dir first, before anything else is read. Mutually exclusive with accessibility.

None
accessibility_cache_dir Path

Where the cache of accessibility_dir is read from and built; default accessibility_dir (CLI --accessibility-cache-dir). Created if absent. Refused without accessibility_dir: alone it would be unused, and the cache of accessibility or genome_file lives in a temporary directory.

None
genome_file Path

Genome FASTA to fold during the run (CLI -f/--fasta), straight into a packed cache in a temporary directory. Refused with accessibility or accessibility_dir.

None
window_size int

RNAplfold window size for folding genome_file (CLI -W/--window).

80
max_span int

Maximum base-pair span for folding genome_file (CLI -L/--span).

40
unpaired_prob int

Maximum unpaired-stretch length for folding genome_file (CLI -u/--unpaired).

30
temperature float

Temperature in degrees Celsius of everything this run computes (CLI -T/--temperature): the RT term of the partition function, the genome_file fold, the in-process search of sirna_fasta and the perfect-match energies of sirna_table. The last two are RIsearch energies, which take whole degrees from 0 to 50. Inputs computed earlier keep their own temperature: fold the accessibility / accessibility_dir profiles and search the risearch_file / predictions hits at this temperature too.

37.0
matrix str or Path

Energy parameter set for the perfect-match energies: a bundled id or the path of a DSM TSV table (CLI -z/--matrix). Use the set the predictions were searched with: E_min is the reference energy of the alpha/gamma clamp.

"t04"
sirna_table Path

Tab-separated siRNA table with a header (CLI --sirna-table): sirna_id, on_target_id (a transcript or gene ID; may be empty) and sequence (the guide strand). Gives each siRNA's on-target and its perfect-match energy. Required when an alpha/gamma pair other than (1, 1) is computed.

None
alpha str

Alpha clamping parameter(s) as a ";"-separated string, e.g. "0.8;1.0" (CLI --alpha). Every alpha is paired with every gamma; pairs with alpha > gamma are dropped, duplicates are removed and the baseline (1.0, 1.0) is always included.

"1.0"
gamma str

Gamma clamping parameter(s), same format as alpha (CLI --gamma).

"1.0"
theta str

Theta scaling parameter(s) as a ";"-separated string, e.g. "0.5;0.7" (CLI --theta). Empty means no theta scaling.

""
sense_only bool

Keep only sense-strand (+) predictions (CLI --sense-only).

False
predictions_type str

"gw" for genome-wide predictions (interval intersection with the annotation) or "tw" for transcriptome-wide predictions (join on transcript ID) (CLI --type). Either way a site counts once per transcript: for "tw" the annotation is reduced to one row per transcript_id, whose rows must agree on expression.

"gw"
n_workers int

Worker processes for splitting and scoring (CLI -j/--workers). A pool is started only when more than one task can run at once.

1
summary_only bool

Only the per-siRNA sums are needed (CLI --summary-only): siRNAs are scored with aggregate_only and df is empty. meta is unchanged and carries "n_rows", the number of scored rows.

False
detailed_report bool

Keep the raw boltzmann_weight*, Z_sirna* and E_min columns in each df (CLI --detailed-report). E_min follows the rule above for a siRNA with a sirna_table row; for one without (no table, or a baseline run's missing row) it is the strongest hit left. Refused with summary_only.

False
worker_log_level str

The loguru level of the spawned workers' stderr sink. They do not inherit this process's handlers, and loguru's own default is DEBUG. The CLI passes "DEBUG" under sioff -v. A run without a pool logs through this process's handlers instead.

"WARNING"
on_split callable

Called once with the number of siRNAs to score, after the inputs are split and checked and before any siRNA is scored.

None
accessibility_progress_callback callable

Called as callback(advance=n, description=str) after each batch of n records of genome_file is folded.

None

Yields:

Type Description
tuple[DataFrame, dict]

(df, meta) for one siRNA. df holds the input columns sirna_id, chrom, start, end, strand, energy, the annotation columns trans_start, trans_end, gene_id, transcript_id, exp_value when gtf_file is given, opening_energy, dG_total, is_on_target and P_off_target, plus dG_total, energy and P_off_target repeated with a :alpha=A,gamma=G or :theta=T suffix for each extra parameter set (empty with summary_only). With detailed_report it also holds E_min, boltzmann_weight* and Z_sirna* (Float64; every P_off_target* column is Float32). meta contains "n_sirnas", "n_rows", "z_per_sirna" ({sirna_id: row} with the Z_sirna* sums), "on_target_weights", "on_target_count", "n_on_target_rows", "default_opening_energy" (with an accessibility source: how many of the siRNA's hits were looked up, found a profile value, are on a sequence without a profile or lie outside their sequence's profile, the last two kept at the default 10.0 kcal/mol, with up to ten sequence names each; None without a source) and "_timings" (per-stage wall times of the task: load_s, intersect_s, prob_s, serialize_s, total_s and the intersection sub-timings). With gtf_file, "on_target_weights" maps each siRNA to its weight sums per parameter set (suffixed as the columns, with and without accessibility): W_on/W_on_noacc over its on-target rows and W_off/W_off_noacc over the others, the .summary's Zoff, summed directly rather than taken as Z - W_on.

Raises:

Type Description
ValueError

When detailed_report and summary_only are both set. When an argument would go unused: both predictions and risearch_file, or both accessibility and accessibility_dir; sirna_fasta, target_fasta or target_index with risearch_file or predictions; genome_file with accessibility or accessibility_dir; accessibility_cache_dir without accessibility_dir. Also when accessibility is empty or has a key that cannot be a file name; when no prediction source is given; when sirna_fasta is given without target_fasta; when predictions lacks a required column; when two targets of one input share the first word of their names; when no row of gtf_file has the feature type feature_type, or none has an expression above 0; when predictions_type is "tw" and rows of one transcript disagree on expression; when sirna_fasta holds a duplicate ID; when the siRNA table cannot be read; when a sirna_id occurs in two input files; and when an alpha/gamma pair other than (1, 1) is computed and a siRNA with predictions has no row in sirna_table (or there is no table).

FileNotFoundError

When risearch_file does not exist, or is a directory without prediction files; when sirna_fasta, sirna_table, target_fasta, target_index or gtf_file does not exist. All of these are checked before any profile is packed or folded.

RIsearchError

sioff.services.risearch_service.RIsearchError, when the in-process search or indexing target_fasta fails.

AccessibilityError

When accessibility_dir (and accessibility_cache_dir) holds no profile, when the cache cannot be built, or when accessibility cannot be packed or genome_file cannot be folded. After the last siRNA, when no scored hit of the run is on a sequence with a profile: the profile names and the predictions' target names do not match.

WorkerFailureError

After the last successful siRNA, when an input file could not be split or a siRNA could not be scored.

See Also

sioff.off_targets : Public wrapper.

Source code in src/sioff/core/off_targets.py
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
def compute_off_targets(
    *,
    predictions: Optional[pl.DataFrame] = None,
    risearch_file: Optional[Path] = None,
    sirna_fasta: Optional[Path] = None,
    target_fasta: Optional[Path] = None,
    target_index: Optional[Path] = None,
    gtf_file: Optional[Path] = None,
    feature_type: Optional[str] = None,
    expression_metric: str = "RPKM",
    transcriptome_format: str = "auto",
    accessibility: Optional[Mapping[str, pl.DataFrame]] = None,
    accessibility_dir: Optional[Path] = None,
    accessibility_cache_dir: Optional[Path] = None,
    genome_file: Optional[Path] = None,
    window_size: int = 80,
    max_span: int = 40,
    unpaired_prob: int = 30,
    temperature: float = 37.0,
    matrix: Union[str, Path] = "t04",
    sirna_table: Optional[Path] = None,
    alpha: str = "1.0",
    gamma: str = "1.0",
    theta: str = "",
    sense_only: bool = False,
    predictions_type: str = "gw",
    n_workers: int = 1,
    summary_only: bool = False,
    detailed_report: bool = False,
    worker_log_level: str = "WARNING",
    on_split: Optional[Callable[[int], None]] = None,
    accessibility_progress_callback=None,
) -> Generator[tuple[pl.DataFrame, dict], None, None]:
    """Compute off-target probabilities, one siRNA at a time.

    A generator yielding ``(df, meta)`` per siRNA, in completion order. Every
    input takes the same path: a file is treated as a folder holding one file,
    and every input file is split into one Parquet part per ``sirna_id``. A
    single ``sioff search`` TSV holding every siRNA and a folder of per-siRNA
    files therefore run the same way, and so do the ``predictions`` frame and
    the hits of the in-process search, which are split in this process. A
    ``sirna_id`` found in two input files is an error. Each siRNA is then
    scored as its own task: its part is
    loaded, filtered to the sense strand with ``sense_only``, intersected with
    the transcriptome and scored with the per-siRNA partition function.
    siRNAs with no predictions left after filtering and intersection are
    skipped.

    **E_min** (the reference of the alpha/gamma clamp) follows the legacy
    rule: the lower of the siRNA's perfect-match energy, computed from its
    ``sirna_table`` sequence with ``matrix``, and the strongest hit left
    after ``sense_only`` and the intersection. The perfect-match energies are
    computed when an alpha/gamma pair other than (1, 1) is, and every siRNA
    with predictions then needs a table row, or with ``detailed_report``.
    The clamp alone uses E_min, and never at the baseline.

    **Tasks** run in a pool of spawned worker processes (``spawn`` rather
    than ``fork`` avoids Rayon/Polars thread-pool deadlocks), started only
    when more than one task can run at once. Otherwise they run in this
    process. Splitting the input files and scoring the siRNAs share the pool.
    A failed task is logged and skipped; once every successful siRNA has been
    yielded, a `WorkerFailureError` summarising the failures is raised, so a
    run where tasks failed never looks like an empty success.

    **Checks and warnings** are made in this process, before any siRNA is
    scored: a siRNA missing from the table (an error when E_min is needed, a
    warning otherwise), table rows without predictions (an info line), and
    on-target IDs without ``gtf_file`` (a warning). After the last siRNA, the
    siRNAs whose on-target matched no row are named in one warning.

    **Default opening energies**: a hit on a sequence without a profile, or
    outside its sequence's profile, keeps the default 10.0 kcal/mol, which
    all but removes it from the partition function. After the last siRNA
    one warning per kind gives the number of such hits and up to ten
    sequence names; if no hit of the run has a profile, an
    `AccessibilityError` is raised instead.

    **Accessibility** reaches the workers as a memory-mapped packed cache,
    whatever its source: the cache of ``accessibility_dir``, the
    ``accessibility`` profiles written to a temporary directory and packed
    there, or ``genome_file`` folded into one. Without any of them, opening
    energies are treated as zero.

    **Temporary files**: the transcriptome is written once to an Arrow IPC
    file that every task memory-maps, the split parts go to another temporary
    directory, and so do the packed ``accessibility`` profiles or the
    ``genome_file`` fold. All of them are removed in a ``finally``, on error
    too. Consume the generator fully, call ``.close()`` on it, or wrap it in
    `contextlib.closing` for deterministic teardown.

    Parameters
    ----------
    predictions : polars.DataFrame, optional
        In-memory predictions, typically the value returned by
        [`sioff.search`][sioff.search]. Must contain the columns ``sirna_id,
        chrom, start, end, strand, energy``; extra columns are dropped and
        compatible dtypes are cast to the RIsearch schema. ``chrom`` is cut
        at its first whitespace, as for ``risearch_file``.
    risearch_file : pathlib.Path, optional
        A predictions file, or a directory of them (CLI
        ``-r/--risearch-file``): RIsearch2 output (plain or ``.gz``), a
        ``sioff search`` TSV, or Parquet. From a directory every ``*.gz``,
        ``*.tsv``, ``*.out`` and ``*.parquet`` is read, each holding one siRNA
        or many. A target is named by the first word of its FASTA header,
        as in the annotation and the accessibility profiles: the
        ``risearch`` command line writes the whole header, which is cut at
        its first whitespace.
    sirna_fasta : pathlib.Path, optional
        Query FASTA for an in-process RIsearch run against ``target_fasta``
        (CLI ``-s/--sirna-fasta``), searched with ``matrix``; duplicate
        sequence IDs are rejected. It is only the query: it cannot be
        combined with ``risearch_file`` or ``predictions``, and the
        perfect-match energies come from ``sirna_table``.
    target_fasta : pathlib.Path, optional
        Target FASTA (genome or transcriptome) for the in-process search
        (CLI ``--target-fasta``/``--genome``); required with ``sirna_fasta``
        and refused with ``risearch_file`` or ``predictions``.
    target_index : pathlib.Path, optional
        Pre-built RIsearch index for ``target_fasta`` (CLI
        ``-idx/--target-index``); refused with ``risearch_file`` or
        ``predictions``. When omitted the index is built (or reused) next to
        ``target_fasta``.
    gtf_file : pathlib.Path, optional
        Transcriptome annotation, GTF or GFF3 (CLI ``-t/--transcriptome``).
        Rows with expression <= 0 are dropped; predictions are intersected
        with the rest and annotated with ``transcript_id``, ``gene_id`` and
        ``exp_value``. Read before ``genome_file`` is folded.
    feature_type : str, optional
        Feature type (column 3) of the annotation rows to use (CLI
        ``--feature``). Default: ``"exon"`` for genome-wide predictions, where
        a site has to lie in an exon, and ``"transcript"`` for
        transcriptome-wide ones, where a hit names its transcript. A type
        that no row of the file has is an error.
    expression_metric : str, default "RPKM"
        Annotation attribute used as the expression score (CLI
        ``--expression-metric``). It must be each transcript's own
        abundance: every transcript containing a site adds its value, so a
        gene-level value copied onto every transcript counts the gene once
        per isoform.
    transcriptome_format : str, default "auto"
        Annotation format: ``"auto"``, ``"gtf"`` or ``"gff3"``; BED is
        rejected (CLI ``--transcriptome-format``).
    accessibility : Mapping[str, polars.DataFrame], optional
        In-memory accessibility profiles, ``dict[chrom -> DataFrame]`` with
        the columns ``position, strand, u1..uN`` and both strands stacked, as
        returned by [`sioff.accessibility`][sioff.accessibility]. They are
        written to a temporary directory, one ``<chrom>.accessibility.parquet``
        per key, and packed there, so a key cannot be empty, ``.`` or ``..``,
        or hold ``/``, the path separator, a NUL or whitespace (a target is
        matched by the first word of its name). Mutually exclusive with
        ``accessibility_dir``.
    accessibility_dir : pathlib.Path, optional
        The npy cache from ``sioff accessibility`` or per-chromosome Parquet
        files (CLI ``-a/--accessibility-dir``). For Parquet the cache is built
        (or rebuilt, when older than its Parquet) in
        ``accessibility_cache_dir`` first, before anything else is read.
        Mutually exclusive with ``accessibility``.
    accessibility_cache_dir : pathlib.Path, optional
        Where the cache of ``accessibility_dir`` is read from and built;
        default ``accessibility_dir`` (CLI ``--accessibility-cache-dir``).
        Created if absent. Refused without ``accessibility_dir``: alone it
        would be unused, and the cache of ``accessibility`` or
        ``genome_file`` lives in a temporary directory.
    genome_file : pathlib.Path, optional
        Genome FASTA to fold during the run (CLI ``-f/--fasta``), straight
        into a packed cache in a temporary directory. Refused with
        ``accessibility`` or ``accessibility_dir``.
    window_size : int, default 80
        RNAplfold window size for folding ``genome_file`` (CLI
        ``-W/--window``).
    max_span : int, default 40
        Maximum base-pair span for folding ``genome_file`` (CLI
        ``-L/--span``).
    unpaired_prob : int, default 30
        Maximum unpaired-stretch length for folding ``genome_file`` (CLI
        ``-u/--unpaired``).
    temperature : float, default 37.0
        Temperature in degrees Celsius of everything this run computes (CLI
        ``-T/--temperature``): the ``RT`` term of the partition function,
        the ``genome_file`` fold, the in-process search of ``sirna_fasta``
        and the perfect-match energies of ``sirna_table``. The last two are
        RIsearch energies, which take whole degrees from 0 to 50. Inputs
        computed earlier keep their own temperature: fold the
        ``accessibility`` / ``accessibility_dir`` profiles and search the
        ``risearch_file`` / ``predictions`` hits at this temperature too.
    matrix : str or pathlib.Path, default "t04"
        Energy parameter set for the perfect-match energies: a bundled id or
        the path of a DSM TSV table (CLI ``-z/--matrix``). Use the set the
        predictions were searched with: E_min is the reference energy of the
        alpha/gamma clamp.
    sirna_table : pathlib.Path, optional
        Tab-separated siRNA table with a header (CLI ``--sirna-table``):
        ``sirna_id``, ``on_target_id`` (a transcript or gene ID; may be empty)
        and ``sequence`` (the guide strand). Gives each siRNA's on-target and
        its perfect-match energy. Required when an alpha/gamma pair other than
        (1, 1) is computed.
    alpha : str, default "1.0"
        Alpha clamping parameter(s) as a ``";"``-separated string, e.g.
        ``"0.8;1.0"`` (CLI ``--alpha``). Every ``alpha`` is paired with every
        ``gamma``; pairs with ``alpha > gamma`` are dropped, duplicates are
        removed and the baseline ``(1.0, 1.0)`` is always included.
    gamma : str, default "1.0"
        Gamma clamping parameter(s), same format as ``alpha`` (CLI
        ``--gamma``).
    theta : str, default ""
        Theta scaling parameter(s) as a ``";"``-separated string, e.g.
        ``"0.5;0.7"`` (CLI ``--theta``). Empty means no theta scaling.
    sense_only : bool, default False
        Keep only sense-strand (``+``) predictions (CLI ``--sense-only``).
    predictions_type : str, default "gw"
        ``"gw"`` for genome-wide predictions (interval intersection with the
        annotation) or ``"tw"`` for transcriptome-wide predictions (join on
        transcript ID) (CLI ``--type``). Either way a site counts once per
        transcript: for ``"tw"`` the annotation is reduced to one row per
        ``transcript_id``, whose rows must agree on expression.
    n_workers : int, default 1
        Worker processes for splitting and scoring (CLI ``-j/--workers``). A
        pool is started only when more than one task can run at once.
    summary_only : bool, default False
        Only the per-siRNA sums are needed (CLI ``--summary-only``): siRNAs
        are scored with ``aggregate_only`` and ``df`` is empty. ``meta`` is
        unchanged and carries ``"n_rows"``, the number of scored rows.
    detailed_report : bool, default False
        Keep the raw ``boltzmann_weight*``, ``Z_sirna*`` and ``E_min``
        columns in each ``df`` (CLI ``--detailed-report``). ``E_min`` follows
        the rule above for a siRNA with a ``sirna_table`` row; for one
        without (no table, or a baseline run's missing row) it is the
        strongest hit left. Refused with ``summary_only``.
    worker_log_level : str, default "WARNING"
        The loguru level of the spawned workers' stderr sink. They do not
        inherit this process's handlers, and loguru's own default is DEBUG.
        The CLI passes ``"DEBUG"`` under ``sioff -v``. A run without a pool
        logs through this process's handlers instead.
    on_split : callable, optional
        Called once with the number of siRNAs to score, after the inputs are
        split and checked and before any siRNA is scored.
    accessibility_progress_callback : callable, optional
        Called as ``callback(advance=n, description=str)`` after each batch
        of ``n`` records of ``genome_file`` is folded.

    Yields
    ------
    tuple[polars.DataFrame, dict]
        ``(df, meta)`` for one siRNA. ``df`` holds the input columns
        ``sirna_id, chrom, start, end, strand, energy``, the annotation
        columns ``trans_start, trans_end, gene_id, transcript_id, exp_value``
        when ``gtf_file`` is given, ``opening_energy``, ``dG_total``,
        ``is_on_target`` and ``P_off_target``, plus ``dG_total``, ``energy``
        and ``P_off_target`` repeated with a ``:alpha=A,gamma=G`` or
        ``:theta=T`` suffix for each extra parameter set (empty with
        ``summary_only``). With ``detailed_report`` it also holds ``E_min``,
        ``boltzmann_weight*`` and ``Z_sirna*`` (Float64; every
        ``P_off_target*`` column is Float32). ``meta`` contains
        ``"n_sirnas"``, ``"n_rows"``, ``"z_per_sirna"`` (``{sirna_id: row}``
        with the ``Z_sirna*`` sums), ``"on_target_weights"``,
        ``"on_target_count"``, ``"n_on_target_rows"``,
        ``"default_opening_energy"`` (with an accessibility source: how many
        of the siRNA's hits were looked up, found a profile value, are on a
        sequence without a profile or lie outside their sequence's profile,
        the last two kept at the default 10.0 kcal/mol, with up to ten
        sequence names each; ``None`` without a source) and ``"_timings"``
        (per-stage wall times of the task: ``load_s``, ``intersect_s``,
        ``prob_s``, ``serialize_s``, ``total_s`` and the intersection
        sub-timings). With ``gtf_file``, ``"on_target_weights"`` maps each
        siRNA to its weight sums per parameter set (suffixed as the columns,
        with and without accessibility): ``W_on``/``W_on_noacc`` over its
        on-target rows and ``W_off``/``W_off_noacc`` over the others, the
        .summary's Zoff, summed directly rather than taken as Z - W_on.

    Raises
    ------
    ValueError
        When ``detailed_report`` and ``summary_only`` are both set. When an
        argument would go unused: both ``predictions`` and
        ``risearch_file``, or both ``accessibility`` and
        ``accessibility_dir``; ``sirna_fasta``, ``target_fasta`` or
        ``target_index`` with ``risearch_file`` or ``predictions``;
        ``genome_file`` with ``accessibility`` or ``accessibility_dir``;
        ``accessibility_cache_dir`` without ``accessibility_dir``.
        Also when ``accessibility`` is empty or has a key that cannot be a
        file name; when no prediction source is given; when ``sirna_fasta``
        is given without ``target_fasta``; when ``predictions`` lacks a
        required column; when two targets of one input share the first
        word of their names; when no row of ``gtf_file`` has the feature
        type ``feature_type``, or none has an expression above 0; when
        ``predictions_type`` is ``"tw"`` and rows of one transcript disagree
        on expression; when
        ``sirna_fasta`` holds a duplicate ID; when the
        siRNA table cannot be read; when a ``sirna_id`` occurs in two input
        files; and when an alpha/gamma pair other than (1, 1) is computed and
        a siRNA with predictions has no row in ``sirna_table`` (or there is
        no table).
    FileNotFoundError
        When ``risearch_file`` does not exist, or is a directory without
        prediction files; when ``sirna_fasta``, ``sirna_table``,
        ``target_fasta``, ``target_index`` or ``gtf_file`` does not exist. All
        of these are checked before any profile is packed or folded.
    RIsearchError
        `sioff.services.risearch_service.RIsearchError`, when the in-process
        search or indexing ``target_fasta`` fails.
    AccessibilityError
        When ``accessibility_dir`` (and ``accessibility_cache_dir``) holds no
        profile, when the cache cannot be built, or when ``accessibility``
        cannot be packed or ``genome_file`` cannot be folded. After the last
        siRNA, when no scored hit of the run is on a sequence with a
        profile: the profile names and the predictions' target names do not
        match.
    WorkerFailureError
        After the last successful siRNA, when an input file could not be
        split or a siRNA could not be scored.

    See Also
    --------
    sioff.off_targets : Public wrapper.
    """
    # 1. Argument combinations, the inputs and the accessibility cache.
    if detailed_report and summary_only:
        raise ValueError(
            "detailed_report adds columns to the per-interaction table, which "
            "summary_only does not build; pass one of them"
        )
    if predictions is not None and risearch_file is not None:
        raise ValueError(
            "predictions and risearch_file are two sources for the same input; "
            "pass one of them"
        )
    if sirna_fasta is not None and (
        risearch_file is not None or predictions is not None
    ):
        raise ValueError(
            "sirna_fasta is the query for the in-process search and cannot be "
            "combined with risearch_file or predictions; the perfect-match energy "
            "for E_min now comes from the siRNA table"
        )
    _check_ignored_arguments(
        risearch_file=risearch_file,
        predictions=predictions,
        target_fasta=target_fasta,
        target_index=target_index,
        accessibility=accessibility,
        accessibility_dir=accessibility_dir,
        accessibility_cache_dir=accessibility_cache_dir,
        genome_file=genome_file,
    )
    if accessibility is not None:
        _check_profile_names(accessibility)
    input_files: list[Path] = []
    frame: Optional[pl.DataFrame] = None
    if risearch_file is not None:
        input_files = _input_files(Path(risearch_file))
    elif predictions is not None:
        frame = _coerce_predictions(predictions)
    elif sirna_fasta is None:
        raise ValueError(
            "Must provide predictions (a DataFrame), risearch_file (a file "
            "or a directory) or sirna_fasta"
        )
    elif target_fasta is None:
        raise ValueError(
            "sirna_fasta requires target_fasta when running RIsearch dynamically"
        )
    else:
        # The search itself runs in step 5; duplicate query IDs fail now.
        RIsearchService().validate_sirna_fasta(Path(sirna_fasta))
    # Cheap, so a typo fails before a long genome fold or cache build.
    for path, what in (
        (sirna_table, "siRNA table"),
        (gtf_file, "Transcriptome file"),
        (target_fasta, "Target FASTA"),
        (target_index, "Index"),
    ):
        if path is not None and not Path(path).exists():
            raise FileNotFoundError(f"{what} not found: {path}")
    # Workers only ever memory-map the finished cache. In-memory profiles and
    # a fold get theirs in step 4, inside the try, so its temporary directory
    # is always removed.
    acc_dir: Optional[Path] = None
    cache_dir: Optional[Path] = None
    if accessibility_dir is not None:
        acc_dir = Path(accessibility_dir)
        cache_dir = _prepare_accessibility_cache(
            acc_dir, accessibility_cache_dir, n_workers
        )

    # 2. The siRNA table: on-targets and perfect-match sequences.
    table = read_sirna_table(Path(sirna_table)) if sirna_table is not None else {}
    on_target_map = {
        sid: rec.on_target_id for sid, rec in table.items() if rec.on_target_id
    }

    # 3. Parameters.
    alpha_gamma_pairs = _build_alpha_gamma_pairs(alpha, gamma)
    skipped_pairs = _skipped_alpha_gamma_pairs(alpha, gamma)
    if skipped_pairs:
        logger.info(f"Skipped alpha > gamma pairs: {skipped_pairs}")
    theta_vals = _parse_theta(theta)
    needs_e_min = any(pair != (1.0, 1.0) for pair in alpha_gamma_pairs)
    # The energies RIsearch computes in this run (the in-process search of
    # step 5, the perfect-match energies of step 7) are taken at the run's
    # temperature, as RT and the genome_file fold are. Checked here, before
    # any fold: RIsearch only takes whole degrees within its range.
    search_temperature = 37
    if sirna_fasta is not None or ((needs_e_min or detailed_report) and table):
        search_temperature = _energy_model_temperature(temperature)

    spill_dir: Optional[str] = None
    ipc_dir: Optional[str] = None
    split_root: Optional[str] = None
    executor: Optional[_Executor] = None
    try:
        # 4. The worker inputs. The transcriptome first: it is quick next to
        # a fold, so a bad annotation fails before the genome is folded. It
        # is sorted by (chrom, strand, start) so each task's partitions are
        # zero-copy slices of the memory-mapped file, and uncompressed so it
        # can be memory-mapped at all; see preload_transcriptome.
        ipc_path = ""
        if gtf_file is not None:
            # A transcriptome-wide hit names its transcript, so the rows that
            # describe it are the transcript rows; a genome-wide site has to
            # lie in an exon.
            feature = feature_type
            if feature is None:
                feature = (
                    "transcript" if predictions_type == PredictionsMode.TW else "exon"
                )
            df_trans = AnnotationParser().load_gtf(
                Path(gtf_file),
                feature=feature,
                score_col=expression_metric,
                format=transcriptome_format,
            )
            n_selected = df_trans.height
            if predictions_type == PredictionsMode.TW:
                # Before the unexpressed rows go: 0 and 10 disagree as well.
                df_trans = _one_row_per_transcript(
                    df_trans, Path(gtf_file).name, expression_metric
                )
            df_trans = _drop_unexpressed(df_trans)
            if df_trans.height == 0:
                # Every site would be dropped by the intersection: a run that
                # scores nothing and exits 0.
                raise ValueError(
                    f"None of the {n_selected:,} {feature or 'annotation'} "
                    f"rows of {Path(gtf_file).name} has a {expression_metric} "
                    "above 0 (a value that is not a number counts as 0), so no "
                    "site could be scored; check --expression-metric and the "
                    "values in the file"
                )
            df_trans = sort_for_preload(df_trans)
            ipc_dir = tempfile.mkdtemp(prefix="risearch_ipc_")
            ipc_path = str(Path(ipc_dir) / "transcriptome.arrow")
            df_trans.write_ipc(
                ipc_path,
                compression="uncompressed",
                compat_level=pl.CompatLevel.oldest(),
            )
            del df_trans
        # Then the profiles: held in memory, they are written out as Parquet
        # and packed; a genome is folded straight into a packed cache. -a
        # needs neither.
        if accessibility is not None:
            spill_dir = tempfile.mkdtemp(prefix="sioff_acc_")
            for chrom, profile in accessibility.items():
                profile.write_parquet(
                    Path(spill_dir) / f"{chrom}{PARQUET_SUFFIX}", compression="lz4"
                )
            acc_dir = Path(spill_dir)
            cache_dir = _prepare_accessibility_cache(acc_dir, None, n_workers)
        elif genome_file is not None:
            spill_dir = tempfile.mkdtemp(prefix="sioff_fold_")
            acc_dir = Path(spill_dir)
            GenomeAccessibilityService(acc_dir).compute_genome_accessibility(
                Path(genome_file),
                window_size=window_size,
                max_span=max_span,
                unpaired_prob=unpaired_prob,
                temperature=temperature,
                output_format="npy",
                progress_callback=accessibility_progress_callback,
            )
        executor = _Executor(
            n_workers,
            {
                "ipc_path": ipc_path,
                "accessibility_dir": str(acc_dir) if acc_dir is not None else "",
                "on_target_map": on_target_map,
                "temperature": temperature,
                "accessibility_cache_dir": (
                    str(cache_dir) if cache_dir is not None else None
                ),
                "summary_only": summary_only,
                "detailed_report": detailed_report,
                "log_level": worker_log_level,
            },
        )

        # 5. Split phase: input files in tasks, a frame here.
        split_root = tempfile.mkdtemp(prefix="sioff_split_")
        if input_files:
            parts = _split_inputs(executor, input_files, Path(split_root))
        else:
            if frame is None:
                # Step 1 checked both FASTAs and the query's IDs.
                assert sirna_fasta is not None and target_fasta is not None
                frame = _search_in_process(
                    Path(sirna_fasta),
                    Path(target_fasta),
                    Path(target_index) if target_index is not None else None,
                    matrix,
                    search_temperature,
                )
            parts = dict(sorted(split_frame(frame, Path(split_root) / "0").items()))
            frame = None  # the parts hold the rows now
        n_split_failures = len(executor.failures)

        # 6. Checks, before any scoring.
        _check_sirna_table(parts, table, needs_e_min, gtf_file is not None)
        if on_split is not None:
            on_split(len(parts))

        # 7. Perfect-match energies: the clamp needs them (every siRNA has a
        # table row by now), and the detailed report's E_min column follows
        # the same rule for every siRNA with a row.
        perfect_match: dict[str, float] = {}
        if needs_e_min or detailed_report:
            service = RIsearchService()
            perfect_match = {
                sid: service.self_hybridization_emin(
                    table[sid].sequence,
                    sid,
                    matrix=matrix,
                    temperature=search_temperature,
                )
                for sid in parts
                if sid in table
            }

        # 8. Scoring phase.
        tasks = {
            sid: (
                sid,
                str(part),
                perfect_match.get(sid),
                alpha_gamma_pairs,
                theta_vals,
                sense_only,
                predictions_type,
            )
            for sid, part in parts.items()
        }
        # Polars threads per worker, if the pool starts here: keeps
        # processes x threads within n_workers.
        n_proc = max(1, min(executor.n_workers, len(tasks)))
        n_on_target_rows: dict[str, int] = {}
        default_energy = new_default_energy_stats()
        default_sirnas = {"unknown": 0, "out_of_bounds": 0}
        for sid, (arrow_table, meta) in executor.run(
            _score_part,
            tasks,
            threads_per_worker=max(1, executor.n_workers // n_proc),
            uses_worker_state=True,
        ):
            if arrow_table is None:
                # --sense-only and the intersection left no row, so none
                # can be its on-target either.
                n_on_target_rows[sid] = 0
                continue
            n_on_target_rows.update(meta["n_on_target_rows"])
            stats = meta.get("default_opening_energy")
            if stats:
                for key in ("n_hits", "n_found", "n_unknown", "n_out_of_bounds"):
                    default_energy[key] += stats[key]
                for key in default_sirnas:
                    add_default_examples(default_energy[key], stats[key])
                    default_sirnas[key] += bool(stats[f"n_{key}"])
            df_chunk = cast(pl.DataFrame, pl.from_arrow(arrow_table))
            del arrow_table  # Polars owns the data now
            yield df_chunk, meta

        # 9. On-targets that matched no row. Without a transcriptome nothing
        # can match, and the check above already said so once.
        if gtf_file is not None:
            unmatched = sorted(
                sid
                for sid, n in n_on_target_rows.items()
                if n == 0 and sid in on_target_map
            )
            if unmatched:
                logger.warning(
                    f"{len(unmatched)} siRNA(s) have no on-target row (W_on = 0): "
                    f"{', '.join(unmatched[:10])}"
                )
        no_profile = _no_hit_has_a_profile(default_energy)
        if not no_profile:
            _warn_default_opening_energies(default_energy, default_sirnas)
        if executor.failures:
            # An input file that could not be split counts as one task: how
            # many siRNAs it held is unknown.
            raise WorkerFailureError(
                "splitting and scoring",
                executor.failures,
                n_split_failures + len(tasks),
            )
        if no_profile:
            # The names of the profiles and of the predictions do not match
            # at all; after the siRNAs, like a worker failure, since a worker
            # only knows its own.
            names = ", ".join(default_energy["unknown"])
            more = (
                ", ..."
                if len(default_energy["unknown"]) >= _MAX_DEFAULT_EXAMPLES
                else ""
            )
            raise AccessibilityError(
                f"None of the {default_energy['n_hits']:,} scored hits is on a "
                f"sequence with an accessibility profile ({names}{more}), so "
                "every opening energy is the default of "
                f"{_OUT_OF_BOUNDS_ENERGY} kcal/mol and the results are those of "
                "a run without accessibility. Profile names must equal the "
                "target names of the predictions; 'sioff accessibility' names "
                "a profile by the first word of its FASTA header"
            )
    finally:
        # 10. Pool first (its workers hold the files open), then the files,
        # even if shutting the pool down fails.
        try:
            if executor is not None:
                executor.close()
        finally:
            for tmp in (split_root, ipc_dir, spill_dir):
                if tmp is not None:
                    shutil.rmtree(tmp, ignore_errors=True)

sioff.core.accessibility

Pure core for accessibility computation, returning in-memory DataFrames.

Folds each sequence in the FASTA with ViennaRNA and returns one Polars DataFrame per chromosome (schema [position, strand, u1..u{unpaired_prob}] -- the same schema the CLI streams to {chrom}.accessibility.parquet), holding nothing on disk. For genome-scale inputs prefer the CLI's streaming path; the in-memory dict keeps every profile resident at once.

The public wrapper is sioff.accessibility; its result feeds the accessibility argument of sioff.off_targets.

compute_accessibility

compute_accessibility(
    genome: Path,
    window_size: int = 80,
    max_span: int = 40,
    unpaired_prob: int = 30,
    temperature: float = 37.0,
    strand: str = "both",
) -> dict[str, pl.DataFrame]

Compute per-chromosome accessibility profiles in memory.

Every sequence in genome is folded twice with ViennaRNA's RNAplfold model, once as given (+ strand) and once as its reverse complement (- strand); strand="+" skips the reverse complement. The resulting opening energies are returned as one Polars DataFrame per chromosome with columns [position, strand, u1..u{unpaired_prob}], the strands stacked (+ then -), matching the on-disk Parquet schema written by sioff accessibility. position is 1-based along the folded sequence and u{k} is the opening energy (kcal/mol) of the k-nt stretch ending at that position. Writes no files and keeps every profile resident at once, so prefer the CLI's streaming path for genome-scale inputs.

Parameters:

Name Type Description Default
genome Path

FASTA file whose records are folded; each record ID becomes a key of the result (CLI positional genome).

required
window_size int

RNAplfold window size W (CLI -W/--window).

80
max_span int

Maximum base-pair span L (CLI -L/--span).

40
unpaired_prob int

Maximum unpaired-stretch length u (CLI -u/--unpaired); the output holds columns u1..u{unpaired_prob}.

30
temperature float

Folding temperature in degrees Celsius (CLI -T/--temperature).

37.0
strand (both, '+')

"+" folds each sequence as given only, for a transcriptome FASTA whose records are already sense; the frames then hold no - rows (CLI --strand).

"both"

Returns:

Type Description
dict[str, DataFrame]

Mapping from chromosome (FASTA record ID) to its profile frame with columns position (Int32), strand (Utf8, "+" or "-") and u1..u{unpaired_prob} (Float32 opening energies).

Raises:

Type Description
FileNotFoundError

When genome does not exist.

AccessibilityError

sioff.services.accessibility.AccessibilityError, when strand is not "both" or "+".

See Also

sioff.accessibility : Public wrapper accepting str paths. sioff.off_targets : Consumes the returned mapping via its accessibility argument.

Source code in src/sioff/core/accessibility.py
def compute_accessibility(
    genome: Path,
    window_size: int = 80,
    max_span: int = 40,
    unpaired_prob: int = 30,
    temperature: float = 37.0,
    strand: str = "both",
) -> dict[str, pl.DataFrame]:
    """Compute per-chromosome accessibility profiles in memory.

    Every sequence in ``genome`` is folded twice with ViennaRNA's RNAplfold
    model, once as given (``+`` strand) and once as its reverse complement
    (``-`` strand); ``strand="+"`` skips the reverse complement. The resulting
    opening energies are returned as one Polars DataFrame per chromosome with
    columns ``[position, strand, u1..u{unpaired_prob}]``, the strands stacked
    (``+`` then ``-``), matching the on-disk Parquet schema written by
    ``sioff accessibility``. ``position``
    is 1-based along the folded sequence and ``u{k}`` is the opening energy
    (kcal/mol) of the ``k``-nt stretch ending at that position. Writes no
    files and keeps every profile resident at once, so prefer the CLI's
    streaming path for genome-scale inputs.

    Parameters
    ----------
    genome : pathlib.Path
        FASTA file whose records are folded; each record ID becomes a key of
        the result (CLI positional ``genome``).
    window_size : int, default 80
        RNAplfold window size ``W`` (CLI ``-W/--window``).
    max_span : int, default 40
        Maximum base-pair span ``L`` (CLI ``-L/--span``).
    unpaired_prob : int, default 30
        Maximum unpaired-stretch length ``u`` (CLI ``-u/--unpaired``); the
        output holds columns ``u1..u{unpaired_prob}``.
    temperature : float, default 37.0
        Folding temperature in degrees Celsius (CLI ``-T/--temperature``).
    strand : {"both", "+"}, default "both"
        ``"+"`` folds each sequence as given only, for a transcriptome FASTA
        whose records are already sense; the frames then hold no ``-`` rows
        (CLI ``--strand``).

    Returns
    -------
    dict[str, polars.DataFrame]
        Mapping from chromosome (FASTA record ID) to its profile frame with
        columns ``position`` (Int32), ``strand`` (Utf8, ``"+"`` or ``"-"``) and
        ``u1..u{unpaired_prob}`` (Float32 opening energies).

    Raises
    ------
    FileNotFoundError
        When ``genome`` does not exist.
    AccessibilityError
        `sioff.services.accessibility.AccessibilityError`, when ``strand`` is
        not ``"both"`` or ``"+"``.

    See Also
    --------
    sioff.accessibility : Public wrapper accepting ``str`` paths.
    sioff.off_targets : Consumes the returned mapping via its ``accessibility``
        argument.
    """
    _check_fold_strand(strand)
    genome = Path(genome)
    if not genome.exists():
        raise FileNotFoundError(f"Genome FASTA not found: {genome}")

    profiles: dict[str, pl.DataFrame] = {}
    for chrom, sequence in read_fasta(genome):
        profiles[chrom] = pl.concat(
            [
                _profile_to_df(
                    fold_sequence(
                        seq,
                        window_size=window_size,
                        max_span=max_span,
                        unpaired_prob=unpaired_prob,
                        temperature=temperature,
                    ),
                    s,
                    unpaired_prob,
                )
                for s, seq in _strands_to_fold(sequence, strand)
            ]
        )
    return profiles

sioff.core.risearch

Pure core for RIsearch index/search.

Wraps sioff.services.risearch_service.RIsearchService without any CLI side-effects (no stdout, no file writes beyond the index binary itself) and returns in-memory objects. parse_seed_spec turns the RIsearch2 -s seed string into the seed_start/seed_end/seed_length arguments of run_search.

The public wrappers are sioff.index and sioff.search.

build_index

build_index(
    target: Path, output: Optional[Path] = None
) -> Path

Build (or reuse) a RIsearch index for a target FASTA.

The index is a binary on-disk artifact consumed by run_search, so this returns its Path rather than in-memory data. An existing index at the output path is reused when it is newer than the target and rebuilt otherwise. The target is registered against the index so that a later run_search in the same process can resolve target names without target.

Exceptions from the underlying index_target propagate unchanged: FileNotFoundError when target does not exist, and RIsearchError when the risearch bindings fail to build the index.

Parameters:

Name Type Description Default
target Path

Target FASTA to index (CLI positional target).

required
output Path

Index path (CLI -o/--output). Defaults to <target>.idx next to the target file.

None

Returns:

Type Description
Path

Path of the (new or reused) index file.

See Also

sioff.index : Public wrapper accepting str paths. run_search : Searches against the index built here.

Source code in src/sioff/core/risearch.py
def build_index(target: Path, output: Optional[Path] = None) -> Path:
    """Build (or reuse) a RIsearch index for a target FASTA.

    The index is a binary on-disk artifact consumed by [`run_search`][sioff.core.risearch.run_search], so
    this returns its `Path` rather than in-memory data. An
    existing index at the output path is reused when it is newer than the
    target and rebuilt otherwise. The target is registered against the index
    so that a later [`run_search`][sioff.core.risearch.run_search] in the same process can resolve target
    names without ``target``.

    Exceptions from the underlying
    `index_target`
    propagate unchanged: `FileNotFoundError` when ``target`` does not
    exist, and `RIsearchError` when
    the risearch bindings fail to build the index.

    Parameters
    ----------
    target : pathlib.Path
        Target FASTA to index (CLI positional ``target``).
    output : pathlib.Path, optional
        Index path (CLI ``-o/--output``). Defaults to ``<target>.idx`` next to
        the target file.

    Returns
    -------
    pathlib.Path
        Path of the (new or reused) index file.

    See Also
    --------
    sioff.index : Public wrapper accepting ``str`` paths.
    run_search : Searches against the index built here.
    """
    target = Path(target)
    output = Path(output) if output is not None else None
    return RIsearchService().index_target(target, output)

parse_seed_spec

parse_seed_spec(
    spec: str,
) -> Tuple[Optional[int], Optional[int], int]

Parse a RIsearch2 -s seed specification into (start, end, length).

Accepts the forms the RIsearch2 CLI accepts, so a command line can be copied between the two without translation (CLI -s/--seed):

  • "7": length only, no positional constraint -> (None, None, 7)
  • "2:8/7": seed must lie in query positions 2..8 and be 7 nt -> (2, 8, 7)
  • "2:8": positions given, length defaults to the window width -> (2, 8, 7)

Positions are 1-based and inclusive, matching RIsearch2. Surrounding whitespace is ignored.

Parameters:

Name Type Description Default
spec str

Seed specification: "l", "n:m" or "n:m/l".

required

Returns:

Type Description
tuple[int or None, int or None, int]

(seed_start, seed_end, seed_length) ready to pass to run_search; seed_start and seed_end are None for the length-only form.

Raises:

Type Description
RIsearchError

When spec is empty, does not match any of the three forms, or gives neither positions nor a length.

See Also

run_search : Consumes the returned triple. sioff.search : Public wrapper around run_search.

Source code in src/sioff/core/risearch.py
def parse_seed_spec(spec: str) -> Tuple[Optional[int], Optional[int], int]:
    """Parse a RIsearch2 ``-s`` seed specification into ``(start, end, length)``.

    Accepts the forms the RIsearch2 CLI accepts, so a command line can be
    copied between the two without translation (CLI ``-s/--seed``):

    - ``"7"``: length only, no positional constraint -> ``(None, None, 7)``
    - ``"2:8/7"``: seed must lie in query positions 2..8 and be 7 nt
      -> ``(2, 8, 7)``
    - ``"2:8"``: positions given, length defaults to the window width
      -> ``(2, 8, 7)``

    Positions are 1-based and inclusive, matching RIsearch2. Surrounding
    whitespace is ignored.

    Parameters
    ----------
    spec : str
        Seed specification: ``"l"``, ``"n:m"`` or ``"n:m/l"``.

    Returns
    -------
    tuple[int or None, int or None, int]
        ``(seed_start, seed_end, seed_length)`` ready to pass to
        [`run_search`][sioff.core.risearch.run_search]; ``seed_start`` and ``seed_end`` are ``None`` for the
        length-only form.

    Raises
    ------
    RIsearchError
        When ``spec`` is empty, does not match any of the three forms, or gives
        neither positions nor a length.

    See Also
    --------
    run_search : Consumes the returned triple.
    sioff.search : Public wrapper around [`run_search`][sioff.core.risearch.run_search].
    """
    m = _SEED_SPEC.match(spec)
    if not m or spec.strip() == "":
        raise RIsearchError(
            f"Could not parse seed spec {spec!r}. Expected 'l', 'n:m' or 'n:m/l' "
            f"(e.g. '7', '2:8', '2:8/7')."
        )
    start, end, length = m.group(1), m.group(2), m.group(3)
    if start is None and length is None:
        raise RIsearchError(f"Could not parse seed spec {spec!r}: no length given.")
    if start is None:
        return None, None, int(length)
    s, e = int(start), int(end)
    return s, e, int(length) if length is not None else e - s + 1
run_search(
    query: Path,
    index: Path,
    target: Optional[Path] = None,
    seed_length: int = 6,
    max_extension: int = 20,
    energy_threshold: float = -10.0,
    seed_start: Optional[int] = None,
    seed_end: Optional[int] = None,
    seed_wobble: bool = True,
    matrix: Union[str, Path] = "t04",
    mismatches: int = 0,
    mismatch_prefix: int = 1,
    mismatch_suffix: int = 0,
    temperature: int = 37,
    penalty: float = 0.0,
    seed_energy: float = 0.0,
    no_max_prune: bool = False,
    no_dedup: bool = False,
    alignment: bool = False,
    threads: Optional[int] = None,
    sense_only: bool = False,
) -> pl.DataFrame

Run a RIsearch search and return hits as a Polars DataFrame.

target is required when the index was built outside this process (it is needed to resolve RIsearch's integer target indices to sequence names); after build_index in the same process it may be omitted.

Every risearch.search option is passed through, each with siOFF's own default, so an upstream default change cannot move the results; the defaults reproduce the searches siOFF ran before these options existed.

Seed geometry and energy-model parameters mirror the RIsearch2 CLI. seed_start/seed_end/seed_length are the -s n:m/l seed spec: the seed must fall within query positions n..m and be l nt long; leaving seed_start/seed_end as None constrains length only, which is RIsearch's default behaviour. seed_wobble=False is --noGUseed and forbids G:U wobble pairs inside the seed; this affects seed location only, not the energy model, so it is a candidate-generation knob rather than a rescoring one. Measured on 3,826 fly S2 3'UTRs x 10 miRNAs it removes 84.7% of hits (783,836 -> 119,928). matrix is -z, the nearest-neighbour energy parameter set: a bundled id or the path of a custom DSM TSV table.

Exceptions from the underlying run_search propagate unchanged: FileNotFoundError when query or index does not exist, and RIsearchError when target is needed but missing, the seed geometry is invalid, matrix is neither a bundled id nor an existing file, a mismatch count is negative, temperature is outside 0-50 °C, threads is below 1, or the risearch bindings fail.

Parameters:

Name Type Description Default
query Path

Query siRNA FASTA (CLI positional query).

required
index Path

Pre-built RIsearch index, typically from build_index (CLI positional index).

required
target Path

Target FASTA the index was built from (CLI -t/--target). Required when the index was built externally or in another process.

None
seed_length int

Seed length l in nt (the l of CLI -s/--seed).

6
max_extension int

Maximum extension length on each side of the seed (CLI -e/--max-extension).

20
energy_threshold float

Energy threshold in kcal/mol; only hits below this value are kept (CLI -E/--energy).

-10.0
seed_start int

First allowed 1-based query position of the seed (the n of -s n:m/l). Must be given together with seed_end.

None
seed_end int

Last allowed 1-based query position of the seed, inclusive (the m of -s n:m/l). Must be given together with seed_start.

None
seed_wobble bool

Allow G:U wobble pairs inside the seed. False is RIsearch2's --noGUseed (CLI --no-gu-seed).

True
matrix str or Path

Nearest-neighbour energy parameter set (CLI -z/--matrix): one of the bundled ids "t04" (Turner 2004, RNA-RNA), "slh04" (SantaLucia-Hicks 2004, DNA-DNA), "s95-rna-dna" or "s95-dna-rna" (Sugimoto 1995, RNA/DNA hybrids), or the path of a custom long-form DSM TSV table with columns q1 q2 t1 t2 delta_g_kcal_per_mol.

"t04"
mismatches int

Mismatches allowed inside a seed (CLI --mismatches; RIsearch's --mismatch-max). A mismatched seed that holds an uninterrupted run of the full seed length is dropped, as the perfect seed covers it.

0
mismatch_prefix int

Matches required at the seed's 5' end before any mismatch (CLI --mismatch-prefix).

1
mismatch_suffix int

Matches required at the seed's 3' end after any mismatch (CLI --mismatch-suffix).

0
temperature int

Energy-model temperature in °C, 0 to 50 (CLI -T/--temperature). A custom DSM table ignores it.

37
penalty float

kcal/mol added per extended nucleotide, included in the reported energy (CLI -d/--penalty). RIsearch2's C -d took dacal/mol: its recommended 30 is 0.3 here.

0.0
seed_energy float

Accepted by risearch for compatibility; it has no effect in risearch 3.0.0a4/a5 (CLI --seed-energy).

0.0
no_max_prune bool

Also extend non-maximal seeds, which gives redundant hits (CLI --no-max-prune).

False
no_dedup bool

Report every seed's hit instead of one best hit per duplex (CLI --no-dedup).

False
alignment bool

Add the columns q_start, q_end (first and last paired query nucleotide, counted from 1 like start/end) and alignment (pairing string, query 5' to 3': P pair, W G:U, U mismatch, T / Q extra target / query base) (CLI --alignment).

False
threads int

Worker threads; None uses RAYON_NUM_THREADS, else every core (CLI -j/--threads).

None
sense_only bool

Keep only +-strand hits, for a target whose records are already in sense orientation, such as a transcriptome (CLI --sense-only). A siOFF filter, not a risearch option: risearch still searches both strands, so the search costs the same time and memory.

False

Returns:

Type Description
DataFrame

One row per hit with columns sirna_id, chrom, start, end, strand, energy (the schema sioff.off_targets accepts as predictions), followed by q_start, q_end, alignment when alignment is set. start and end are the first and last target nucleotide of the site, counted from 1 along the target as written (the RIsearch2 convention; the risearch package counts from 0).

See Also

sioff.search : Public wrapper accepting str paths. parse_seed_spec : Builds seed_start/seed_end/seed_length from a -s string. build_index : Builds the index argument.

Source code in src/sioff/core/risearch.py
def run_search(
    query: Path,
    index: Path,
    target: Optional[Path] = None,
    seed_length: int = 6,
    max_extension: int = 20,
    energy_threshold: float = -10.0,
    seed_start: Optional[int] = None,
    seed_end: Optional[int] = None,
    seed_wobble: bool = True,
    matrix: Union[str, Path] = "t04",
    mismatches: int = 0,
    mismatch_prefix: int = 1,
    mismatch_suffix: int = 0,
    temperature: int = 37,
    penalty: float = 0.0,
    seed_energy: float = 0.0,
    no_max_prune: bool = False,
    no_dedup: bool = False,
    alignment: bool = False,
    threads: Optional[int] = None,
    sense_only: bool = False,
) -> pl.DataFrame:
    """Run a RIsearch search and return hits as a Polars DataFrame.

    ``target`` is required when the index was built outside this process (it
    is needed to resolve RIsearch's integer target indices to sequence names);
    after [`build_index`][sioff.core.risearch.build_index] in the same process it may be omitted.

    Every ``risearch.search`` option is passed through, each with siOFF's own
    default, so an upstream default change cannot move the results; the
    defaults reproduce the searches siOFF ran before these options existed.

    Seed geometry and energy-model parameters mirror the RIsearch2 CLI.
    ``seed_start``/``seed_end``/``seed_length`` are the ``-s n:m/l`` seed spec:
    the seed must fall within query positions ``n..m`` and be ``l`` nt long;
    leaving ``seed_start``/``seed_end`` as ``None`` constrains length only,
    which is RIsearch's default behaviour. ``seed_wobble=False`` is
    ``--noGUseed`` and forbids G:U wobble pairs inside the seed; this affects
    seed location only, not the energy model, so it is a candidate-generation
    knob rather than a rescoring one. Measured on 3,826 fly S2 3'UTRs x 10
    miRNAs it removes 84.7% of hits (783,836 -> 119,928). ``matrix`` is ``-z``,
    the nearest-neighbour energy parameter set: a bundled id or the path of a
    custom DSM TSV table.

    Exceptions from the underlying
    `run_search`
    propagate unchanged: `FileNotFoundError` when ``query`` or ``index``
    does not exist, and `RIsearchError`
    when ``target`` is needed but missing, the seed geometry is invalid,
    ``matrix`` is neither a bundled id nor an existing file, a mismatch count
    is negative, ``temperature`` is outside 0-50 °C, ``threads`` is below 1,
    or the risearch bindings fail.

    Parameters
    ----------
    query : pathlib.Path
        Query siRNA FASTA (CLI positional ``query``).
    index : pathlib.Path
        Pre-built RIsearch index, typically from [`build_index`][sioff.core.risearch.build_index] (CLI
        positional ``index``).
    target : pathlib.Path, optional
        Target FASTA the index was built from (CLI ``-t/--target``). Required
        when the index was built externally or in another process.
    seed_length : int, default 6
        Seed length ``l`` in nt (the ``l`` of CLI ``-s/--seed``).
    max_extension : int, default 20
        Maximum extension length on each side of the seed (CLI
        ``-e/--max-extension``).
    energy_threshold : float, default -10.0
        Energy threshold in kcal/mol; only hits below this value are kept (CLI
        ``-E/--energy``).
    seed_start : int, optional
        First allowed 1-based query position of the seed (the ``n`` of ``-s
        n:m/l``). Must be given together with ``seed_end``.
    seed_end : int, optional
        Last allowed 1-based query position of the seed, inclusive (the ``m``
        of ``-s n:m/l``). Must be given together with ``seed_start``.
    seed_wobble : bool, default True
        Allow G:U wobble pairs inside the seed. ``False`` is RIsearch2's
        ``--noGUseed`` (CLI ``--no-gu-seed``).
    matrix : str or pathlib.Path, default "t04"
        Nearest-neighbour energy parameter set (CLI ``-z/--matrix``): one of
        the bundled ids ``"t04"`` (Turner 2004, RNA-RNA), ``"slh04"``
        (SantaLucia-Hicks 2004, DNA-DNA), ``"s95-rna-dna"`` or
        ``"s95-dna-rna"`` (Sugimoto 1995, RNA/DNA hybrids), or the path of a
        custom long-form DSM TSV table with columns
        ``q1 q2 t1 t2 delta_g_kcal_per_mol``.
    mismatches : int, default 0
        Mismatches allowed inside a seed (CLI ``--mismatches``; RIsearch's
        ``--mismatch-max``). A mismatched seed that holds an uninterrupted run
        of the full seed length is dropped, as the perfect seed covers it.
    mismatch_prefix : int, default 1
        Matches required at the seed's 5' end before any mismatch (CLI
        ``--mismatch-prefix``).
    mismatch_suffix : int, default 0
        Matches required at the seed's 3' end after any mismatch (CLI
        ``--mismatch-suffix``).
    temperature : int, default 37
        Energy-model temperature in °C, 0 to 50 (CLI ``-T/--temperature``). A
        custom DSM table ignores it.
    penalty : float, default 0.0
        kcal/mol added per extended nucleotide, included in the reported
        energy (CLI ``-d/--penalty``). RIsearch2's C ``-d`` took dacal/mol: its
        recommended 30 is 0.3 here.
    seed_energy : float, default 0.0
        Accepted by risearch for compatibility; it has no effect in risearch
        3.0.0a4/a5 (CLI ``--seed-energy``).
    no_max_prune : bool, default False
        Also extend non-maximal seeds, which gives redundant hits (CLI
        ``--no-max-prune``).
    no_dedup : bool, default False
        Report every seed's hit instead of one best hit per duplex (CLI
        ``--no-dedup``).
    alignment : bool, default False
        Add the columns ``q_start``, ``q_end`` (first and last paired query
        nucleotide, counted from 1 like ``start``/``end``) and ``alignment``
        (pairing string,
        query 5' to 3': ``P`` pair, ``W`` G:U, ``U`` mismatch, ``T`` / ``Q``
        extra target / query base) (CLI ``--alignment``).
    threads : int, optional
        Worker threads; ``None`` uses ``RAYON_NUM_THREADS``, else every core
        (CLI ``-j/--threads``).
    sense_only : bool, default False
        Keep only ``+``-strand hits, for a target whose records are already in
        sense orientation, such as a transcriptome (CLI ``--sense-only``). A
        siOFF filter, not a risearch option: risearch still searches both
        strands, so the search costs the same time and memory.

    Returns
    -------
    polars.DataFrame
        One row per hit with columns ``sirna_id, chrom, start, end, strand,
        energy`` (the schema [`sioff.off_targets`][sioff.off_targets] accepts as
        ``predictions``), followed by ``q_start, q_end, alignment`` when
        ``alignment`` is set. ``start`` and ``end`` are the first and last
        target nucleotide of the site, counted from 1 along the target as
        written (the RIsearch2 convention; the ``risearch`` package counts
        from 0).

    See Also
    --------
    sioff.search : Public wrapper accepting ``str`` paths.
    parse_seed_spec : Builds ``seed_start``/``seed_end``/``seed_length`` from
        a ``-s`` string.
    build_index : Builds the ``index`` argument.
    """
    return RIsearchService().run_search(
        query_path=Path(query),
        index_path=Path(index),
        target_fasta=Path(target) if target is not None else None,
        seed_length=seed_length,
        max_extension=max_extension,
        energy_threshold=energy_threshold,
        seed_start=seed_start,
        seed_end=seed_end,
        seed_wobble=seed_wobble,
        matrix=matrix,
        mismatches=mismatches,
        mismatch_prefix=mismatch_prefix,
        mismatch_suffix=mismatch_suffix,
        temperature=temperature,
        penalty=penalty,
        seed_energy=seed_energy,
        no_max_prune=no_max_prune,
        no_dedup=no_dedup,
        alignment=alignment,
        threads=threads,
        sense_only=sense_only,
    )