Skip to content

Batch

A batch is the work done inside one framework: which genes are surveyed on which charts, with which run parameters. The framework decides where the charts are, and the batch decides what is looked for and how hard. A batch and its framework are two files, or one file with the framework written inline, and one parser reads both. A batch that names its framework by path can run beside other batches on the same coordinates.

Batch holds the work. Batch.resolve_framework reads the framework the batch names, Batch.validate checks that every unit of work names a chart and genes that exist, and Batch.tasks gives one SurveyTask per gene per chart. A WorkSpec names the genes to survey on one chart. A gene need not be an anchor of the chart it is surveyed on.

A SurveyTask is the unit of work: one gene on one chart. SurveyTask.key is the content digest of the unit, and SurveyTask.continues is true when the task continues an illumination that a survey file already records. SurveyRun runs the tasks of a batch.

Batch dataclass

Work to do inside one framework.

Attributes:

Name Type Description
framework FrameworkSpec or str

The coordinate system, written inline or named by path. A path is resolved relative to the batch file it was read from.

label str

A name for the run this batch produces, which the survey file uses to make its group readable.

work list of WorkSpec

Which genes go on which chart.

params dict

Overrides for :class:~hifuku.params.ArchiveParams, cell and origin among them. Two batches in one framework may set them differently: they decide how a run bins the plane the charts define, not where that plane is.

gpu_params dict

Overrides for :class:~hifuku.params.GpuParams.

