Skip to content
37 changes: 37 additions & 0 deletions src/quadrat/_engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

import contextlib
import importlib
import numbers
import os
import threading

Expand Down Expand Up @@ -159,6 +160,42 @@ def item_list(value):
return list(value) if isinstance(value, (list, tuple)) else [value]


def require_integer(label, value):
"""Return ``value`` as an `int`, refusing anything that is not an integer.

An integer is any `numbers.Integral`, numpy's integers included,
except a ``bool``; a float, an array and a tensor are not integers,
whatever their value or size.

:param label: The name of the argument, for the message, e.g.,
``"batch_size"`` or ``"Exclusion.bin_width"``.
:param value: The value given.
:returns: ``value`` as an `int`.
:raises TypeError: if ``value`` is not an integer, or is a
``bool``.

.. rubric:: Implementation notes

A ``bool`` is refused although Python counts it an integer, because
``True`` in an integer argument is almost always a field passed in
the wrong place, and reading it as ``1`` would answer silently. A
float is refused rather than truncated for the same reason.

`quadrat.rules.as_jitter` and `quadrat.groups.validate_signal_groups`
refuse the same values in their own words, because their messages
name what this one cannot: that a `quadrat.rules.Jitter` is also accepted, and the
whole specification an entry sits in.
"""

# A plain `int` is answered before the ABC test, which costs several
# times the call on the epoch path; `bool` is a subclass and fails it.
if type(value) is int:
return value
if isinstance(value, bool) or not isinstance(value, numbers.Integral):
raise TypeError("{} must be an integer, got {!r}.".format(label, value))
return int(value)


def name_list(names, empty, limit=3):
"""Return the first few of ``names`` as message text, with a count of the rest.

Expand Down
54 changes: 29 additions & 25 deletions src/quadrat/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import hashlib
import json
import multiprocessing
import numbers
import os
import shutil
import sys
Expand All @@ -35,6 +34,7 @@
import_on_first_use,
item_list,
registered_frames,
require_integer,
transpile_intervals,
)
from quadrat.rules import as_exclusions, as_jitter
Expand Down Expand Up @@ -214,6 +214,20 @@ def n_channels(self):

return int(self._n_channels)

@property
def n_windows(self):
"""Return how many windows this cache was built for, as `array_meta` counts them.

Read from ``meta``, which every cache `build`, `from_arrays` and
`adopt` make carries, so nothing is mapped to answer it; a cache
constructed with no ``meta`` is counted from its arrays.
"""

meta = self.meta
if meta is None:
meta = array_meta((*self._arrays(), self.n_channels))
return int(meta["n_windows"])

@classmethod
def build(
cls,
Expand Down Expand Up @@ -1122,37 +1136,26 @@ def require_windows(caller, windows):
)


def require_index(label, index, size=None, of=None):
def require_index(label, index, size, of=None):
"""Return ``index`` as an `int`, refusing a non-integer or one outside ``range(size)``.

An index is any `numbers.Integral`, numpy's integers included,
except a ``bool``; a float, an array and a tensor are not integers,
whatever their value or size.
An index is an integer as `quadrat._engine.require_integer` takes
one.

:param label: The name of the index, for the message.
:param index: The value given as an index.
:param size: The number of rows it indexes, or ``None`` to check
only that it is an integer.
:param size: The number of rows it indexes.
:param of: What the rows are, for the message, e.g., ``"the
windows this cache was built for"``, or ``None`` to leave them
unnamed.
:returns: ``index`` as an `int`.
:raises TypeError: if ``index`` is not an integer, or is a
``bool``.
:raises IndexError: if ``size`` is given and ``index`` is negative
or not less than it.

.. rubric:: Implementation notes