Source code in src/hifuku/batch.py
@dataclass
class Batch:
    """Work to do inside one framework.

    Attributes
    ----------
    framework : FrameworkSpec or str
        The coordinate system, written inline or named by path.  A path is
        resolved relative to the batch file it was read from.
    label : str
        A name for the run this batch produces, which the survey file uses to
        make its group readable.
    work : list of WorkSpec
        Which genes go on which chart.
    params : dict
        Overrides for :class:`~hifuku.params.ArchiveParams`, ``cell`` and
        ``origin`` among them.  Two batches in one framework may set them
        differently: they decide how a run bins the plane the charts define,
        not where that plane is.
    gpu_params : dict
        Overrides for :class:`~hifuku.params.GpuParams`.
    """

    framework: object                          # FrameworkSpec | str
    label: str = ""
    work: list = field(default_factory=list)
    params: dict = field(default_factory=dict)
    gpu_params: dict = field(default_factory=dict)
    #: Where this batch was read from, so a framework path resolves against it.
    source: object = None                      # Path | None

    def __post_init__(self):
        from hifuku.params import ArchiveParams, GpuParams
        self.work = [w if isinstance(w, WorkSpec) else WorkSpec(**w)
                     for w in self.work]
        self.params = dict(self.params)
        self.gpu_params = dict(self.gpu_params)
        # Reject an unknown parameter name here, where the user wrote it.
        ArchiveParams.resolve(self.params)
        GpuParams.resolve(self.gpu_params)

    def resolve_framework(self) -> FrameworkSpec:
        """The framework this batch runs in, read from its file if named."""
        if isinstance(self.framework, FrameworkSpec):
            return self.framework
        path = Path(self.framework)
        if self.source is not None and not path.is_absolute():
            path = Path(self.source).parent / path
        return FrameworkSpec.from_toml(path)

    def validate(self, framework=None) -> None:
        """Check that every work unit names a chart and genes that exist.

        ``framework`` is a :class:`~hifuku.framework.FrameworkSpec` or a built
        :class:`~hifuku.framework.Framework`, and defaults to the spec this
        batch names.  Reading the spec is cheap and building it is not, so a
        caller that has already built one passes it rather than paying twice.
        """
        spec = framework if framework is not None else self.resolve_framework()
        known = (set(spec.alignments) if isinstance(spec, FrameworkSpec)
                 else set(spec.labels))
        self._check_work(len(spec.charts), known)

    def _check_work(self, n_charts: int, known: set) -> None:
        """The chart and gene check, against a count and a set of labels."""
        for unit in self.work:
            if not 0 <= unit.chart < n_charts:
                raise ValueError(
                    f"this batch surveys chart {unit.chart}, and its framework "
                    f"holds {n_charts} charts")
            for gene in unit.genes:
                if gene not in known:
                    raise ValueError(
                        f"this batch surveys gene {gene!r} on chart "
                        f"{unit.chart}, which is not in the framework's "
                        f"alignments; known labels are {sorted(known)}")

    def tasks(self, framework, survey=None) -> list:
        """One work unit per gene per chart, each keyed to this framework.

        The parameters are resolved without any backend's capability defaults,
        so a task digest records the question and not the machine.  The backend
        still resolves the parameters the survey executes with, and that
        resolution does not reach this key.

        ``survey`` is the project file a work unit's ``resume`` is looked up in.
        A unit that names a run to continue needs it; a batch that continues
        nothing does not, which is why it is optional.
        """
        from hifuku.params import DIGESTED_FIELDS, ArchiveParams

        self.validate(framework)
        params = ArchiveParams.resolve(self.params)
        digest = framework.digest()
        out = []
        for unit in self.work:
            anchors = [(label, framework.alignment(label).alignment_sha256)
                       for label in framework.charts[unit.chart].anchors]
            parents = self._parents_of(unit, survey)
            for gene in unit.genes:
                parent, parent_seal = parents[gene]
                out.append(SurveyTask(
                    chart=unit.chart, gene=gene,
                    parent=parent, parent_seal=parent_seal,
                    digest=task_digest(
                        framework_digest=digest, anchors=anchors,
                        gene=(gene,
                              framework.alignment(gene).alignment_sha256),
                        model=framework.model, metric_w=framework.metric_w,
                        params=params, digested=DIGESTED_FIELDS,
                        parent=parent, parent_seal=parent_seal)))
        return out

    @staticmethod
    def _parents_of(unit, survey) -> dict:
        """``gene -> (parent, parent_seal)`` for one work unit.

        Every gene of a unit that names no run starts from nothing.  A unit that
        names one must find that run, by label or by id, and must find the gene
        in it, on the chart the unit surveys.  The record found must be sealed,
        because a continuation names its parent by the parent's seal.
        """
        if not unit.resume:
            return {gene: (AB_INITIO, "") for gene in unit.genes}
        if survey is None:
            raise ValueError(
                f"chart {unit.chart} of this batch resumes run "
                f"{unit.resume!r}, so it needs the project file that holds it; "
                f"pass survey= to read the run from")

        try:
            run = survey.run_by_label(unit.resume)
        except KeyError:
            try:
                run = survey.run_by_id(unit.resume)
            except KeyError:
                labels = sorted({r.label for r in survey.runs})
                raise ValueError(
                    f"this batch resumes run {unit.resume!r}, which is not in "
                    f"the project file; it holds "
                    f"{', '.join(labels) or 'no runs'}") from None

        held = {(rec.chart, rec.gene): rec for rec in run.surveys}
        out = {}
        for gene in unit.genes:
            rec = held.get((unit.chart, gene))
            if rec is None:
                there = sorted(g for c, g in held if c == unit.chart)
                raise ValueError(
                    f"this batch resumes {gene!r} on chart {unit.chart} from "
                    f"run {unit.resume!r}, which holds no such illumination; "
                    f"on that chart it holds {', '.join(there) or 'none'}")
            if not rec.snapshot:
                raise ValueError(
                    f"the illumination of {gene!r} in run {unit.resume!r} was "
                    f"written without the state a survey continues from, so it "
                    f"cannot be resumed")
            if not rec.sealed:
                raise ValueError(
                    f"the illumination of {gene!r} in run {unit.resume!r} has "
                    f"no seal, so nothing binds a continuation to the state it "
                    f"would start from, and it cannot be resumed")
            out[gene] = (run.run_id, rec.seal)
        return out

    @classmethod
    def from_toml(cls, path) -> "Batch":
        """Read a batch file.

        The file holds ``label``, either a ``framework`` path or an inline
        framework, one ``[[work]]`` table per chart, and optional ``[params]``
        and ``[gpu]`` tables.
        """
        import tomllib
        path = Path(path)
        with open(path, "rb") as fh:
            raw = tomllib.load(fh)

        if any("genes" in chart for chart in raw.get("charts", [])):
            raise ValueError(
                f"{path} looks like a plan file: its charts carry genes beside "
                "anchors, which is how the framework and the batch were "
                "written together before they were separated. Rebuild it with "
                "'hifuku charts', which now writes a framework file and a "
                "batch file")

        named = raw.get("framework")
        framework = named if isinstance(named, str) \
            else FrameworkSpec.from_mapping(raw)
        return cls(
            framework=framework,
            label=raw.get("label", path.stem),
            work=[WorkSpec(chart=int(w["chart"]), genes=list(w["genes"]),
                           resume=str(w.get("resume", "")))
                  for w in raw.get("work", [])],
            params=dict(raw.get("params", {})),
            gpu_params=dict(raw.get("gpu", {})),
            source=path,
        )

    def to_toml(self, path) -> None:
        """Write the batch file that :meth:`from_toml` reads."""
        lines = [f"label = {toml_value(self.label)}"]
        if isinstance(self.framework, FrameworkSpec):
            inline = self.framework.as_toml_lines()
        else:
            lines.append(f"framework = {toml_value(str(self.framework))}")
            inline = []
        for unit in self.work:
            lines += ["", "[[work]]",
                      f"chart = {unit.chart}",
                      f"genes = {json.dumps(list(unit.genes))}"]
            # A unit that continues a run asks a different question from one
            # that starts from nothing, so the file keeps which.
            if unit.resume:
                lines.append(f"resume = {toml_value(unit.resume)}")
        for table, values in (("params", self.params), ("gpu", self.gpu_params)):
            if values:
                lines += ["", f"[{table}]"]
                lines += [f"{k} = {toml_value(v)}"
                          for k, v in sorted(values.items())]
        if inline:
            lines += [""] + inline
        Path(path).write_text("\n".join(lines) + "\n")