A ``bool`` is refused although Python counts it an integer, because
``True`` in an index is almost always a field passed in the wrong
place, and reading it as ``1`` would answer row 1 silently.
:raises TypeError: as `quadrat._engine.require_integer` raises it.
:raises IndexError: if ``index`` is negative or not less than
``size``.
"""

if isinstance(index, bool) or not isinstance(index, numbers.Integral):
raise TypeError("{} must be an integer, got {!r}.".format(label, index))
index = int(index)
if size is not None and not 0 <= index < size:
index = require_integer(label, index)
if not 0 <= index < size:
raise IndexError(
"{} must be in range(0, {}){}; got {}.".format(
label, size, "" if of is None else ", " + of, index
Expand Down Expand Up @@ -1349,9 +1352,9 @@ def group_track(windows, tracks, bound_columns=("sig_start", "sig_end")):
``tracks`` is a single track or an unordered collection of
them, or if a track is of no shape a track can take.
:raises ValueError: if there are more channels than ``int16`` can
index, or if a track directory does not verify complete, as
`quadrat.stores.track_frame` refuses it.
index, or for a track `quadrat.stores.track_frame` refuses.
:raises FileNotFoundError: if a track path does not exist.
:raises OSError: for a track `quadrat.stores.track_frame` cannot read.
:raises ImportError: if the ``pileup`` extra is not installed.

.. rubric:: Implementation notes
Expand Down Expand Up @@ -1617,12 +1620,13 @@ def window_group_sums(
:returns: A `torch.Tensor` of shape ``(len(windows),
len(channel_group_sizes))`` and dtype ``float32``.
:raises ValueError: if ``channel_group_sizes`` does not sum to
the channel count, or if a track is a directory that cannot be
verified complete.
the channel count, or for a track `quadrat.stores.track_frame`
refuses.
:raises TypeError: if ``tracks`` is a single track or an unordered
collection of them, or if a track is of no shape a track can
take.
:raises FileNotFoundError: if a track path does not exist.
:raises OSError: for a track `quadrat.stores.track_frame` cannot read.

.. rubric:: Implementation notes

Expand Down
95 changes: 79 additions & 16 deletions src/quadrat/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import numpy
import torch

from quadrat._engine import require_integer
from quadrat.cache import joint_windows, require_index, require_windows
from quadrat.groups import channel_permutation_from_groups
from quadrat.sampling import LocusDraw, PeakNegativeMixSampler
Expand All @@ -25,8 +26,9 @@ class LocusDataset(torch.utils.data.Dataset):
integer is named as such, since it says neither which locus set
to read from nor which epoch's plan.

A pair's epoch and slot and a draw's ``index`` are integers as
`quadrat.cache.require_index` takes them, and anything else raises
A pair's epoch is an integer as `quadrat._engine.require_integer`
takes one, and its slot and a draw's ``index`` are integers as
`quadrat.cache.require_index` takes them; anything else raises
`TypeError`. The epoch is planned as given. A slot outside the
plan, or a draw's ``index`` outside the set its ``is_peak`` picks,
raises `IndexError` rather than reading from the end.
Expand Down Expand Up @@ -82,15 +84,18 @@ class LocusDataset(torch.utils.data.Dataset):
answering ``window(chrom, start, end)`` as
`quadrat.stores.SequenceStore` does.
:param signal_cache: The signal reader, i.e., anything answering
``n_channels`` and ``window(index, jitter, length,
``n_channels``, ``n_windows`` and ``window(index, jitter, length,
reverse_complement, perm)`` as `quadrat.cache.WindowSignalCache`
does, built over the `quadrat.cache.joint_windows` of the two
frames between their ``sig_start`` and ``sig_end``.
:param in_window: The input window's width, in bases.
:param out_window: The output window's width, in bases.
frames between their ``sig_start`` and ``sig_end``. Kept as the
read-only attribute of the same name.
:param in_window: The input window's width, in bases, kept as the
read-only attribute of the same name.
:param out_window: The output window's width, in bases, kept
likewise.
:param control_cache: The control reader, of the same form, built
over the same windows between ``in_start`` and ``in_end``, or
``None`` for no controls.
``None`` for no controls, kept likewise.
:param signal_groups: The size of every signal group in channel
order, as `quadrat.groups.validate_signal_groups` accepts
them, or ``None`` to leave the channels alone under a mirror.
Expand All @@ -106,12 +111,18 @@ class LocusDataset(torch.utils.data.Dataset):
``None``. An attribute of the same name, which may be assigned
later and is checked as it is here.
:raises TypeError: if either window frame is not a
`polars.DataFrame`; if ``sampler`` is neither ``None`` nor a
`polars.DataFrame`; if ``in_window`` or ``out_window`` is not an
integer as `quadrat._engine.require_integer` takes one; if
``sampler`` is neither ``None`` nor a
`quadrat.sampling.PeakNegativeMixSampler`; or for a grouping
`quadrat.groups.validate_signal_groups` refuses by type.
:raises ValueError: if ``peak_windows`` is empty; if
``control_groups`` is given without ``control_cache``; if a
grouping's sizes do not sum to its cache's ``n_channels``; if
``control_groups`` is given without ``control_cache``; if
``signal_cache`` is ``None``; if a
grouping's sizes do not sum to its cache's ``n_channels``; if a
cache's ``n_windows`` is not the two frames' rows combined (a
cache over other windows of the same count is not refused, no
count being able to tell it apart); if
``sampler`` draws from another number of peaks or negatives
than the frames hold; or for a grouping
`quadrat.groups.validate_signal_groups` refuses by value.
Expand Down Expand Up @@ -143,7 +154,11 @@ class LocusDataset(torch.utils.data.Dataset):
A sampler is refused where it is given, rather than at the first
``(epoch, index)`` pair, which would fail inside a loader worker far
from the mistake, or, for a sampler sized for other windows, not
fail at all: it would read negatives as peaks and label them so.
fail at all: it would read negatives as peaks and label them so. A
cache over another number of windows is refused here for the same
reason: one over more windows answers whatever window its row names
there, which need not be this dataset's, and one over fewer can
misread before it fails at the first read past its end.
"""