resolve_framework

resolve_framework() -> FrameworkSpec

The framework this batch runs in, read from its file if named.

Source code in src/hifuku/batch.py
def resolve_framework(self) -> FrameworkSpec:
    """The framework this batch runs in, read from its file if named."""
    if isinstance(self.framework, FrameworkSpec):
        return self.framework
    path = Path(self.framework)
    if self.source is not None and not path.is_absolute():
        path = Path(self.source).parent / path
    return FrameworkSpec.from_toml(path)

validate

validate(framework=None) -> None

Check that every work unit names a chart and genes that exist.

framework is a :class:~hifuku.framework.FrameworkSpec or a built :class:~hifuku.framework.Framework, and defaults to the spec this batch names. Reading the spec is cheap and building it is not, so a caller that has already built one passes it rather than paying twice.

Source code in src/hifuku/batch.py
def validate(self, framework=None) -> None:
    """Check that every work unit names a chart and genes that exist.

    ``framework`` is a :class:`~hifuku.framework.FrameworkSpec` or a built
    :class:`~hifuku.framework.Framework`, and defaults to the spec this
    batch names.  Reading the spec is cheap and building it is not, so a
    caller that has already built one passes it rather than paying twice.
    """
    spec = framework if framework is not None else self.resolve_framework()
    known = (set(spec.alignments) if isinstance(spec, FrameworkSpec)
             else set(spec.labels))
    self._check_work(len(spec.charts), known)

tasks

tasks(framework, survey=None) -> list

One work unit per gene per chart, each keyed to this framework.

The parameters are resolved without any backend's capability defaults, so a task digest records the question and not the machine. The backend still resolves the parameters the survey executes with, and that resolution does not reach this key.

survey is the project file a work unit's resume is looked up in. A unit that names a run to continue needs it; a batch that continues nothing does not, which is why it is optional.

Source code in src/hifuku/batch.py
def tasks(self, framework, survey=None) -> list:
    """One work unit per gene per chart, each keyed to this framework.

    The parameters are resolved without any backend's capability defaults,
    so a task digest records the question and not the machine.  The backend
    still resolves the parameters the survey executes with, and that
    resolution does not reach this key.

    ``survey`` is the project file a work unit's ``resume`` is looked up in.
    A unit that names a run to continue needs it; a batch that continues
    nothing does not, which is why it is optional.
    """
    from hifuku.params import DIGESTED_FIELDS, ArchiveParams

    self.validate(framework)
    params = ArchiveParams.resolve(self.params)
    digest = framework.digest()
    out = []
    for unit in self.work:
        anchors = [(label, framework.alignment(label).alignment_sha256)
                   for label in framework.charts[unit.chart].anchors]
        parents = self._parents_of(unit, survey)
        for gene in unit.genes:
            parent, parent_seal = parents[gene]
            out.append(SurveyTask(
                chart=unit.chart, gene=gene,
                parent=parent, parent_seal=parent_seal,
                digest=task_digest(
                    framework_digest=digest, anchors=anchors,
                    gene=(gene,
                          framework.alignment(gene).alignment_sha256),
                    model=framework.model, metric_w=framework.metric_w,
                    params=params, digested=DIGESTED_FIELDS,
                    parent=parent, parent_seal=parent_seal)))
    return out

from_toml classmethod

from_toml(path) -> 'Batch'

Read a batch file.

The file holds label, either a framework path or an inline framework, one [[work]] table per chart, and optional [params] and [gpu] tables.

Source code in src/hifuku/batch.py
@classmethod
def from_toml(cls, path) -> "Batch":
    """Read a batch file.

    The file holds ``label``, either a ``framework`` path or an inline
    framework, one ``[[work]]`` table per chart, and optional ``[params]``
    and ``[gpu]`` tables.
    """
    import tomllib
    path = Path(path)
    with open(path, "rb") as fh:
        raw = tomllib.load(fh)

    if any("genes" in chart for chart in raw.get("charts", [])):
        raise ValueError(
            f"{path} looks like a plan file: its charts carry genes beside "
            "anchors, which is how the framework and the batch were "
            "written together before they were separated. Rebuild it with "
            "'hifuku charts', which now writes a framework file and a "
            "batch file")

    named = raw.get("framework")
    framework = named if isinstance(named, str) \
        else FrameworkSpec.from_mapping(raw)
    return cls(
        framework=framework,
        label=raw.get("label", path.stem),
        work=[WorkSpec(chart=int(w["chart"]), genes=list(w["genes"]),
                       resume=str(w.get("resume", "")))
              for w in raw.get("work", [])],
        params=dict(raw.get("params", {})),
        gpu_params=dict(raw.get("gpu", {})),
        source=path,
    )

to_toml

to_toml(path) -> None

Write the batch file that :meth:from_toml reads.

Source code in src/hifuku/batch.py
def to_toml(self, path) -> None:
    """Write the batch file that :meth:`from_toml` reads."""
    lines = [f"label = {toml_value(self.label)}"]
    if isinstance(self.framework, FrameworkSpec):
        inline = self.framework.as_toml_lines()
    else:
        lines.append(f"framework = {toml_value(str(self.framework))}")
        inline = []
    for unit in self.work:
        lines += ["", "[[work]]",
                  f"chart = {unit.chart}",
                  f"genes = {json.dumps(list(unit.genes))}"]
        # A unit that continues a run asks a different question from one
        # that starts from nothing, so the file keeps which.
        if unit.resume:
            lines.append(f"resume = {toml_value(unit.resume)}")
    for table, values in (("params", self.params), ("gpu", self.gpu_params)):
        if values:
            lines += ["", f"[{table}]"]
            lines += [f"{k} = {toml_value(v)}"
                      for k, v in sorted(values.items())]
    if inline:
        lines += [""] + inline
    Path(path).write_text("\n".join(lines) + "\n")