def __init__(
Expand All @@ -165,12 +180,17 @@ def __init__(
raise ValueError("peak_windows is empty; there is nothing to draw from")
if control_groups is not None and control_cache is None:
raise ValueError("control_groups was supplied but control_cache is None")
if signal_cache is None:
raise ValueError(
"LocusDataset reads signal through signal_cache, and none was "
"given; build one over joint_windows of the two frames."
)

self.sequence_store = sequence_store
self.signal_cache = signal_cache
self.control_cache = control_cache
self.in_window = in_window
self.out_window = out_window
self._signal_cache = signal_cache
self._control_cache = control_cache
self._in_window = require_integer("in_window", in_window)
self._out_window = require_integer("out_window", out_window)
self.signal_groups, self.signal_perm = _grouping(
"signal_groups", signal_groups, signal_cache
)
Expand All @@ -180,6 +200,23 @@ def __init__(

self._n_peaks = len(peak_windows)
self._n_negatives = len(negative_windows)
# Refused here for the reason in the notes.
readers = [("signal_cache", signal_cache)]
if control_cache is not None:
readers.append(("control_cache", control_cache))
for label, reader in readers:
if reader.n_windows != self._n_peaks + self._n_negatives:
raise ValueError(
"LocusDataset holds {} peaks and {} negatives, {} windows "
"in all, and its {} was built for {}; build the cache over "
"joint_windows of the same frames.".format(
self._n_peaks,
self._n_negatives,
self._n_peaks + self._n_negatives,
label,
reader.n_windows,
)
)
self.sampler = sampler
windows = joint_windows(peak_windows, negative_windows)
names, codes = numpy.unique(windows["chrom"].to_numpy(), return_inverse=True)
Expand All @@ -204,7 +241,9 @@ def __getitem__(self, draw):
"index it with a LocusDraw."
)
epoch, slot = draw
plan = self.sampler.plan(require_index("(epoch, index) pair's epoch", epoch))
plan = self.sampler.plan(
require_integer("(epoch, index) pair's epoch", epoch)
)
slot = require_index(
"(epoch, index) pair's index",
slot,
Expand Down Expand Up @@ -272,6 +311,30 @@ def n_negatives(self):

return self._n_negatives

@property
def in_window(self):
"""Return the input window's width, in bases, fixed at construction."""

return self._in_window

@property
def out_window(self):
"""Return the output window's width, in bases, fixed at construction."""

return self._out_window

@property
def signal_cache(self):
"""Return the signal reader, fixed at construction."""

return self._signal_cache

@property
def control_cache(self):
"""Return the control reader, or ``None``, fixed at construction."""

return self._control_cache

@property
def sampler(self):
"""Return the sampler an ``(epoch, index)`` pair is resolved against, or ``None``."""
Expand Down
Loading
Loading