WorkSpec dataclass

The genes to survey on one chart of the framework.

resume names a run already in the project file, and every gene of this unit then continues that run's illumination of it rather than starting from nothing. A gene the named run does not hold is an error rather than a silent fresh start, because a batch that meant to continue and quietly did not would be indistinguishable from one that meant to start.

The parent is part of what a task asks for, so it enters the task digest. Resuming therefore has to be written in the batch, where the question is posed, rather than passed at execution: by the time a run executes, what it asked has already been hashed.

Source code in src/hifuku/batch.py
@dataclass
class WorkSpec:
    """The genes to survey on one chart of the framework.

    ``resume`` names a run already in the project file, and every gene of this
    unit then continues that run's illumination of it rather than starting from
    nothing.  A gene the named run does not hold is an error rather than a
    silent fresh start, because a batch that meant to continue and quietly did
    not would be indistinguishable from one that meant to start.

    The parent is part of what a task asks for, so it enters the task digest.
    Resuming therefore has to be written in the batch, where the question is
    posed, rather than passed at execution: by the time a run executes, what it
    asked has already been hashed.
    """

    chart: int
    genes: list
    resume: str = ""

    def __post_init__(self):
        self.chart = int(self.chart)
        self.genes = list(self.genes)
        self.resume = str(self.resume or "")

SurveyTask dataclass

One gene surveyed on one chart: the unit of work.

The task holds a chart index, a gene label and a digest. Every field is a string or an integer, so the task round-trips through JSON and travels to another host as data.

digest covers the framework, the chart's anchors and their alignment digests, the gene and its digest, the model, the metric weight, and the run parameters that decide what the survey is looking for. It leaves out the parameters each backend sets for itself, so one batch keeps one identity wherever it runs. A caller resumes with if task.key() in done: continue.

Source code in src/hifuku/batch.py
@dataclass(frozen=True)
class SurveyTask:
    """One gene surveyed on one chart: the unit of work.

    The task holds a chart index, a gene label and a digest.  Every field is a
    string or an integer, so the task round-trips through JSON and travels to
    another host as data.

    ``digest`` covers the framework, the chart's anchors and their alignment
    digests, the gene and its digest, the model, the metric weight, and the run
    parameters that decide what the survey is looking for.  It leaves out the
    parameters each backend sets for itself, so one batch keeps one identity
    wherever it runs.  A caller resumes with
    ``if task.key() in done: continue``.
    """

    chart: int
    gene: str
    digest: str
    #: The run holding the illumination this one continues, or ``AB_INITIO``.
    #: It has no default, so a task says where it starts.
    parent: str
    #: The ``seal`` of that illumination's record, empty when there is none.
    parent_seal: str = ""

    def key(self) -> str:
        """The content digest of this unit of work."""
        return self.digest

    @property
    def continues(self) -> bool:
        """True when this task carries on an illumination already recorded."""
        return self.parent != AB_INITIO

    def as_dict(self) -> dict:
        """A plain mapping, ready for JSON."""
        return {"chart": self.chart, "gene": self.gene, "digest": self.digest,
                "parent": self.parent, "parent_seal": self.parent_seal}

continues property

continues: bool

True when this task carries on an illumination already recorded.

key

key() -> str

The content digest of this unit of work.

Source code in src/hifuku/batch.py
def key(self) -> str:
    """The content digest of this unit of work."""
    return self.digest

as_dict

as_dict() -> dict

A plain mapping, ready for JSON.

Source code in src/hifuku/batch.py
def as_dict(self) -> dict:
    """A plain mapping, ready for JSON."""
    return {"chart": self.chart, "gene": self.gene, "digest": self.digest,
            "parent": self.parent, "parent_seal": self.parent_seal}