From 7e215b9d965968336a20ceadeb5bb2d25e357001 Mon Sep 17 00:00:00 2001 From: Simon Heybrock Date: Mon, 23 Nov 2026 06:47:26 +0000 Subject: [PATCH 1/5] Name the row source and the parameter columns The dataclass Source becomes RowSource, so that it is not confused with the file source of the workspace; the function from files to a frame, which held the name RowSource, becomes RowFunction. Batch.columns becomes Batch.parameter_columns, the term that the guide uses: a batch table has note columns too. The command names the class in its refusal of a source that is none, so that message names RowSource. Co-Authored-By: Claude Opus 5.5 --- docs/developer/README.md | 2 +- ...013-follow-adds-the-rows-not-considered.md | 4 +-- docs/developer/tours/layers.html | 2 +- docs/developer/user-stories.md | 6 ++-- packages/essapps/docs/batch.md | 26 +++++++-------- .../essapps/src/ess/apps/batch/__init__.py | 4 +-- packages/essapps/src/ess/apps/batch/auto.py | 4 +-- packages/essapps/src/ess/apps/batch/cli.py | 20 +++++------ packages/essapps/src/ess/apps/batch/frames.py | 2 +- .../essapps/src/ess/apps/batch/manager.py | 10 +++--- .../essapps/src/ess/apps/batch/reduction.py | 33 +++++++++++-------- packages/essapps/src/ess/apps/batch/source.py | 20 +++++------ .../essapps/src/ess/apps/batch/web/demo.py | 4 +-- .../essapps/src/ess/apps/batch/web/page.py | 26 ++++++++------- .../essapps/src/ess/apps/batch/web/pages.py | 4 +-- packages/essapps/tests/batch/auto_test.py | 16 ++++----- .../essapps/tests/batch/definition_test.py | 4 +-- packages/essapps/tests/batch/files_test.py | 10 +++--- packages/essapps/tests/batch/manager_test.py | 10 ++++-- .../essapps/tests/batch/reduction_test.py | 15 +++++---- packages/essapps/tests/batch/toys.py | 6 ++-- .../essapps/tests/batch/web_browser_test.py | 6 +++- packages/essapps/tests/batch/web_test.py | 22 ++++++------- packages/essapps/tests/folder_test.py | 4 +-- .../essapps/tests/stories/e_automatic_test.py | 6 ++-- .../src/ess/instruments/loki/batch.py | 4 +-- .../essinstruments/tests/loki/batch_test.py | 2 +- 27 files changed, 146 insertions(+), 126 deletions(-) diff --git a/docs/developer/README.md b/docs/developer/README.md index ef89f6b0..e695ebb3 100644 --- a/docs/developer/README.md +++ b/docs/developer/README.md @@ -302,7 +302,7 @@ def transmission_runs(files: Sequence[FileInfo]) -> pd.DataFrame: return pd.DataFrame.from_records(rows, columns=['key', 'run']).set_index('key') manager = BatchManager(client, definitions=FolderDefinitions(folder), - sources={'transmission-runs': Source(transmission_runs, fills=('run',))}) + sources={'transmission-runs': RowSource(transmission_runs, fills=('run',))}) manager.create('transmission', title='Transmissions', source='transmission-runs', follow=True) manager.step() # called by a timer of the application diff --git a/docs/developer/adr/0013-follow-adds-the-rows-not-considered.md b/docs/developer/adr/0013-follow-adds-the-rows-not-considered.md index 14d53244..0cb2ee2e 100644 --- a/docs/developer/adr/0013-follow-adds-the-rows-not-considered.md +++ b/docs/developer/adr/0013-follow-adds-the-rows-not-considered.md @@ -72,7 +72,7 @@ What removes a bad run from the later rows is a correction of the run, which the ### A row waits until the source has filled it -A source says which columns it fills (`Source.fills`, such as `sample` and `sample_transmission`). A row is added once it has a value in each of these that is a column of the batch. Until then it is *waiting*: the source gives it again at every step, and the page says how many rows wait. +A source says which columns it fills (`RowSource.fills`, such as `sample` and `sample_transmission`). A row is added once it has a value in each of these that is a column of the batch. Until then it is *waiting*: the source gives it again at every step, and the page says how many rows wait. - A sample run measured before its transmission run is added when the transmission run is listed. - A row is added whatever its other columns hold. A column that the source does not fill is empty in a new row, and the row is incomplete if the template needs it. @@ -175,7 +175,7 @@ A batch made from `sample-runs` with the rows from run 60339 on, with Follow. ## Consequences -- `Scope`, `Row.index`, `Source.index_type`, `Source.index_title`, `Header.scope`, `Header.source` and `manager.change(scope=...)` go. `Source.fills` stays, with a second use: it says when a row is filled. +- `Scope`, `Row.index`, `Source.index_type`, `Source.index_title`, `Header.scope`, `Header.source` and `manager.change(scope=...)` go. `RowSource.fills` stays, with a second use: it says when a row is filled. - The rule of a step is "ready and without a record". `RowState.changed_by_hand`, the columns `at` of `Automatic`, and the exception for cells set by hand go. - A row that only waits is not in the table. The page says how many rows wait, and a person can add them. - A transmission run measured again reaches no earlier row, and a correction of a run changes no row that the table has. diff --git a/docs/developer/tours/layers.html b/docs/developer/tours/layers.html index 0e03cfef..a996f9c7 100644 --- a/docs/developer/tours/layers.html +++ b/docs/developer/tours/layers.html @@ -180,7 +180,7 @@

essapps, layer by layer

runs.setdefault(f.metadata['sample'], []).append(str(f.ref)) return pd.DataFrame({'runs': runs.values()}, index=list(runs)) -source = Source(angles, fills=('runs',), selector=Selector(role='sample')) +source = RowSource(angles, fills=('runs',), selector=Selector(role='sample')) manager = BatchManager(client, sources={'angles': source}, definitions=FolderDefinitions(folder)) manager.create('stitch', title='reflectivity', source='angles', follow=True, diff --git a/docs/developer/user-stories.md b/docs/developer/user-stories.md index a0e5e6bf..fcfa6bb2 100644 --- a/docs/developer/user-stories.md +++ b/docs/developer/user-stories.md @@ -112,7 +112,7 @@ Automatic reduction belongs to its sub-design ([automatic-reduction.md](automati The stories use these calls: ```python -source = Source(rows_of_files, fills=(...)) # rows_of_files: the files -> a DataFrame of rows +source = RowSource(rows_of_files, fills=(...)) # rows_of_files: the files -> a DataFrame of rows batch = Batch(client, SPEC, label=..., rows=rows_of(client, source), persist=True) done = step(batch, source, considered) # reads batch.settings at each step done.records # the step added the new rows of the source, and reduced the ready rows without a result; their records by key @@ -648,7 +648,7 @@ def per_run(files): # every raw file return pd.DataFrame({'sample': [f.ref.file for f in files]}, index=[str(f.metadata['run']) for f in files]) -PER_RUN = Source(per_run, fills=('sample',)) +PER_RUN = RowSource(per_run, fills=('sample',)) def iofq_batch(client): return Batch(client, IOFQ, label='iofq', rows=rows_of(client, PER_RUN), @@ -674,7 +674,7 @@ def angles(files): # a row per sampl return pd.DataFrame({'sample': list(runs), 'runs': [[f.ref.file for f in found] for found in runs.values()]}, index=keys) -source = Source(angles, fills=('runs',)) +source = RowSource(angles, fills=('runs',)) batch = Batch(client, STITCH, label='reflectivity', rows=rows_of(client, source), persist=True, settings={'reference': reference}) counts = {2: [1.0, 2.0], 3: [1.0, 1.0], 4: [4.0, 8.0]} diff --git a/packages/essapps/docs/batch.md b/packages/essapps/docs/batch.md index fa3c55da..b4c2683c 100644 --- a/packages/essapps/docs/batch.md +++ b/packages/essapps/docs/batch.md @@ -25,7 +25,7 @@ flowchart TD table["batch table"] end step["step: auto.step"] - source["source: Source"] + source["source: RowSource"] end definitions["definitions"] client["Client: files, records"] @@ -49,7 +49,7 @@ Nothing in the batch layer imports the page or the command. | Component | Code | Owns | |---|---|---| | table | `table.py` | the form of a batch table: dtypes, cells, cell to request value and back, `rows.json`, table files | -| source | `source.py`: `Source`, `rows_of` | the code of the application that makes rows from the files | +| row source | `source.py`: `RowSource`, `rows_of` | the code of the application that makes rows from the files | | batch | `reduction.py`: `Batch` | the settings and the batch table of one label: `put`, `state`, `reduce`, `cancel`, and `version`, which moves when the batch table, the settings or a record changes; the only part that submits to the client | | state | `state.py`: `RowState`, the rules | where each row stands; the rules are functions from the states of rows to keys | | step | `auto.py`: `step`, `Step` | one step of Follow on one batch: add rows of the source, reduce rows | @@ -71,8 +71,8 @@ Nothing in the batch layer imports the page or the command. | state of a row | its result, the status of the result, its problems, and where its request differs from that of its result | | outdated | a result whose request differs from the row's request now, or that is of another spec | | earlier | a completed result whose request differs from the row's only at settings: at parameters that have no column, or where the row's cell is empty | -| source | code of the application that makes rows from the files (a `Source`) | -| filled, waits | a row of the source is filled once it has a value in each of `Source.fills`; until then it waits | +| row source | code of the application that makes rows from the files (a `RowSource`) | +| filled, waits | a row of the source is filled once it has a value in each of `RowSource.fills`; until then it waits | | considered | the keys of the source that a batch made from it has taken or left out | | Follow | a step every few seconds on one batch: add the rows of its source that are filled and not considered, then reduce the rows that are ready and have no result; chosen when the batch is made, until it is stopped | @@ -88,7 +88,7 @@ The batch table of the example below, as `batch.frame()` gives it: | Part | What it is | |---|---| | the index, `key` | text that names the row, unique in the batch table; the member of the row's records | -| a parameter column | a column named as a parameter of the spec (`sample`, `sample_transmission`, `thickness`), with the dtype of that parameter: there a row may give its own value. `batch.columns` names them | +| a parameter column | a column named as a parameter of the spec (`sample`, `sample_transmission`, `thickness`), with the dtype of that parameter: there a row may give its own value. `batch.parameter_columns` names them | | a note column | any other column (`run`, `name`); shown, never part of a request | | a cell | plain data, such as `'run:60339'`, `2.0`, `['run:1', 'run:2']`, or empty | @@ -155,7 +155,7 @@ A table file is written and read by pandas (`to_csv`, `read_csv`, `to_excel`, `r An afternoon at LoKI. The spec `loki-iofq` has, among others, the parameters `sample` and `sample_transmission` (files) and `thickness: float = 1.0`. -The source `sample-runs` (`SAMPLE_RUNS` in "Writing a source") makes one row per sample run and fills `sample` and `sample_transmission`. +The source `sample-runs` (`SAMPLE_RUNS` in "Writing a row source") makes one row per sample run and fills `sample` and `sample_transmission`. **1. A batch is made from the source.** Runs 60337 to 60340 are listed, each with its transmission run. @@ -249,12 +249,12 @@ A batch that follows has no last row: the rows filled between a last row and the For a batch of only the rows that arrive from now on, `choose` takes none: `choose=Range(later=True)`. Every row filled now is then considered, and none is reduced again. -## Writing a source +## Writing a row source -A source is a function from files to a table, and the columns that it fills: +A row source is a function from files to a table, and the columns that it fills: ```python -from ess.apps.batch import FileInfo, Source +from ess.apps.batch import FileInfo, RowSource def pair_by_sample(files: Sequence[FileInfo]) -> pd.DataFrame: samples = [f for f in files if f.metadata.get('role') == 'sample'] @@ -267,7 +267,7 @@ def pair_by_sample(files: Sequence[FileInfo]) -> pd.DataFrame: columns = ['key', 'run', 'name', 'sample', 'sample_transmission'] return pd.DataFrame.from_records(records, columns=columns).set_index('key') -SAMPLE_RUNS = Source(pair_by_sample, fills=('sample', 'sample_transmission')) +SAMPLE_RUNS = RowSource(pair_by_sample, fills=('sample', 'sample_transmission')) ``` - The index is the key, as text. A number as key is refused: write `str(run)`. @@ -439,7 +439,7 @@ stateDiagram-v2 result --> incomplete: a problem ``` -A problem is any of `RowState.problems`: a value missing, such as an empty cell of a column that the source fills, a cell that the workspace refuses, or a referenced record that failed. +A problem is any of `RowState.problems`: a value missing, such as an empty cell of a column that the row source fills, a cell that the workspace refuses, or a referenced record that failed. The workspace refuses a cell that names a file that the file source does not know, or cannot read now: it raised `OSError`, as when a mount is gone or a catalogue timed out. Only the rows that name that file have the problem, and the reason names the file. A refusal is not kept, so the next state resolves the cell again, and the problem goes once the file is known and can be read. @@ -508,7 +508,7 @@ manager.create(..., choose=Range(later=True), follow=True) `columns` are parameters that are columns of empty cells, besides those of the table. - `create` refuses a label that has definitions or records, a spec that the workspace does not bind, and rows that `put` refuses. -- With `source=`, `create` keeps `Source.fills` with the batch in `source.json` (`batch.fills`), refuses a table from `choose` without one of their columns, and leaves out the settings there (`batch.settable`). Every other setting stays, at a column too. +- With `source=`, `create` keeps `RowSource.fills` with the batch in `source.json` (`batch.fills`), refuses a table from `choose` without one of their columns, and leaves out the settings there (`batch.settable`). Every other setting stays, at a column too. - It refuses `rows=` with `source=`, `choose=` or `follow=True` without `source=`, and a key from `choose` that is not in `arrived`. - `manager.batch(label)` reads `settings.json`, `rows.json` and the fills in `source.json`, binds the spec by name, and passes the definitions, so the `Batch` writes each change. - Ask for the batch each time: one handed out before `remove` must not be used after. @@ -558,7 +558,7 @@ sequenceDiagram participant timer as timer: Pages.tick participant manager as manager: BatchManager participant step as step: auto.step - participant source as source: Source + participant source as source: RowSource participant batch as Batch participant definitions timer->>manager: step() diff --git a/packages/essapps/src/ess/apps/batch/__init__.py b/packages/essapps/src/ess/apps/batch/__init__.py index f7e939d1..b4d45218 100644 --- a/packages/essapps/src/ess/apps/batch/__init__.py +++ b/packages/essapps/src/ess/apps/batch/__init__.py @@ -12,7 +12,7 @@ from .definition import DefinitionStore, FolderDefinitions, Header, NotKept from .manager import BatchManager from .reduction import Batch -from .source import FileInfo, Range, RowSource, Source, rows_of +from .source import FileInfo, Range, RowFunction, RowSource, rows_of from .state import ( RowState, earlier_settings, @@ -32,9 +32,9 @@ 'Header', 'NotKept', 'Range', + 'RowFunction', 'RowSource', 'RowState', - 'Source', 'earlier_settings', 'left_to_reduce', 'not_reduced', diff --git a/packages/essapps/src/ess/apps/batch/auto.py b/packages/essapps/src/ess/apps/batch/auto.py index 7c2fbe44..37493ae2 100644 --- a/packages/essapps/src/ess/apps/batch/auto.py +++ b/packages/essapps/src/ess/apps/batch/auto.py @@ -58,7 +58,7 @@ from ..errors import SubmitError from ..records import Record from .reduction import Batch -from .source import Source, filled, rows_of +from .source import RowSource, filled, rows_of from .state import not_reduced @@ -119,7 +119,7 @@ class Step: records: Mapping[str, Record] -def step(batch: Batch, source: Source, considered: Collection[str]) -> Step: +def step(batch: Batch, source: RowSource, considered: Collection[str]) -> Step: """ Add the rows of ``source`` that are new and filled to ``batch``, and reduce the rows that :func:`~.state.not_reduced` gives, with the batch's diff --git a/packages/essapps/src/ess/apps/batch/cli.py b/packages/essapps/src/ess/apps/batch/cli.py index ed59a01a..5604677c 100644 --- a/packages/essapps/src/ess/apps/batch/cli.py +++ b/packages/essapps/src/ess/apps/batch/cli.py @@ -80,7 +80,7 @@ from .definition import FolderDefinitions, NotKept from .export import export_table from .manager import BatchManager -from .source import Source, rows_of +from .source import RowSource, rows_of from .table import KEY, SUFFIXES, read_table, read_text, write_table from .templates import checked_settings, load_template @@ -91,26 +91,26 @@ def _named(name: str) -> Any: return getattr(import_module(module), attribute) -def _source(parser: argparse.ArgumentParser, name: str) -> Source: - """The :class:`~.source.Source` that ``name`` names; exits if it is none.""" +def _source(parser: argparse.ArgumentParser, name: str) -> RowSource: + """The :class:`~.source.RowSource` that ``name`` names; exits if it is none.""" source = _named(name) - if not isinstance(source, Source): + if not isinstance(source, RowSource): parser.error( - f'{name} is a {type(source).__name__}, not a Source ' - '(ess.apps.batch.Source), such as package.module:SAMPLE_RUNS' + f'{name} is a {type(source).__name__}, not a row source ' + '(ess.apps.batch.RowSource), such as package.module:SAMPLE_RUNS' ) return source -def _sources(parser: argparse.ArgumentParser, name: str) -> Mapping[str, Source]: +def _sources(parser: argparse.ArgumentParser, name: str) -> Mapping[str, RowSource]: """The sources by name that ``name`` names; exits if it names other things.""" sources = _named(name) if not isinstance(sources, Mapping) or not all( - isinstance(source, Source) for source in sources.values() + isinstance(source, RowSource) for source in sources.values() ): parser.error( f'{name} is a {type(sources).__name__}, not a mapping of names to ' - 'Sources (ess.apps.batch.Source), such as package.module:SOURCES' + 'row sources (ess.apps.batch.RowSource), such as package.module:SOURCES' ) return sources @@ -198,7 +198,7 @@ def _parser() -> argparse.ArgumentParser: rows = commands.add_parser( 'rows', parents=[output], help='make a table from the files' ) - rows.add_argument('source', help='a Source, as package.module:NAME') + rows.add_argument('source', help='a RowSource, as package.module:NAME') return parser diff --git a/packages/essapps/src/ess/apps/batch/frames.py b/packages/essapps/src/ess/apps/batch/frames.py index 04c6a6c4..31e40729 100644 --- a/packages/essapps/src/ess/apps/batch/frames.py +++ b/packages/essapps/src/ess/apps/batch/frames.py @@ -189,7 +189,7 @@ def reduce_batch( ValueError If a blank is named as one of :data:`RESULT`. """ - if taken := sorted(set(batch.columns) & set(RESULT)): + if taken := sorted(set(batch.parameter_columns) & set(RESULT)): raise ValueError(f'a table cannot hold the blank {", ".join(taken)}') client = batch.client which: list[Which] = ['remaining'] if remaining else ['all'] diff --git a/packages/essapps/src/ess/apps/batch/manager.py b/packages/essapps/src/ess/apps/batch/manager.py index 1990f7a3..a7c89f02 100644 --- a/packages/essapps/src/ess/apps/batch/manager.py +++ b/packages/essapps/src/ess/apps/batch/manager.py @@ -79,11 +79,11 @@ template_of, ) from .reduction import Batch -from .source import Range, Source, filled, rows_of +from .source import Range, RowSource, filled, rows_of from .table import frame_of, typed -def fits(spec: WorkflowSpec[Any, Any], source: Source | None) -> bool: +def fits(spec: WorkflowSpec[Any, Any], source: RowSource | None) -> bool: """ Whether a batch of ``spec`` can be made with ``source``: whether each parameter that the source fills is a parameter of the spec. With no @@ -169,7 +169,7 @@ def __init__( self, client: Client, *, - sources: Mapping[str, Source], + sources: Mapping[str, RowSource], definitions: DefinitionStore, settings: Mapping[str, Mapping[str, Any]] | None = None, staged: Collection[str] = (), @@ -221,7 +221,7 @@ def rows_of(self, source: str) -> pd.DataFrame: """ return rows_of(self.client, self._source(source)) - def _given(self, source: Source, fills: Collection[str]) -> pd.DataFrame: + def _given(self, source: RowSource, fills: Collection[str]) -> pd.DataFrame: """ What ``source`` makes now, with a column ``waits``: whether a cell of ``fills`` is empty (:func:`~.source.filled`). A column of the source @@ -412,7 +412,7 @@ def create( self._version += 1 return label - def _source(self, name: str) -> Source: + def _source(self, name: str) -> RowSource: """The source registered as ``name``; ``ValueError`` if none is.""" if name not in self.sources: raise ValueError(f'the source {name} is not registered') diff --git a/packages/essapps/src/ess/apps/batch/reduction.py b/packages/essapps/src/ess/apps/batch/reduction.py index 2581077b..54779176 100644 --- a/packages/essapps/src/ess/apps/batch/reduction.py +++ b/packages/essapps/src/ess/apps/batch/reduction.py @@ -164,14 +164,14 @@ class Batch: without them keeps nothing. fills: The parameters that the source of the batch fills, if it was made - from one (:attr:`~.source.Source.fills`), as the manager keeps them + from one (:attr:`~.source.RowSource.fills`), as the manager keeps them with the batch. Each is a column, and an empty cell there means that the row waits for its file: the row is incomplete, whatever the settings hold and whatever the default of the parameter is. Attributes ---------- - columns: + parameter_columns: The parameter columns of the table, in its order: the blanks of the template. settings_fields: @@ -254,13 +254,13 @@ def version(self) -> int: return self._version @property - def columns(self) -> tuple[str, ...]: + def parameter_columns(self) -> tuple[str, ...]: return self._template.blanks @property def settings_fields(self) -> tuple[str, ...]: fields = self.spec.params.model_fields - return tuple(n for n in fields if n not in self.columns) + return tuple(n for n in fields if n not in self.parameter_columns) def settable(self, settings: Mapping[str, Any]) -> dict[str, Any]: """ @@ -353,7 +353,9 @@ def settings(self, settings: Mapping[str, Any]) -> None: settings = copy.deepcopy(dict(settings)) self._save(settings) self._settings = settings - self._template = Template(self.spec, params=settings, blanks=self.columns) + self._template = Template( + self.spec, params=settings, blanks=self.parameter_columns + ) self._version += 1 def make_column(self, name: str) -> None: @@ -388,7 +390,7 @@ def make_setting(self, name: str, key: str | None = None) -> None: take different values; :class:`~.definition.NotKept` if the definitions refuse a write. """ - self._keeps_fills([c for c in self.columns if c != name]) + self._keeps_fills([c for c in self.parameter_columns if c != name]) if key is None: values = self.values(name) if len(values) > 1: @@ -415,7 +417,7 @@ def values(self, name: str) -> dict[str, Any]: (:meth:`empty`, :func:`~.table.cell_of`), or ``None`` if it gives nothing. Raises ``ValueError`` if ``name`` is not a column. """ - if name not in self.columns: + if name not in self.parameter_columns: raise ValueError(f'{name} is not a column of the batch') cells = {k: row[name] for k, row in self._rows[[name]].to_dict('index').items()} if name in (empty := self.empty()): @@ -451,7 +453,7 @@ def empty(self) -> dict[str, Any]: """ fields = self.spec.params.model_fields empty = {} - for c in self.columns: + for c in self.parameter_columns: if c in self.fills: continue if c in self._settings: @@ -469,7 +471,7 @@ def cells(self, keys: Sequence[str] | None = None) -> dict[str, dict[str, Any]]: :meth:`empty` gives it, and left out where it gives nothing, a problem of the row. Raises ``KeyError`` for a key that the table lacks. """ - rows = self._rows[list(self.columns)] + rows = self._rows[list(self.parameter_columns)] if keys is not None: rows = rows.loc[list(keys)] empty = self.empty() @@ -572,14 +574,14 @@ def _states( ) -> dict[str, RowState]: upstream = self._known(sorted(state.references(cells.values()))) status = self._status([*found.values(), *upstream]) - given = self._rows.loc[list(cells), list(self.columns)].notna() + given = self._rows.loc[list(cells), list(self.parameter_columns)].notna() own = { key: frozenset(c for c, filled in row.items() if filled) for key, row in given.to_dict('index').items() } return state.row_states( cells, - self.columns, + self.parameter_columns, found, status, changed, @@ -647,14 +649,15 @@ def _compare( raise resolved asked = {} for key, given in cells.items(): - if len(given) < len(self.columns): + if len(given) < len(self.parameter_columns): continue # an empty cell is a problem, and nothing to resolve if (record := found.get(key)) is None: asked[key] = dict(given) else: was = record.request.params asked[key] = { - c: given[c] for c in state.differs(given, was, self.columns) + c: given[c] + for c in state.differs(given, was, self.parameter_columns) } cells_now, refused = self._resolve_cells(asked) changed = {} @@ -761,7 +764,9 @@ def _open(self, template: Template) -> Stage: def _once(self, errors: tuple[FieldError, ...]) -> list[FieldError]: """Each reason that names no column once, without a row's key.""" placed = [ - e if e.loc and e.loc[0] in self.columns else replace(e, entry=None) + e + if e.loc and e.loc[0] in self.parameter_columns + else replace(e, entry=None) for e in errors ] return list(dict.fromkeys(placed)) diff --git a/packages/essapps/src/ess/apps/batch/source.py b/packages/essapps/src/ess/apps/batch/source.py index 5de13d26..4bfb2cd6 100644 --- a/packages/essapps/src/ess/apps/batch/source.py +++ b/packages/essapps/src/ess/apps/batch/source.py @@ -1,11 +1,11 @@ # SPDX-License-Identifier: BSD-3-Clause # Copyright (c) 2026 Scipp contributors (https://github.com/scipp) """ -What an application gives a batch: a :class:`Source` makes a table from the +What an application gives a batch: a :class:`RowSource` makes a table from the files. -A source is code of the application, registered by name with a -:class:`~.manager.BatchManager`. Its :data:`RowSource` takes the files with +A row source is code of the application, registered by name with a +:class:`~.manager.BatchManager`. Its :data:`RowFunction` takes the files with their metadata and returns a frame, the form that ``Batch.put`` takes:: key run name sample sample_transmission @@ -40,7 +40,7 @@ @dataclass(frozen=True) class FileInfo: - """A file and its metadata, as a :data:`RowSource` is given it.""" + """A file and its metadata, as a :data:`RowFunction` is given it.""" ref: FileRef metadata: Mapping[str, Any] @@ -54,7 +54,7 @@ def _file_infos(client: Client, selector: Selector | None = None) -> list[FileIn ] -type RowSource = Callable[[Sequence[FileInfo]], pd.DataFrame] +type RowFunction = Callable[[Sequence[FileInfo]], pd.DataFrame] """ What an application knows of its technique: which files make which rows. It takes plain data and returns a frame, so it is tested on its own. @@ -62,9 +62,9 @@ def _file_infos(client: Client, selector: Selector | None = None) -> list[FileIn @dataclass(frozen=True) -class Source: +class RowSource: """ - A source of rows: a :data:`RowSource`, the columns it fills, and the files + A row source: a :data:`RowFunction`, the columns it fills, and the files it is given. Parameters @@ -78,15 +78,15 @@ class Source: The files that ``rows`` is given; raw files if not given. """ - rows: RowSource + rows: RowFunction fills: tuple[str, ...] selector: Selector | None = None -def rows_of(client: Client, source: Source) -> pd.DataFrame: +def rows_of(client: Client, source: RowSource) -> pd.DataFrame: """ The table that ``source`` makes from the files of ``client`` now, with an - empty column for each of :attr:`Source.fills` that it lacks, so that a + empty column for each of :attr:`RowSource.fills` that it lacks, so that a batch made from it has its columns also when no file is listed yet. Raises ``ValueError`` for a key that is not text, empty, or given twice, diff --git a/packages/essapps/src/ess/apps/batch/web/demo.py b/packages/essapps/src/ess/apps/batch/web/demo.py index 5d9ddc6b..46c38083 100644 --- a/packages/essapps/src/ess/apps/batch/web/demo.py +++ b/packages/essapps/src/ess/apps/batch/web/demo.py @@ -56,7 +56,7 @@ WorkflowSpec, ) -from .. import BatchManager, CorrectedFiles, FileInfo, FolderDefinitions, Source +from .. import BatchManager, CorrectedFiles, FileInfo, FolderDefinitions, RowSource from ..table import KEY, cell_of from . import Pages, create_app, plots from .api import STATIC, every @@ -206,7 +206,7 @@ def pair_by_sample(files: Sequence[FileInfo]) -> pd.DataFrame: return pd.DataFrame.from_records(rows, columns=columns).set_index(KEY) -SOURCES = {'sample-runs': Source(pair_by_sample, fills=('sample', 'transmission'))} +SOURCES = {'sample-runs': RowSource(pair_by_sample, fills=('sample', 'transmission'))} """The sources of the demo's batches, by name.""" STAGED = frozenset({DEMO.name}) """The specs whose batches run through a stage: the demo's.""" diff --git a/packages/essapps/src/ess/apps/batch/web/page.py b/packages/essapps/src/ess/apps/batch/web/page.py index 2bd30be6..212ebe5f 100644 --- a/packages/essapps/src/ess/apps/batch/web/page.py +++ b/packages/essapps/src/ess/apps/batch/web/page.py @@ -393,11 +393,11 @@ def _fit(self) -> None: then shows the batch's settings. """ batch = self.batch - if batch.columns == self._columns: + if batch.parameter_columns == self._columns: return - self._columns = batch.columns + self._columns = batch.parameter_columns self._cells = Fields( - batch.spec.params, self.pages.listing, fields=batch.columns + batch.spec.params, self.pages.listing, fields=batch.parameter_columns ) self.settings = self._form() self._show_settings() @@ -455,7 +455,7 @@ def _form_held(self) -> tuple[dict[str, Any], list[FieldError]]: What the form holds; a column left unset has no setting (:func:`.forms.held`). """ - return forms.held(self.settings, self.batch.columns) + return forms.held(self.settings, self.batch.parameter_columns) def _show_settings(self) -> None: """Show the batch's settings in the form, which then holds no change.""" @@ -521,7 +521,7 @@ def _setting_title(self, error: FieldError) -> str: def state(self, notice: str = '') -> State: """Everything the page shows but a row's details, the plot, and the runs.""" batch = self.batch - columns = batch.columns + columns = batch.parameter_columns states, unusable = self._states() unsubmitted = self.pages.unsubmitted(self.label, states) failures = self._failures(states) @@ -705,7 +705,7 @@ def _row( text=self._text(given.get(c, UNSET)), problem=problems.get(c), ) - for c in self.batch.columns + for c in self.batch.parameter_columns }, ) @@ -748,7 +748,7 @@ def _placed(self, error: FieldError, keys: Iterable[str]) -> bool: return False if error.entry is None: return str(error.loc[0]) in self.settings.fields - return error.entry in keys and str(error.loc[0]) in self.batch.columns + return error.entry in keys and str(error.loc[0]) in self.batch.parameter_columns def _refused(self, error: FieldError, named: Mapping[str, str]) -> Refused: if error.entry is None: @@ -921,7 +921,7 @@ def reduce(self, request: Reduce) -> str: except SubmitError as error: self.refused = [e for e in error.errors if self._placed(e, frame.index)] unplaced = [e for e in error.errors if e not in self.refused] - named = names(frame, self.batch.columns) + named = names(frame, self.batch.parameter_columns) raise _Refusal( [self._refused(e, named).text for e in unplaced], len(self.refused) ) from None @@ -1010,7 +1010,7 @@ def use_settings(self, key: str) -> str: where its cell is empty, the value that the row took. """ frame = self._frame([key]) - name = names(frame, self.batch.columns)[key] + name = names(frame, self.batch.parameter_columns)[key] row = self._states([key])[0][key] if row.record is None: raise Problem(f'{name} has no result.') @@ -1020,7 +1020,11 @@ def use_settings(self, key: str) -> str: 'whose settings this one does not take.' ) batch = self.batch - given = frame.loc[[key], list(batch.columns)].notna().to_dict('index')[key] + given = ( + frame.loc[[key], list(batch.parameter_columns)] + .notna() + .to_dict('index')[key] + ) own = {c for c, filled in given.items() if filled} kept = {n: v for n, v in batch.settings.items() if n in own} took = {n: v for n, v in row.record.request.params.items() if n not in own} @@ -1102,7 +1106,7 @@ def plot(self, keys: Sequence[str]) -> Plot: if not chosen or draw is None: return Plot(figure=None, note=note) colors = plots.colors([order[s.key] for s in chosen]) - named = names(frame, self.batch.columns) + named = names(frame, self.batch.parameter_columns) shown = [ Shown(s.key, named[s.key], s.record, s.text == 'outdated', c) for s, c in zip(chosen, colors, strict=True) diff --git a/packages/essapps/src/ess/apps/batch/web/pages.py b/packages/essapps/src/ess/apps/batch/web/pages.py index c9e9bce8..d2090aa0 100644 --- a/packages/essapps/src/ess/apps/batch/web/pages.py +++ b/packages/essapps/src/ess/apps/batch/web/pages.py @@ -70,7 +70,7 @@ from ..auto import Step from ..corrections import CorrectedFiles from ..manager import BatchManager, fits -from ..source import Range, Source +from ..source import Range, RowSource from ..state import RowState, not_reduced from ..table import read_table from . import forms @@ -497,7 +497,7 @@ def sources(self) -> list[SourceChoice]: specs = [client.spec_named(name) for name in names] listing = self._listing - def choice(name: str | None, source: Source | None) -> SourceChoice: + def choice(name: str | None, source: RowSource | None) -> SourceChoice: fills = () if source is None else source.fills return SourceChoice( name=name, diff --git a/packages/essapps/tests/batch/auto_test.py b/packages/essapps/tests/batch/auto_test.py index 822914ad..38c3734d 100644 --- a/packages/essapps/tests/batch/auto_test.py +++ b/packages/essapps/tests/batch/auto_test.py @@ -22,8 +22,8 @@ FileInfo, FolderDefinitions, NotKept, + RowFunction, RowSource, - Source, rows_of, ) from ess.apps.batch.auto import Step, added, step @@ -62,7 +62,7 @@ class Stepping: """ def __init__( - self, batch: Batch, source: Source, considered: Iterable[str] = () + self, batch: Batch, source: RowSource, considered: Iterable[str] = () ) -> None: self.batch, self.source = batch, source self.considered = frozenset(considered) @@ -82,13 +82,13 @@ def loop(batch: Batch) -> Stepping: return Stepping(batch, PAIRS) -def _loop(client: Any, make: RowSource = pair) -> Stepping: +def _loop(client: Any, make: RowFunction = pair) -> Stepping: """A loop on ``client``, which may be a fake that wraps a client.""" batch = Batch(client, PLAIN, label='scan', rows=rows(client)) return Stepping(batch, replace(PAIRS, rows=make)) -def _changed(make: RowSource, **cells: Any) -> RowSource: +def _changed(make: RowFunction, **cells: Any) -> RowFunction: """``make``, with ``cells`` set in each row that it makes, by key.""" def changed(files: Sequence[FileInfo]) -> pd.DataFrame: @@ -126,7 +126,7 @@ def test_a_source_that_makes_a_key_twice_is_refused( client: Client, sample: Measure ) -> None: sample(1, 'water') - twice = Source(lambda files: pd.concat([pair(files)] * 2), fills=PAIRS.fills) + twice = RowSource(lambda files: pd.concat([pair(files)] * 2), fills=PAIRS.fills) with pytest.raises(ValueError, match="the key '1' is given twice"): rows_of(client, twice) @@ -182,7 +182,7 @@ def _per_sample(files: Sequence[FileInfo]) -> pd.DataFrame: def _repeated(client: Client) -> Stepping: - source = Source(_per_sample, fills=('sample_runs', 'trans_runs')) + source = RowSource(_per_sample, fills=('sample_runs', 'trans_runs')) table = rows_of(client, source) batch = Batch(client, REPEATED, label='repeated', rows=table, fills=source.fills) return Stepping(batch, source) @@ -486,7 +486,7 @@ def with_offset(files: Sequence[FileInfo]) -> pd.DataFrame: offsets = {k: {'offset': cell_of(r.ref('offset'))} for k, r in found.items()} return _changed(pair, **offsets)(files) - source = Source(with_offset, fills=(*PAIRS.fills, 'offset')) + source = RowSource(with_offset, fills=(*PAIRS.fills, 'offset')) table = rows_of(client, source) reduce = Batch(client, PLAIN, label='reduce', rows=table, fills=source.fills) loops = [Stepping(find, SAMPLES), Stepping(reduce, source)] @@ -689,7 +689,7 @@ def test_a_row_added_by_a_step_whose_submission_raised_stays_away_once_removed( def test_a_cell_of_the_source_that_the_batch_refuses_is_named_with_the_source( client: Client, definitions: FolderDefinitions, sample: Measure ) -> None: - thick = Source(_changed(pair, **{'1': {'thickness': 'thick'}}), PAIRS.fills) + thick = RowSource(_changed(pair, **{'1': {'thickness': 'thick'}}), PAIRS.fills) manager = BatchManager(client, sources={'pairs': thick}, definitions=definitions) from_pairs(manager, PLAIN.name, title='A', label='a', follow=True) sample(1, 'water') diff --git a/packages/essapps/tests/batch/definition_test.py b/packages/essapps/tests/batch/definition_test.py index 6a1d2bd1..1c3997bb 100644 --- a/packages/essapps/tests/batch/definition_test.py +++ b/packages/essapps/tests/batch/definition_test.py @@ -20,7 +20,7 @@ FolderDefinitions, Header, NotKept, - Source, + RowSource, ) from ess.apps.batch.definition import ( CORRECTIONS, @@ -63,7 +63,7 @@ def first_transmission(files: Sequence[FileInfo]) -> pd.DataFrame: ).set_index(KEY) -FIRST_TRANSMISSION = Source(first_transmission, fills=('sample', 'transmission')) +FIRST_TRANSMISSION = RowSource(first_transmission, fills=('sample', 'transmission')) type Opened = Callable[[], AbstractContextManager[tuple[BatchManager, CorrectedFiles]]] diff --git a/packages/essapps/tests/batch/files_test.py b/packages/essapps/tests/batch/files_test.py index 749f1227..502c32f8 100644 --- a/packages/essapps/tests/batch/files_test.py +++ b/packages/essapps/tests/batch/files_test.py @@ -58,7 +58,7 @@ def test_a_template_may_leave_out_the_blanks_and_the_params(tmp_path: Path) -> N MODULE = ''' import pandas as pd -from ess.apps.batch import Source +from ess.apps.batch import RowSource from ess.apps.testing import StagedFunction, read_file from ess.spec import RunFile, WorkflowSpec, function_binding from pydantic import BaseModel @@ -127,8 +127,8 @@ def pair(files): return pd.DataFrame.from_records(rows, columns=columns).set_index('key') -PAIRS = Source(pair, fills=('sample',)) -BROKEN = Source(lambda files: [f.metadata['nope'] for f in files], fills=('sample',)) +PAIRS = RowSource(pair, fills=('sample',)) +BROKEN = RowSource(lambda files: [f.metadata['nope'] for f in files], fills=('sample',)) SOURCES = {'pairs': PAIRS, 'broken': BROKEN} ''' @@ -835,10 +835,10 @@ def test_main_reduces_a_template_without_a_table_as_one_row_keyed_by_the_label( @pytest.mark.parametrize( ('arguments', 'said'), [ - (['rows', 'cli_toys_batch_files:pair'], 'is a function, not a Source'), + (['rows', 'cli_toys_batch_files:pair'], 'is a function, not a row source'), ( ['reduce', '-s', 'cli_toys_batch_files:pair', '-l', 'x'], - 'is a function, not a mapping of names to Sources', + 'is a function, not a mapping of names to row sources', ), ( ['reduce', *SOURCES, '--source', 'p', '-l', 'x'], diff --git a/packages/essapps/tests/batch/manager_test.py b/packages/essapps/tests/batch/manager_test.py index 06ee9f65..29b3b16e 100644 --- a/packages/essapps/tests/batch/manager_test.py +++ b/packages/essapps/tests/batch/manager_test.py @@ -84,7 +84,7 @@ def test_a_manager_made_again_on_the_definitions_hands_out_the_batch_as_it_was( again = _again(client, definitions).batch(label) assert again.spec == STAGED - assert again.columns == COLUMNS + assert again.parameter_columns == COLUMNS assert again.settings == batch.settings assert again.cells() == batch.cells() pd.testing.assert_frame_equal(again.frame(), batch.frame()) @@ -97,8 +97,12 @@ def test_the_columns_of_a_batch_are_the_parameter_columns_of_its_rows( chosen = manager.create('plain', title='Evening', rows=given) empty = manager.create('plain', title='Morning') - assert manager.batch(chosen).columns == ('thickness', 'transmission', 'sample') - assert manager.batch(empty).columns == () + assert manager.batch(chosen).parameter_columns == ( + 'thickness', + 'transmission', + 'sample', + ) + assert manager.batch(empty).parameter_columns == () @pytest.mark.parametrize( diff --git a/packages/essapps/tests/batch/reduction_test.py b/packages/essapps/tests/batch/reduction_test.py index 1dc89c41..6e215cf2 100644 --- a/packages/essapps/tests/batch/reduction_test.py +++ b/packages/essapps/tests/batch/reduction_test.py @@ -128,7 +128,7 @@ def test_the_table_put_is_the_table_and_its_parameter_columns_the_blanks( assert list(frame.index) == ['1'] assert list(frame.columns) == ['run', 'name', *COLUMNS, 'note'] assert (frame.loc['1', 'name'], frame.loc['1', 'sample']) == ('water', 'uuid:run-1') - assert batch.columns == batch.template().blanks == COLUMNS + assert batch.parameter_columns == batch.template().blanks == COLUMNS assert batch.settings_fields == ('binning', 'offset') @@ -168,11 +168,14 @@ def test_a_put_keeps_the_settings_at_a_column_added_and_at_a_column_dropped( batch.settings = settings batch.put(batch.frame().assign(offset=None)) - as_column = (batch.settings, batch.columns, batch.template().params) + as_column = (batch.settings, batch.parameter_columns, batch.template().params) batch.put(batch.frame().drop(columns=['offset', 'thickness'])) assert as_column == (settings, (*COLUMNS, 'offset'), SETTINGS) - assert (batch.settings, batch.columns) == (settings, ('sample', 'transmission')) + assert (batch.settings, batch.parameter_columns) == ( + settings, + ('sample', 'transmission'), + ) assert batch.template().params == settings kept = definitions.load(settings_key('s'), template_of) assert kept == Template(PLAIN, params=settings) @@ -551,7 +554,7 @@ def test_make_setting_gives_the_setting_the_value_that_the_row_takes( measured.make_setting('thickness', key) - assert 'thickness' not in measured.columns + assert 'thickness' not in measured.parameter_columns assert measured.settings == {**SETTINGS, 'thickness': setting} @@ -573,7 +576,7 @@ def test_make_setting_refuses_rows_that_take_different_values_without_a_row( assert measured.values('thickness') == {'1': 3.0, '2': 2.0} with pytest.raises(ValueError, match='the rows differ at thickness'): measured.make_setting('thickness') - assert 'thickness' in measured.columns + assert 'thickness' in measured.parameter_columns def test_make_setting_of_a_batch_without_rows_keeps_the_setting( @@ -629,7 +632,7 @@ def test_a_batch_from_a_source_refuses_a_setting_at_and_a_table_without_a_column from_source.settings = from_source.settable(given) assert from_source.settings == {'thickness': 2.0} - assert set(FILLS) <= set(from_source.columns) + assert set(FILLS) <= set(from_source.parameter_columns) def test_a_batch_is_not_made_on_a_table_without_a_column_of_its_fills( diff --git a/packages/essapps/tests/batch/toys.py b/packages/essapps/tests/batch/toys.py index 9d933e43..70a64bcb 100644 --- a/packages/essapps/tests/batch/toys.py +++ b/packages/essapps/tests/batch/toys.py @@ -19,7 +19,7 @@ DefinitionStore, FileInfo, NotKept, - Source, + RowSource, rows_of, ) from ess.apps.batch.definition import Key @@ -236,8 +236,8 @@ def samples(files: Sequence[FileInfo]) -> pd.DataFrame: return pd.DataFrame.from_records(rows, columns=[KEY, 'sample']).set_index(KEY) -PAIRS = Source(pair, fills=('sample', 'transmission')) -SAMPLES = Source(samples, fills=('sample',)) +PAIRS = RowSource(pair, fills=('sample', 'transmission')) +SAMPLES = RowSource(samples, fills=('sample',)) SOURCES = {'pairs': PAIRS} STAGED_NAMES = frozenset({STAGED.name}) """The specs whose batches run through a stage.""" diff --git a/packages/essapps/tests/batch/web_browser_test.py b/packages/essapps/tests/batch/web_browser_test.py index b813c636..cc32ffe9 100644 --- a/packages/essapps/tests/batch/web_browser_test.py +++ b/packages/essapps/tests/batch/web_browser_test.py @@ -1505,7 +1505,11 @@ def test_a_person_makes_a_batch_and_lands_on_its_page( (label,) = (k for k, h in manager.headers().items() if h.title == 'Afternoon') assert page.url.endswith(f'/batches/{label}/') page.wait_for_selector('.chip.st-all .n:text-is("3")') - assert manager.batch(label).columns == ('sample', 'transmission', 'thickness') + assert manager.batch(label).parameter_columns == ( + 'sample', + 'transmission', + 'thickness', + ) assert manager.following is None # Follow is off unless ticked assert page.is_hidden('#stop-follow') diff --git a/packages/essapps/tests/batch/web_test.py b/packages/essapps/tests/batch/web_test.py index ce1ff4d6..2b79bfdd 100644 --- a/packages/essapps/tests/batch/web_test.py +++ b/packages/essapps/tests/batch/web_test.py @@ -29,7 +29,7 @@ DefinitionStore, FolderDefinitions, Header, - Source, + RowSource, ) from ess.apps.batch.definition import Key, NotKept, rows_key, settings_key from ess.apps.batch.web import Pages, Shown, create_app, demo, plots @@ -818,7 +818,7 @@ def test_a_table_loaded_replaces_the_rows_the_columns_and_so_the_forms( shown = loaded.json() assert [(r['key'], r['name']) for r in shown['rows']] == [('a', 'first')] assert [c['name'] for c in shown['columns']] == ['sample', 'transmission'] - assert batch.columns == ('sample', 'transmission') + assert batch.parameter_columns == ('sample', 'transmission') assert 'thickness' in [n['path'][0] for n in shown['settings']] assert thickness(http, ['a'], 3) == {'message': 'There is no column thickness.'} @@ -1426,7 +1426,7 @@ def test_a_column_whose_rows_agree_is_made_a_setting_of_their_value( made = make_setting(http).json() assert made['notice'] == 'Thickness is a setting: one value for every row.' - assert batch.columns == ('sample', 'transmission') + assert batch.parameter_columns == ('sample', 'transmission') assert batch.settings['thickness'] == 2.0 assert [c['name'] for c in made['columns']] == ['sample', 'transmission'] (shown,) = [n for n in made['settings'] if n['path'] == ['thickness']] @@ -1455,7 +1455,7 @@ def test_a_column_made_a_setting_whose_table_is_refused_keeps_its_cells( assert answer.status_code == 422 batch = started(client, definitions).manager.batch('scan') - assert batch.columns == ('sample', 'transmission', 'thickness') + assert batch.parameter_columns == ('sample', 'transmission', 'thickness') assert batch.frame()['thickness'].tolist() == [2.5, 2.5, 2.5] @@ -1488,7 +1488,7 @@ def test_a_setting_made_a_column_is_shown_in_the_form_and_in_each_empty_cell( assert made['notice'] == ( 'Thickness is a column: a row takes the setting until its cell is set.' ) - assert batch.columns == ('sample', 'transmission', 'thickness') + assert batch.parameter_columns == ('sample', 'transmission', 'thickness') assert batch.frame()['thickness'].isna().all() assert batch.settings['thickness'] == 2.5 assert [r['cells']['thickness']['text'] for r in made['rows']] == [''] * 3 @@ -1519,7 +1519,7 @@ def test_a_group_setting_made_a_column_and_a_setting_again_keeps_its_value( assert [c['name'] for c in column['columns']][-1] == 'binning' assert cells == [None] * 3 - assert 'binning' not in batch.columns + assert 'binning' not in batch.parameter_columns assert form_bins(setting) == 5 @@ -1540,7 +1540,7 @@ def test_columns_do_not_change_while_the_form_holds_a_change( assert answer.json()['message'] == ( 'Nothing was changed: apply or discard the settings first.' ) - assert batch.columns == ('sample', 'transmission', 'thickness') + assert batch.parameter_columns == ('sample', 'transmission', 'thickness') assert list(batch.frame().index) == ['1', '2', '3'] assert form_bins(state(http)) == 9 @@ -2091,7 +2091,7 @@ def test_the_sources_offer_the_specs_that_fit_and_the_parameters_a_cell_edits( def test_a_source_that_no_spec_fits_is_not_offered_and_no_source_always_is( client: Client, definitions: DefinitionStore ) -> None: - odd = Source(pair, fills=('sample', 'background')) + odd = RowSource(pair, fills=('sample', 'background')) manager = BatchManager(client, sources={'odd': odd}, definitions=definitions) pages = Pages(manager) @@ -2171,7 +2171,7 @@ def test_a_batch_without_a_source_is_made_with_the_columns_sent_and_no_rows( made = TestClient(create_app(pages)).post('/api/batches', json=sent).json() batch = manager.batch(made['label']) - assert (batch.spec.name, batch.columns, len(batch.frame())) == ( + assert (batch.spec.name, batch.parameter_columns, len(batch.frame())) == ( 'find', ('sample',), 0, @@ -2358,7 +2358,7 @@ def test_a_setting_of_the_batch_at_a_column_of_the_new_one_is_its_empty_cells( ).json() batch = manager.batch(made['label']) - assert batch.columns == tuple(columns) + assert batch.parameter_columns == tuple(columns) assert batch.frame()['thickness'].isna().tolist() == [True, True] assert [c['thickness'] for c in batch.cells().values()] == [2.5, 2.5] @@ -2422,7 +2422,7 @@ def test_a_batch_made_from_a_table_file_has_its_rows_and_columns_and_no_source( made = from_table(http, text, settings_from='scan').json() batch = manager.batch(made['label']) - assert batch.columns == ('sample', 'transmission') + assert batch.parameter_columns == ('sample', 'transmission') assert list(batch.frame().index) == ['a', 'b'] assert manager.source(made['label']) is None assert manager.headers()[made['label']].title == 'From a file' diff --git a/packages/essapps/tests/folder_test.py b/packages/essapps/tests/folder_test.py index e32b29cf..53d81bd9 100644 --- a/packages/essapps/tests/folder_test.py +++ b/packages/essapps/tests/folder_test.py @@ -11,7 +11,7 @@ import scipp as sc from ess.apps import Client, Selector, file -from ess.apps.batch import Batch, FileInfo, Source, rows_of +from ess.apps.batch import Batch, FileInfo, RowSource, rows_of from ess.apps.batch.auto import step from ess.apps.batch.frames import with_results from ess.apps.batch.table import KEY @@ -165,7 +165,7 @@ def _runs(files: Sequence[FileInfo]) -> pd.DataFrame: return pd.DataFrame({'sample': [str(f.ref) for f in files]}, index=keys) -RUNS = Source(_runs, fills=('sample',)) +RUNS = RowSource(_runs, fills=('sample',)) """A row per run.""" diff --git a/packages/essapps/tests/stories/e_automatic_test.py b/packages/essapps/tests/stories/e_automatic_test.py index c6230973..3ec57a0f 100644 --- a/packages/essapps/tests/stories/e_automatic_test.py +++ b/packages/essapps/tests/stories/e_automatic_test.py @@ -10,7 +10,7 @@ import pytest from ess.apps import Client, Record -from ess.apps.batch import Batch, FileInfo, Source, rows_of +from ess.apps.batch import Batch, FileInfo, RowSource, rows_of from ess.apps.batch.auto import step from ess.apps.testing import FakeFiles @@ -27,7 +27,7 @@ def per_run(files: Sequence[FileInfo]) -> pd.DataFrame: ) -PER_RUN = Source(per_run, fills=('sample',)) +PER_RUN = RowSource(per_run, fills=('sample',)) def iofq_batch(client: Client) -> Batch: @@ -68,7 +68,7 @@ def test_e1_series_grows_reduction_follows( client: Client, connect: Callable[..., Client], measure: toys.Measure ) -> None: reference = measure(1, [1.0, 1.0], role='reference') - source = Source(angles, fills=('runs',)) + source = RowSource(angles, fills=('runs',)) batch = Batch( client, toys.STITCH, diff --git a/packages/essinstruments/src/ess/instruments/loki/batch.py b/packages/essinstruments/src/ess/instruments/loki/batch.py index 5bb97be9..35b23bc3 100644 --- a/packages/essinstruments/src/ess/instruments/loki/batch.py +++ b/packages/essinstruments/src/ess/instruments/loki/batch.py @@ -26,7 +26,7 @@ import pandas as pd -from ess.apps.batch import FileInfo, Source +from ess.apps.batch import FileInfo, RowSource from ess.apps.batch.table import KEY, cell_of from .specs import IOFQ @@ -81,7 +81,7 @@ def _measured(f: FileInfo) -> tuple[int, str]: return (sys.maxsize, f.ref.file) if run is None else (run, '') -SAMPLE_RUNS = Source(pair_by_sample, fills=('sample', 'sample_transmission')) +SAMPLE_RUNS = RowSource(pair_by_sample, fills=('sample', 'sample_transmission')) """A row per sample run, paired by :func:`pair_by_sample`.""" SOURCES = {'sample-runs': SAMPLE_RUNS} """The sources of LoKI's batches, by name.""" diff --git a/packages/essinstruments/tests/loki/batch_test.py b/packages/essinstruments/tests/loki/batch_test.py index 355d6566..5eeed1dd 100644 --- a/packages/essinstruments/tests/loki/batch_test.py +++ b/packages/essinstruments/tests/loki/batch_test.py @@ -118,7 +118,7 @@ def test_the_source_gives_its_columns_without_files(tmp_path: Path) -> None: with local(proposal='p1', files=FolderFiles(tmp_path, []), bind=BINDINGS) as client: batch = Batch(client, IOFQ, label='iofq', rows=rows_of(client, SAMPLE_RUNS)) - assert batch.columns == ('sample', 'sample_transmission') + assert batch.parameter_columns == ('sample', 'sample_transmission') @pytest.fixture From d6b8a434cee4caaf0e7c675a930fd996f0ecae1e Mon Sep 17 00:00:00 2001 From: Simon Heybrock Date: Mon, 23 Nov 2026 07:00:38 +0000 Subject: [PATCH 2/5] Bring rows of a row source into a batch with Intake BatchManager did two jobs: it kept the batches of a workspace, and it brought the rows of a row source into a batch (create from a source, take, offered, step, and which batch follows). All of the second job writes `considered`, so it moves as a whole to Intake, which holds the manager and the sources. The manager then knows no row source: create takes a table (rows=, fills=), and both create methods return the Batch, not its label. The parameters that a row source fills are data of the batch: they are kept as the blanks of the template in settings.json, which the Batch writes. So source.json holds the source and the keys considered only, and the Intake is its one writer, as of following.json. A source.json with other entries is refused when read. manager.remove deletes every table of the label and does not write following.json; Intake.following counts a label without a header as none. Intake.create makes the batch with the manager, then writes source.json and following.json, and removes the batch again if one of these is refused. The page, the command, the demo and LoKI hold an Intake where they need a row source or Follow, and reach the manager as intake.manager. Co-Authored-By: Claude Opus 5.5 --- .../essapps/src/ess/apps/batch/__init__.py | 2 + packages/essapps/src/ess/apps/batch/auto.py | 6 +- packages/essapps/src/ess/apps/batch/cli.py | 33 +- .../essapps/src/ess/apps/batch/definition.py | 49 +- packages/essapps/src/ess/apps/batch/intake.py | 409 ++++++++++ .../essapps/src/ess/apps/batch/manager.py | 475 ++---------- .../essapps/src/ess/apps/batch/reduction.py | 19 +- packages/essapps/src/ess/apps/batch/source.py | 8 +- .../essapps/src/ess/apps/batch/web/demo.py | 19 +- .../essapps/src/ess/apps/batch/web/page.py | 31 +- .../essapps/src/ess/apps/batch/web/pages.py | 114 +-- packages/essapps/tests/batch/auto_test.py | 78 +- packages/essapps/tests/batch/conftest.py | 21 +- .../essapps/tests/batch/definition_test.py | 74 +- packages/essapps/tests/batch/files_test.py | 82 +- packages/essapps/tests/batch/intake_test.py | 549 ++++++++++++++ packages/essapps/tests/batch/manager_test.py | 716 +++--------------- packages/essapps/tests/batch/toys.py | 13 +- .../essapps/tests/batch/web_browser_test.py | 62 +- .../essapps/tests/batch/web_follow_test.py | 68 +- packages/essapps/tests/batch/web_test.py | 176 ++--- .../src/ess/instruments/loki/batch.py | 6 +- .../src/ess/instruments/loki/web.py | 8 +- .../essinstruments/tests/loki/web_test.py | 13 +- 24 files changed, 1620 insertions(+), 1411 deletions(-) create mode 100644 packages/essapps/src/ess/apps/batch/intake.py create mode 100644 packages/essapps/tests/batch/intake_test.py diff --git a/packages/essapps/src/ess/apps/batch/__init__.py b/packages/essapps/src/ess/apps/batch/__init__.py index b4d45218..8cfd9846 100644 --- a/packages/essapps/src/ess/apps/batch/__init__.py +++ b/packages/essapps/src/ess/apps/batch/__init__.py @@ -10,6 +10,7 @@ from .corrections import CorrectedFiles from .definition import DefinitionStore, FolderDefinitions, Header, NotKept +from .intake import Intake from .manager import BatchManager from .reduction import Batch from .source import FileInfo, Range, RowFunction, RowSource, rows_of @@ -30,6 +31,7 @@ 'FileInfo', 'FolderDefinitions', 'Header', + 'Intake', 'NotKept', 'Range', 'RowFunction', diff --git a/packages/essapps/src/ess/apps/batch/auto.py b/packages/essapps/src/ess/apps/batch/auto.py index 37493ae2..a1205552 100644 --- a/packages/essapps/src/ess/apps/batch/auto.py +++ b/packages/essapps/src/ess/apps/batch/auto.py @@ -7,8 +7,8 @@ ``docs/developer/adr/0013-follow-adds-the-rows-not-considered.md``. :func:`step` is one step on one batch. Follow is a step on the batch that the -manager keeps as the one that follows, every few seconds -(:meth:`~.manager.BatchManager.step`); whoever serves owns the timer that +intake keeps as the one that follows, every few seconds +(:meth:`~.intake.Intake.step`); whoever serves owns the timer that calls it. A step adds the rows of the source that are new and filled, as a person does @@ -24,7 +24,7 @@ A step never changes a row that the table has, and never changes the blanks of the template: it takes only the columns that the table has. A row whose key is considered, such as one a person removed, is never added again; the caller -keeps :attr:`Step.considered` and gives it to the next step (the manager in +keeps :attr:`Step.considered` and gives it to the next step (the intake in ``source.json``). A key of the source that the table has is considered, whoever added the row, and the step keeps it so. So a row that a person added by hand with a key that the source gives later stays away once removed, and diff --git a/packages/essapps/src/ess/apps/batch/cli.py b/packages/essapps/src/ess/apps/batch/cli.py index 5604677c..baadf374 100644 --- a/packages/essapps/src/ess/apps/batch/cli.py +++ b/packages/essapps/src/ess/apps/batch/cli.py @@ -16,9 +16,10 @@ command, by its ID or by its label (see :func:`.templates.with_latest`). The command makes and reads its batch with a :class:`~.manager.BatchManager`, -as a page does, so a label is one batch whoever works on it: +and an :class:`~.intake.Intake` for the row sources, as a page does, so a +label is one batch whoever works on it: -- ``reduce`` reduces the batch of its label, with the sources of the +- ``reduce`` reduces the batch of its label, with the row sources of the application that ``-s/--sources`` names:: essapps-batch -b my.package:BINDINGS reduce -s my.package:SOURCES -l LABEL @@ -27,10 +28,11 @@ the batch (:meth:`~.manager.BatchManager.create`) of the template's spec, with the label as title. Its table is the table given (:func:`.table.read_table`), or the rows that the source ``--source NAME`` - has filled now, not both; without either, one row keyed by the label. - With ``--source``, the batch keeps its source, so that its page offers the - rows of the source that its table lacks; it does not follow. ``create`` - refuses a label that has definitions or records. + has filled now (:meth:`~.intake.Intake.create`), not both; without either, + one row keyed by the label. With ``--source``, the batch keeps its + source, so that its page offers the rows of the source that its table + lacks; it does not follow. ``create`` refuses a label that has + definitions or records. For a label with a batch, the template becomes its settings and the table replaces its table (:meth:`.reduction.Batch.put`); ``--source`` is refused. @@ -79,6 +81,7 @@ from .corrections import CorrectedFiles from .definition import FolderDefinitions, NotKept from .export import export_table +from .intake import Intake from .manager import BatchManager from .source import RowSource, rows_of from .table import KEY, SUFFIXES, read_table, read_text, write_table @@ -213,7 +216,6 @@ def _reduce( template = None if args.template is None else load_template(args.template) manager = BatchManager( client, - sources=args.sources, definitions=definitions, staged={bound.name for bound in client.specs()} if args.staged else (), ) @@ -236,7 +238,7 @@ def _reduce( elif args.source is None: rows = pd.DataFrame(index=pd.Index([label], name=KEY)) else: - rows = None # create takes them from the source + rows = None # the intake takes them from the source settings = None if template is not None: # Checked before anything is written. @@ -248,16 +250,15 @@ def _reduce( batch.put(rows) if settings is not None: batch.settings = batch.settable(settings) + elif args.source is not None: + intake = Intake(manager, sources=args.sources) + batch = intake.create( + spec.name, title=label, source=args.source, settings=settings, label=label + ) else: - manager.create( - spec.name, - title=label, - rows=rows, - source=args.source, - settings=settings, - label=label, + batch = manager.create( + spec.name, title=label, rows=rows, settings=settings, label=label ) - batch = manager.batch(label) return frames.reduce_batch( batch, remaining=args.remaining, earlier_settings=args.earlier_settings ) diff --git a/packages/essapps/src/ess/apps/batch/definition.py b/packages/essapps/src/ess/apps/batch/definition.py index 233293d8..7fe7184b 100644 --- a/packages/essapps/src/ess/apps/batch/definition.py +++ b/packages/essapps/src/ess/apps/batch/definition.py @@ -8,13 +8,13 @@ rows of a batch are written by its ``Batch``, which the manager makes: corrections metadata of a file set by hand, by file CorrectedFiles - header title, description the manager - settings the template: spec, settings Batch.settings, + header title, description BatchManager + settings the template: spec, settings, fills Batch.settings, Batch.make_setting rows the table Batch.put - source the source a batch was made from, and the the manager - keys of it that the batch has considered - following the label of the batch that follows the manager + source the row source a batch was made from, and Intake + the keys of it that the batch has considered + following the label of the batch that follows Intake The corrections are about files, and every batch of a workspace reads the files through one :class:`~.corrections.CorrectedFiles`, so a workspace has @@ -38,16 +38,18 @@ corrections {'pid:20.500.12269/abc': {'role': 'sample'}} header {'title': 'Sample runs', 'description': ''} - settings {'spec': ..., 'params': {...}, 'blanks': []}: a template + settings {'spec': ..., 'params': {...}, 'blanks': ['sample']}: a template rows {'schema': ..., 'data': [{'key': '60339', ...}, ...]} source {'source': 'sample-runs', 'considered': ['60337', '60338']} following {'label': '20261118-130204'}, or {'label': None} -The settings are a template without blanks, in the format of the file that a -person saves from a page: its params are the settings of the batch, also -those at the columns, which each row with an empty cell takes. Blanks are not -read: the parameter columns of the rows are the blanks of the template that -the rows fill (:meth:`~.reduction.Batch.template`). +The settings are a template in the format of the file that a person saves +from a page: its params are the settings of the batch, also those at the +columns, which each row with an empty cell takes; its blanks are the +parameters that the row source of the batch fills +(:attr:`~.reduction.Batch.fills`), which take no setting and which each row +must fill. The template that the rows fill has other blanks, all the +parameter columns of the rows (:meth:`~.reduction.Batch.template`). The rows are :func:`~.table.data_of` of the table. Each table is checked when read: data of another shape raises ``ValueError`` naming the entry, and :class:`FolderDefinitions` adds the file. @@ -64,7 +66,7 @@ from typing import Any, Protocol, TypedDict from urllib.parse import quote, unquote -from pydantic import TypeAdapter, ValidationError +from pydantic import ConfigDict, TypeAdapter, ValidationError from pydantic_core import from_json, to_json from ess.spec import FileRef @@ -94,6 +96,11 @@ def source_key(label: str) -> Key: return ('labels', label, 'source') +def label_keys(label: str) -> tuple[Key, ...]: + """Every table of ``label``: the header first, then the others.""" + return header_key(label), source_key(label), rows_key(label), settings_key(label) + + class NotKept(OSError): """A :class:`DefinitionStore` could not keep a table; it holds what it did.""" @@ -258,16 +265,16 @@ def __post_init__(self) -> None: @dataclass(frozen=True) class FromSource: """ - What a batch made from a source keeps of it: the name of the source, the - keys of its rows that the batch has considered, those put into the batch - from the source or left out when the batch was made, and the parameters - that the source fills (:attr:`.reduction.Batch.fills`), as they were when - the batch was made. + What a batch made from a row source keeps of it: the name of the source, + and the keys of its rows that the batch has considered, those put into + the batch from the source or left out when the batch was made. Data with + other entries is refused when read. """ + __pydantic_config__ = ConfigDict(extra='forbid') + source: str considered: frozenset[str] - fills: tuple[str, ...] class _Following(TypedDict): @@ -320,11 +327,7 @@ def header_of(data: Any) -> Header: def source_data(made: FromSource) -> dict[str, Any]: """What a batch keeps of its source, as plain data; the keys sorted.""" - return { - 'source': made.source, - 'considered': sorted(made.considered), - 'fills': list(made.fills), - } + return {'source': made.source, 'considered': sorted(made.considered)} def source_of(data: Any) -> FromSource: diff --git a/packages/essapps/src/ess/apps/batch/intake.py b/packages/essapps/src/ess/apps/batch/intake.py new file mode 100644 index 00000000..df26489d --- /dev/null +++ b/packages/essapps/src/ess/apps/batch/intake.py @@ -0,0 +1,409 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026 Scipp contributors (https://github.com/scipp) +""" +Rows of a row source into a batch: :class:`Intake` makes a batch from a +source, adds rows of its source by hand (:meth:`Intake.take`), and keeps +which batch follows and steps it. All three write ``considered``. The guide +is the section "Follow" of ``packages/essapps/docs/batch.md``; the decision +is ``docs/developer/adr/0013-follow-adds-the-rows-not-considered.md``. + +``Intake`` makes and reads the batches through its +:class:`~.manager.BatchManager`, and writes two tables of the definitions +(:mod:`.definition`):: + + source the source and the keys considered of a batch made from a source + following the label of the batch that follows of the workspace + +:meth:`Intake.create` makes the batch with the manager, which writes its +settings, rows and header, then writes ``source``, then ``following`` if the +batch follows. A batch follows from the time it is made, if made so, until +:meth:`Intake.stop` or its removal; nothing turns Follow on for a batch made +before. The manager removes a batch without writing ``following``, so a +label of ``following`` without a header counts as none, at each read +(:attr:`Intake.following`). :meth:`Intake.step` is one step of Follow on the +batch that follows:: + + made = source_of(label) # source.json + done = step(batch(label), sources[made.source], made.considered) # put, reduce + source.json = replace(made, considered=done.considered) # after the table; + # if the step raised: made.considered | the keys of the table + +Whoever serves owns the timer that calls it, and the lock. ``Intake`` has +neither. +""" + +from __future__ import annotations + +from collections.abc import Callable, Collection, Iterable, Mapping +from contextlib import suppress +from dataclasses import replace +from typing import Any + +import pandas as pd + +from ess.spec import WorkflowSpec + +from . import auto +from .auto import SourceError, Step +from .definition import ( + FOLLOWING, + FromSource, + NotKept, + following_data, + following_of, + source_data, + source_key, + source_of, +) +from .manager import BatchManager +from .reduction import Batch +from .source import Range, RowSource, filled, rows_of + + +def fits(spec: WorkflowSpec[Any, Any], source: RowSource | None) -> bool: + """ + Whether a batch of ``spec`` can be made with ``source``: whether each + parameter that the source fills is a parameter of the spec. With no + source, every spec fits. + """ + fills = () if source is None else source.fills + return set(fills) <= spec.params.model_fields.keys() + + +def _check_chosen(chosen: pd.DataFrame, arrived: pd.DataFrame) -> None: + """ + Raise ``ValueError`` unless ``chosen`` is a frame whose keys are keys of + ``arrived``. Its columns are the person's to choose. + """ + if not isinstance(chosen, pd.DataFrame): + raise ValueError(f'choose gives a {type(chosen).__name__}, not a frame') + if rows := [k for k in chosen.index if k not in arrived.index]: + raise ValueError(f'choose gives rows {rows} that the source does not') + + +class Intake: + """ + Brings the rows of row sources into the batches of ``manager``: makes a + batch from a source, offers and takes the rows that its table lacks, and + keeps which batch follows. See ``packages/essapps/docs/batch.md``. + + Refusals are as those of :class:`~.manager.BatchManager`: ``ValueError`` + for what is asked, such as a source that is not registered, + ``KeyError`` for a label that no batch has, and + :class:`~.definition.NotKept` for a write that the definitions refuse. + Anything else is an error of the code of the application, such as a + source that raises. + + :attr:`version` moves whenever :attr:`following` may give something else + by a call of this object; a removal through the manager moves + :attr:`.manager.BatchManager.version`. + + Parameters + ---------- + manager: + The batches. + sources: + The row sources that a batch can be made with, by name. + """ + + def __init__( + self, manager: BatchManager, *, sources: Mapping[str, RowSource] + ) -> None: + self.manager = manager + self.sources = sources + self._following = manager.definitions.load(FOLLOWING, following_of) + self._version = 0 + + @property + def version(self) -> int: + """Counts the changes of which batch follows, made through this object.""" + return self._version + + @property + def following(self) -> str | None: + """ + The label of the batch that follows, ``None`` if none does. It is + kept in the definitions and read when the intake is made; a label + without a header counts as none. + """ + if self._following not in self.manager.headers(): + return None + return self._following + + def stop(self) -> None: + """ + End Follow: no batch follows from then on, and the batch that followed + cannot follow again. Nothing is done if no batch follows. + """ + if self.following is None: + return + self.manager.definitions.save(FOLLOWING, following_data(None)) + self._following = None + self._version += 1 + + def _source(self, name: str) -> RowSource: + """The source registered as ``name``; ``ValueError`` if none is.""" + if name not in self.sources: + raise ValueError(f'the source {name} is not registered') + return self.sources[name] + + def rows_of(self, source: str) -> pd.DataFrame: + """ + The table that the source registered as ``source`` makes from the + files now (:func:`~.source.rows_of`). Raises ``ValueError`` if no + source is registered so. + """ + return rows_of(self.manager.client, self._source(source)) + + def _given(self, source: RowSource, fills: Collection[str]) -> pd.DataFrame: + """ + What ``source`` makes now, with a column ``waits``: whether a cell of + ``fills`` is empty (:func:`~.source.filled`). A column of the source + named ``waits`` is replaced by it. + """ + given = rows_of(self.manager.client, source) + return given.assign(waits=~filled(given, fills)) + + def marked( + self, + source: str, + choose: Callable[[pd.DataFrame], pd.DataFrame] | None = None, + ) -> pd.DataFrame: + """ + The table that the source registered as ``source`` makes now, with a + column ``waits``, whether the row waits, and a column ``taken``, + whether :meth:`create` takes it with ``choose``, such as + ``Range(first='60339')`` (:class:`~.source.Range`); every row that + does not wait if not given. Raises ``ValueError`` if no source is + registered so, and what ``choose`` raises. + """ + found = self._source(source) + given = self._given(found, found.fills) + arrived = given[~given['waits']].drop(columns='waits') + taken = arrived.index if choose is None else choose(arrived).index + return given.assign(taken=given.index.isin(taken)) + + def create( + self, + spec: str, + *, + title: str, + source: str, + choose: Callable[[pd.DataFrame], pd.DataFrame] | None = None, + follow: bool = False, + columns: Collection[str] = (), + description: str = '', + settings: Mapping[str, Any] | None = None, + label: str | None = None, + ) -> Batch: + """ + Make a batch from ``source`` with the manager + (:meth:`~.manager.BatchManager.create`) and keep what it considered; + its ``Batch``. Nothing is written if a check fails. + + The source is listed once, and the rows that are filled + (:func:`~.source.filled`) are taken and considered:: + + given = rows_of(client, source) + arrived = given[filled] # a value in each of source.fills + table = arrived if choose is None else choose(arrived) + considered = arrived.index # the rows taken and those left out + + A row that waits is neither taken nor considered: Follow adds it once + it is filled, if the batch follows. The batch keeps ``source.fills`` + (:attr:`.reduction.Batch.fills`): its table keeps a column for each, + an empty cell there means that the row waits for its file, and the + settings given are left out there. + + The manager writes the settings, the rows and the header; then + ``source.json`` is written, then, with ``follow``, ``following``. If + the definitions refuse one of these two, the batch is removed again + (:meth:`~.manager.BatchManager.remove`), and which batch follows + stays. A process that stops between the header and ``source.json`` + leaves a batch made without a source, which neither offers rows nor + follows. + + Parameters + ---------- + spec, title, columns, description, settings, label: + As :meth:`~.manager.BatchManager.create` takes them. + source: + The name of a registered source to take the rows from. The batch + keeps it, to offer the rows that its table lacks and to follow. + choose: + Makes the table of the batch from the rows of the source that are + filled: some of its rows, with any columns, such as + ``lambda given: given[given.run >= 60339].assign(thickness=pd.NA)``, + or a range of them as a person picks it, such as + ``Range(first='60339')`` (:class:`~.source.Range`). All of them, + as they are, if not given. + follow: + Whether the batch follows its source from the time it is made, in + place of the batch that followed before. A batch made without + ``follow`` never follows. A :class:`~.source.Range` with a + ``last`` is refused with ``follow``; a function may choose any + rows, and the filled rows that it leaves out are considered, so + Follow adds only the rows that arrive later. + + Raises + ------ + ValueError + If ``follow`` is given with a ``last`` of a + :class:`~.source.Range`; if no source ``source`` is registered; + if ``choose`` gives a row that the source did not; and as + :meth:`~.manager.BatchManager.create` refuses. + """ + if follow and isinstance(choose, Range) and choose.last is not None: + raise ValueError( + 'a batch that follows takes every row that arrives later, ' + 'so it has no last row' + ) + found = self._source(source) + given = self._given(found, found.fills) + arrived = given[~given['waits']].drop(columns='waits') + rows = arrived if choose is None else choose(arrived) + _check_chosen(rows, arrived) + batch = self.manager.create( + spec, + title=title, + rows=rows, + fills=found.fills, + columns=columns, + description=description, + settings=settings, + label=label, + ) + definitions = self.manager.definitions + try: + made = FromSource(source, frozenset(arrived.index)) + definitions.save(source_key(batch.label), source_data(made)) + if follow: + definitions.save(FOLLOWING, following_data(batch.label)) + except NotKept: + with suppress(NotKept): # the first error is what to say + self.manager.remove(batch.label) + raise + if follow: + self._following = batch.label + self._version += 1 + return batch + + def _from(self, label: str) -> FromSource | None: + """ + What the batch of ``label`` keeps of its source, ``None`` if it was + not made from one. Raises ``KeyError`` if no batch has the label. + """ + if label not in self.manager.headers(): + raise KeyError(label) + return self.manager.definitions.load(source_key(label), source_of) + + def _made(self, label: str) -> FromSource: + """ + What the batch of ``label`` keeps of its source. Raises ``KeyError`` + if no batch has the label, and ``ValueError`` if it was not made from + a source. + """ + if (made := self._from(label)) is None: + raise ValueError(f'{label} was not made from a source of rows') + return made + + def source(self, label: str) -> str | None: + """ + The name of the source that the batch of ``label`` was made from, + ``None`` if it was made without one and cannot follow. Raises + ``KeyError`` if no batch has the label. + """ + made = self._from(label) + return None if made is None else made.source + + def step(self) -> Step | None: + """ + One step of Follow on the batch that follows, ``None`` if none does: + add the rows of its source that are new and filled, reduce the rows + that are ready and have no result (:func:`~.auto.step`), then keep the + keys considered. The step is returned, to read what it refused and + which rows wait. + + If the step raises, such as when a submission is cut off after the + rows were added, the keys of the table are kept as considered: + otherwise a row that it added and a person removes would come back. + + Raises ``ValueError`` if the source of the batch is not registered, + if the source raises ``ValueError``, or if the batch refuses a row + that the source makes, naming the source, the row and the column; + and what the step raises otherwise, also if the definitions then + refuse the keys considered. + """ + if (label := self.following) is None: + return None + made = self._made(label) + batch = self.manager.batch(label) + source = self._source(made.source) + try: + done = auto.step(batch, source, made.considered) + except SourceError as error: # a defect of the code of the source + raise ValueError(f'the source {made.source}: {error}') from error + except BaseException: + with suppress(NotKept): # the exception of the step is what to say + kept = made.considered | set(batch.frame().index) + self._consider(label, made, kept) + raise + self._consider(label, made, done.considered) + return done + + def offered(self, label: str) -> pd.DataFrame: + """ + The rows that the source of the batch of ``label`` makes now and its + table lacks, with the columns of the source and a column ``waits``: + whether a cell of the batch's :attr:`~.reduction.Batch.fills` is + empty, so that Follow adds the row once it is filled, unless it is + considered. + A row that does not wait was left out when the batch was made, or + removed from it, and is considered, so Follow does not add it; or it + was filled after the batch was made and is not considered, so Follow + adds it at its next step if the batch follows. A column of the source + named ``waits`` is replaced by it. + + Raises ``KeyError`` if no batch has the label, and ``ValueError`` if + it was not made from a source, if its source is not registered, or + raises ``ValueError``, or no longer gives a column of the batch's + fills (:func:`~.source.filled`). + """ + made = self._made(label) + source = self._source(made.source) + batch = self.manager.batch(label) + try: + given = self._given(source, batch.fills) + except ValueError as error: # as step says it + raise ValueError(f'the source {made.source}: {error}') from error + return given[~given.index.isin(batch.frame().index)] + + def take(self, label: str, keys: Iterable[str]) -> None: + """ + Add the rows of ``keys`` to the batch of ``label``, as its source + makes them now, with the columns of its table; then consider them, so + that Follow does not add them again once removed. + + Raises ``KeyError`` if no batch has the label; ``ValueError`` if it + was not made from a source, if its source is not registered or makes + no row of a key, or if its table has a row of a key. + """ + made = self._made(label) + given = self.rows_of(made.source) + keys = list(keys) + if unknown := [k for k in keys if k not in given.index]: + raise ValueError(f'the source {made.source} makes no rows {unknown}') + batch = self.manager.batch(label) + table = batch.frame() + if held := [k for k in keys if k in table.index]: + raise ValueError(f'rows {held} are in the batch already') + batch.put(pd.concat([table, given.loc[keys].reindex(columns=table.columns)])) + self._consider(label, made, made.considered | set(keys)) + + def _consider( + self, label: str, made: FromSource, considered: frozenset[str] + ) -> None: + """Keep ``considered`` as the keys of the source of ``label``, if changed.""" + if considered != made.considered: + kept = replace(made, considered=considered) + self.manager.definitions.save(source_key(label), source_data(kept)) diff --git a/packages/essapps/src/ess/apps/batch/manager.py b/packages/essapps/src/ess/apps/batch/manager.py index a7c89f02..47c07fff 100644 --- a/packages/essapps/src/ess/apps/batch/manager.py +++ b/packages/essapps/src/ess/apps/batch/manager.py @@ -2,9 +2,10 @@ # Copyright (c) 2026 Scipp contributors (https://github.com/scipp) """ The batches of a workspace: :class:`BatchManager` makes, lists, changes and -removes them, keeps which batch follows, and steps it. The guide is the -section "The batches of a workspace" of ``packages/essapps/docs/batch.md``; -the decisions are ``docs/developer/adr/0011``, ``0012`` and ``0013``. +removes them. It knows no row source: :class:`~.intake.Intake` brings the +rows of a source into a batch. The guide is the section "The batches of a +workspace" of ``packages/essapps/docs/batch.md``; the decisions are +``docs/developer/adr/0011``, ``0012`` and ``0013``. A batch is a label with a header. A :class:`~.reduction.Batch` is the object that holds its template and its table; the manager makes the one ``Batch`` of @@ -12,44 +13,28 @@ (:mod:`.definition`), each with one writer:: header title, description BatchManager - settings the template the Batch + settings the template, with the fills as blanks the Batch rows the table the Batch - source the source and the keys considered BatchManager; only for - a batch made from a source + source the source and the keys considered Intake; only for a + batch made from a source so a manager made again, after a restart, makes the same ``Batch`` of a label from them, the specs that the workspace binds, and the specs that run staged. Making a batch makes its ``Batch``, which writes the settings and the rows; -then the manager writes the source, then the header: a label without a header -is not a batch. Removing a batch deletes the header first. So a ``create`` or -a ``remove`` cut off at any write leaves a label with tables and no header, -or a batch that does not follow, which :meth:`BatchManager.remove` removes. -After a restart, the ``Batch`` of a label is made at the first call of -:meth:`BatchManager.batch`. - -The manager writes one more table, ``following``: the label of the batch that -follows, or none. A batch follows from the time it is made, if made so, until -:meth:`BatchManager.stop` or its removal; nothing turns Follow on for a batch -made before. ``create`` writes ``following`` after the header, ``remove`` -before deleting it, so it never names a label without a header. -:meth:`BatchManager.step` is one step of Follow on the batch that follows:: - - made = source_of(label) # source.json - done = step(batch(label), sources[made.source], made.considered) # put, reduce - source.json = replace(made, considered=done.considered) # after the table; - # if the step raised: made.considered | the keys of the table - -Whoever serves owns the timer that calls it, and the lock. The manager has -neither. +then the manager writes the header: a label without a header is not a batch. +Removing a batch deletes the header first, then every other table of the +label, whoever wrote it. So a ``create`` or a ``remove`` cut off at any +write leaves a label with tables and no header, which +:meth:`BatchManager.remove` removes. After a restart, the ``Batch`` of a +label is made at the first call of :meth:`BatchManager.batch`. """ from __future__ import annotations import re import time -from collections.abc import Callable, Collection, Iterable, Mapping +from collections.abc import Collection, Mapping from contextlib import suppress -from dataclasses import replace from typing import Any import pandas as pd @@ -57,42 +42,22 @@ from ess.spec import WorkflowSpec from ..client import Client -from . import auto -from .auto import SourceError, Step from .definition import ( - FOLLOWING, DefinitionStore, - FromSource, Header, - Key, NotKept, - following_data, - following_of, header_data, header_key, header_of, + label_keys, rows_key, settings_key, - source_data, - source_key, - source_of, template_of, ) from .reduction import Batch -from .source import Range, RowSource, filled, rows_of from .table import frame_of, typed -def fits(spec: WorkflowSpec[Any, Any], source: RowSource | None) -> bool: - """ - Whether a batch of ``spec`` can be made with ``source``: whether each - parameter that the source fills is a parameter of the spec. With no - source, every spec fits. - """ - fills = () if source is None else source.fills - return set(fills) <= spec.params.model_fields.keys() - - def _check_label(label: str) -> None: """ Raise ``ValueError`` unless ``label`` is letters, digits, ``_``, ``.`` @@ -106,38 +71,21 @@ def _check_label(label: str) -> None: ) -def _parts(label: str) -> tuple[Key, ...]: - """The tables of ``label`` but its header, in the order they are deleted.""" - return source_key(label), rows_key(label), settings_key(label) - - -def _check_chosen(chosen: pd.DataFrame, arrived: pd.DataFrame) -> None: - """ - Raise ``ValueError`` unless ``chosen`` is a frame whose keys are keys of - ``arrived``. Its columns are the person's to choose. - """ - if not isinstance(chosen, pd.DataFrame): - raise ValueError(f'choose gives a {type(chosen).__name__}, not a frame') - if rows := [k for k in chosen.index if k not in arrived.index]: - raise ValueError(f'choose gives rows {rows} that the source does not') - - class BatchManager: """ - Makes, lists, changes and removes the batches of a workspace, holds the - one :class:`~.reduction.Batch` of each label, and keeps which batch - follows. See ``packages/essapps/docs/batch.md``. + Makes, lists, changes and removes the batches of a workspace, and holds + the one :class:`~.reduction.Batch` of each label. See + ``packages/essapps/docs/batch.md``. Every refusal of what is asked raises ``ValueError``, with a message for a - person, such as for a spec that the workspace does not bind, a source that - is not registered, or a label that is taken. ``KeyError`` says only that - no batch has the label asked for, and :class:`~.definition.NotKept` that - the definitions refuse a write. Anything else is an error of the code of - the application, such as a source that raises. + person, such as for a spec that the workspace does not bind, or a label + that is taken. ``KeyError`` says only that no batch has the label asked + for, and :class:`~.definition.NotKept` that the definitions refuse a + write. Anything else is an error of the code of the application. - :attr:`version` moves whenever :meth:`headers` or :attr:`following` may - give something else: while it is the same, they give the same. A batch - counts its own changes (:attr:`.reduction.Batch.version`). + :attr:`version` moves whenever :meth:`headers` may give something else: + while it is the same, they give the same. A batch counts its own changes + (:attr:`.reduction.Batch.version`). The headers are read when the manager is made. Each change of a header is written to the definitions before the manager holds it, so the manager @@ -149,34 +97,36 @@ class BatchManager: ---------- client: The client of the workspace. Its batches persist what they submit. - sources: - The sources that a batch can be made with, by name. definitions: Where the batches are kept. settings: The settings that a new batch of a spec starts with, by the name of the spec; none for a spec not named. They are copied when a batch is made, so a change of them leaves the batches made before as they are. - :meth:`create` leaves out those of the columns that a source fills. + :meth:`create` leaves out those at ``fills``. staged: The names of the specs whose batches run their rows through a stage, as :class:`~.reduction.Batch` takes it. It is read each time the manager makes the ``Batch`` of a label, so it applies to the batches made before too. + + Attributes + ---------- + definitions: + Where the batches are kept, also the tables that + :class:`~.intake.Intake` writes. """ def __init__( self, client: Client, *, - sources: Mapping[str, RowSource], definitions: DefinitionStore, settings: Mapping[str, Mapping[str, Any]] | None = None, staged: Collection[str] = (), ) -> None: self.client = client - self.sources = sources - self._definitions = definitions + self.definitions = definitions self._settings = {} if settings is None else settings self._staged = staged self._headers: dict[str, Header] = {} @@ -184,112 +134,34 @@ def __init__( if (header := definitions.load(header_key(label), header_of)) is not None: self._headers[label] = header self._batches: dict[str, Batch] = {} - following = definitions.load(FOLLOWING, following_of) - self._following = following if following in self._headers else None self._version = 0 @property def version(self) -> int: - """Counts the changes of the headers and of which batch follows.""" + """Counts the changes of the headers.""" return self._version - @property - def following(self) -> str | None: - """ - The label of the batch that follows, ``None`` if none does. It is - kept in the definitions and read when the manager is made; a label - kept without a header counts as none. - """ - return self._following - - def stop(self) -> None: - """ - End Follow: no batch follows from then on, and the batch that followed - cannot follow again. Nothing is done if no batch follows. - """ - if self._following is None: - return - self._definitions.save(FOLLOWING, following_data(None)) - self._following = None - self._version += 1 - - def rows_of(self, source: str) -> pd.DataFrame: - """ - The table that the source registered as ``source`` makes from the - files now (:func:`~.source.rows_of`). Raises ``ValueError`` if no - source is registered so. - """ - return rows_of(self.client, self._source(source)) - - def _given(self, source: RowSource, fills: Collection[str]) -> pd.DataFrame: - """ - What ``source`` makes now, with a column ``waits``: whether a cell of - ``fills`` is empty (:func:`~.source.filled`). A column of the source - named ``waits`` is replaced by it. - """ - given = rows_of(self.client, source) - return given.assign(waits=~filled(given, fills)) - - def marked( - self, - source: str, - choose: Callable[[pd.DataFrame], pd.DataFrame] | None = None, - ) -> pd.DataFrame: - """ - The table that the source registered as ``source`` makes now, with a - column ``waits``, whether the row waits, and a column ``taken``, - whether :meth:`create` takes it with ``choose``, such as - ``Range(first='60339')`` (:class:`~.source.Range`); every row that - does not wait if not given. Raises ``ValueError`` if no source is - registered so, and what ``choose`` raises. - """ - found = self._source(source) - given = self._given(found, found.fills) - arrived = given[~given['waits']].drop(columns='waits') - taken = arrived.index if choose is None else choose(arrived).index - return given.assign(taken=given.index.isin(taken)) - def create( self, spec: str, *, title: str, rows: pd.DataFrame | None = None, - source: str | None = None, - choose: Callable[[pd.DataFrame], pd.DataFrame] | None = None, + fills: Collection[str] = (), columns: Collection[str] = (), description: str = '', settings: Mapping[str, Any] | None = None, label: str | None = None, - follow: bool = False, - ) -> str: + ) -> Batch: """ - Make a batch and keep it; its label. Nothing is written if a check - fails. The header is written after the other tables of the batch, so - a label without a header is no batch; with ``follow``, ``following`` - is written last, so that it never names a label without a header. + Make a batch and keep it; its ``Batch``, whose ``label`` names it. + Nothing is written if a check fails. The header is written after the + other tables of the batch, so a label without a header is no batch. If the definitions refuse a write, the tables written are deleted, - and what was kept before stays, also which batch follows. If a delete - is refused too, as when the process stops, what is left is either a - label with tables and no header, or, with ``follow``, a batch that - does not follow. :meth:`remove` removes either. - - With a source, the source is listed once, and the rows that are - filled (:func:`~.source.filled`) are taken and considered:: - - given = rows_of(client, source) - arrived = given[filled] # a value in each of source.fills - table = arrived if choose is None else choose(arrived) - considered = arrived.index # the rows taken and those left out - - A row that waits is neither taken nor considered: Follow adds it once - it is filled, if the batch follows. - - The batch keeps ``source.fills`` in ``source.json`` - (:attr:`.reduction.Batch.fills`): its table keeps a column for each, - an empty cell there means that the row waits for its file, and the - settings given are left out there (:meth:`.reduction.Batch.settable`). + and what was kept before stays. If a delete is refused too, as when + the process stops, what is left is a label with tables and no header, + which :meth:`remove` removes. Parameters ---------- @@ -299,68 +171,37 @@ def create( title: What the batch is called. rows: - The first table of a batch without a source, as - :meth:`~.reduction.Batch.put` takes it; its parameter columns are - the blanks of the template. A table without rows or columns if - not given. - source: - The name of a registered source to take the rows from. The batch - keeps it, to offer the rows that its table lacks and to follow. - choose: - Makes the table of the batch from the rows of the source that are - filled: some of its rows, with any columns, such as - ``lambda given: given[given.run >= 60339].assign(thickness=pd.NA)``, - or a range of them as a person picks it, such as - ``Range(first='60339')`` (:class:`~.source.Range`). All of them, - as they are, if not given. + The first table, as :meth:`~.reduction.Batch.put` takes it; its + parameter columns are the blanks of the template. A table without + rows or columns if not given. + fills: + The parameters that a row source fills + (:attr:`.reduction.Batch.fills`), kept as the blanks of the + settings: each is a column of ``rows``, an empty cell there means + that the row waits for its file, and the settings given are left + out there (:meth:`.reduction.Batch.settable`). columns: Parameters that are columns of the batch, of empty cells, besides - those of ``rows`` or of the table from the source; a column that - these have keeps its cells. + those of ``rows``; a column of ``rows`` keeps its cells. description: What a person says of the batch. settings: The settings to start with, in place of those that the manager - was given for the spec; those of the columns that the source fills - are left out. + was given for the spec; those at ``fills`` are left out. label: The label of the batch. If not given, the time of making, ``YYYYMMDD-HHMMSS``, with ``-2``, ``-3``, ... added if that is taken. - follow: - Whether the batch follows its source from the time it is made, in - place of the batch that followed before. A batch made without - ``follow`` never follows. Only a batch made from a source can - follow. A :class:`~.source.Range` with a ``last`` is refused with - ``follow``; a function may choose any rows, and the filled rows - that it leaves out are considered, so Follow adds only the rows - that arrive later. Raises ------ ValueError If ``title`` is empty or only spaces; if ``label`` is not letters, digits, ``_``, ``.`` and ``-``, starting with none of the last - two, or has definitions or records; if - ``rows`` and ``source`` are both given, or ``choose`` without - ``source``, or ``follow`` without ``source`` or with a ``last`` - of a :class:`~.source.Range`; if no source - ``source`` is registered; if ``choose`` - gives a row that the source did not; if the workspace - binds no spec ``spec``; or if the rows are refused, as ``put`` - refuses them. + two, or has definitions or records; if the workspace binds no + spec ``spec``; or if the rows are refused, as ``put`` refuses + them, also for a table without a column of ``fills``. """ - if rows is not None and source is not None: - raise ValueError('a batch made from a source takes its rows from it') - if choose is not None and source is None: - raise ValueError('choose picks rows of a source, and none is given') - if follow and source is None: - raise ValueError('a batch follows its source, and none is given') - if follow and isinstance(choose, Range) and choose.last is not None: - raise ValueError( - 'a batch that follows takes every row that arrives later, ' - 'so it has no last row' - ) if label is None: stamp = time.strftime('%Y%m%d-%H%M%S') label, n = stamp, 1 @@ -375,48 +216,26 @@ def create( bound = self.spec_named(spec) if settings is None: settings = self._settings.get(spec, {}) - made = None - fills: tuple[str, ...] = () - if source is not None: - found = self._source(source) - given = self._given(found, found.fills) - arrived = given[~given['waits']].drop(columns='waits') - rows = arrived if choose is None else choose(arrived) - _check_chosen(rows, arrived) - made = FromSource(source, frozenset(arrived.index), found.fills) - fills = found.fills table = pd.DataFrame() if rows is None else rows empty = [c for c in columns if c not in table.columns] # Refused here, before anything is written. table = typed(table.assign(**dict.fromkeys(empty)), bound.params) batch = self._kept(label, bound, {}, None, fills) - written = list(_parts(label)) # what to delete if a write is refused + _, *written = label_keys(label) # what to delete if a write is refused try: batch.put(table) batch.settings = batch.settable(settings) - if made is not None: - self._definitions.save(source_key(label), source_data(made)) - self._definitions.save(header_key(label), header_data(header)) + self.definitions.save(header_key(label), header_data(header)) written.insert(0, header_key(label)) - if follow: - self._definitions.save(FOLLOWING, following_data(label)) except NotKept: with suppress(NotKept): # the first error is what to say for key in written: - self._definitions.delete(key) + self.definitions.delete(key) raise self._headers[label] = header self._batches[label] = batch - if follow: - self._following = label self._version += 1 - return label - - def _source(self, name: str) -> RowSource: - """The source registered as ``name``; ``ValueError`` if none is.""" - if name not in self.sources: - raise ValueError(f'the source {name} is not registered') - return self.sources[name] + return batch def spec_named(self, spec: str) -> WorkflowSpec[Any, Any]: """ @@ -430,38 +249,10 @@ def spec_named(self, spec: str) -> WorkflowSpec[Any, Any]: def _taken(self, label: str) -> bool: """Whether ``label`` has definitions or records.""" - return label in self._definitions.labels() or bool( + return label in self.definitions.labels() or bool( self.client.records(label=label) ) - def _from(self, label: str) -> FromSource | None: - """ - What the batch of ``label`` keeps of its source, ``None`` if it was - not made from one. Raises ``KeyError`` if no batch has the label. - """ - if label not in self._headers: - raise KeyError(label) - return self._definitions.load(source_key(label), source_of) - - def _made(self, label: str) -> FromSource: - """ - What the batch of ``label`` keeps of its source. Raises ``KeyError`` - if no batch has the label, and ``ValueError`` if it was not made from - a source. - """ - if (made := self._from(label)) is None: - raise ValueError(f'{label} was not made from a source of rows') - return made - - def source(self, label: str) -> str | None: - """ - The name of the source that the batch of ``label`` was made from, - ``None`` if it was made without one and cannot follow. Raises - ``KeyError`` if no batch has the label. - """ - made = self._from(label) - return None if made is None else made.source - def headers(self) -> dict[str, Header]: """The header of each batch, by label, sorted by label.""" return dict(sorted(self._headers.items())) @@ -479,24 +270,21 @@ def batch(self, label: str) -> Batch: parameter of the name of a note, refuses the cells of the table, and the batch cannot be shown either. - A batch made from a source is given the parameters that its source - filled when it was made (:attr:`.reduction.Batch.fills`), as kept in - ``source.json``. + The blanks of the settings kept are the parameters that the source of + the batch filled when it was made (:attr:`.reduction.Batch.fills`). """ if (batch := self._batches.get(label)) is not None: return batch if label not in self._headers: raise KeyError(label) - template = self._definitions.load(settings_key(label), template_of) + template = self.definitions.load(settings_key(label), template_of) if template is None: raise ValueError(f'{label}: no settings are kept') spec = self.spec_named(template.spec.name) - rows = self._definitions.load( + rows = self.definitions.load( rows_key(label), lambda data: typed(frame_of(data), spec.params) ) - made = self._from(label) - fills = () if made is None else made.fills - batch = self._kept(label, spec, template.params, rows, fills) + batch = self._kept(label, spec, template.params, rows, template.blanks) self._batches[label] = batch return batch @@ -517,7 +305,7 @@ def _kept( rows=rows, staged=spec.name in self._staged, persist=True, - definitions=self._definitions, + definitions=self.definitions, fills=fills, ) @@ -534,126 +322,31 @@ def change( header.title if title is None else title, header.description if description is None else description, ) - self._definitions.save(header_key(label), header_data(header)) + self.definitions.save(header_key(label), header_data(header)) self._headers[label] = header self._version += 1 - def step(self) -> Step | None: - """ - One step of Follow on the batch that follows, ``None`` if none does: - add the rows of its source that are new and filled, reduce the rows - that are ready and have no result (:func:`~.auto.step`), then keep the - keys considered. The step is returned, to read what it refused and - which rows wait. - - If the step raises, such as when a submission is cut off after the - rows were added, the keys of the table are kept as considered: - otherwise a row that it added and a person removes would come back. - - Raises ``ValueError`` if the source of the batch is not registered, - if the source raises ``ValueError``, or if the batch refuses a row - that the source makes, naming the source, the row and the column; - and what the step raises otherwise, also if the definitions then - refuse the keys considered. - """ - if (label := self._following) is None: - return None - made = self._made(label) - batch = self.batch(label) - source = self._source(made.source) - try: - done = auto.step(batch, source, made.considered) - except SourceError as error: # a defect of the code of the source - raise ValueError(f'the source {made.source}: {error}') from error - except BaseException: - with suppress(NotKept): # the exception of the step is what to say - kept = made.considered | set(batch.frame().index) - self._consider(label, made, kept) - raise - self._consider(label, made, done.considered) - return done - - def offered(self, label: str) -> pd.DataFrame: - """ - The rows that the source of the batch of ``label`` makes now and its - table lacks, with the columns of the source and a column ``waits``: - whether a cell of the batch's :attr:`~.reduction.Batch.fills` is - empty, so that Follow adds the row once it is filled, unless it is - considered. - A row that does not wait was left out when the batch was made, or - removed from it, and is considered, so Follow does not add it; or it - was filled after the batch was made and is not considered, so Follow - adds it at its next step if the batch follows. A column of the source - named ``waits`` is replaced by it. - - Raises ``KeyError`` if no batch has the label, and ``ValueError`` if - it was not made from a source, if its source is not registered, or - raises ``ValueError``, or no longer gives a column of the batch's - fills (:func:`~.source.filled`). - """ - made = self._made(label) - source = self._source(made.source) - batch = self.batch(label) - try: - given = self._given(source, batch.fills) - except ValueError as error: # as step says it - raise ValueError(f'the source {made.source}: {error}') from error - return given[~given.index.isin(batch.frame().index)] - - def take(self, label: str, keys: Iterable[str]) -> None: - """ - Add the rows of ``keys`` to the batch of ``label``, as its source - makes them now, with the columns of its table; then consider them, so - that Follow does not add them again once removed. - - Raises ``KeyError`` if no batch has the label; ``ValueError`` if it - was not made from a source, if its source is not registered or makes - no row of a key, or if its table has a row of a key. - """ - made = self._made(label) - given = self.rows_of(made.source) - keys = list(keys) - if unknown := [k for k in keys if k not in given.index]: - raise ValueError(f'the source {made.source} makes no rows {unknown}') - batch = self.batch(label) - table = batch.frame() - if held := [k for k in keys if k in table.index]: - raise ValueError(f'rows {held} are in the batch already') - batch.put(pd.concat([table, given.loc[keys].reindex(columns=table.columns)])) - self._consider(label, made, made.considered | set(keys)) - - def _consider( - self, label: str, made: FromSource, considered: frozenset[str] - ) -> None: - """Keep ``considered`` as the keys of the source of ``label``, if changed.""" - if considered != made.considered: - kept = replace(made, considered=considered) - self._definitions.save(source_key(label), source_data(kept)) - def remove(self, label: str) -> None: """ - Forget the batch of ``label`` and remove its definitions; its records - stay, and those running keep running. If the batch follows, none - follows from then on. A ``Batch`` of the label handed out before must - not be used after: it would write its definitions again. A label that - keeps tables but no header, as a ``create`` or ``remove`` cut off - leaves it, is removed too, and can then be made again. Raises - ``KeyError`` if no batch has the label and no table is kept of it. - - If the batch follows, ``following`` is written first, so that it - never names a label without a header. Then the header is deleted, so - a batch is never listed half removed. + Forget the batch of ``label`` and remove every table of it + (:func:`~.definition.label_keys`); its records stay, and those running + keep running. A ``Batch`` of the label handed out before must not be + used after: it would write its definitions again. A label that keeps + tables but no header, as a ``create`` or ``remove`` cut off leaves + it, is removed too, and can then be made again. Raises ``KeyError`` + if no batch has the label and no table is kept of it. + + The header is deleted first, so a batch is never listed half removed. + ``following`` is not written: :attr:`.intake.Intake.following` counts + a label without a header as none. """ - if label not in self._headers and label not in self._definitions.labels(): + if label not in self._headers and label not in self.definitions.labels(): raise KeyError(label) - if label == self._following: - self._definitions.save(FOLLOWING, following_data(None)) - self._following = None - self._version += 1 - self._definitions.delete(header_key(label)) + header, *parts = label_keys(label) + self.definitions.delete(header) self._headers.pop(label, None) self._version += 1 if (batch := self._batches.pop(label, None)) is not None: batch.close() - for key in _parts(label): - self._definitions.delete(key) + for key in parts: + self.definitions.delete(key) diff --git a/packages/essapps/src/ess/apps/batch/reduction.py b/packages/essapps/src/ess/apps/batch/reduction.py index 54779176..754d4e84 100644 --- a/packages/essapps/src/ess/apps/batch/reduction.py +++ b/packages/essapps/src/ess/apps/batch/reduction.py @@ -159,15 +159,16 @@ class Batch: definitions: Where the settings and the rows of the label are written at each change (:mod:`~.definition`). Nothing is read from them: the manager - reads them and gives them as ``settings`` and ``rows`` + reads them and gives them as ``settings``, ``rows`` and ``fills`` (:meth:`.manager.BatchManager.batch`). A ``Batch`` made in code without them keeps nothing. fills: The parameters that the source of the batch fills, if it was made - from one (:attr:`~.source.RowSource.fills`), as the manager keeps them - with the batch. Each is a column, and an empty cell there means that - the row waits for its file: the row is incomplete, whatever the - settings hold and whatever the default of the parameter is. + from a row source (:attr:`~.source.RowSource.fills`); they are kept + as the blanks of its settings. Each is a column, and an empty cell + there means that the row waits for its file: the row is incomplete, + whatever the settings hold and whatever the default of the parameter + is. Attributes ---------- @@ -429,10 +430,14 @@ def values(self, name: str) -> dict[str, Any]: return {key: cells[key] for key in first.values()} def _save(self, settings: Mapping[str, Any]) -> None: - """Write ``settings`` as the settings of the label, if kept.""" + """ + Write ``settings`` as the settings of the label, if kept, with + :attr:`fills` as the blanks of the template. + """ if self._definitions is not None: key = definition.settings_key(self.label) - data = definition.template_data(Template(self.spec, params=settings)) + kept = Template(self.spec, params=settings, blanks=sorted(self.fills)) + data = definition.template_data(kept) self._definitions.save(key, data) def template(self) -> Template: diff --git a/packages/essapps/src/ess/apps/batch/source.py b/packages/essapps/src/ess/apps/batch/source.py index 4bfb2cd6..921ab6b0 100644 --- a/packages/essapps/src/ess/apps/batch/source.py +++ b/packages/essapps/src/ess/apps/batch/source.py @@ -4,8 +4,8 @@ What an application gives a batch: a :class:`RowSource` makes a table from the files. -A row source is code of the application, registered by name with a -:class:`~.manager.BatchManager`. Its :data:`RowFunction` takes the files with +A row source is code of the application, registered by name with an +:class:`~.intake.Intake`. Its :data:`RowFunction` takes the files with their metadata and returns a frame, the form that ``Batch.put`` takes:: key run name sample sample_transmission @@ -122,8 +122,8 @@ class Range: """ Which rows a new batch takes of those that its source has filled now, as a person picks them, given as ``choose`` to - :meth:`~.manager.BatchManager.create` and - :meth:`~.manager.BatchManager.marked`: called on the filled rows, it gives + :meth:`~.intake.Intake.create` and + :meth:`~.intake.Intake.marked`: called on the filled rows, it gives the rows from the row of key ``first`` to the row of key ``last``, both included, in their order; an end not given is open. With ``later``, it gives none, so that the batch gets only the rows added later, by Follow diff --git a/packages/essapps/src/ess/apps/batch/web/demo.py b/packages/essapps/src/ess/apps/batch/web/demo.py index 46c38083..debad475 100644 --- a/packages/essapps/src/ess/apps/batch/web/demo.py +++ b/packages/essapps/src/ess/apps/batch/web/demo.py @@ -56,7 +56,14 @@ WorkflowSpec, ) -from .. import BatchManager, CorrectedFiles, FileInfo, FolderDefinitions, RowSource +from .. import ( + BatchManager, + CorrectedFiles, + FileInfo, + FolderDefinitions, + Intake, + RowSource, +) from ..table import KEY, cell_of from . import Pages, create_app, plots from .api import STATIC, every @@ -319,11 +326,11 @@ def build( a batch of the samples there are is made, with a column of thickness, so also at a start after a person removed the last one. """ - manager = BatchManager( - client, sources=SOURCES, definitions=definitions, staged=STAGED + intake = Intake( + BatchManager(client, definitions=definitions, staged=STAGED), sources=SOURCES ) - if not manager.headers(): - manager.create( + if not intake.manager.headers(): + intake.create( DEMO.name, title='Samples', source='sample-runs', @@ -338,7 +345,7 @@ def draw(shown: Sequence[Shown]) -> dict[str, object]: return plots.figure(curves, quantity='I(Q)') pages = Pages( - manager, + intake, interval=interval, title=DEMO.title, draw={DEMO.name: draw}, diff --git a/packages/essapps/src/ess/apps/batch/web/page.py b/packages/essapps/src/ess/apps/batch/web/page.py index 212ebe5f..b00fb80f 100644 --- a/packages/essapps/src/ess/apps/batch/web/page.py +++ b/packages/essapps/src/ess/apps/batch/web/page.py @@ -98,7 +98,7 @@ batch never follows again; the page of a batch that does not follow has no action of Follow. While a batch follows, :meth:`Pages.tick <.pages.Pages.tick>` steps it every ``interval`` seconds -(:meth:`~ess.apps.batch.BatchManager.step`), which adds the rows of its +(:meth:`~ess.apps.batch.Intake.step`), which adds the rows of its source that are new and filled, and reduces the rows that :func:`~ess.apps.batch.not_reduced` gives, the rows that are ready and have no result, under the lock of all pages, with the batch's settings, whatever @@ -343,9 +343,9 @@ class Page: Parameters ---------- pages: - What the pages share: the manager of the batch, the lock, the - listing of the files, Follow, and what the application gives every - page. + What the pages share: the manager of the batch, the intake of its + rows and Follow, the lock, the listing of the files, and what the + application gives every page. label: The label of the batch. """ @@ -365,7 +365,7 @@ def __init__(self, pages: Pages, label: str) -> None: @property def batch(self) -> Batch: """The batch, asked of the manager at each use.""" - return self.pages.manager.batch(self.label) + return self.pages.intake.manager.batch(self.label) @property def lock(self) -> AbstractContextManager[object]: @@ -404,7 +404,7 @@ def _fit(self) -> None: def _follows(self) -> bool: """Whether this batch is the one that follows.""" - return self.pages.manager.following == self.label + return self.pages.intake.following == self.label # Reading @@ -423,7 +423,8 @@ def _live(self) -> tuple[object, ...]: self.batch.version, pages.listing.cursor, pages.files_version, - pages.manager.version, + pages.intake.manager.version, + pages.intake.version, pages.follow_token(self.label), ) @@ -561,7 +562,7 @@ def shown(error: FieldError) -> bool: unapplied = self._unapplied() marks = [e for e in (*unusable, *self.refused) if not e.entry and shown(e)] empty = batch.empty() - header = self.pages.manager.headers()[self.label] + header = self.pages.intake.manager.headers()[self.label] return State( version=self.version, start=self.start, @@ -820,12 +821,12 @@ def add(self, key: str) -> str: def offered(self) -> SourceRows: """ The rows of the source that the table lacks, those that wait marked - (:meth:`~ess.apps.batch.BatchManager.offered`), for :meth:`take`; + (:meth:`~ess.apps.batch.Intake.offered`), for :meth:`take`; what the source refuses is a :class:`~.refusals.Problem` (:func:`~.refusals.refused`). """ with refused('The rows of the source cannot be listed'): - given = self.pages.manager.offered(self.label) + given = self.pages.intake.offered(self.label) return listed(given, self.batch.fills) @_action @@ -833,12 +834,12 @@ def take(self, keys: Sequence[str]) -> str: """ Add the rows of ``keys`` as the source makes them now, so that Follow does not add them again once removed - (:meth:`~ess.apps.batch.BatchManager.take`). What the manager or the + (:meth:`~ess.apps.batch.Intake.take`). What the intake or the source refuses is a :class:`~.refusals.Problem` (:func:`~.refusals.refused`). """ with refused('No row was added'): - self.pages.manager.take(self.label, keys) + self.pages.intake.take(self.label, keys) # The rows may name files that the listing lacks. self._list_again() return f'Added {_rows(len(keys))}.' @@ -941,11 +942,11 @@ def cancel(self) -> str: def stop_following(self) -> str: """ Let none follow, if this batch follows - (:meth:`~ess.apps.batch.BatchManager.stop`); it cannot follow again. + (:meth:`~ess.apps.batch.Intake.stop`); it cannot follow again. """ if not self._follows(): return '' # another batch follows, or none - self.pages.manager.stop() + self.pages.intake.stop() return 'Stopped following.' def stepped(self) -> None: @@ -1043,7 +1044,7 @@ def change(self, edit: HeaderEdit) -> str: refuses is a :class:`~.refusals.Problem`, and changes nothing. """ try: - self.pages.manager.change( + self.pages.intake.manager.change( self.label, title=edit.title, description=edit.description ) except ValueError as error: diff --git a/packages/essapps/src/ess/apps/batch/web/pages.py b/packages/essapps/src/ess/apps/batch/web/pages.py index d2090aa0..7307f979 100644 --- a/packages/essapps/src/ess/apps/batch/web/pages.py +++ b/packages/essapps/src/ess/apps/batch/web/pages.py @@ -32,16 +32,16 @@ now (:meth:`Pages.rows_of`); from a table file; or without rows. Made from the page of a batch, it may start with the settings of that batch. A batch made from a source may follow it from then on, in place of the batch that -followed before; no other action makes a batch follow. The manager decides -what can be made. With no batch at all, the page is served +followed before; no other action makes a batch follow. The manager and the +intake decide what can be made. With no batch at all, the page is served without one: it shows the list of batches and the runs. So is the page of a batch that cannot be made (:meth:`Pages.page`), with the reason, and that of a batch removed (:meth:`Pages.remove`): a :class:`~.page.Page` handed out before answers :class:`~.refusals.Missing` from then on. -The manager keeps which batch follows -(:attr:`~ess.apps.batch.BatchManager.following`). :meth:`Pages.tick` is one -step of it (:meth:`~ess.apps.batch.BatchManager.step`), with or without a +The intake keeps which batch follows +(:attr:`~ess.apps.batch.Intake.following`). :meth:`Pages.tick` is one +step of it (:meth:`~ess.apps.batch.Intake.step`), with or without a page open, plus what the page shows of the step (:meth:`Pages.follow_shown`, :meth:`Pages.unsubmitted`): why rows were refused, how many rows wait, and what the step raised; then @@ -69,7 +69,7 @@ from ...listing import Listing from ..auto import Step from ..corrections import CorrectedFiles -from ..manager import BatchManager, fits +from ..intake import Intake, fits from ..source import Range, RowSource from ..state import RowState, not_reduced from ..table import read_table @@ -137,7 +137,7 @@ def listed(self, selector: Selector) -> dict[FileRef, dict[str, Any]]: class Pages: """ - What the pages of the batches of ``manager`` share. It owns, and only it + What the pages of the batches of ``intake.manager`` share. It owns, and only it writes, the listing of the files and its version, the corrections of runs, and the step of Follow and what it said; a :class:`~.page.Page` writes its batch through the manager. Each public method takes @@ -146,8 +146,8 @@ class Pages: Parameters ---------- - manager: - The batches. + intake: + The row sources and Follow; its manager holds the batches. interval: The seconds between two steps of Follow, for the timer of :func:`~.api.create_app`. @@ -171,7 +171,7 @@ class Pages: def __init__( self, - manager: BatchManager, + intake: Intake, *, interval: float = 5.0, title: str = '', @@ -180,7 +180,7 @@ def __init__( marks: type[BaseModel] | None = None, folder: str = '', ) -> None: - self.manager = manager + self.intake = intake self.interval = interval self.title = title self.draw = {} if draw is None else draw @@ -192,7 +192,7 @@ def __init__( # last step that did not raise, whose refusals :meth:`applied` empties. self._failure: str | None = None self._last: tuple[str, Step] | None = None - self._listing = SafeListing(manager.client) + self._listing = SafeListing(intake.manager.client) # The files of the listing with their metadata, and why they cannot # be listed, as at :attr:`files_version`. self._files = (self._listing.files_listed, self._listing.failure) @@ -225,7 +225,7 @@ def check(self, label: str) -> None: gets a page of its own. """ with self.lock: - if label not in self.manager.headers(): + if label not in self.intake.manager.headers(): self._pages.pop(label, None) raise Missing(f'There is no batch {label}.') @@ -236,15 +236,15 @@ def home(self) -> str | None: ``/`` lists them rather than guess. """ with self.lock: - if (label := self.manager.following) is not None: + if (label := self.intake.following) is not None: return label - headers = self.manager.headers() + headers = self.intake.manager.headers() return next(iter(headers)) if len(headers) == 1 else None def tick(self) -> None: """ A step of Follow on the batch that follows, if one does - (:meth:`~ess.apps.batch.BatchManager.step`), and what the page shows + (:meth:`~ess.apps.batch.Intake.step`), and what the page shows of it; then :meth:`Page.stepped <.page.Page.stepped>` of its page. :func:`~.api.create_app` calls it on a timer. What the step raises is said on the page (:meth:`follow_shown`), and the next step tries @@ -255,10 +255,10 @@ def tick(self) -> None: # said, such as an exception whose text raises, or a page that cannot # be made, must not end the timer. with self.lock, suppress(Exception): - if (label := self.manager.following) is None: + if (label := self.intake.following) is None: return try: - if (done := self.manager.step()) is None: + if (done := self.intake.step()) is None: return self._last = (label, done) self._failure = None @@ -301,7 +301,9 @@ def list_again(self) -> None: the files or why they cannot be listed differ from the last listing. """ with self.lock: - self._listing = SafeListing(self.manager.client, previous=self._listing) + self._listing = SafeListing( + self.intake.manager.client, previous=self._listing + ) self._new_files() def _new_files(self) -> None: @@ -405,7 +407,7 @@ def _kept(self, correction: Callable[[], None]) -> None: def _step(self, label: str) -> Step | None: """Follow's last step that did not raise, if on ``label``, which follows.""" - if self.manager.following != label or self._last is None: + if self.intake.following != label or self._last is None: return None on, step = self._last return step if on == label else None @@ -417,7 +419,7 @@ def follow_token(self, label: str) -> object: read: equal while what the page shows of Follow stays the same. """ with self.lock: - if self.manager.following != label: + if self.intake.following != label: return None step = self._step(label) shown = None if step is None else (len(step.waiting), step.refused) @@ -430,11 +432,11 @@ def follow_shown(self, label: str) -> Following: many rows wait. """ with self.lock: - on = self.manager.following == label + on = self.intake.following == label step = self._step(label) return Following( on=on, - source=self.manager.source(label), + source=self.intake.source(label), interval=self.interval, failure=self._failure if on else None, waiting=0 if step is None else len(step.waiting), @@ -471,9 +473,9 @@ def batches(self) -> Batches: label=label, title=header.title, description=header.description, - follows=label == self.manager.following, + follows=label == self.intake.following, ) - for label, header in self.manager.headers().items() + for label, header in self.intake.manager.headers().items() ] return Batches( application=self.title, @@ -484,7 +486,7 @@ def batches(self) -> Batches: def sources(self) -> list[SourceChoice]: """ What a new batch can be made with: each registered source that a spec - fits (:func:`~ess.apps.batch.fits`), then no source, which every spec + fits (:func:`~ess.apps.batch.intake.fits`), then no source, which every spec fits, each with the specs that fit it. The specs are those that the workspace binds, of the version that :meth:`~ess.apps.batch.BatchManager.create` takes. The parameters @@ -492,7 +494,7 @@ def sources(self) -> list[SourceChoice]: whose cell the page edits. """ with self.lock: - client = self.manager.client + client = self.intake.manager.client names = dict.fromkeys(spec.name for spec in client.specs()) specs = [client.spec_named(name) for name in names] listing = self._listing @@ -509,7 +511,7 @@ def choice(name: str | None, source: RowSource | None) -> SourceChoice: ], ) - given = [choice(n, s) for n, s in self.manager.sources.items()] + given = [choice(n, s) for n, s in self.intake.sources.items()] return [c for c in given if c.specs] + [choice(None, None)] def rows_of( @@ -523,19 +525,20 @@ def rows_of( The table that the source registered as ``source`` makes now, each row marked as taken, left out, or waiting, for a new batch of the :class:`~ess.apps.batch.Range` of ``first``, ``last`` and ``later`` - (:meth:`~ess.apps.batch.BatchManager.marked`). Raises + (:meth:`~ess.apps.batch.Intake.marked`). Raises :class:`~.refusals.Problem` if no source is registered so, if the range is refused, and with what the source refuses (:func:`~.refusals.refused`). """ with self.lock: with refused(): - given = self.manager.marked(source, Range(first, last, later)) - return listed(given, self.manager.sources[source].fills) + given = self.intake.marked(source, Range(first, last, later)) + return listed(given, self.intake.sources[source].fills) def create(self, new: NewBatch, file: tuple[str, bytes] | None = None) -> Made: """ - Make the batch of ``new`` with the manager, in one call + Make the batch of ``new`` in one call, with the intake if it has a + source (:meth:`~ess.apps.batch.Intake.create`), else with the manager (:meth:`~ess.apps.batch.BatchManager.create`), so that it is made as asked or not at all: with a source, of the rows of the :class:`~ess.apps.batch.Range` of ``new.first``, ``new.last`` and @@ -550,22 +553,23 @@ def create(self, new: NewBatch, file: tuple[str, bytes] | None = None) -> Made: It starts with the settings of the batch ``new.settings_from``, else with those that the application gives its spec. A setting at a column of ``new.columns`` stays, and each row with an empty cell takes it; - the manager leaves out the setting of a column that the source fills, + the intake leaves out the setting of a column that the source fills, whose cells are those of the source. - Raises :class:`~.refusals.Problem` with what the file, the manager or - the source refuses, for a label of ``settings_from`` that is no - batch, if the definitions refuse a write, and with what the source - raises otherwise (:func:`~.refusals.refused`). + Raises :class:`~.refusals.Problem` with what the file, the manager, + the intake or the source refuses, for Follow without a source, for + a label of ``settings_from`` that is no batch, if the definitions + refuse a write, and with what the source raises otherwise + (:func:`~.refusals.refused`). """ with self.lock, refused('The batch was not made'): - manager = self.manager + manager = self.intake.manager settings = None if (other := new.settings_from) is not None: if other not in manager.headers(): raise ValueError(f'there is no batch {other} to start from') settings = manager.batch(other).settings - rows = choose = source = None + rows = None if file is not None: name, content = file params = manager.spec_named(new.spec).params @@ -574,22 +578,30 @@ def create(self, new: NewBatch, file: tuple[str, bytes] | None = None) -> Made: except ValueError as error: raise ValueError(f'{name}: {error}') from None elif new.source is not None: - source = new.source - choose = Range(new.first, new.last, new.later) - label = manager.create( + batch = self.intake.create( + new.spec, + title=new.title, + description=new.description, + source=new.source, + choose=Range(new.first, new.last, new.later), + columns=new.columns, + settings=settings, + follow=new.follow, + ) + if new.follow: + self._failure = None # said of the batch that followed before + return Made(label=batch.label) + if new.follow: + raise ValueError('a batch follows its source, and none is given') + batch = manager.create( new.spec, title=new.title, description=new.description, rows=rows, - source=source, - choose=choose, columns=new.columns, settings=settings, - follow=new.follow, ) - if new.follow: - self._failure = None # said of the batch that followed before - return Made(label=label) + return Made(label=batch.label) def remove(self, label: str) -> Notice: """ @@ -603,8 +615,8 @@ def remove(self, label: str) -> Notice: """ with self.lock, kept(): self.check(label) - title = self.manager.headers()[label].title - self.manager.remove(label) + title = self.intake.manager.headers()[label].title + self.intake.manager.remove(label) self._pages.pop(label, None) return Notice(notice=f'Removed {title}.') @@ -622,7 +634,7 @@ def counts(self) -> BatchCounts: reason in ``failed``, and names no files. """ with self.lock: - manager = self.manager + manager = self.intake.manager rows: dict[str, dict[str, int]] = {} files: dict[str, list[str]] = {} failed: dict[str, str] = {} diff --git a/packages/essapps/tests/batch/auto_test.py b/packages/essapps/tests/batch/auto_test.py index 38c3734d..97c71480 100644 --- a/packages/essapps/tests/batch/auto_test.py +++ b/packages/essapps/tests/batch/auto_test.py @@ -21,6 +21,7 @@ CorrectedFiles, FileInfo, FolderDefinitions, + Intake, NotKept, RowFunction, RowSource, @@ -541,14 +542,14 @@ def test_two_loops_on_one_label_submit_a_file_once( @pytest.fixture -def following(manager: BatchManager, client: Client, sample: Measure) -> BatchManager: +def following(intake: Intake, client: Client, sample: Measure) -> Intake: """ - ``manager`` with runs 1 to 4 measured, each with its transmission run, + ``intake`` with runs 1 to 4 measured, each with its transmission run, and the batch ``a`` of the rows from run 3 on, which follows. """ for run, name in enumerate(['water', 'sds', 'dmso', 'd2o'], start=1): sample(run, name) - manager.create( + intake.create( PLAIN.name, title='A', source='pairs', @@ -556,7 +557,7 @@ def following(manager: BatchManager, client: Client, sample: Measure) -> BatchMa label='a', follow=True, ) - return manager + return intake def considered(definitions: FolderDefinitions) -> frozenset[str]: @@ -564,18 +565,18 @@ def considered(definitions: FolderDefinitions) -> frozenset[str]: def test_a_batch_made_from_a_source_considers_every_row_it_gave( - following: BatchManager, client: Client, definitions: FolderDefinitions + following: Intake, client: Client, definitions: FolderDefinitions ) -> None: following.step() client.wait(client.records(label='a')) - assert list(following.batch('a').frame().index) == ['3', '4'] + assert list(following.manager.batch('a').frame().index) == ['3', '4'] assert {r.member for r in client.records(label='a')} == {'3', '4'} assert considered(definitions) == {'1', '2', '3', '4'} def test_a_row_of_a_sample_measured_before_its_transmission_waits_then_is_added( - following: BatchManager, + following: Intake, client: Client, fake: FakeFiles, sample: Measure, @@ -590,13 +591,13 @@ def test_a_row_of_a_sample_measured_before_its_transmission_waits_then_is_added( assert isinstance(waits, Step) assert isinstance(adds, Step) assert (waits.waiting, adds.waiting) == (('5',), ()) - assert list(following.batch('a').frame().index) == ['3', '4', '5'] + assert list(following.manager.batch('a').frame().index) == ['3', '4', '5'] assert '5' in {r.member for r in client.records(label='a')} assert considered(definitions) == {'1', '2', '3', '4', '5'} -def test_a_row_that_a_person_removes_stays_away(following: BatchManager) -> None: - batch = following.batch('a') +def test_a_row_that_a_person_removes_stays_away(following: Intake) -> None: + batch = following.manager.batch('a') batch.put(batch.frame().drop('4')) following.step() @@ -605,9 +606,9 @@ def test_a_row_that_a_person_removes_stays_away(following: BatchManager) -> None def test_a_row_added_by_hand_with_a_key_the_source_gives_later_stays_away_once_removed( - following: BatchManager, sample: Measure + following: Intake, sample: Measure ) -> None: - batch = following.batch('a') + batch = following.manager.batch('a') edit(batch, '5', sample='uuid:run-1', transmission='uuid:run-1') sample(5, 'oil') following.step() # the table has 5: the step adds no row, and considers it @@ -619,7 +620,7 @@ def test_a_row_added_by_hand_with_a_key_the_source_gives_later_stays_away_once_r def test_a_row_of_a_step_cut_off_before_considered_stays_away_once_removed( - following: BatchManager, refusing: Refusing, client: Client, sample: Measure + following: Intake, refusing: Refusing, client: Client, sample: Measure ) -> None: sample(5, 'oil') refusing.part = 'source' # as a process that stops after rows.json @@ -628,7 +629,7 @@ def test_a_row_of_a_step_cut_off_before_considered_stays_away_once_removed( refusing.part = None client.wait(client.records(label='a')) following.step() # the table has 5: the step considers it - batch = following.batch('a') + batch = following.manager.batch('a') batch.put(batch.frame().drop('5')) following.step() @@ -639,14 +640,14 @@ def test_a_row_of_a_step_cut_off_before_considered_stays_away_once_removed( def test_an_error_of_a_step_is_said_also_if_considered_is_refused_after_it( client: Client, refusing: Refusing, sample: Measure ) -> None: - manager = BatchManager(Flaky(client), sources=SOURCES, definitions=refusing) - manager.create(PLAIN.name, title='A', source='pairs', label='a', follow=True) + intake = Intake(BatchManager(Flaky(client), definitions=refusing), sources=SOURCES) + intake.create(PLAIN.name, title='A', source='pairs', label='a', follow=True) sample(1, 'water') - manager.client.fail = 1 # type: ignore[attr-defined] + intake.manager.client.fail = 1 # type: ignore[attr-defined] refusing.part = 'source' with pytest.raises(ConnectionError): - manager.step() + intake.step() class _Refusing(Flaky): @@ -659,28 +660,31 @@ def submit(self, *args: Any, **kwargs: Any) -> Any: def test_a_value_error_of_a_submission_is_not_said_as_one_of_the_source( client: Client, definitions: FolderDefinitions, sample: Measure ) -> None: - manager = BatchManager(_Refusing(client), sources=SOURCES, definitions=definitions) - manager.create(PLAIN.name, title='A', source='pairs', label='a', follow=True) + manager = BatchManager(_Refusing(client), definitions=definitions) + intake = Intake(manager, sources=SOURCES) + intake.create(PLAIN.name, title='A', source='pairs', label='a', follow=True) sample(1, 'water') with pytest.raises(ValueError, match=r'^the service refused the connection$'): - manager.step() + intake.step() def test_a_row_added_by_a_step_whose_submission_raised_stays_away_once_removed( client: Client, definitions: FolderDefinitions, sample: Measure ) -> None: flaky = Flaky(client) - manager = BatchManager(flaky, sources={'pairs': PAIRS}, definitions=definitions) - from_pairs(manager, PLAIN.name, title='A', label='a', follow=True) + intake = Intake( + BatchManager(flaky, definitions=definitions), sources={'pairs': PAIRS} + ) + from_pairs(intake, PLAIN.name, title='A', label='a', follow=True) sample(1, 'water') flaky.fail = 1 with pytest.raises(ConnectionError): - manager.step() - batch = manager.batch('a') + intake.step() + batch = intake.manager.batch('a') batch.put(batch.frame().drop('1')) - manager.step() + intake.step() assert batch.frame().empty assert considered(definitions) == {'1'} @@ -690,39 +694,45 @@ def test_a_cell_of_the_source_that_the_batch_refuses_is_named_with_the_source( client: Client, definitions: FolderDefinitions, sample: Measure ) -> None: thick = RowSource(_changed(pair, **{'1': {'thickness': 'thick'}}), PAIRS.fills) - manager = BatchManager(client, sources={'pairs': thick}, definitions=definitions) - from_pairs(manager, PLAIN.name, title='A', label='a', follow=True) + intake = Intake( + BatchManager(client, definitions=definitions), sources={'pairs': thick} + ) + from_pairs(intake, PLAIN.name, title='A', label='a', follow=True) sample(1, 'water') with pytest.raises( ValueError, match=r"the source pairs: .*row '1', column 'thickness'" ): - manager.step() + intake.step() def test_a_step_after_a_restart_adds_the_rows_that_arrived_meanwhile( - following: BatchManager, + following: Intake, client: Client, definitions: FolderDefinitions, sample: Measure, ) -> None: following.step() sample(6, 'oil') - again = BatchManager(client, sources=following.sources, definitions=definitions) + again = Intake( + BatchManager(client, definitions=definitions), sources=following.sources + ) again.step() assert again.following == 'a' - assert list(again.batch('a').frame().index) == ['3', '4', '6'] + assert list(again.manager.batch('a').frame().index) == ['3', '4', '6'] def test_a_transmission_measured_again_changes_no_row( - following: BatchManager, fake: FakeFiles + following: Intake, fake: FakeFiles ) -> None: following.step() fake.measure(2003, 1.0, role='transmission', sample='dmso') following.step() - assert following.batch('a').frame().loc['3', 'transmission'] == 'uuid:run-1003' + assert ( + following.manager.batch('a').frame().loc['3', 'transmission'] == 'uuid:run-1003' + ) assert following.rows_of('pairs').loc['3', 'transmission'] == 'uuid:run-2003' diff --git a/packages/essapps/tests/batch/conftest.py b/packages/essapps/tests/batch/conftest.py index aaae7e41..7f3eaade 100644 --- a/packages/essapps/tests/batch/conftest.py +++ b/packages/essapps/tests/batch/conftest.py @@ -14,6 +14,7 @@ BatchManager, CorrectedFiles, FolderDefinitions, + Intake, ) from ess.apps.batch.table import KEY from ess.apps.folder import open_folder @@ -136,19 +137,23 @@ def refusing(definitions: FolderDefinitions) -> toys.Refusing: @pytest.fixture def manager(client: Client, refusing: toys.Refusing) -> BatchManager: """A manager on ``definitions``, through ``refusing``, which refuses nothing.""" - return BatchManager( - client, sources=toys.SOURCES, definitions=refusing, staged=toys.STAGED_NAMES - ) + return BatchManager(client, definitions=refusing, staged=toys.STAGED_NAMES) + + +@pytest.fixture +def intake(manager: BatchManager) -> Intake: + """The intake of ``manager``, with the sources of ``toys``.""" + return Intake(manager, sources=toys.SOURCES) @pytest.fixture -def label(manager: BatchManager) -> str: +def label(intake: Intake) -> str: """ - A batch of ``manager`` with the spec, columns and label of ``batch``, made - from the source ``pairs`` before a file is measured: it has no rows, and - Follow or ``manager.take`` adds those measured since. + A batch of ``intake.manager`` with the spec, columns and label of + ``batch``, made from the source ``pairs`` before a file is measured: it + has no rows, and Follow or ``intake.take`` adds those measured since. """ - return toys.from_pairs(manager, toys.STAGED.name, title='Scan', label='scan') + return toys.from_pairs(intake, toys.STAGED.name, title='Scan', label='scan') # A workspace kept in a folder of toy files, for batches from tables diff --git a/packages/essapps/tests/batch/definition_test.py b/packages/essapps/tests/batch/definition_test.py index 1c3997bb..c9c1f925 100644 --- a/packages/essapps/tests/batch/definition_test.py +++ b/packages/essapps/tests/batch/definition_test.py @@ -19,6 +19,7 @@ FileInfo, FolderDefinitions, Header, + Intake, NotKept, RowSource, ) @@ -65,20 +66,23 @@ def first_transmission(files: Sequence[FileInfo]) -> pd.DataFrame: FIRST_TRANSMISSION = RowSource(first_transmission, fills=('sample', 'transmission')) -type Opened = Callable[[], AbstractContextManager[tuple[BatchManager, CorrectedFiles]]] +type Opened = Callable[[], AbstractContextManager[tuple[Intake, CorrectedFiles]]] @pytest.fixture def opened(folder: Path, folder_bindings: list[Binding]) -> Opened: - """Opens the folder: a manager of its batches, and the file source.""" + """Opens the folder: an intake of its batches, and the file source.""" @contextmanager - def opened() -> Iterator[tuple[BatchManager, CorrectedFiles]]: + def opened() -> Iterator[tuple[Intake, CorrectedFiles]]: store = FolderDefinitions(folder) files = CorrectedFiles(folder_files(folder), definitions=store) with open_folder(folder, folder_bindings, files=files) as client: sources = {'first': FIRST_TRANSMISSION} - yield BatchManager(client, sources=sources, definitions=store), files + yield ( + Intake(BatchManager(client, definitions=store), sources=sources), + files, + ) return opened @@ -86,17 +90,17 @@ def opened() -> Iterator[tuple[BatchManager, CorrectedFiles]]: @pytest.fixture def made(opened: Opened) -> str: """A batch ``b`` of PLAIN of the rows of samples 1, 2 and 3, kept in the folder.""" - with opened() as (manager, _): - return manager.create( - PLAIN.name, title='B', rows=manager.rows_of('first'), label='b' - ) + with opened() as (intake, _): + return intake.manager.create( + PLAIN.name, title='B', rows=intake.rows_of('first'), label='b' + ).label def test_a_batch_opened_again_has_the_table_and_the_settings_it_had( opened: Opened, made: str ) -> None: - with opened() as (manager, _): - batch = manager.batch(made) + with opened() as (intake, _): + batch = intake.manager.batch(made) batch.settings = {'binning': {'bins': 3}} frame = batch.frame().drop('3').assign(thickness=[0.1 + 0.2, None]) frame.loc['mine', 'sample'] = 'run:2' @@ -104,8 +108,8 @@ def test_a_batch_opened_again_has_the_table_and_the_settings_it_had( batch.put(frame) before = batch.frame() - with opened() as (manager, _): - batch = manager.batch(made) + with opened() as (intake, _): + batch = intake.manager.batch(made) pd.testing.assert_frame_equal(batch.frame(), before) assert batch.settings == {'binning': {'bins': 3}} @@ -114,14 +118,14 @@ def test_a_batch_opened_again_has_the_table_and_the_settings_it_had( def test_a_table_kept_stays_when_its_files_go( opened: Opened, made: str, folder: Path ) -> None: - with opened() as (manager, _): - before = manager.batch(made).frame() + with opened() as (intake, _): + before = intake.manager.batch(made).frame() files = folder / 'files.csv' files.write_text(files.read_text().replace('run-1001.json,1001,transmission', '')) - with opened() as (manager, _): - pd.testing.assert_frame_equal(manager.batch(made).frame(), before) - assert manager.batch(made).state()['1'].problems != () + with opened() as (intake, _): + pd.testing.assert_frame_equal(intake.manager.batch(made).frame(), before) + assert intake.manager.batch(made).state()['1'].problems != () def test_the_corrections_of_the_files_are_there_after_a_restart( @@ -131,25 +135,25 @@ def test_the_corrections_of_the_files_are_there_after_a_restart( (bad,) = files.list(Selector(role='bad')) files.correct(bad, role='sample') - with opened() as (manager, files): + with opened() as (intake, files): assert files.corrections(bad) == {'role': 'sample'} - assert '4' in manager.rows_of('first').index + assert '4' in intake.rows_of('first').index def test_the_settings_kept_are_a_template_of_all_settings_that_the_command_reads( opened: Opened, made: str, folder: Path ) -> None: settings = {'binning': {'bins': 3}, 'thickness': 2.0} # thickness: a column - with opened() as (manager, _): - batch = manager.batch(made) + with opened() as (intake, _): + batch = intake.manager.batch(made) batch.settings = settings batch.make_column('thickness') path = FolderDefinitions(folder).path(settings_key(made)) assert load_template(path) == Template(batch.spec, params=settings) - with opened() as (manager, _): - assert manager.batch(made).settings == settings + with opened() as (intake, _): + assert intake.manager.batch(made).settings == settings @pytest.mark.parametrize( @@ -171,9 +175,9 @@ def test_rows_that_cannot_be_read_are_refused_naming_the_file_and_the_entry( ) -> None: FolderDefinitions(folder).save(rows_key(made), data) - with opened() as (manager, _): + with opened() as (intake, _): with pytest.raises(ValueError, match=rf'b/rows\.json: {re.escape(entry)}'): - manager.batch(made) + intake.manager.batch(made) def test_a_file_that_is_not_json_is_refused_naming_it( @@ -203,8 +207,8 @@ def test_settings_of_another_version_are_taken_as_they_are( kept = {'spec': {'name': 'plain', 'version': 9}, 'params': {'gone': 1}} FolderDefinitions(folder).save(settings_key(made), kept) - with opened() as (manager, _): - batch = manager.batch(made) + with opened() as (intake, _): + batch = intake.manager.batch(made) assert batch.settings == {'gone': 1} with pytest.raises(SubmitError, match='gone'): batch.state() @@ -246,9 +250,9 @@ def test_a_label_that_looks_like_a_path_keeps_its_rows_inside_the_definitions( def test_a_label_too_long_to_name_a_file_is_refused_when_the_batch_is_made( opened: Opened, folder: Path ) -> None: - with opened() as (manager, _): + with opened() as (intake, _): with pytest.raises(ValueError, match='too long to name a file'): - manager.create(PLAIN.name, title='B', label='Ã…' * 120) + intake.manager.create(PLAIN.name, title='B', label='Ã…' * 120) assert FolderDefinitions(folder).labels() == [] @@ -256,15 +260,15 @@ def test_a_label_too_long_to_name_a_file_is_refused_when_the_batch_is_made( def test_a_file_left_by_a_write_cut_off_is_not_read_and_not_removed( opened: Opened, made: str, folder: Path ) -> None: - with opened() as (manager, _): - edit(manager.batch(made), '1', thickness=2.0) + with opened() as (intake, _): + edit(intake.manager.batch(made), '1', thickness=2.0) path = FolderDefinitions(folder).path(rows_key(made)) # A reader cannot tell it from the file of a write of another process. left = path.parent / f'.{path.name}.x1y2z3' left.write_text('{"half') - with opened() as (manager, _): - assert manager.batch(made).frame().loc['1', 'thickness'] == 2.0 + with opened() as (intake, _): + assert intake.manager.batch(made).frame().loc['1', 'thickness'] == 2.0 assert left.exists() @@ -369,14 +373,14 @@ def test_a_header_that_cannot_be_read_is_refused_naming_the_file_and_the_entry( def test_the_source_of_a_batch_is_kept_with_its_keys_sorted(folder: Path) -> None: store = FolderDefinitions(folder) - made = FromSource('pairs', frozenset({'60340', '0342', '60339'}), ('sample',)) + made = FromSource('pairs', frozenset({'60340', '0342', '60339'})) key = source_key('a') store.save(key, source_data(made)) assert source_data(made)['considered'] == ['0342', '60339', '60340'] assert store.load(key, source_of) == made - store.save(key, {'source': 'pairs', 'considered': '60339', 'fills': []}) + store.save(key, {'source': 'pairs', 'considered': '60339'}) with pytest.raises(ValueError, match=r'source\.json: considered: '): store.load(key, source_of) diff --git a/packages/essapps/tests/batch/files_test.py b/packages/essapps/tests/batch/files_test.py index 502c32f8..19d491a9 100644 --- a/packages/essapps/tests/batch/files_test.py +++ b/packages/essapps/tests/batch/files_test.py @@ -18,6 +18,7 @@ CorrectedFiles, FolderDefinitions, Header, + Intake, Range, left_to_reduce, ) @@ -336,8 +337,8 @@ def test_main_refuses_earlier_settings_without_remaining( @contextmanager def app(folder: Path, label: str = 'x') -> Iterator[Batch]: """The batch of ``label`` as an application on the folder makes it.""" - with manager(folder) as batches: - yield batches.batch(label) + with intake_on(folder) as intake: + yield intake.manager.batch(label) def edit(batch: Batch, key: str, sample: str) -> None: @@ -435,9 +436,9 @@ def test_a_value_of_the_template_at_a_column_is_that_of_each_empty_cell( def test_a_template_leaves_out_a_value_at_a_column_that_the_source_fills( command: list[str], folder: Path, sources: list[str] ) -> None: - with manager(folder) as batches: - label = later(batches) - batch = batches.batch(label) + with intake_on(folder) as intake: + label = later(intake) + batch = intake.manager.batch(label) waits = pd.DataFrame({'sample': [None]}, index=pd.Index(['9'], name=KEY)) batch.put(pd.concat([batch.frame(), waits])) template = folder / 'one.yaml' @@ -448,11 +449,11 @@ def test_a_template_leaves_out_a_value_at_a_column_that_the_source_fills( main([*command, 'reduce', *sources, str(template), '-l', label]) - with manager(folder) as batches: - batch = batches.batch(label) + with intake_on(folder) as intake: + batch = intake.manager.batch(label) assert batch.settings == {'offset': {'value': 0.5}} assert batch.state()['9'].text == 'incomplete' - assert '9' not in {r.member for r in batches.client.records(label=label)} + assert '9' not in {r.member for r in intake.manager.client.records(label=label)} def test_a_table_given_with_a_source_is_refused( @@ -471,17 +472,18 @@ def test_a_table_given_with_a_source_is_refused( assert FolderDefinitions(folder).labels() == [] -# The command and the batches of a manager on one folder +# The command and the batches of an intake on one folder @contextmanager -def manager(folder: Path) -> Iterator[BatchManager]: - """The manager of an application on the folder, with the sources by name.""" +def intake_on(folder: Path) -> Iterator[Intake]: + """The intake of an application on the folder, with the sources by name.""" module = import_module('cli_toys_batch_files') definitions = FolderDefinitions(folder) files = CorrectedFiles(folder_files(folder), definitions=definitions) with open_folder(folder, module.BINDINGS, files=files) as client: - yield BatchManager(client, sources=module.SOURCES, definitions=definitions) + manager = BatchManager(client, definitions=definitions) + yield Intake(manager, sources=module.SOURCES) def test_reduce_on_a_new_label_writes_a_header_so_the_manager_lists_it( @@ -491,8 +493,8 @@ def test_reduce_on_a_new_label_writes_a_header_so_the_manager_lists_it( assert main([*command, 'reduce', *SOURCES, *reduce]) == 0 - with manager(folder) as batches: - assert batches.headers() == {'x': Header(title='x')} + with intake_on(folder) as intake: + assert intake.manager.headers() == {'x': Header(title='x')} def test_reduce_with_a_source_and_no_table_makes_a_batch_of_every_row_of_the_source( @@ -504,8 +506,8 @@ def test_reduce_with_a_source_and_no_table_makes_a_batch_of_every_row_of_the_sou assert main([*command, 'reduce', *SOURCES, *reduce]) == 0 assert list(read_text(out)['key']) == ['1', '2', '3'] - with manager(folder) as batches: - assert batches.offered('x').empty + with intake_on(folder) as intake: + assert intake.offered('x').empty def test_reduce_refuses_a_label_that_has_definitions_but_no_batch( @@ -514,9 +516,9 @@ def test_reduce_refuses_a_label_that_has_definitions_but_no_batch( folder: Path, capsys: pytest.CaptureFixture[str], ) -> None: - with manager(folder) as batches: + with intake_on(folder) as intake: old = Batch( - batches.client, + intake.manager.client, import_module('cli_toys_batch_files').SPEC, label='old', definitions=FolderDefinitions(folder), @@ -528,37 +530,37 @@ def test_reduce_refuses_a_label_that_has_definitions_but_no_batch( assert code == 2 assert 'old: the label has definitions or records' in capsys.readouterr().err - with manager(folder) as batches: - assert batches.headers() == {} - assert batches.client.records(label='old') == [] + with intake_on(folder) as intake: + assert intake.manager.headers() == {} + assert intake.manager.client.records(label='old') == [] -def later(batches: BatchManager, **options: object) -> str: +def later(intake: BatchManager, **options: object) -> str: """A batch of the samples 2 and 3 of the source, which it keeps.""" - return batches.create( + return intake.create( 'cli-toy', title='Later', source='pairs', choose=lambda given: given.loc[['2', '3']], **options, - ) + ).label def test_reduce_on_a_batch_of_the_manager_reduces_its_rows_without_its_source( command: list[str], folder: Path ) -> None: - with manager(folder) as batches: - label = later(batches) - before = batches.headers() + with intake_on(folder) as intake: + label = later(intake) + before = intake.manager.headers() out = folder / 'done.csv' code = main([*command, 'reduce', '-l', label, '-o', str(out)]) assert code == 0 assert list(read_text(out)['key']) == ['2', '3'] - with manager(folder) as batches: - assert batches.headers() == before - reduced = {r.member for r in batches.client.records(label=label)} + with intake_on(folder) as intake: + assert intake.manager.headers() == before + reduced = {r.member for r in intake.manager.client.records(label=label)} assert reduced == {'2', '3'} @@ -715,9 +717,9 @@ def kept(folder: Path, label: str) -> dict[str, str]: def test_a_refused_reduce_changes_neither_the_settings_nor_the_rows_of_a_batch( command: list[str], folder: Path, table: str ) -> None: - with manager(folder) as batches: - label = later(batches, settings={'offset': {'value': 0.5}}) - edit(batches.batch(label), '2', 'run:3') + with intake_on(folder) as intake: + label = later(intake, settings={'offset': {'value': 0.5}}) + edit(intake.manager.batch(label), '2', 'run:3') before = kept(folder, label) template = folder / 'other.yaml' template.write_text( @@ -736,10 +738,10 @@ def test_a_refused_reduce_changes_neither_the_settings_nor_the_rows_of_a_batch( def test_reduce_on_a_batch_without_rows_writes_a_table_of_its_columns( command: list[str], folder: Path ) -> None: - with manager(folder) as batches: - label = batches.create( + with intake_on(folder) as intake: + label = intake.create( 'cli-toy', title='None', source='pairs', choose=Range(later=True) - ) + ).label out = folder / 'done.csv' code = main([*command, 'reduce', '-l', label, '-o', str(out)]) @@ -759,8 +761,8 @@ def test_reduce_on_a_batch_without_rows_writes_a_table_of_its_columns( def test_a_template_without_a_table_is_the_settings_of_a_batch_that_keeps_its_rows( command: list[str], folder: Path ) -> None: - with manager(folder) as batches: - label = later(batches) + with intake_on(folder) as intake: + label = later(intake) template = folder / 'offset.yaml' template.write_text( 'spec: {name: cli-toy, version: 1}\nblanks: [sample]\n' @@ -771,8 +773,8 @@ def test_a_template_without_a_table_is_the_settings_of_a_batch_that_keeps_its_ro assert main([*command, 'reduce', str(template), '-l', label, '-o', str(out)]) == 0 assert list(read_text(out)['key']) == ['2', '3'] - with manager(folder) as batches: - assert batches.batch(label).settings == {'offset': {'value': 0.5}} + with intake_on(folder) as intake: + assert intake.manager.batch(label).settings == {'offset': {'value': 0.5}} def test_reduce_with_staged_runs_the_rows_of_its_batch_through_a_stage( diff --git a/packages/essapps/tests/batch/intake_test.py b/packages/essapps/tests/batch/intake_test.py new file mode 100644 index 00000000..61e747cd --- /dev/null +++ b/packages/essapps/tests/batch/intake_test.py @@ -0,0 +1,549 @@ +# SPDX-License-Identifier: BSD-3-Clause +# Copyright (c) 2026 Scipp contributors (https://github.com/scipp) +"""Rows of a row source brought into batches by an intake, and Follow.""" + +from collections.abc import Callable +from typing import Any + +import pandas as pd +import pytest + +from ess.apps import Client +from ess.apps.batch import BatchManager, FolderDefinitions, Intake, NotKept, Range +from ess.apps.batch.definition import ( + FOLLOWING, + Key, + header_key, + settings_key, + source_key, + source_of, +) +from ess.apps.testing import FakeFiles + +from .toys import PLAIN, SAMPLES, SOURCES, Measure, Refusing, edit, from_pairs + + +def _again(client: Client, definitions: FolderDefinitions) -> Intake: + """ + The intake of the fixture made again on ``definitions``, with a manager + made again, as after a restart. + """ + return Intake(BatchManager(client, definitions=definitions), sources=SOURCES) + + +@pytest.fixture +def made(intake: Intake, sample: Measure) -> Intake: + """ + ``intake`` with runs 1 to 4 measured, run 5 without its transmission + run, and the batch ``a`` of the rows from run 3 on, and a row ``mine`` + added by hand. + """ + for run, name in enumerate(['water', 'sds', 'dmso', 'd2o'], start=1): + sample(run, name) + sample(5, 'oil', partner=False) + batch = intake.create( + PLAIN.name, + title='A', + source='pairs', + choose=lambda given: given[given.run >= 3], + label='a', + ) + edit(batch, 'mine', sample='run:1') + return intake + + +def test_a_batch_made_from_a_source_takes_and_considers_its_filled_rows( + made: Intake, definitions: FolderDefinitions +) -> None: + kept = definitions.load(source_key('a'), source_of) + + assert list(made.manager.batch('a').frame().index) == ['3', '4', 'mine'] + assert made.source('a') == 'pairs' + assert kept.considered == {'1', '2', '3', '4'} # not 5, which waits + + +def test_a_batch_made_from_a_source_keeps_its_fills_when_read_again( + intake: Intake, client: Client, definitions: FolderDefinitions +) -> None: + from_pairs(intake, 'plain', title='A', label='a') + + again = BatchManager(client, definitions=definitions).batch('a') + + assert again.fills == {'sample', 'transmission'} + + +def test_a_source_json_with_fills_is_refused_when_read( + intake: Intake, client: Client, definitions: FolderDefinitions +) -> None: + from_pairs(intake, 'plain', title='A', label='a') + kept = definitions.load(source_key('a'), dict) + definitions.save(source_key('a'), {**kept, 'fills': ['sample']}) + + with pytest.raises(ValueError, match=r'source\.json: fills: Unexpected'): + _again(client, definitions).source('a') + + +def test_choose_may_give_columns_that_the_source_does_not( + intake: Intake, sample: Measure +) -> None: + sample(1, 'water') + + batch = intake.create( + PLAIN.name, + title='A', + source='pairs', + choose=lambda given: given.assign(thickness=2.0), + ) + + assert batch.frame()['thickness'].tolist() == [2.0] + + +def test_columns_given_are_empty_and_a_column_of_the_table_keeps_its_cells( + intake: Intake, sample: Measure +) -> None: + sample(1, 'water') + + batch = intake.create( + PLAIN.name, title='A', source='pairs', columns=['sample', 'thickness'] + ) + + frame = batch.frame() + assert frame['sample'].tolist() == ['uuid:run-1'] + assert frame['thickness'].isna().tolist() == [True] + + +@pytest.fixture +def four(intake: Intake, sample: Measure) -> Intake: + """``intake`` with runs 1, 2 and 4 measured, and run 3 without its partner.""" + for run, name in [(1, 'water'), (2, 'sds'), (4, 'ethanol')]: + sample(run, name) + sample(3, 'oil', partner=False) + return intake + + +@pytest.mark.parametrize( + ('chosen', 'taken'), + [ + (Range(first='2'), ['2', '4']), + (Range(last='2'), ['1', '2']), + (Range('2', '2'), ['2']), + (Range(later=True), []), + ], + ids=['from', 'to', 'one', 'later'], +) +def test_a_range_takes_the_filled_rows_between_its_ends_and_considers_all( + four: Intake, + definitions: FolderDefinitions, + chosen: Range, + taken: list[str], +) -> None: + batch = four.create(PLAIN.name, title='A', source='pairs', choose=chosen) + + assert list(batch.frame().index) == taken + considered = definitions.load(source_key(batch.label), source_of).considered + assert considered == {'1', '2', '4'} # not 3, which waits + + +@pytest.mark.parametrize( + ('chosen', 'said'), + [ + (Range(first='3'), '3 is not a filled row'), + (Range('2', '1'), 'the row 2 comes after the row 1'), + ], + ids=['waits', 'reversed'], +) +def test_a_range_that_takes_no_row_of_its_ends_is_refused_and_nothing_is_kept( + four: Intake, definitions: FolderDefinitions, chosen: Range, said: str +) -> None: + with pytest.raises(ValueError, match=f'^{said}$'): + four.create(PLAIN.name, title='A', source='pairs', choose=chosen) + + assert (four.manager.headers(), definitions.labels()) == ({}, []) + + +def test_a_range_of_the_rows_that_arrive_later_has_no_end() -> None: + with pytest.raises(ValueError, match='arrive later has no first or last'): + Range(first='1', later=True) + + +def test_a_batch_of_the_rows_that_arrive_later_that_follows_gets_only_those( + four: Intake, fake: FakeFiles, sample: Measure +) -> None: + batch = four.create( + 'plain', title='A', source='pairs', choose=Range(later=True), follow=True + ) + sample(5, 'dmso') + fake.measure(1003, 1.0, role='transmission', sample='oil') # 3 waited + + four.step() + + assert list(batch.frame().index) == ['3', '5'] + + +def test_a_row_that_waits_when_a_batch_is_made_is_added_by_follow_once_filled( + intake: Intake, fake: FakeFiles, sample: Measure +) -> None: + sample(1, 'water') + sample(2, 'oil', partner=False) + batch = intake.create('plain', title='A', source='pairs', follow=True) + fake.measure(1002, 1.0, role='transmission', sample='oil') + + intake.step() + + assert list(batch.frame().index) == ['1', '2'] + + +def test_a_batch_made_without_a_source_has_none(intake: Intake) -> None: + intake.manager.create('plain', title='A', label='a') + + assert intake.source('a') is None + + +def test_a_source_that_is_not_registered_is_refused( + intake: Intake, definitions: FolderDefinitions +) -> None: + with pytest.raises(ValueError, match='the source runs is not registered'): + intake.create('plain', title='Morning', source='runs') + with pytest.raises(ValueError, match='the source runs is not registered'): + intake.rows_of('runs') + assert definitions.labels() == [] + + +def test_a_row_chosen_that_the_source_does_not_give_is_refused_and_nothing_is_kept( + intake: Intake, definitions: FolderDefinitions, sample: Measure +) -> None: + sample(1, 'water') + + def choose(given: pd.DataFrame) -> pd.DataFrame: + return given.rename({'1': '9'}) + + with pytest.raises(ValueError, match=r"choose gives rows \['9'\] that the"): + intake.create('plain', title='A', source='pairs', choose=choose) + assert intake.manager.headers() == {} + assert definitions.labels() == [] + + +@pytest.mark.parametrize( + 'call', + [ + lambda i: i.source('b'), + lambda i: i.offered('b'), + lambda i: i.take('b', []), + ], + ids=['source', 'offered', 'take'], +) +def test_a_label_that_is_no_batch_is_refused( + intake: Intake, call: Callable[[Intake], Any] +) -> None: + with pytest.raises(KeyError): + call(intake) + + +def test_the_rows_offered_are_those_of_the_source_that_the_table_lacks( + made: Intake, +) -> None: + batch = made.manager.batch('a') + batch.put(batch.frame().drop('4')) + + offered = made.offered('a') + + assert offered['waits'].to_dict() == { + '1': False, + '2': False, + '4': False, + '5': True, + } + assert list(offered.columns) == [*made.rows_of('pairs').columns, 'waits'] + + +def test_a_row_of_the_source_that_waits_is_offered_as_waiting( + intake: Intake, sample: Measure +) -> None: + sample(1, 'water') + intake.create('plain', title='A', source='pairs', label='a') + sample(2, 'oil', partner=False) + + assert intake.offered('a')['waits'].to_dict() == {'2': True} + + +def test_rows_taken_are_put_as_the_source_makes_them_and_considered( + intake: Intake, + fake: FakeFiles, + sample: Measure, + definitions: FolderDefinitions, +) -> None: + sample(1, 'water') + batch = intake.create('plain', title='A', source='pairs', label='a', follow=True) + sample(2, 'oil', partner=False) + + intake.take('a', ['2']) + taken = batch.frame().loc['2'] + batch.put(batch.frame().drop('2')) + fake.measure(1002, 1.0, role='transmission', sample='oil') + intake.step() + + assert taken['sample'] == 'uuid:run-2' + assert pd.isna(taken['transmission']) + assert list(batch.frame().index) == ['1'] + assert definitions.load(source_key('a'), source_of).considered == {'1', '2'} + + +@pytest.mark.parametrize('added_by', ['step', 'take']) +def test_a_row_added_after_make_column_takes_the_setting( + intake: Intake, client: Client, sample: Measure, added_by: str +) -> None: + sample(1, 'water') + settings = {'thickness': 2.0} + batch = intake.create( + 'plain', title='A', source='pairs', label='a', settings=settings, follow=True + ) + client.wait(batch.reduce(['1'])) + batch.make_column('thickness') + sample(2, 'oil') + + if added_by == 'step': + client.wait(list(intake.step().records.values())) + else: + intake.take('a', ['2']) + client.wait(batch.reduce(['2'])) + + assert pd.isna(batch.frame().loc['2', 'thickness']) + assert batch.state()['2'].record.request.params['thickness'] == 2.0 + assert batch.state()['1'].text == 'done' + + +def test_a_waiting_row_taken_or_stepped_waits_whatever_the_settings_kept( + intake: Intake, + client: Client, + sample: Measure, + definitions: FolderDefinitions, +) -> None: + sample(1, 'water') + from_pairs(intake, 'plain', title='A', label='a', follow=True) + sample(2, 'oil', partner=False) + kept = definitions.load(settings_key('a'), dict) + stale = {**kept['params'], 'transmission': 'run:1001'} + definitions.save(settings_key('a'), {**kept, 'params': stale}) + again = _again(client, definitions) # as after a restart + + again.take('a', ['2']) + done = again.step() + state = again.manager.batch('a').state()['2'] + + assert again.manager.batch('a').state()['1'].text != 'incomplete' + assert done is not None + assert '2' not in done.records + assert [(e.loc, e.msg) for e in state.problems] == [(('transmission',), 'empty')] + + +def test_a_source_that_no_longer_gives_a_column_of_the_fills_kept_is_named( + intake: Intake, client: Client, definitions: FolderDefinitions +) -> None: + from_pairs(intake, 'plain', title='A', label='a', follow=True) + sources = {'pairs': SAMPLES} # its code now fills sample only + again = Intake(BatchManager(client, definitions=definitions), sources=sources) + said = 'the source pairs: it no longer gives the column transmission' + + with pytest.raises(ValueError, match=said): + again.offered('a') + with pytest.raises(ValueError, match=said): + again.step() + + +def test_a_step_whose_source_is_not_registered_is_refused_and_keeps_nothing( + client: Client, sample: Measure, definitions: FolderDefinitions +) -> None: + sample(1, 'water') + sources = dict(SOURCES) + intake = Intake(BatchManager(client, definitions=definitions), sources=sources) + batch = intake.create('plain', title='A', source='pairs', label='a', follow=True) + typed = batch.frame().rename(index={'1': 'typed'}) + batch.put(pd.concat([batch.frame(), typed])) + del sources['pairs'] + + with pytest.raises(ValueError, match='the source pairs is not registered'): + intake.step() + + # A key typed by hand is considered only by a step that reads the source. + assert definitions.load(source_key('a'), source_of).considered == {'1'} + + +@pytest.mark.parametrize( + ('keys', 'said'), + [ + (['9'], r"makes no rows \['9'\]"), + (['3'], r"rows \['3'\] are in the batch already"), + ], +) +def test_rows_that_cannot_be_taken_are_refused_and_nothing_changes( + made: Intake, keys: list[str], said: str +) -> None: + before = made.manager.batch('a').frame() + + with pytest.raises(ValueError, match=said): + made.take('a', keys) + + pd.testing.assert_frame_equal(made.manager.batch('a').frame(), before) + + +def test_a_batch_made_without_a_source_offers_and_takes_no_rows( + intake: Intake, +) -> None: + intake.manager.create('plain', title='A', label='a') + + with pytest.raises(ValueError, match='a was not made from a source'): + intake.offered('a') + with pytest.raises(ValueError, match='a was not made from a source'): + intake.take('a', ['1']) + + +class _SourceRefused(Refusing): + """:class:`Refusing` that refuses to save ``source.json`` only.""" + + def save(self, key: Key, data: Any) -> None: + if key[-1] == 'source': + raise NotKept(f'{key}: refused') + super().save(key, data) + + +def test_a_batch_whose_source_is_refused_is_removed_again( + client: Client, definitions: FolderDefinitions, sample: Measure +) -> None: + sample(1, 'water') + refusing = _SourceRefused(definitions) + intake = Intake(BatchManager(client, definitions=refusing), sources=SOURCES) + + with pytest.raises(NotKept): + intake.create('plain', title='A', source='pairs', label='a', follow=True) + + assert intake.manager.headers() == {} + assert definitions.labels() == [] + assert intake.following is None + + +def test_the_source_of_a_batch_is_written_after_its_header_and_following_last( + intake: Intake, refusing: Refusing +) -> None: + intake.create('plain', title='A', source='pairs', label='b', follow=True) + + assert refusing.saved[-3:] == [header_key('b'), source_key('b'), FOLLOWING] + + +# Which batch follows + + +@pytest.fixture +def two(intake: Intake) -> Intake: + """ + ``intake`` with two batches of a source: ``a``, which follows, and ``b``, + made without Follow. + """ + intake.create('plain', title='A', source='pairs', label='a', follow=True) + intake.create('plain', title='B', source='pairs', label='b') + return intake + + +def test_a_batch_made_to_follow_follows_in_place_of_the_one_before( + two: Intake, client: Client, definitions: FolderDefinitions +) -> None: + assert two.following == 'a' # b was made without Follow + + two.create('plain', title='C', source='pairs', label='c', follow=True) + + assert two.following == 'c' + assert _again(client, definitions).following == 'c' + + +def test_a_batch_that_follows_with_a_last_row_is_refused_and_nothing_changes( + two: Intake, definitions: FolderDefinitions, sample: Measure +) -> None: + sample(1, 'water') + + with pytest.raises(ValueError, match='so it has no last row'): + two.create( + 'plain', + title='C', + source='pairs', + choose=Range(last='1'), + label='c', + follow=True, + ) + + assert (list(two.manager.headers()), two.following) == (['a', 'b'], 'a') + assert 'c' not in definitions.labels() + + +def test_after_a_stop_no_batch_follows_and_an_intake_made_again_has_none( + two: Intake, client: Client, definitions: FolderDefinitions +) -> None: + two.stop() + + assert two.following is None + assert two.step() is None + assert _again(client, definitions).following is None + version = two.version + two.stop() # none follows: nothing is done + assert two.version == version + + +def test_a_stopped_batch_gets_no_rows_at_a_step( + intake: Intake, sample: Measure +) -> None: + sample(1, 'water') + batch = intake.create('plain', title='A', source='pairs', label='a', follow=True) + intake.stop() + sample(2, 'oil') + + intake.step() + + assert list(batch.frame().index) == ['1'] + assert intake.offered('a')['waits'].to_dict() == {'2': False} + + +def test_a_batch_removed_through_the_manager_follows_no_longer( + two: Intake, client: Client, definitions: FolderDefinitions +) -> None: + two.manager.remove('a') + + assert two.following is None + assert two.step() is None + assert _again(client, definitions).following is None + + +def test_a_kept_label_without_a_header_follows_not( + two: Intake, client: Client, definitions: FolderDefinitions +) -> None: + definitions.delete(('labels', 'a', 'header')) + + assert _again(client, definitions).following is None + + +def test_which_batch_follows_stays_if_the_definitions_refuse_a_change( + two: Intake, refusing: Refusing +) -> None: + refusing.part = 'following' + + with pytest.raises(NotKept): + two.create('plain', title='C', source='pairs', label='c', follow=True) + with pytest.raises(NotKept): + two.stop() + assert (list(two.manager.headers()), two.following) == (['a', 'b'], 'a') + assert 'c' not in refusing.labels() + + +@pytest.mark.parametrize( + 'change', + [ + lambda i: i.create('plain', title='C', source='pairs', follow=True), + lambda i: i.stop(), + ], + ids=['create', 'stop'], +) +def test_the_version_moves_at_each_change_of_which_follows( + two: Intake, change: Callable[[Intake], object] +) -> None: + before = two.version + + change(two) + + assert two.version != before diff --git a/packages/essapps/tests/batch/manager_test.py b/packages/essapps/tests/batch/manager_test.py index 29b3b16e..8893bf9e 100644 --- a/packages/essapps/tests/batch/manager_test.py +++ b/packages/essapps/tests/batch/manager_test.py @@ -19,24 +19,22 @@ CorrectedFiles, FolderDefinitions, Header, + Intake, NotKept, - Range, ) from ess.apps.batch.definition import ( - FOLLOWING, Key, header_key, + rows_key, settings_key, - source_key, - source_of, + template_of, ) -from ess.apps.testing import FakeFiles, FakeStore, StagedFunction +from ess.apps.testing import FakeStore, StagedFunction from ess.spec import function_binding from .toys import ( COLUMNS, PLAIN, - SAMPLES, SOURCES, STAGED, STAGED_NAMES, @@ -50,20 +48,18 @@ def _again(client: Client, definitions: FolderDefinitions) -> BatchManager: """The manager of the fixture made again on ``definitions``, as after a restart.""" - return BatchManager( - client, sources=SOURCES, definitions=definitions, staged=STAGED_NAMES - ) + return BatchManager(client, definitions=definitions, staged=STAGED_NAMES) def test_a_batch_made_is_listed_with_its_header( manager: BatchManager, client: Client, definitions: FolderDefinitions ) -> None: - label = manager.create( + batch = manager.create( 'plain', title='Morning', rows=rows(client), description='2 mm cells', label='b' ) header = Header('Morning', '2 mm cells') - assert label == 'b' + assert batch.label == 'b' assert manager.headers() == {'b': header} assert _again(client, definitions).headers() == {'b': header} @@ -75,13 +71,12 @@ def test_a_manager_made_again_on_the_definitions_hands_out_the_batch_as_it_was( sample: Measure, ) -> None: sample(1, 'water') - label = manager.create('staged', title='Morning', rows=rows(client), label='b') - batch = manager.batch(label) + batch = manager.create('staged', title='Morning', rows=rows(client), label='b') batch.settings = {'binning': {'bins': 3}, 'thickness': 3.0} # thickness: a column edit(batch, '1', thickness=2.0) edit(batch, 'mine', sample='run:1') - again = _again(client, definitions).batch(label) + again = _again(client, definitions).batch(batch.label) assert again.spec == STAGED assert again.parameter_columns == COLUMNS @@ -97,12 +92,8 @@ def test_the_columns_of_a_batch_are_the_parameter_columns_of_its_rows( chosen = manager.create('plain', title='Evening', rows=given) empty = manager.create('plain', title='Morning') - assert manager.batch(chosen).parameter_columns == ( - 'thickness', - 'transmission', - 'sample', - ) - assert manager.batch(empty).parameter_columns == () + assert chosen.parameter_columns == ('thickness', 'transmission', 'sample') + assert empty.parameter_columns == () @pytest.mark.parametrize( @@ -145,20 +136,14 @@ def test_a_batch_whose_spec_is_no_longer_bound_is_refused( def with_defaults(client: Client, definitions: FolderDefinitions) -> BatchManager: """A manager that registers settings for the spec ``plain``.""" settings = {'thickness': 2.0, 'binning': {'bins': 3}} - return BatchManager( - client, - sources=SOURCES, - definitions=definitions, - settings={'plain': settings}, - ) + return BatchManager(client, definitions=definitions, settings={'plain': settings}) def test_a_batch_starts_with_the_settings_registered_for_its_spec( with_defaults: BatchManager, client: Client, sample: Measure ) -> None: sample(1, 'water') - label = with_defaults.create('plain', title='Morning', rows=rows(client)) - batch = with_defaults.batch(label) + batch = with_defaults.create('plain', title='Morning', rows=rows(client)) assert batch.settings == {'thickness': 2.0, 'binning': {'bins': 3}} assert batch.cells()['1']['thickness'] == 2.0 # the column's empty cell @@ -168,34 +153,64 @@ def test_settings_given_to_create_replace_those_registered( with_defaults: BatchManager, client: Client ) -> None: settings = {'thickness': 3.0, 'offset': {'value': 1.0}} - label = with_defaults.create( + batch = with_defaults.create( 'plain', title='Morning', rows=rows(client), settings=settings ) - assert with_defaults.batch(label).settings == settings + assert batch.settings == settings -def test_a_batch_made_from_a_source_has_no_setting_at_a_column_that_it_fills( - with_defaults: BatchManager, sample: Measure +def test_a_batch_has_no_setting_at_a_column_of_its_fills( + with_defaults: BatchManager, client: Client, sample: Measure ) -> None: sample(1, 'water') settings = {'thickness': 3.0, 'transmission': 'run:1001'} - label = from_pairs(with_defaults, 'plain', title='Morning', settings=settings) + fills = ('sample', 'transmission') + batch = with_defaults.create( + 'plain', title='Morning', rows=rows(client), fills=fills, settings=settings + ) + + assert batch.settings == {'thickness': 3.0} + + +def test_the_fills_of_a_batch_are_kept_as_the_blanks_of_its_settings( + manager: BatchManager, + client: Client, + definitions: FolderDefinitions, + sample: Measure, +) -> None: + sample(1, 'water') + fills = ('transmission', 'sample') + manager.create('plain', title='Morning', rows=rows(client), fills=fills, label='b') + + kept = definitions.load(settings_key('b'), template_of) - assert with_defaults.batch(label).settings == {'thickness': 3.0} + assert kept.blanks == ('sample', 'transmission') + assert _again(client, definitions).batch('b').fills == {'sample', 'transmission'} + + +def test_a_table_without_a_column_of_its_fills_is_refused_and_nothing_is_kept( + manager: BatchManager, client: Client, definitions: FolderDefinitions +) -> None: + table = rows(client).drop(columns='transmission') + + with pytest.raises(ValueError, match='fills transmission: a row waits'): + manager.create('plain', title='M', rows=table, fills=['transmission']) + assert definitions.labels() == [] def test_settings_registered_later_leave_the_settings_of_a_batch_made_before( with_defaults: BatchManager, client: Client, definitions: FolderDefinitions ) -> None: - label = with_defaults.create('plain', title='Morning', rows=rows(client)) + batch = with_defaults.create('plain', title='Morning', rows=rows(client)) later = {'plain': {'binning': {'bins': 7}}} - again = BatchManager( - client, sources=SOURCES, definitions=definitions, settings=later - ) + again = BatchManager(client, definitions=definitions, settings=later) - assert again.batch(label).settings == {'thickness': 2.0, 'binning': {'bins': 3}} + assert again.batch(batch.label).settings == { + 'thickness': 2.0, + 'binning': {'bins': 3}, + } def test_a_batch_is_of_the_highest_version_of_its_spec_that_the_workspace_binds( @@ -208,11 +223,11 @@ def test_a_batch_is_of_the_highest_version_of_its_spec_that_the_workspace_binds( workspace = Workspace(proposal='p1', files=files, bind=bind, store=FakeStore()) with closing(workspace): client = Client(workspace, submitter='anna') - manager = BatchManager(client, sources=SOURCES, definitions=definitions) + manager = BatchManager(client, definitions=definitions) - label = manager.create('plain', title='Morning') + batch = manager.create('plain', title='Morning') - assert manager.batch(label).spec == newer + assert batch.spec == newer def _with_definitions(client: Client, definitions: FolderDefinitions) -> None: @@ -250,16 +265,6 @@ def test_a_label_with_a_slash_or_a_leading_dot_is_refused( assert manager.headers() == {} -def test_a_source_that_is_not_registered_is_refused( - manager: BatchManager, definitions: FolderDefinitions -) -> None: - with pytest.raises(ValueError, match='the source runs is not registered'): - manager.create('plain', title='Morning', source='runs') - with pytest.raises(ValueError, match='the source runs is not registered'): - manager.rows_of('runs') - assert definitions.labels() == [] - - def test_a_spec_that_the_workspace_does_not_bind_is_refused( manager: BatchManager, ) -> None: @@ -271,8 +276,8 @@ def test_a_spec_that_the_workspace_does_not_bind_is_refused( def test_generated_labels_are_the_time_of_making_and_differ( manager: BatchManager, ) -> None: - first = manager.create('plain', title='Morning') - second = manager.create('plain', title='Afternoon') + first = manager.create('plain', title='Morning').label + second = manager.create('plain', title='Afternoon').label assert re.fullmatch(r'\d{8}-\d{6}', first) # made in the same second, or in the next @@ -282,9 +287,9 @@ def test_generated_labels_are_the_time_of_making_and_differ( def test_the_batch_of_a_label_is_one_object(manager: BatchManager) -> None: - label = manager.create('plain', title='Morning', source='pairs') + batch = manager.create('plain', title='Morning') - assert manager.batch(label) is manager.batch(label) + assert manager.batch(batch.label) is batch @pytest.mark.parametrize( @@ -293,10 +298,8 @@ def test_the_batch_of_a_label_is_one_object(manager: BatchManager) -> None: lambda m: m.batch('b'), lambda m: m.change('b', title='Afternoon'), lambda m: m.remove('b'), - lambda m: m.offered('b'), - lambda m: m.take('b', []), ], - ids=['batch', 'change', 'remove', 'offered', 'take'], + ids=['batch', 'change', 'remove'], ) def test_a_label_that_is_no_batch_is_refused( manager: BatchManager, call: Callable[[BatchManager], Any] @@ -308,7 +311,7 @@ def test_a_label_that_is_no_batch_is_refused( def test_a_title_and_description_changed_are_kept( manager: BatchManager, client: Client, definitions: FolderDefinitions ) -> None: - label = manager.create('plain', title='Morning', description='a') + label = manager.create('plain', title='Morning', description='a').label manager.change(label, title='Afternoon') manager.change(label, description='1 mm cells\n2 mm cells') @@ -319,13 +322,14 @@ def test_a_title_and_description_changed_are_kept( def test_a_batch_removed_is_gone_with_its_definitions_and_its_records_stay( - manager: BatchManager, + intake: Intake, client: Client, definitions: FolderDefinitions, sample: Measure, ) -> None: + manager = intake.manager sample(1, 'water') - label = from_pairs(manager, 'plain', title='Morning') + label = from_pairs(intake, 'plain', title='Morning') # source.json too batch = manager.batch(label) edit(batch, '1', thickness=2.0) client.wait(batch.reduce(['1'])) @@ -360,38 +364,38 @@ def test_a_staged_batch_removed_releases_its_stage( releases = Releases(client) manager = BatchManager( releases, # type: ignore[arg-type] - sources=SOURCES, definitions=definitions, staged=STAGED_NAMES, ) sample(1, 'water') - label = manager.create('staged', title='Morning', rows=rows(client)) - client.wait(manager.batch(label).reduce(['1'])) + batch = manager.create('staged', title='Morning', rows=rows(client)) + client.wait(batch.reduce(['1'])) - manager.remove(label) + manager.remove(batch.label) assert [type(s) for s in releases.released] == [Stage] def test_a_batch_whose_header_is_refused_is_not_made( - manager: BatchManager, refusing: Refusing + manager: BatchManager, client: Client, refusing: Refusing ) -> None: refusing.part = 'header' with pytest.raises(NotKept): - manager.create('plain', title='Morning', source='pairs', label='b') + manager.create('plain', title='Morning', rows=rows(client), label='b') assert manager.headers() == {} assert refusing.labels() == [] refusing.part = None - assert manager.create('plain', title='Morning', label='c') == 'c' + assert manager.create('plain', title='Morning', label='c').label == 'c' -def test_the_header_of_a_batch_is_written_after_its_tables_and_following_last( - manager: BatchManager, refusing: Refusing +def test_the_header_of_a_batch_is_written_after_its_tables( + manager: BatchManager, client: Client, refusing: Refusing, sample: Measure ) -> None: - manager.create('plain', title='Morning', source='pairs', label='b', follow=True) + sample(1, 'water') + manager.create('plain', title='Morning', rows=rows(client), label='b') - assert refusing.saved[-2:] == [header_key('b'), FOLLOWING] + assert refusing.saved == [rows_key('b'), settings_key('b'), header_key('b')] def test_a_setting_keeps_its_value_if_the_table_that_makes_it_a_column_is_refused( @@ -403,14 +407,13 @@ def test_a_setting_keeps_its_value_if_the_table_that_makes_it_a_column_is_refuse ) -> None: sample(1, 'water') table = rows(client).drop(columns='thickness') - label = manager.create('plain', title='M', rows=table, settings={'thickness': 2.0}) - batch = manager.batch(label) + batch = manager.create('plain', title='M', rows=table, settings={'thickness': 2.0}) refusing.part = 'rows' with pytest.raises(NotKept): batch.put(batch.frame().assign(thickness=3.0)) - assert _again(client, definitions).batch(label).settings == {'thickness': 2.0} + assert _again(client, definitions).batch(batch.label).settings == {'thickness': 2.0} def test_rows_reduced_are_not_outdated_in_a_manager_made_again( @@ -420,13 +423,12 @@ def test_rows_reduced_are_not_outdated_in_a_manager_made_again( sample: Measure, ) -> None: sample(1, 'water') - label = manager.create('plain', title='Morning', rows=rows(client)) - batch = manager.batch(label) + batch = manager.create('plain', title='Morning', rows=rows(client)) batch.settings = {'binning': {'bins': 3}} edit(batch, '1', thickness=1 / 3) client.wait(list(batch.reduce(['1']).values())) - state = _again(client, definitions).batch(label).state()['1'] + state = _again(client, definitions).batch(batch.label).state()['1'] assert (state.text, state.outdated) == ('done', False) @@ -438,7 +440,7 @@ def test_an_empty_or_blank_title_is_refused( with pytest.raises(ValueError, match='a title that is not empty'): manager.create('plain', title=title) assert definitions.labels() == [] - label = manager.create('plain', title='Morning') + label = manager.create('plain', title='Morning').label with pytest.raises(ValueError, match='a title that is not empty'): manager.change(label, title=title) @@ -448,8 +450,7 @@ def test_an_empty_or_blank_title_is_refused( def test_a_batch_whose_removal_is_refused_is_kept( manager: BatchManager, refusing: Refusing ) -> None: - manager.create('plain', title='Morning', label='b') - batch = manager.batch('b') + batch = manager.create('plain', title='Morning', label='b') refusing.part = 'header' with pytest.raises(NotKept): @@ -461,508 +462,13 @@ def test_a_batch_whose_removal_is_refused_is_kept( def test_a_batch_made_without_rows_takes_the_rows_put( manager: BatchManager, client: Client, definitions: FolderDefinitions ) -> None: - label = manager.create('plain', title='Morning') - batch = manager.batch(label) + batch = manager.create('plain', title='Morning') assert batch.frame().empty batch.put(pd.DataFrame({'sample': ['run:2']}, index=['mine'])) - assert list(_again(client, definitions).batch(label).frame().index) == ['mine'] - - -# A batch made from a source - - -@pytest.fixture -def made(manager: BatchManager, sample: Measure) -> BatchManager: - """ - ``manager`` with runs 1 to 4 measured, run 5 without its transmission - run, and the batch ``a`` of the rows from run 3 on, and a row ``mine`` - added by hand. - """ - for run, name in enumerate(['water', 'sds', 'dmso', 'd2o'], start=1): - sample(run, name) - sample(5, 'oil', partner=False) - manager.create( - PLAIN.name, - title='A', - source='pairs', - choose=lambda given: given[given.run >= 3], - label='a', - ) - edit(manager.batch('a'), 'mine', sample='run:1') - return manager - - -def test_a_batch_made_from_a_source_takes_and_considers_its_filled_rows( - made: BatchManager, definitions: FolderDefinitions -) -> None: - kept = definitions.load(source_key('a'), source_of) - - assert list(made.batch('a').frame().index) == ['3', '4', 'mine'] - assert made.source('a') == 'pairs' - assert kept.considered == {'1', '2', '3', '4'} # not 5, which waits - - -def test_choose_may_give_columns_that_the_source_does_not( - manager: BatchManager, sample: Measure -) -> None: - sample(1, 'water') - - label = manager.create( - PLAIN.name, - title='A', - source='pairs', - choose=lambda given: given.assign(thickness=2.0), - ) - - assert manager.batch(label).frame()['thickness'].tolist() == [2.0] - - -def test_columns_given_are_empty_and_a_column_of_the_table_keeps_its_cells( - manager: BatchManager, sample: Measure -) -> None: - sample(1, 'water') - - label = manager.create( - PLAIN.name, title='A', source='pairs', columns=['sample', 'thickness'] - ) - - frame = manager.batch(label).frame() - assert frame['sample'].tolist() == ['uuid:run-1'] - assert frame['thickness'].isna().tolist() == [True] - - -@pytest.fixture -def four(manager: BatchManager, sample: Measure) -> BatchManager: - """``manager`` with runs 1, 2 and 4 measured, and run 3 without its partner.""" - for run, name in [(1, 'water'), (2, 'sds'), (4, 'ethanol')]: - sample(run, name) - sample(3, 'oil', partner=False) - return manager - - -@pytest.mark.parametrize( - ('chosen', 'taken'), - [ - (Range(first='2'), ['2', '4']), - (Range(last='2'), ['1', '2']), - (Range('2', '2'), ['2']), - (Range(later=True), []), - ], - ids=['from', 'to', 'one', 'later'], -) -def test_a_range_takes_the_filled_rows_between_its_ends_and_considers_all( - four: BatchManager, - definitions: FolderDefinitions, - chosen: Range, - taken: list[str], -) -> None: - four.create(PLAIN.name, title='A', source='pairs', choose=chosen, label='a') - - assert list(four.batch('a').frame().index) == taken - considered = definitions.load(source_key('a'), source_of).considered - assert considered == {'1', '2', '4'} # not 3, which waits - - -@pytest.mark.parametrize( - ('chosen', 'said'), - [ - (Range(first='3'), '3 is not a filled row'), - (Range('2', '1'), 'the row 2 comes after the row 1'), - ], - ids=['waits', 'reversed'], -) -def test_a_range_that_takes_no_row_of_its_ends_is_refused_and_nothing_is_kept( - four: BatchManager, definitions: FolderDefinitions, chosen: Range, said: str -) -> None: - with pytest.raises(ValueError, match=f'^{said}$'): - four.create(PLAIN.name, title='A', source='pairs', choose=chosen) - - assert (four.headers(), definitions.labels()) == ({}, []) - - -def test_a_range_of_the_rows_that_arrive_later_has_no_end() -> None: - with pytest.raises(ValueError, match='arrive later has no first or last'): - Range(first='1', later=True) - - -def test_a_batch_of_the_rows_that_arrive_later_that_follows_gets_only_those( - four: BatchManager, fake: FakeFiles, sample: Measure -) -> None: - four.create( - 'plain', - title='A', - source='pairs', - choose=Range(later=True), - label='a', - follow=True, - ) - sample(5, 'dmso') - fake.measure(1003, 1.0, role='transmission', sample='oil') # 3 waited - - four.step() - - assert list(four.batch('a').frame().index) == ['3', '5'] - - -def test_a_row_that_waits_when_a_batch_is_made_is_added_by_follow_once_filled( - manager: BatchManager, fake: FakeFiles, sample: Measure -) -> None: - sample(1, 'water') - sample(2, 'oil', partner=False) - manager.create('plain', title='A', source='pairs', label='a', follow=True) - fake.measure(1002, 1.0, role='transmission', sample='oil') - - manager.step() - - assert list(manager.batch('a').frame().index) == ['1', '2'] - - -def test_a_batch_made_without_a_source_has_none(manager: BatchManager) -> None: - manager.create('plain', title='A', label='a') - - assert manager.source('a') is None - with pytest.raises(KeyError): - manager.source('b') - - -@pytest.mark.parametrize( - ('options', 'said'), - [ - ( - {'source': 'pairs', 'rows': pd.DataFrame()}, - 'a batch made from a source takes its rows from it', - ), - ({'choose': lambda given: given}, 'choose picks rows of a source'), - ( - {'source': 'pairs', 'choose': lambda given: given.rename({'1': '9'})}, - r"choose gives rows \['9'\] that the source does not", - ), - ], - ids=['rows and source', 'choose without source', 'other row'], -) -def test_rows_of_a_source_that_cannot_be_chosen_are_refused_and_nothing_is_kept( - manager: BatchManager, - definitions: FolderDefinitions, - sample: Measure, - options: dict[str, Any], - said: str, -) -> None: - sample(1, 'water') - - with pytest.raises(ValueError, match=said): - manager.create('plain', title='A', **options) - assert manager.headers() == {} - assert definitions.labels() == [] - - -def test_the_rows_offered_are_those_of_the_source_that_the_table_lacks( - made: BatchManager, -) -> None: - batch = made.batch('a') - batch.put(batch.frame().drop('4')) - - offered = made.offered('a') - - assert offered['waits'].to_dict() == { - '1': False, - '2': False, - '4': False, - '5': True, - } - assert list(offered.columns) == [*made.rows_of('pairs').columns, 'waits'] - - -def test_a_row_of_the_source_that_waits_is_offered_as_waiting( - manager: BatchManager, client: Client, sample: Measure -) -> None: - sample(1, 'water') - manager.create('plain', title='A', source='pairs', label='a') - sample(2, 'oil', partner=False) - - assert manager.offered('a')['waits'].to_dict() == {'2': True} - - -def test_rows_taken_are_put_as_the_source_makes_them_and_considered( - manager: BatchManager, - client: Client, - fake: FakeFiles, - sample: Measure, - definitions: FolderDefinitions, -) -> None: - sample(1, 'water') - manager.create('plain', title='A', source='pairs', label='a', follow=True) - sample(2, 'oil', partner=False) - - manager.take('a', ['2']) - batch = manager.batch('a') - taken = batch.frame().loc['2'] - batch.put(batch.frame().drop('2')) - fake.measure(1002, 1.0, role='transmission', sample='oil') - manager.step() - - assert taken['sample'] == 'uuid:run-2' - assert pd.isna(taken['transmission']) - assert list(batch.frame().index) == ['1'] - assert definitions.load(source_key('a'), source_of).considered == {'1', '2'} - - -@pytest.mark.parametrize('added_by', ['step', 'take']) -def test_a_row_added_after_make_column_takes_the_setting( - manager: BatchManager, client: Client, sample: Measure, added_by: str -) -> None: - sample(1, 'water') - settings = {'thickness': 2.0} - manager.create( - 'plain', title='A', source='pairs', label='a', settings=settings, follow=True - ) - batch = manager.batch('a') - client.wait(batch.reduce(['1'])) - batch.make_column('thickness') - sample(2, 'oil') - - if added_by == 'step': - client.wait(list(manager.step().records.values())) - else: - manager.take('a', ['2']) - client.wait(batch.reduce(['2'])) - - assert pd.isna(batch.frame().loc['2', 'thickness']) - assert batch.state()['2'].record.request.params['thickness'] == 2.0 - assert batch.state()['1'].text == 'done' - - -def test_a_waiting_row_taken_or_stepped_waits_whatever_the_settings_kept( - manager: BatchManager, - client: Client, - sample: Measure, - definitions: FolderDefinitions, -) -> None: - sample(1, 'water') - from_pairs(manager, 'plain', title='A', label='a', follow=True) - sample(2, 'oil', partner=False) - kept = definitions.load(settings_key('a'), dict) - stale = {**kept['params'], 'transmission': 'run:1001'} - definitions.save(settings_key('a'), {**kept, 'params': stale}) - unregistered = BatchManager(client, sources={}, definitions=definitions) - again = _again(client, definitions) # as after a restart - - again.take('a', ['2']) - done = again.step() - state = again.batch('a').state()['2'] - - assert unregistered.batch('a').fills == {'sample', 'transmission'} - assert again.batch('a').state()['1'].text != 'incomplete' - assert done is not None - assert '2' not in done.records - assert [(e.loc, e.msg) for e in state.problems] == [(('transmission',), 'empty')] - - -def test_a_source_that_no_longer_gives_a_column_of_the_fills_kept_is_named( - manager: BatchManager, client: Client, definitions: FolderDefinitions -) -> None: - from_pairs(manager, 'plain', title='A', label='a', follow=True) - sources = {'pairs': SAMPLES} # its code now fills sample only - again = BatchManager(client, sources=sources, definitions=definitions) - said = 'the source pairs: it no longer gives the column transmission' - - with pytest.raises(ValueError, match=said): - again.offered('a') - with pytest.raises(ValueError, match=said): - again.step() - - -def test_a_step_whose_source_is_not_registered_is_refused_and_keeps_nothing( - client: Client, sample: Measure, definitions: FolderDefinitions -) -> None: - sample(1, 'water') - sources = dict(SOURCES) - manager = BatchManager(client, sources=sources, definitions=definitions) - manager.create('plain', title='A', source='pairs', label='a', follow=True) - batch = manager.batch('a') - typed = batch.frame().rename(index={'1': 'typed'}) - batch.put(pd.concat([batch.frame(), typed])) - del sources['pairs'] - - with pytest.raises(ValueError, match='the source pairs is not registered'): - manager.step() - - # A key typed by hand is considered only by a step that reads the source. - assert definitions.load(source_key('a'), source_of).considered == {'1'} - - -@pytest.mark.parametrize( - ('keys', 'said'), - [ - (['9'], r"makes no rows \['9'\]"), - (['3'], r"rows \['3'\] are in the batch already"), - ], -) -def test_rows_that_cannot_be_taken_are_refused_and_nothing_changes( - made: BatchManager, keys: list[str], said: str -) -> None: - before = made.batch('a').frame() - - with pytest.raises(ValueError, match=said): - made.take('a', keys) - - pd.testing.assert_frame_equal(made.batch('a').frame(), before) - - -def test_a_batch_made_without_a_source_offers_and_takes_no_rows( - manager: BatchManager, -) -> None: - manager.create('plain', title='A', label='a') - - with pytest.raises(ValueError, match='a was not made from a source'): - manager.offered('a') - with pytest.raises(ValueError, match='a was not made from a source'): - manager.take('a', ['1']) - - -# Which batch follows - - -@pytest.fixture -def two(manager: BatchManager) -> BatchManager: - """ - ``manager`` with two batches of a source: ``a``, which follows, and - ``b``, made without Follow. - """ - manager.create('plain', title='A', source='pairs', label='a', follow=True) - manager.create('plain', title='B', source='pairs', label='b') - return manager - - -def test_a_batch_made_to_follow_follows_in_place_of_the_one_before( - two: BatchManager, client: Client, definitions: FolderDefinitions -) -> None: - assert two.following == 'a' # b was made without Follow - - two.create('plain', title='C', source='pairs', label='c', follow=True) - - assert two.following == 'c' - assert _again(client, definitions).following == 'c' - - -def test_a_batch_that_follows_without_a_source_is_refused_and_nothing_changes( - two: BatchManager, definitions: FolderDefinitions -) -> None: - with pytest.raises(ValueError, match='a batch follows its source, and none'): - two.create('plain', title='C', label='c', follow=True) - - assert (list(two.headers()), two.following) == (['a', 'b'], 'a') - assert 'c' not in definitions.labels() - - -def test_a_batch_that_follows_with_a_last_row_is_refused_and_nothing_changes( - two: BatchManager, definitions: FolderDefinitions, sample: Measure -) -> None: - sample(1, 'water') - - with pytest.raises(ValueError, match='so it has no last row'): - two.create( - 'plain', - title='C', - source='pairs', - choose=Range(last='1'), - label='c', - follow=True, - ) - - assert (list(two.headers()), two.following) == (['a', 'b'], 'a') - assert 'c' not in definitions.labels() - - -def test_after_a_stop_no_batch_follows_and_a_manager_made_again_has_none( - two: BatchManager, client: Client, definitions: FolderDefinitions -) -> None: - two.stop() - - assert two.following is None - assert two.step() is None - assert _again(client, definitions).following is None - version = two.version - two.stop() # none follows: nothing is done - assert two.version == version - - -def test_a_stopped_batch_gets_no_rows_at_a_step( - manager: BatchManager, sample: Measure -) -> None: - sample(1, 'water') - manager.create('plain', title='A', source='pairs', label='a', follow=True) - manager.stop() - sample(2, 'oil') - - manager.step() - - assert list(manager.batch('a').frame().index) == ['1'] - assert manager.offered('a')['waits'].to_dict() == {'2': False} - - -def test_a_batch_removed_follows_no_longer( - two: BatchManager, client: Client, definitions: FolderDefinitions -) -> None: - two.remove('a') - - assert two.following is None - assert _again(client, definitions).following is None - - -def test_a_kept_label_without_a_header_follows_not( - two: BatchManager, client: Client, definitions: FolderDefinitions -) -> None: - definitions.delete(('labels', 'a', 'header')) - - assert _again(client, definitions).following is None - - -def test_which_batch_follows_stays_if_the_definitions_refuse_a_change( - two: BatchManager, refusing: Refusing -) -> None: - refusing.part = 'following' - - with pytest.raises(NotKept): - two.create('plain', title='C', source='pairs', label='c', follow=True) - with pytest.raises(NotKept): - two.stop() - assert (list(two.headers()), two.following) == (['a', 'b'], 'a') - assert 'c' not in refusing.labels() - - -def test_a_removal_whose_end_of_follow_is_refused_changes_nothing( - two: BatchManager, refusing: Refusing -) -> None: - refusing.part = 'following' - - with pytest.raises(NotKept): - two.remove('a') - - assert list(two.headers()) == ['a', 'b'] - assert two.following == 'a' - - -def test_a_removal_whose_header_is_refused_leaves_the_batch_not_following( - two: BatchManager, - refusing: Refusing, - client: Client, - definitions: FolderDefinitions, -) -> None: - refusing.part = 'header' - version = two.version - - with pytest.raises(NotKept): - two.remove('a') - - assert list(two.headers()) == ['a', 'b'] - assert two.following is None - assert two.version != version - assert _again(client, definitions).following is None - - -# The version + again = _again(client, definitions).batch(batch.label) + assert list(again.frame().index) == ['mine'] @pytest.mark.parametrize( @@ -971,18 +477,18 @@ def test_a_removal_whose_header_is_refused_leaves_the_batch_not_following( lambda m: m.create('plain', title='C', label='c'), lambda m: m.remove('b'), lambda m: m.change('b', title='Other'), - lambda m: m.stop(), ], - ids=['create', 'remove', 'change', 'stop'], + ids=['create', 'remove', 'change'], ) -def test_the_version_moves_at_each_change_of_the_headers_or_of_which_follows( - two: BatchManager, change: Callable[[BatchManager], object] +def test_the_version_moves_at_each_change_of_the_headers( + manager: BatchManager, change: Callable[[BatchManager], object] ) -> None: - before = two.version + manager.create('plain', title='B', label='b') + before = manager.version - change(two) + change(manager) - assert two.version != before + assert manager.version != before # A create or remove cut off @@ -1019,9 +525,9 @@ def _write(self) -> None: raise NotKept('stopped') -def _create(manager: BatchManager, *, follow: bool) -> None: +def _create(intake: Intake, *, follow: bool) -> None: """Make the batch ``a`` with every table: settings, rows and source.""" - manager.create( + intake.create( 'plain', title='A', source='pairs', @@ -1031,6 +537,11 @@ def _create(manager: BatchManager, *, follow: bool) -> None: ) +def _intake(client: Client, definitions: Any) -> Intake: + """An intake of a manager made again on ``definitions``, as after a restart.""" + return Intake(BatchManager(client, definitions=definitions), sources=SOURCES) + + def _made_again( client: Client, definitions: FolderDefinitions, *, follow: bool ) -> None: @@ -1039,12 +550,12 @@ def _made_again( it again, following if ``follow``; with ``follow``, it is the batch that follows, and else none follows. """ - again = _again(client, definitions) + again = _intake(client, definitions) if 'a' in definitions.labels(): - again.remove('a') + again.manager.remove('a') _create(again, follow=follow) - assert 'a' in again.headers() - assert _again(client, definitions).following == ('a' if follow else None) + assert 'a' in again.manager.headers() + assert _intake(client, definitions).following == ('a' if follow else None) def test_a_create_cut_off_at_any_write_leaves_what_remove_removes( @@ -1053,22 +564,21 @@ def test_a_create_cut_off_at_any_write_leaves_what_remove_removes( sample(1, 'water') for at in itertools.count(1): definitions = FolderDefinitions(tmp_path / str(at)) - _again(client, definitions).create( + _intake(client, definitions).create( 'plain', title='Z', source='pairs', label='z', follow=True ) stopping = Stopping(definitions, at) - manager = BatchManager(client, sources=SOURCES, definitions=stopping) try: - _create(manager, follow=True) + _create(_intake(client, stopping), follow=True) except NotKept: - # No batch a, or one that does not follow; z follows still. - again = _again(client, definitions) - assert set(again.headers()) - {'z'} <= {'a'} + # No batch a, or one made without a source; z follows still. + again = _intake(client, definitions) + assert set(again.manager.headers()) - {'z'} <= {'a'} assert again.following == 'z' _made_again(client, definitions, follow=True) else: break - assert at > 5 # settings, rows, source, header, following + assert at > 5 # rows, settings, header, source, following def test_a_remove_cut_off_at_any_write_leaves_what_remove_removes( @@ -1077,13 +587,13 @@ def test_a_remove_cut_off_at_any_write_leaves_what_remove_removes( sample(1, 'water') for at in itertools.count(1): definitions = FolderDefinitions(tmp_path / str(at)) - _create(_again(client, definitions), follow=True) + _create(_intake(client, definitions), follow=False) stopping = Stopping(definitions, at) - manager = BatchManager(client, sources=SOURCES, definitions=stopping) + manager = BatchManager(client, definitions=stopping) try: manager.remove('a') except NotKept: _made_again(client, definitions, follow=False) else: break - assert at > 4 # following, header, source, rows, settings + assert at > 4 # header, source, rows, settings diff --git a/packages/essapps/tests/batch/toys.py b/packages/essapps/tests/batch/toys.py index 70a64bcb..7aaedb3a 100644 --- a/packages/essapps/tests/batch/toys.py +++ b/packages/essapps/tests/batch/toys.py @@ -15,9 +15,9 @@ from ess.apps import Client from ess.apps.batch import ( Batch, - BatchManager, DefinitionStore, FileInfo, + Intake, NotKept, RowSource, rows_of, @@ -261,15 +261,10 @@ def edit(batch: Batch, key: str, **cells: Any) -> None: batch.put(frame) -def from_pairs(manager: BatchManager, spec: str, **options: Any) -> str: +def from_pairs(intake: Intake, spec: str, **options: Any) -> str: """ - A batch of ``manager`` made from the source ``pairs`` with ``options``, + A batch of ``intake`` made from the source ``pairs`` with ``options``, with an empty column ``thickness``, so that its columns are :data:`COLUMNS`; its label. """ - return manager.create( - spec, - source='pairs', - columns=['thickness'], - **options, - ) + return intake.create(spec, source='pairs', columns=['thickness'], **options).label diff --git a/packages/essapps/tests/batch/web_browser_test.py b/packages/essapps/tests/batch/web_browser_test.py index cc32ffe9..174c8960 100644 --- a/packages/essapps/tests/batch/web_browser_test.py +++ b/packages/essapps/tests/batch/web_browser_test.py @@ -28,7 +28,7 @@ from pydantic import BaseModel from ess.apps import Client -from ess.apps.batch import Batch, BatchManager, CorrectedFiles, Header +from ess.apps.batch import Batch, BatchManager, CorrectedFiles, Header, Intake from ess.apps.batch.definition import rows_key from ess.apps.batch.web import Pages, Shown, create_app from ess.apps.batch.web.api import STATIC @@ -78,10 +78,10 @@ def batch(manager: BatchManager, label: str) -> Batch: @pytest.fixture -def pages(manager: BatchManager, files: CorrectedFiles) -> Pages: +def pages(intake: Intake, files: CorrectedFiles) -> Pages: """The pages, with a step of Follow every 0.2 s while a batch follows.""" return Pages( - manager, + intake, interval=0.2, draw={STAGED.name: draw}, files=files, @@ -702,9 +702,9 @@ def test_a_click_on_a_row_mostly_shown_at_the_bottom_does_not_scroll( @pytest.fixture -def following(browser: Any, pages: Pages, manager: BatchManager) -> Iterator[Any]: +def following(browser: Any, pages: Pages, intake: Intake) -> Iterator[Any]: """The page of the batch ``scan`` with no rows yet, made to follow.""" - toys.from_pairs(manager, STAGED.name, title='Scan', label='scan', follow=True) + toys.from_pairs(intake, STAGED.name, title='Scan', label='scan', follow=True) with serve(create_app(pages)) as url: page = browser.new_page(viewport={'width': 1440, 'height': 900}) errors: list[str] = [] @@ -728,7 +728,7 @@ def test_while_a_batch_follows_rows_appear_and_are_reduced_without_a_click( def test_stop_following_asks_once_and_then_the_page_has_no_follow_control( - following: Any, manager: BatchManager + following: Any, intake: Intake ) -> None: asked: list[str] = [] @@ -738,21 +738,21 @@ def answer(dialog: Any) -> None: following.on('dialog', answer) following.click('#stop-follow') - assert manager.following == 'scan' + assert intake.following == 'scan' following.click('#stop-follow') following.wait_for_selector('#stop-follow', state='hidden') assert following.is_hidden('#follow-status') - assert manager.following is None + assert intake.following is None assert 'cannot follow again' in asked[0] assert 'Add rows from the runs' in asked[0] def test_a_batch_that_does_not_follow_has_no_follow_control( - page: Any, manager: BatchManager + page: Any, intake: Intake ) -> None: - toys.from_pairs(manager, STAGED.name, title='Other', follow=True) + toys.from_pairs(intake, STAGED.name, title='Other', follow=True) page.click('[data-view=batches]') @@ -987,12 +987,12 @@ def heard(request: Any) -> None: return len(urls) -def make_second(manager: BatchManager, *, follow: bool = False) -> str: +def make_second(intake: Intake, *, follow: bool = False) -> str: """ A second batch, ``other``, of the row ``2`` of the source, sds, with a thickness of 5; the batch ``scan`` has the same row, with no thickness. """ - return manager.create( + return intake.create( STAGED.name, title='Other', description='The second series', @@ -1000,13 +1000,13 @@ def make_second(manager: BatchManager, *, follow: bool = False) -> str: choose=lambda given: given.loc[['2']].assign(thickness=5.0), label='other', follow=follow, - ) + ).label @pytest.fixture -def second(manager: BatchManager, url: str) -> str: +def second(intake: Intake, url: str) -> str: """The batch of :func:`make_second`, made after the page is served.""" - return make_second(manager) + return make_second(intake) KEEP = 'window.kept = true' @@ -1028,9 +1028,9 @@ def shows(page: Any, title: str) -> None: def test_a_click_on_a_title_shows_its_batch_in_place_in_the_rows_view( - page: Any, manager: BatchManager + page: Any, intake: Intake ) -> None: - second = make_second(manager, follow=True) + second = make_second(intake, follow=True) page.evaluate(KEEP) page.click('[data-tab=settings]') page.click('[data-view=batches]') @@ -1491,7 +1491,7 @@ def fill_new_batch(page: Any, title: str) -> None: def test_a_person_makes_a_batch_and_lands_on_its_page( - page: Any, manager: BatchManager + page: Any, manager: BatchManager, intake: Intake ) -> None: page.click('[data-view=batches]') page.click('#new-batch-open') @@ -1510,7 +1510,7 @@ def test_a_person_makes_a_batch_and_lands_on_its_page( 'transmission', 'thickness', ) - assert manager.following is None # Follow is off unless ticked + assert intake.following is None # Follow is off unless ticked assert page.is_hidden('#stop-follow') @@ -1535,9 +1535,9 @@ def test_a_batch_made_after_apply_starts_with_the_settings_applied( def test_a_batch_made_with_follow_follows_in_place_of_the_one_named_at_the_box( - page: Any, manager: BatchManager + page: Any, manager: BatchManager, intake: Intake ) -> None: - toys.from_pairs(manager, STAGED.name, title='Other', follow=True) + toys.from_pairs(intake, STAGED.name, title='Other', follow=True) page.click('[data-view=batches]') page.click('#new-batch-open') page.wait_for_selector('#new-follow-other:text-is("Other follows.")') @@ -1557,7 +1557,7 @@ def test_a_batch_made_with_follow_follows_in_place_of_the_one_named_at_the_box( page.wait_for_selector('#title:has-text("Evening")') page.wait_for_selector('#stop-follow:not([hidden])') (label,) = (k for k, h in manager.headers().items() if h.title == 'Evening') - assert manager.following == label + assert intake.following == label def test_follow_opens_the_end_of_the_range(page: Any, manager: BatchManager) -> None: @@ -1580,7 +1580,7 @@ def test_follow_opens_the_end_of_the_range(page: Any, manager: BatchManager) -> def test_a_batch_of_the_rows_that_arrive_later_is_made_without_rows_and_follows( - page: Any, manager: BatchManager + page: Any, manager: BatchManager, intake: Intake ) -> None: page.click('[data-view=batches]') page.click('#new-batch-open') @@ -1600,7 +1600,7 @@ def test_a_batch_of_the_rows_that_arrive_later_is_made_without_rows_and_follows( page.wait_for_selector('#title:has-text("Later")') page.wait_for_selector('#stop-follow:not([hidden])') (label,) = (k for k, h in manager.headers().items() if h.title == 'Later') - assert manager.following == label + assert intake.following == label assert manager.batch(label).frame().empty said = 'No rows yet. Follow adds the rows of the runs that arrive.' page.wait_for_selector(f'#rows .empty:text-is("{said}")') @@ -1791,12 +1791,12 @@ def test_a_batch_that_cannot_be_shown_says_why_and_shows_the_list( sample: Measure, ) -> None: sample(1, 'water') - first = BatchManager(client, sources=SOURCES, definitions=refusing) + first = BatchManager(client, definitions=refusing) first.create(STAGED.name, title='Good', rows=toys.rows(client), label='good') first.create(STAGED.name, title='Broken', label='broken') refusing.save(rows_key('broken'), {'nonsense': 1}) - manager = BatchManager(client, sources=SOURCES, definitions=refusing) - pages = Pages(manager, files=files, marks=Marks) + manager = BatchManager(client, definitions=refusing) + pages = Pages(Intake(manager, sources=SOURCES), files=files, marks=Marks) with serve(create_app(pages)) as url: page = watched(browser) page.goto(f'{url}batches/broken/') @@ -1847,9 +1847,9 @@ def test_a_refused_header_shows_at_the_form_and_changes_nothing( def test_remove_goes_to_another_batch_then_to_the_root_without_one( - page: Any, manager: BatchManager + page: Any, manager: BatchManager, intake: Intake ) -> None: - manager.create(STAGED.name, title='Other', source='pairs', label='other') + intake.create(STAGED.name, title='Other', source='pairs', label='other') page.on('dialog', lambda dialog: dialog.accept()) page.click('[data-tab=batch]') @@ -1869,9 +1869,9 @@ def test_remove_goes_to_another_batch_then_to_the_root_without_one( def test_another_page_of_a_removed_batch_shows_why_and_the_list( - page: Any, pages: Pages, manager: BatchManager + page: Any, pages: Pages, intake: Intake ) -> None: - manager.create(STAGED.name, title='Other', source='pairs', label='other') + intake.create(STAGED.name, title='Other', source='pairs', label='other') pages.remove('scan') diff --git a/packages/essapps/tests/batch/web_follow_test.py b/packages/essapps/tests/batch/web_follow_test.py index c58e2b0e..28c4bc32 100644 --- a/packages/essapps/tests/batch/web_follow_test.py +++ b/packages/essapps/tests/batch/web_follow_test.py @@ -18,7 +18,7 @@ from pydantic import BaseModel from ess.apps import Client, Status -from ess.apps.batch import BatchManager, CorrectedFiles, FolderDefinitions +from ess.apps.batch import BatchManager, CorrectedFiles, FolderDefinitions, Intake from ess.apps.batch.web import Page, Pages, create_app from ess.apps.batch.web.api import every from ess.apps.batch.web.models import CellEdit, Edit, NewBatch, Reduce, State @@ -37,16 +37,14 @@ class Marks(BaseModel): @pytest.fixture -def pages(manager: BatchManager, files: CorrectedFiles) -> Pages: - return Pages(manager, files=files, marks=Marks) +def pages(intake: Intake, files: CorrectedFiles) -> Pages: + return Pages(intake, files=files, marks=Marks) @pytest.fixture -def label(manager: BatchManager) -> str: +def label(intake: Intake) -> str: """The batch ``scan`` of the conftest, made to follow.""" - return toys.from_pairs( - manager, STAGED.name, title='Scan', label='scan', follow=True - ) + return toys.from_pairs(intake, STAGED.name, title='Scan', label='scan', follow=True) @pytest.fixture @@ -234,13 +232,13 @@ def test_a_result_that_finishes_while_a_step_runs_reaches_the_page_at_its_next_p finishing = FinishingClient(client, gate) manager = BatchManager( finishing, # type: ignore[arg-type] - sources=SOURCES, definitions=definitions, staged=STAGED_NAMES, ) - label = toys.from_pairs(manager, STAGED.name, title='Scan', follow=True) + intake = Intake(manager, sources=SOURCES) + label = toys.from_pairs(intake, STAGED.name, title='Scan', follow=True) sample(1, 'water') - pages = Pages(manager) + pages = Pages(intake) http = opened(pages, label) page = pages.page(label) gate.close() @@ -285,9 +283,9 @@ def test_a_step_changes_no_row_that_the_table_has( def test_a_run_that_a_step_finds_can_be_chosen_in_a_cell_without_a_runs_view( - manager: BatchManager, label: str, sample: Measure + intake: Intake, label: str, sample: Measure ) -> None: - pages = Pages(manager) + pages = Pages(intake) page = pages.page(label) page.pages.tick() sample(1, 'water', partner=False) # a row that waits, so no record is made @@ -427,13 +425,13 @@ def test_stop_following_ends_the_steps_and_leaves_the_rows_running( def test_a_page_that_does_not_follow_stops_nothing( - page: Page, pages: Pages, manager: BatchManager + page: Page, pages: Pages, intake: Intake ) -> None: - other = pages.page(manager.create(STAGED.name, title='By hand')) + other = pages.page(intake.manager.create(STAGED.name, title='By hand').label) stopped = other.stop_following() - assert (stopped.notice, manager.following) == ('', page.label) + assert (stopped.notice, intake.following) == ('', page.label) assert (stopped.follow.on, stopped.follow.source) == (False, None) assert page.state().follow.source == 'pairs' @@ -535,7 +533,7 @@ def test_a_tick_whose_step_raises_what_cannot_be_said_lets_the_next_tick_run( def test_a_tick_does_nothing_while_not_following( page: Page, pages: Pages, sample: Measure ) -> None: - pages.manager.stop() + pages.intake.stop() sample(1, 'water') pages.tick() @@ -578,14 +576,14 @@ def test_a_tick_that_waited_for_the_request_that_stops_following_does_nothing( def test_the_app_steps_while_following_and_stops_with_the_app( - manager: BatchManager, + intake: Intake, label: str, sample: Measure, client: Client, ) -> None: sample(1, 'water') - with opened(Pages(manager, interval=0.01), label) as http: + with opened(Pages(intake, interval=0.01), label) as http: give_up = time.monotonic() + 10 while not client.records() and time.monotonic() < give_up: time.sleep(0.01) @@ -597,13 +595,13 @@ def test_the_app_steps_while_following_and_stops_with_the_app( def test_a_parent_that_runs_the_lifespan_of_the_app_it_mounts_steps_follow( - manager: BatchManager, + intake: Intake, label: str, sample: Measure, client: Client, ) -> None: sample(1, 'water') - batch = create_app(Pages(manager, interval=0.01)) + batch = create_app(Pages(intake, interval=0.01)) parent = FastAPI(lifespan=lambda _: batch.router.lifespan_context(batch)) parent.mount('/batch', batch) @@ -631,7 +629,7 @@ def test_a_batch_made_to_follow_ends_follow_on_the_page_of_the_one_before( assert shown is not None assert shown.follow.on is False assert pages.page(made.label).state().follow.on - assert pages.manager.following == made.label + assert pages.intake.following == made.label def test_follow_resumes_after_a_restart( @@ -641,10 +639,8 @@ def test_follow_resumes_after_a_restart( sample: Measure, definitions: FolderDefinitions, ) -> None: - manager = BatchManager( - client, sources=SOURCES, definitions=definitions, staged=STAGED_NAMES - ) - again = Pages(manager) + manager = BatchManager(client, definitions=definitions, staged=STAGED_NAMES) + again = Pages(Intake(manager, sources=SOURCES)) sample(1, 'water') again.tick() @@ -667,9 +663,9 @@ def test_a_tick_steps_the_batch_that_follows_without_a_page_open( def test_a_tick_after_follow_moved_steps_the_batch_that_follows_now( - page: Page, pages: Pages, manager: BatchManager, client: Client, sample: Measure + page: Page, pages: Pages, intake: Intake, client: Client, sample: Measure ) -> None: - other = toys.from_pairs(manager, STAGED.name, title='Other', follow=True) + other = toys.from_pairs(intake, STAGED.name, title='Other', follow=True) sample(1, 'water') pages.tick() @@ -679,9 +675,9 @@ def test_a_tick_after_follow_moved_steps_the_batch_that_follows_now( def test_the_failure_of_a_step_shows_on_the_page_of_the_batch_that_follows_only( - page: Page, pages: Pages, manager: BatchManager, fake: FakeFiles + page: Page, pages: Pages, intake: Intake, fake: FakeFiles ) -> None: - other = pages.page(manager.create(STAGED.name, title='Other', source='pairs')) + other = pages.page(intake.create(STAGED.name, title='Other', source='pairs').label) fake.list = lambda selector: (_ for _ in ()).throw(OSError('half written')) pages.tick() @@ -694,13 +690,13 @@ def test_the_failure_of_a_step_shows_on_the_page_of_the_batch_that_follows_only( @pytest.fixture -def unmarked(manager: BatchManager, label: str) -> tuple[Pages, Page]: +def unmarked(intake: Intake, label: str) -> tuple[Pages, Page]: """ Pages without a Runs view, and the page of a batch that does not follow, once a step on ``label`` has run. """ - pages = Pages(manager) - other = pages.page(manager.create(STAGED.name, title='Other', source='pairs')) + pages = Pages(intake) + other = pages.page(intake.create(STAGED.name, title='Other', source='pairs').label) pages.tick() return pages, other @@ -759,7 +755,7 @@ def test_the_failure_of_the_batch_that_followed_is_not_said_on_the_next_that_fol def test_why_follow_refused_rows_of_one_batch_is_not_said_on_the_next_that_follows( page: Page, pages: Pages, - manager: BatchManager, + intake: Intake, sample: Measure, fake: FakeFiles, client: Client, @@ -775,7 +771,7 @@ def test_why_follow_refused_rows_of_one_batch_is_not_said_on_the_next_that_follo other = pages.page(pages.create(new).label) else: other = pages.page( - toys.from_pairs(manager, STAGED.name, title='Other', follow=True) + toys.from_pairs(intake, STAGED.name, title='Other', follow=True) ) # No step runs on the other batch: its first step raises. fake.list = lambda selector: (_ for _ in ()).throw(OSError('half written')) @@ -786,10 +782,10 @@ def test_why_follow_refused_rows_of_one_batch_is_not_said_on_the_next_that_follo def test_a_correction_on_another_page_moves_the_version_of_the_runs_once( - page: Page, pages: Pages, manager: BatchManager, sample: Measure + page: Page, pages: Pages, intake: Intake, sample: Measure ) -> None: sample(1, 'water') - other = pages.page(manager.create(STAGED.name, title='Other', source='pairs')) + other = pages.page(intake.create(STAGED.name, title='Other', source='pairs').label) pages.tick() before = pages.runs_version diff --git a/packages/essapps/tests/batch/web_test.py b/packages/essapps/tests/batch/web_test.py index 2b79bfdd..920e9431 100644 --- a/packages/essapps/tests/batch/web_test.py +++ b/packages/essapps/tests/batch/web_test.py @@ -29,6 +29,7 @@ DefinitionStore, FolderDefinitions, Header, + Intake, RowSource, ) from ess.apps.batch.definition import Key, NotKept, rows_key, settings_key @@ -74,9 +75,9 @@ def batch(manager: BatchManager, label: str) -> Batch: @pytest.fixture -def pages(manager: BatchManager, files: CorrectedFiles) -> Pages: +def pages(intake: Intake, files: CorrectedFiles) -> Pages: return Pages( - manager, + intake, draw={STAGED.name: draw}, files=files, marks=Marks, @@ -95,12 +96,15 @@ def home(app: FastAPI) -> TestClient: return TestClient(app, base_url=str(page.url)) +def restarted(client: Client, definitions: DefinitionStore) -> Pages: + """The pages of an intake with the sources of ``toys`` on ``definitions``.""" + return Pages(Intake(BatchManager(client, definitions=definitions), sources=SOURCES)) + + def started(client: Client, definitions: DefinitionStore) -> Pages: - """The pages of a manager made on ``definitions``, as after a restart.""" - manager = BatchManager( - client, sources=SOURCES, definitions=definitions, staged=STAGED_NAMES - ) - return Pages(manager) + """The pages of an intake made on ``definitions``, as after a restart.""" + manager = BatchManager(client, definitions=definitions, staged=STAGED_NAMES) + return Pages(Intake(manager, sources=SOURCES)) @pytest.fixture @@ -551,7 +555,7 @@ def test_the_setting_of_a_column_without_a_default_can_be_reset_to_none( {'sample': [None], 'transmission': ['run:1001']}, index=pd.Index(['a']) ) settings = {'sample': FileRef(file='run:1')} - label = manager.create(STAGED.name, title='T', rows=table, settings=settings) + label = manager.create(STAGED.name, title='T', rows=table, settings=settings).label page = opened(pages, label) shown = state(page) @@ -650,7 +654,7 @@ def test_a_row_reduced_by_another_spec_version_is_outdated( sample(1, 'water') with local(proposal='p1', files=files, bind=bind) as client: pages = started(client, definitions) - label = toys.from_pairs(pages.manager, PLAIN.name, title='New') + label = toys.from_pairs(pages.intake, PLAIN.name, title='New') old = Batch(client, PLAIN, label=label, rows=toys.rows(client)) client.wait(old.reduce(['1'])) page = opened(pages, label) @@ -793,7 +797,7 @@ def test_the_table_downloaded_and_uploaded_gives_the_same_table( ) -> None: thickness(http, ['2'], 4) content = http.get(f'/api/table.{suffix}').content - other = manager.create(STAGED.name, title='Other') + other = manager.create(STAGED.name, title='Other').label loaded = opened(pages, other).post( '/api/table', params={'name': f'rows.{suffix}'}, content=content @@ -918,10 +922,10 @@ def kept(client: Client, fake: FakeFiles, sample: Measure, flaky: Flaky) -> Test """A page on a batch and runs whose definitions are :class:`Flaky`.""" sample(1, 'water') sample(2, 'sds') - manager = BatchManager(client, sources=SOURCES, definitions=flaky) - label = toys.from_pairs(manager, STAGED.name, title='Kept', label='kept') + intake = Intake(BatchManager(client, definitions=flaky), sources=SOURCES) + label = toys.from_pairs(intake, STAGED.name, title='Kept', label='kept') files = CorrectedFiles(fake, definitions=flaky) - return opened(Pages(manager, files=files, marks=Marks), label) + return opened(Pages(intake, files=files, marks=Marks), label) def test_a_change_the_definitions_cannot_keep_answers_422_and_nothing_changes( @@ -1154,7 +1158,7 @@ def test_the_plot_draws_the_results_of_the_rows_asked_for_in_their_colours( def test_a_drawing_that_raises_says_so_in_place_of_the_figure( - manager: BatchManager, + intake: Intake, label: str, client: Client, sample: Measure, @@ -1163,8 +1167,8 @@ def broken(_: Sequence[Shown]) -> Any: raise RuntimeError('released') sample(1, 'water') - manager.batch(label).put(toys.rows(client)) - pages = Pages(manager, draw={STAGED.name: broken}) + intake.manager.batch(label).put(toys.rows(client)) + pages = Pages(intake, draw={STAGED.name: broken}) page = opened(pages, label) reduced(page, client) @@ -1186,11 +1190,11 @@ def test_plotting_and_saving_chosen_rows_reads_their_records_only( client: Client, sample: Measure, definitions: DefinitionStore ) -> None: counting = CountingClient(client) - manager = BatchManager(counting, sources=SOURCES, definitions=definitions) # type: ignore[arg-type] + manager = BatchManager(counting, definitions=definitions) # type: ignore[arg-type] for run in (1, 2, 3): sample(run, f's{run}') - label = manager.create(STAGED.name, title='Scan', rows=toys.rows(client)) - pages = Pages(manager, draw={STAGED.name: draw}) + label = manager.create(STAGED.name, title='Scan', rows=toys.rows(client)).label + pages = Pages(Intake(manager, sources=SOURCES), draw={STAGED.name: draw}) page = opened(pages, label) reduced(page, client, 'all') chosen = {'keys': ['1']} @@ -1316,9 +1320,9 @@ def test_rows_taken_are_added_as_the_source_makes_them( def test_a_row_taken_then_removed_is_offered_again_and_follow_does_not_add_it( - http: TestClient, pages: Pages, manager: BatchManager, sample: Measure + http: TestClient, pages: Pages, intake: Intake, sample: Measure ) -> None: - label = toys.from_pairs(manager, STAGED.name, title='Later', follow=True) + label = toys.from_pairs(intake, STAGED.name, title='Later', follow=True) following = opened(pages, label) sample(4, 'ethanol') following.post('/api/rows/take', json={'keys': ['4']}) @@ -1398,7 +1402,9 @@ def test_a_source_that_no_longer_gives_a_column_of_the_batch_is_said( pages: Pages, label: str, client: Client, definitions: DefinitionStore ) -> None: sources = {'pairs': toys.SAMPLES} # its code now fills sample only - again = Pages(BatchManager(client, sources=sources, definitions=definitions)) + again = Pages( + Intake(BatchManager(client, definitions=definitions), sources=sources) + ) answer = opened(again, label).get('/api/rows/offered') @@ -1454,7 +1460,7 @@ def test_a_column_made_a_setting_whose_table_is_refused_keeps_its_cells( answer = make_setting(http) assert answer.status_code == 422 - batch = started(client, definitions).manager.batch('scan') + batch = started(client, definitions).intake.manager.batch('scan') assert batch.parameter_columns == ('sample', 'transmission', 'thickness') assert batch.frame()['thickness'].tolist() == [2.5, 2.5, 2.5] @@ -1604,7 +1610,7 @@ def form(files: CorrectedFiles, definitions: DefinitionStore) -> Iterator[TestCl with local(proposal='p1', files=files, bind=bind) as client: pages = started(client, definitions) rows = pd.DataFrame(columns=['sample']) - label = pages.manager.create(FORMS.name, title='Forms', rows=rows) + label = pages.intake.manager.create(FORMS.name, title='Forms', rows=rows).label yield opened(pages, label) @@ -1769,7 +1775,7 @@ def test_a_large_answer_is_compressed_for_a_client_that_accepts_gzip( def test_each_batch_has_its_page_at_its_label( http: TestClient, manager: BatchManager, pages: Pages, client: Client ) -> None: - other = manager.create(STAGED.name, title='Other', rows=toys.rows(client)) + other = manager.create(STAGED.name, title='Other', rows=toys.rows(client)).label page = opened(pages, other) bins(page, 5) @@ -1784,11 +1790,11 @@ def test_each_batch_has_its_page_at_its_label( def test_the_root_redirects_to_the_batch_that_follows( - pages: Pages, manager: BatchManager + pages: Pages, intake: Intake ) -> None: http = TestClient(create_app(pages), follow_redirects=False) for label in ('a', 'b'): - manager.create( + intake.create( STAGED.name, title=label, source='pairs', label=label, follow=label == 'b' ) @@ -1797,11 +1803,9 @@ def test_the_root_redirects_to_the_batch_that_follows( assert (page.status_code, page.headers['location']) == (307, 'batches/b/') -def test_the_root_redirects_to_the_only_batch( - pages: Pages, manager: BatchManager -) -> None: +def test_the_root_redirects_to_the_only_batch(pages: Pages, intake: Intake) -> None: http = TestClient(create_app(pages), follow_redirects=False) - manager.create(STAGED.name, title='a', source='pairs', label='a') + intake.create(STAGED.name, title='a', source='pairs', label='a') page = http.get('/') @@ -1809,11 +1813,11 @@ def test_the_root_redirects_to_the_only_batch( def test_the_root_lists_several_batches_if_none_follows( - pages: Pages, manager: BatchManager + pages: Pages, intake: Intake ) -> None: http = TestClient(create_app(pages), follow_redirects=False) for label in ('a', 'b'): - manager.create(STAGED.name, title=label, source='pairs', label=label) + intake.create(STAGED.name, title=label, source='pairs', label=label) page = http.get('/') @@ -1843,9 +1847,9 @@ def test_a_label_that_is_no_batch_answers_404_and_its_page_says_so( def test_the_batches_view_lists_every_batch_and_the_one_that_follows( - http: TestClient, manager: BatchManager + http: TestClient, intake: Intake ) -> None: - manager.create( + intake.create( STAGED.name, title='Other', source='pairs', @@ -1868,9 +1872,9 @@ def test_the_batches_view_lists_every_batch_and_the_one_that_follows( def test_the_list_of_batches_is_the_same_from_every_page( - http: TestClient, pages: Pages, manager: BatchManager + http: TestClient, pages: Pages, intake: Intake ) -> None: - other = manager.create(STAGED.name, title='Other', source='pairs') + other = intake.create(STAGED.name, title='Other', source='pairs').label listed = http.get('/api/batches').json() @@ -1879,7 +1883,7 @@ def test_the_list_of_batches_is_the_same_from_every_page( def test_a_page_learns_from_its_poll_that_another_batch_follows( - http: TestClient, manager: BatchManager + http: TestClient, ) -> None: now = state(http) @@ -1898,10 +1902,12 @@ def test_a_page_learns_from_its_poll_that_another_batch_follows( def test_a_correction_on_one_page_shows_in_the_runs_view_of_another( - http: TestClient, pages: Pages, manager: BatchManager, fake: FakeFiles + http: TestClient, pages: Pages, intake: Intake, fake: FakeFiles ) -> None: key = fake.measure(4, 1.0, role='sample', sample='oil').file - other = opened(pages, manager.create(STAGED.name, title='Other', source='pairs')) + other = opened( + pages, intake.create(STAGED.name, title='Other', source='pairs').label + ) runs = state(other)['runs'] edit = {'keys': [key], 'column': 'role', 'value': 'transmission'} @@ -1978,13 +1984,12 @@ def test_a_batch_that_cannot_be_counted_has_its_reason( client: Client, definitions: FolderDefinitions, sample: Measure ) -> None: sample(1, 'water') - first = BatchManager(client, sources=SOURCES, definitions=definitions) + first = BatchManager(client, definitions=definitions) first.create('plain', title='Fine', rows=toys.rows(client), label='a') first.create('plain', title='Broken', rows=toys.rows(client), label='b') definitions.save(rows_key('b'), {'nonsense': 1}) - manager = BatchManager(client, sources=SOURCES, definitions=definitions) - counted = Pages(manager).counts() + counted = restarted(client, definitions).counts() assert list(counted.rows) == list(counted.files) == ['a'] assert 'rows.json: not a table' in counted.failed['b'] @@ -2016,9 +2021,9 @@ def test_the_counts_name_the_runs_of_each_batch_also_a_run_two_share( def test_a_row_that_follow_adds_names_its_runs_in_the_next_count( - pages: Pages, manager: BatchManager, sample: Measure + pages: Pages, intake: Intake, sample: Measure ) -> None: - label = toys.from_pairs(manager, STAGED.name, title='Scan', follow=True) + label = toys.from_pairs(intake, STAGED.name, title='Scan', follow=True) page = TestClient(create_app(pages)) before = named(page)[label] sample(1, 'water') @@ -2092,9 +2097,9 @@ def test_a_source_that_no_spec_fits_is_not_offered_and_no_source_always_is( client: Client, definitions: DefinitionStore ) -> None: odd = RowSource(pair, fills=('sample', 'background')) - manager = BatchManager(client, sources={'odd': odd}, definitions=definitions) + manager = BatchManager(client, definitions=definitions) - pages = Pages(manager) + pages = Pages(Intake(manager, sources={'odd': odd})) offered = TestClient(create_app(pages)).get('/api/sources').json() assert [s['name'] for s in offered] == [None] @@ -2122,12 +2127,12 @@ def test_a_batch_made_from_a_source_has_every_row_it_filled_and_the_columns_sent def test_a_batch_made_to_follow_follows_and_one_without_a_source_cannot( - http: TestClient, manager: BatchManager + http: TestClient, intake: Intake ) -> None: made = http.post('/api/batches', json=new_batch(follow=True)).json() refused = http.post('/api/batches', json=new_batch(source=None, follow=True)) - assert manager.following == made['label'] + assert intake.following == made['label'] assert (refused.status_code, refused.json()) == ( 422, { @@ -2138,24 +2143,22 @@ def test_a_batch_made_to_follow_follows_and_one_without_a_source_cannot( def test_stop_following_answers_the_page_of_a_batch_that_follows_no_more( - pages: Pages, manager: BatchManager + pages: Pages, intake: Intake ) -> None: - label = toys.from_pairs(manager, STAGED.name, title='F', follow=True) + label = toys.from_pairs(intake, STAGED.name, title='F', follow=True) stopped = opened(pages, label).post('/api/follow/stop').json() assert (stopped['notice'], stopped['follow']['on']) == ('Stopped following.', False) - assert manager.following is None + assert intake.following is None def test_a_batch_made_from_the_page_starts_with_the_settings_of_its_spec( client: Client, definitions: DefinitionStore ) -> None: settings = {STAGED.name: {'binning': {'bins': 5}}} - manager = BatchManager( - client, sources=SOURCES, definitions=definitions, settings=settings - ) - pages = Pages(manager) + manager = BatchManager(client, definitions=definitions, settings=settings) + pages = Pages(Intake(manager, sources=SOURCES)) made = TestClient(create_app(pages)).post('/api/batches', json=new_batch()) @@ -2224,7 +2227,7 @@ def test_a_range_that_takes_no_row_of_its_ends_makes_no_batch( def test_a_batch_that_follows_with_a_last_row_is_not_made( - http: TestClient, manager: BatchManager + http: TestClient, manager: BatchManager, intake: Intake ) -> None: answer = http.post('/api/batches', json=new_batch(last='2', follow=True)) @@ -2233,7 +2236,7 @@ def test_a_batch_that_follows_with_a_last_row_is_not_made( 'The batch was not made: a batch that follows takes every row that ' 'arrives later, so it has no last row.', ) - assert (list(manager.headers()), manager.following) == (['scan'], None) + assert (list(manager.headers()), intake.following) == (['scan'], None) def test_a_batch_of_the_rows_that_arrive_later_takes_none_now_and_follow_adds_them( @@ -2298,7 +2301,7 @@ def test_a_batch_made_on_the_page_is_made_as_asked_or_not_at_all( ) for at in itertools.count(1): definitions = FolderDefinitions(tmp_path / str(at)) - BatchManager(client, sources=SOURCES, definitions=definitions).create( + Intake(BatchManager(client, definitions=definitions), sources=SOURCES).create( STAGED.name, title='Old', source='pairs', @@ -2307,20 +2310,25 @@ def test_a_batch_made_on_the_page_is_made_as_asked_or_not_at_all( follow=True, ) refusing = RefusingAt(definitions, at) - pages = Pages(BatchManager(client, sources=SOURCES, definitions=refusing)) + pages = Pages( + Intake(BatchManager(client, definitions=refusing), sources=SOURCES) + ) try: made = pages.create(new) except Problem: - manager = pages.manager - assert (list(manager.headers()), manager.following) == (['old'], 'old') + manager = pages.intake.manager + assert (list(manager.headers()), pages.intake.following) == ( + ['old'], + 'old', + ) else: break - batch = pages.manager.batch(made.label) - assert at > 4 # settings, rows, source, header, following + batch = pages.intake.manager.batch(made.label) + assert at > 4 # settings, rows, header, source, following assert batch.frame()['thickness'].isna().tolist() == [True] assert batch.settings['thickness'] == 2.0 - assert pages.manager.following == made.label + assert pages.intake.following == made.label def test_a_batch_that_starts_with_the_settings_of_no_batch_is_not_made( @@ -2366,7 +2374,6 @@ def test_a_setting_of_the_batch_at_a_column_of_the_new_one_is_its_empty_cells( def test_a_row_that_arrives_in_a_new_batch_that_follows_takes_a_setting_ticked( http: TestClient, pages: Pages, - manager: BatchManager, client: Client, sample: Measure, ) -> None: @@ -2415,7 +2422,7 @@ def from_table(http: TestClient, text: str, **given: Any) -> Any: def test_a_batch_made_from_a_table_file_has_its_rows_and_columns_and_no_source( - http: TestClient, manager: BatchManager + http: TestClient, manager: BatchManager, intake: Intake ) -> None: text = 'key,run,sample,transmission\na,1,run:1,run:1001\nb,2,run:2,run:1002\n' @@ -2424,7 +2431,7 @@ def test_a_batch_made_from_a_table_file_has_its_rows_and_columns_and_no_source( batch = manager.batch(made['label']) assert batch.parameter_columns == ('sample', 'transmission') assert list(batch.frame().index) == ['a', 'b'] - assert manager.source(made['label']) is None + assert intake.source(made['label']) is None assert manager.headers()[made['label']].title == 'From a file' @@ -2512,12 +2519,12 @@ def test_the_root_without_a_batch_serves_the_page_and_the_routes_of_the_workspac def test_the_root_is_not_kept_by_the_browser_with_or_without_a_batch( - pages: Pages, manager: BatchManager + pages: Pages, intake: Intake ) -> None: http = TestClient(create_app(pages), follow_redirects=False) page = http.get('/') - manager.create(STAGED.name, title='First', source='pairs') + intake.create(STAGED.name, title='First', source='pairs') redirect = http.get('/') assert (page.status_code, redirect.status_code) == (200, 307) @@ -2544,11 +2551,10 @@ def test_runs_are_corrected_without_a_batch(pages: Pages, sample: Measure) -> No def test_a_batch_whose_rows_cannot_be_read_answers_422_and_the_list_stays( client: Client, definitions: DefinitionStore ) -> None: - first = BatchManager(client, sources=SOURCES, definitions=definitions) - label = first.create(STAGED.name, title='Odd') + first = BatchManager(client, definitions=definitions) + label = first.create(STAGED.name, title='Odd').label definitions.save(rows_key(label), {'nonsense': 1}) - manager = BatchManager(client, sources=SOURCES, definitions=definitions) - pages = Pages(manager) + pages = restarted(client, definitions) shown = opened(pages, label).get('/api/state') @@ -2639,7 +2645,7 @@ def test_a_header_change_the_definitions_refuse_answers_422_and_changes_nothing( def test_a_batch_to_follow_whose_follow_the_definitions_refuse_is_not_made( - http: TestClient, manager: BatchManager, refusing: Refusing + http: TestClient, manager: BatchManager, intake: Intake, refusing: Refusing ) -> None: refusing.part = 'following' @@ -2649,7 +2655,7 @@ def test_a_batch_to_follow_whose_follow_the_definitions_refuse_is_not_made( 422, {'message': "The change was not kept: ('following',): refused"}, ) - assert (list(manager.headers()), manager.following) == (['scan'], None) + assert (list(manager.headers()), intake.following) == (['scan'], None) def test_a_title_and_description_saved_on_the_page_are_kept( @@ -2695,19 +2701,19 @@ def test_a_batch_removed_from_its_page_is_gone_and_its_results_stay( def test_removing_the_batch_that_follows_turns_follow_off( - pages: Pages, manager: BatchManager + pages: Pages, intake: Intake ) -> None: - label = toys.from_pairs(manager, STAGED.name, title='F', follow=True) + label = toys.from_pairs(intake, STAGED.name, title='F', follow=True) opened(pages, label).post('/api/batch/remove') - assert pages.manager.following is None + assert pages.intake.following is None def test_a_removal_the_definitions_refuse_answers_422_and_the_batch_stays( - pages: Pages, manager: BatchManager, refusing: Refusing + pages: Pages, manager: BatchManager, intake: Intake, refusing: Refusing ) -> None: - label = toys.from_pairs(manager, STAGED.name, title='F', label='f', follow=True) + label = toys.from_pairs(intake, STAGED.name, title='F', label='f', follow=True) refusing.part = 'header' answer = opened(pages, label).post('/api/batch/remove') @@ -2716,9 +2722,9 @@ def test_a_removal_the_definitions_refuse_answers_422_and_the_batch_stays( assert answer.json()['message'] == ( "The change was not kept: ('labels', 'f', 'header'): refused" ) - # It follows no longer, so that no label without a header follows. + # Nothing was removed: the header is kept, and the batch still follows. assert list(manager.headers()) == ['f'] - assert manager.following is None + assert intake.following == 'f' def test_another_page_of_a_removed_batch_answers_404_at_its_next_poll( @@ -2753,12 +2759,12 @@ def test_a_page_handed_out_before_its_batch_is_removed_answers_missing( def test_a_batch_made_again_under_a_removed_label_gets_a_new_page( - http: TestClient, pages: Pages, manager: BatchManager + http: TestClient, pages: Pages, intake: Intake ) -> None: page = pages.page('scan') pages.remove('scan') - manager.create(STAGED.name, title='Again', source='pairs', label='scan') + intake.create(STAGED.name, title='Again', source='pairs', label='scan') assert pages.page('scan') is not page assert state(http)['title'] == 'Again' diff --git a/packages/essinstruments/src/ess/instruments/loki/batch.py b/packages/essinstruments/src/ess/instruments/loki/batch.py index 35b23bc3..308d8726 100644 --- a/packages/essinstruments/src/ess/instruments/loki/batch.py +++ b/packages/essinstruments/src/ess/instruments/loki/batch.py @@ -10,9 +10,9 @@ {'file': 'run-1.nxs', 'run': 1, 'role': 'sample', 'sample': 'water'} {'file': 'run-2.nxs', 'run': 2, 'role': 'transmission', 'sample': 'water'} -:data:`SOURCES` and :data:`STAGED` give a -:class:`~ess.apps.batch.BatchManager` the batches of I(Q). A batch without a -manager keeps nothing:: +:data:`SOURCES` gives an :class:`~ess.apps.batch.Intake`, and :data:`STAGED` +a :class:`~ess.apps.batch.BatchManager`, the batches of I(Q). A batch without +a manager keeps nothing:: Batch(client, IOFQ, label='iofq', rows=rows_of(client, SAMPLE_RUNS), staged=True) diff --git a/packages/essinstruments/src/ess/instruments/loki/web.py b/packages/essinstruments/src/ess/instruments/loki/web.py index 651d4faa..25b90f63 100644 --- a/packages/essinstruments/src/ess/instruments/loki/web.py +++ b/packages/essinstruments/src/ess/instruments/loki/web.py @@ -64,7 +64,7 @@ from pydantic import BaseModel, Field from ess.apps import Client -from ess.apps.batch import BatchManager, CorrectedFiles, FolderDefinitions +from ess.apps.batch import BatchManager, CorrectedFiles, FolderDefinitions, Intake from ess.apps.batch.web import Pages, Shown, create_app, plots from ess.apps.batch.web.api import STATIC from ess.apps.folder import ArrivingFiles, open_folder @@ -130,17 +130,17 @@ def build( """ manager = BatchManager( client, - sources=SOURCES, definitions=definitions, settings={IOFQ.name: settings or {}}, staged=STAGED, ) + intake = Intake(manager, sources=SOURCES) if not manager.headers(): - manager.create( + intake.create( IOFQ.name, title='Sample runs', source='sample-runs', follow=follow ) pages = Pages( - manager, + intake, interval=interval, title='LoKI I(Q)', draw={IOFQ.name: _draw(client)}, diff --git a/packages/essinstruments/tests/loki/web_test.py b/packages/essinstruments/tests/loki/web_test.py index 302eedda..c0e7f0ec 100644 --- a/packages/essinstruments/tests/loki/web_test.py +++ b/packages/essinstruments/tests/loki/web_test.py @@ -33,18 +33,17 @@ def test_the_first_batch_follows_only_if_asked(tmp_path: Path) -> None: register(tmp_path, (1, 'sample', 'a'), (2, 'transmission', 'a')) client, files, definitions = open_loki(tmp_path) with client: - manager = build(client, files, definitions).state.pages.manager - assert manager.following is None - (label,) = manager.headers() - manager.remove(label) - manager = build(client, files, definitions, follow=True).state.pages.manager - assert manager.following == next(iter(manager.headers())) + intake = build(client, files, definitions).state.pages.intake + assert intake.following is None + (label,) = intake.manager.headers() + intake.manager.remove(label) + intake = build(client, files, definitions, follow=True).state.pages.intake + assert intake.following == next(iter(intake.manager.headers())) def test_a_run_registered_while_the_page_runs_is_added_by_a_step_of_follow( tmp_path: Path, ) -> None: - def names(state: dict[str, Any]) -> list[str]: return [row['name'] for row in state['rows']] From c90c622aed96120fec01030475e691fd64adb77f Mon Sep 17 00:00:00 2001 From: Simon Heybrock Date: Mon, 23 Nov 2026 07:00:46 +0000 Subject: [PATCH 3/5] Batch guides: the manager knows no row source; Intake brings rows in The guide draws Intake between the callers and the manager, the step and the row source, and says who writes each file: the intake writes source.json and following.json, and settings.json holds the fills as the blanks of its template. A label names a batch to every method but create, which returns the Batch. The page README, the developer README, the tour and ADRs 0011 to 0013 get the identifiers and the sentences that the split made false; the ADRs keep their decisions. Co-Authored-By: Claude Opus 5.5 --- docs/developer/README.md | 10 +- ...person-makes-the-batches-of-a-workspace.md | 22 +-- docs/developer/adr/0012-a-batch-is-a-table.md | 2 +- ...013-follow-adds-the-rows-not-considered.md | 28 +-- docs/developer/tours/layers.html | 16 +- packages/essapps/docs/batch.md | 185 ++++++++++-------- .../essapps/src/ess/apps/batch/web/README.md | 46 +++-- 7 files changed, 168 insertions(+), 141 deletions(-) diff --git a/docs/developer/README.md b/docs/developer/README.md index e695ebb3..cd406503 100644 --- a/docs/developer/README.md +++ b/docs/developer/README.md @@ -301,11 +301,11 @@ def transmission_runs(files: Sequence[FileInfo]) -> pd.DataFrame: for f in files if f.metadata.get('role') == 'transmission'] return pd.DataFrame.from_records(rows, columns=['key', 'run']).set_index('key') -manager = BatchManager(client, definitions=FolderDefinitions(folder), - sources={'transmission-runs': RowSource(transmission_runs, fills=('run',))}) -manager.create('transmission', title='Transmissions', source='transmission-runs', - follow=True) -manager.step() # called by a timer of the application +manager = BatchManager(client, definitions=FolderDefinitions(folder)) +intake = Intake(manager, sources={'transmission-runs': RowSource(transmission_runs, fills=('run',))}) +intake.create('transmission', title='Transmissions', source='transmission-runs', + follow=True) +intake.step() # called by a timer of the application ``` A step never changes a row that the table has. The results are read from the records under the label, so a restarted application reduces no row that has a result. A record under the label with a row's key as member, from any batch, is that row's result. diff --git a/docs/developer/adr/0011-a-person-makes-the-batches-of-a-workspace.md b/docs/developer/adr/0011-a-person-makes-the-batches-of-a-workspace.md index 3f37682d..1d95eeed 100644 --- a/docs/developer/adr/0011-a-person-makes-the-batches-of-a-workspace.md +++ b/docs/developer/adr/0011-a-person-makes-the-batches-of-a-workspace.md @@ -39,9 +39,9 @@ Problem 3 is not decided (see "Not decided"). ### The manager ```python -manager = BatchManager(client, sources={'sample-runs': SAMPLE_RUNS}, - definitions=FolderDefinitions(folder)) -label = manager.create('loki-iofq', title='Afternoon', source='sample-runs') +manager = BatchManager(client, definitions=FolderDefinitions(folder)) +intake = Intake(manager, sources={'sample-runs': SAMPLE_RUNS}) +label = intake.create('loki-iofq', title='Afternoon', source='sample-runs').label manager.headers() # {label: Header(title, description)}, sorted by label manager.batch(label) # the Batch: frame(), put(), state(), reduce(), cancel(), settings manager.change(label, title='Afternoon, 2 mm cells') @@ -58,7 +58,7 @@ What the application gives once, and what a person chooses for each batch: | Part | Given by | |---|---| | spec | a person, from the specs that the workspace binds (`client.specs()`); the name is kept, the version is the one bound, the highest if several are ([ADR 0009](0009-a-record-of-another-spec-stays-readable.md)) | -| source | a person, from the sources that the application registers by name (`BatchManager(sources=...)`), or none | +| source | a person, from the sources that the application registers by name (`Intake(sources=...)`), or none | | title, description | a person | | label | the manager | | first settings, `staged` | the application, for each spec (`BatchManager(settings=..., staged=...)`) | @@ -92,18 +92,18 @@ Nothing checks that the batches cover every row or that they do not overlap. ### One batch follows -The manager keeps the label of the batch that follows, or none: +The intake keeps the label of the batch that follows, or none: ```python -manager.create(..., source='sample-runs', follow=True) # this batch follows, and no other -manager.following # its label, or None -manager.stop() # none follows -manager.step() # one step of Follow on it (ADR 0013) +intake.create(..., source='sample-runs', follow=True) # this batch follows, and no other +intake.following # its label, or None +intake.stop() # none follows +intake.step() # one step of Follow on it (ADR 0013) ``` - One value means that at most one batch follows, with no rule to enforce. Making a batch that follows stops the batch that followed before. -- The manager keeps the value in the definitions, apart from any batch, so a restart resumes. Removing the batch that follows ends Follow. -- Whoever serves the pages owns the timer that calls `step`. The manager has no thread, no timer and no lock. +- The intake keeps the value in the definitions, apart from any batch, so a restart resumes. Removing the batch that follows ends Follow. +- Whoever serves the pages owns the timer that calls `step`. The intake has no thread, no timer and no lock. - The workspace has one lock: every request of every page and each step take it, so the batches, the manager and the corrections change in one request at a time. ### A page shows one batch, named in its URL diff --git a/docs/developer/adr/0012-a-batch-is-a-table.md b/docs/developer/adr/0012-a-batch-is-a-table.md index 50d93013..6a76a264 100644 --- a/docs/developer/adr/0012-a-batch-is-a-table.md +++ b/docs/developer/adr/0012-a-batch-is-a-table.md @@ -271,7 +271,7 @@ The code of this ADR and of ADR 0013 is written together, since Follow is in use - An empty cell depends on the settings, outside the table. The page shows it in grey as the value that the row takes. - A table file shows an empty cell where a row takes the setting, so it needs the settings file to say what a row was reduced with. - A cell emptied after its row was reduced counts its value as a setting: the row reads `earlier`, not `outdated`. -- A batch made from a source keeps the names that its source fills with it, in `source.json`, as they were when it was made; the batch, the command without the sources, and Follow read them there. A step asks the batch which names a row waits for. +- A batch made from a source keeps the names that its source fills with it, as the blanks of `settings.json`, as they were when it was made; the batch, the command without the sources, and Follow read them there. A step asks the batch which names a row waits for. - The table of a batch made from a source keeps a column for each name that its source fills: `put`, a table file loaded, and "Make this a setting" refuse to drop one. - `settings.json` holds every setting, those at the columns too, as a template without blanks. A file whose template has blanks, as one written before, reads the same: its blanks are not read, and it has no settings at the columns. - A row that only wrong metadata made stays until a person removes it, and a correction of a run changes no batch (the example above). diff --git a/docs/developer/adr/0013-follow-adds-the-rows-not-considered.md b/docs/developer/adr/0013-follow-adds-the-rows-not-considered.md index 0cb2ee2e..49479399 100644 --- a/docs/developer/adr/0013-follow-adds-the-rows-not-considered.md +++ b/docs/developer/adr/0013-follow-adds-the-rows-not-considered.md @@ -84,8 +84,8 @@ A source says which columns it fills (`RowSource.fills`, such as `sample` and `s `create` lists the source once, and a person chooses the table of the batch from the rows that are filled: ```python -manager.create('loki-iofq', title='Afternoon', source='sample-runs', - choose=Range(first='60339'), columns=['thickness'], follow=True) +intake.create('loki-iofq', title='Afternoon', source='sample-runs', + choose=Range(first='60339'), columns=['thickness'], follow=True) # in create: given = rows_of(client, source) # one listing @@ -116,10 +116,10 @@ The rule is on the state of the rows, as in ADR 0011. So in a batch that follows No row moves from one batch to another. A person who wants the runs from 60400 on in a batch of their own makes it with Follow: ```python -label = manager.create('loki-iofq', title='Evening', source='sample-runs', - choose=Range(first='60400'), - settings=manager.batch('afternoon').settings, - follow=True) # the batch 'afternoon' stops following +intake.create('loki-iofq', title='Evening', source='sample-runs', + choose=Range(first='60400'), + settings=manager.batch('afternoon').settings, + follow=True) # the batch 'afternoon' stops following ``` The earlier batch keeps its rows, also those from 60400 on, until a person removes them. It has considered the keys it has seen, and takes no row that arrives later, since it cannot follow again. @@ -127,8 +127,8 @@ The earlier batch keeps its rows, also those from 60400 on, until a person remov A batch of only the rows that arrive later takes no row at making. Every row filled then is considered, so no row is reduced again: ```python -manager.create('loki-iofq', title='Night', source='sample-runs', - choose=Range(later=True), follow=True) +intake.create('loki-iofq', title='Night', source='sample-runs', + choose=Range(later=True), follow=True) ``` ### A batch follows from the time it is made, until it is stopped @@ -136,14 +136,14 @@ manager.create('loki-iofq', title='Night', source='sample-runs', Follow is chosen when a batch is made. A batch that follows can be stopped. A batch that does not follow cannot be made to follow. ```python -manager.create(..., source='sample-runs', follow=True) # follows; the batch that followed before stops -manager.following # its label -manager.stop() # none follows; that batch cannot follow again +intake.create(..., source='sample-runs', follow=True) # follows; the batch that followed before stops +intake.following # its label +intake.stop() # none follows; that batch cannot follow again ``` -- At most one batch follows, as in ADR 0011: the manager keeps its label in `following.json`, a restart resumes, and removing that batch ends Follow. Since `considered` is kept, the first step after a restart adds the rows that arrived in between. -- A batch made without a source cannot follow; `create` refuses `follow=True` without a source. -- A batch that follows has no last row. With one, the rows filled between the last row chosen and the making would be considered and never added, and the rows that arrive later would be. The range that a person picks is a value, `Range(first, last, later)`, which the manager reads: `create(follow=True)` with a `Range` that has a `last` is refused there. The page leaves the end of the range open while Follow is ticked, to say so before a person sends the form; the command does not follow. A `choose` that is a function may pick any rows, also with Follow: the rows were chosen in code, and the filled rows that it leaves out are considered, so Follow adds only the rows that arrive later. +- At most one batch follows, as in ADR 0011: the intake (`Intake`) keeps its label in `following.json`, a restart resumes, and removing that batch ends Follow. Since `considered` is kept, the first step after a restart adds the rows that arrived in between. +- A batch made without a source cannot follow: only `intake.create`, which takes a source, takes `follow=True`. +- A batch that follows has no last row. With one, the rows filled between the last row chosen and the making would be considered and never added, and the rows that arrive later would be. The range that a person picks is a value, `Range(first, last, later)`, which the intake reads: `create(follow=True)` with a `Range` that has a `last` is refused there. The page leaves the end of the range open while Follow is ticked, to say so before a person sends the form; the command does not follow. A `choose` that is a function may pick any rows, also with Follow: the rows were chosen in code, and the filled rows that it leaves out are considered, so Follow adds only the rows that arrive later. - Nothing is kept that says a batch has followed. A batch is stopped when another label, or none, is in `following.json`, and no call writes its label there again. - So the next batch is one form, "New batch" with Follow, and a step never takes a row that another batch took since. - On the page, Follow is a state with one action, "Stop following", not a switch. diff --git a/docs/developer/tours/layers.html b/docs/developer/tours/layers.html index a996f9c7..e58381d0 100644 --- a/docs/developer/tours/layers.html +++ b/docs/developer/tours/layers.html @@ -181,11 +181,11 @@

essapps, layer by layer

return pd.DataFrame({'runs': runs.values()}, index=list(runs)) source = RowSource(angles, fills=('runs',), selector=Selector(role='sample')) -manager = BatchManager(client, sources={'angles': source}, - definitions=FolderDefinitions(folder)) -manager.create('stitch', title='reflectivity', source='angles', follow=True, - settings={'reference': file(run=500)}) -manager.step() # called every few seconds` }, +intake = Intake(BatchManager(client, definitions=FolderDefinitions(folder)), + sources={'angles': source}) +intake.create('stitch', title='reflectivity', source='angles', follow=True, + settings={'reference': file(run=500)}) +intake.step() # called every few seconds` }, { level: 11, caller: 'all', placement: 'service', planned: SERVICE, title: 'Many controllers, one history', body: `

All clients of a proposal share its history. A notebook can reference a transmission that the automatic reduction computed, and the app lists that record in its pickers.

Every client of a workspace reads the same values. The automatic reduction persists its outputs, so they outlive the workspace. A proposal has one workspace. Whether its users share the values in memory, or the service separates or bounds them per user, is open. Provenance follows each reference back to the files.

`, @@ -290,7 +290,7 @@

essapps, layer by layer

const CALLER_SMALL = [ h('Jupyter notebook', '', '
client.submit(IOFQ, ...)
'), h('Panel app', '', '
App(client)
'), - h('Automatic reduction', '', '
manager.step()
'), + h('Automatic reduction', '', '
intake.step()
'), ]; function layout(cfg, { box, arrow }) { @@ -405,8 +405,8 @@

essapps, layer by layer

caller: { notebook: `record = client.submit(SPEC, params={...})\nclient.output(record, ...)`, app: 'app = App(client)', - trigger: 'manager.step() # every few seconds', - all: '# each in its own process, with its own client\nclient.submit(SPEC, params={...})\nApp(client)\nmanager.step() # every few seconds', + trigger: 'intake.step() # every few seconds', + all: '# each in its own process, with its own client\nclient.submit(SPEC, params={...})\nApp(client)\nintake.step() # every few seconds', }, }; diff --git a/packages/essapps/docs/batch.md b/packages/essapps/docs/batch.md index b4c2683c..e6371383 100644 --- a/packages/essapps/docs/batch.md +++ b/packages/essapps/docs/batch.md @@ -19,6 +19,7 @@ flowchart TD notebook["notebook, test"] end subgraph layer ["batch layer"] + intake["intake: Intake"] manager["manager: BatchManager"] subgraph batch ["Batch"] settings @@ -31,9 +32,13 @@ flowchart TD client["Client: files, records"] callers --> batch callers --> manager + callers --> intake + intake --> manager + intake --> step + intake --> source + intake --> batch + intake --> definitions manager --> batch - manager --> step - manager --> source manager --> definitions step --> batch step --> source @@ -53,7 +58,8 @@ Nothing in the batch layer imports the page or the command. | batch | `reduction.py`: `Batch` | the settings and the batch table of one label: `put`, `state`, `reduce`, `cancel`, and `version`, which moves when the batch table, the settings or a record changes; the only part that submits to the client | | state | `state.py`: `RowState`, the rules | where each row stands; the rules are functions from the states of rows to keys | | step | `auto.py`: `step`, `Step` | one step of Follow on one batch: add rows of the source, reduce rows | -| manager | `manager.py`: `BatchManager` | the batches of a workspace: make, list, change, remove; which batch follows; `considered` | +| manager | `manager.py`: `BatchManager` | the batches of a workspace: make one from a table, list, change, remove; it knows no row source | +| intake | `intake.py`: `Intake` | rows of a row source into a batch: make a batch from a source, offer and take its rows; which batch follows, and its step; `considered` | | definitions | `definition.py`: `DefinitionStore`, `FolderDefinitions` | what a workspace keeps besides files and records (table below) | ### Terms @@ -62,7 +68,7 @@ Nothing in the batch layer imports the page or the command. |---|---| | workspace | a `Client` (specs bound, files, records) and the definitions; one folder | | batch | one spec reduced for many samples: a header (title, description), a spec, settings and a batch table | -| label | the name of a batch outside the process: its folder in the definitions, the label of its records, its address on the page and for the command. `manager.batch(label)` gives the `Batch`, the object that changes and reduces it | +| label | the name of a batch outside the process: its folder in the definitions, the label of its records, its address on the page and for the command. `create` returns the `Batch`, the object that changes and reduces it, and `batch.label` is its label; every other method that names a batch takes the label, and `manager.batch(label)` gives the `Batch` again | | setting | the value of a parameter for the batch: an entry of `batch.settings` | | batch table | the rows of a batch, one per reduction: one `pandas.DataFrame` (below) | | value of a parameter for a row | what the row is reduced with at that parameter (rule 2) | @@ -127,29 +133,35 @@ Other tables are always named with what they are of: 4. **A step never changes a row that the batch table has.** It adds rows, and reduces rows that have no result. 5. **A batch is shown without its source and without the files.** A file that is not found is a problem of its row. 6. **The rules are in the batch layer.** A refusal is a `ValueError`. The page and the command show it and copy no rule. The batch layer has no lock and no timer. -7. **Follow is chosen when a batch is made.** A batch follows from `create(..., follow=True)` until `stop()`, its removal, or the making of another batch that follows. A batch that does not follow cannot be made to follow. +7. **Follow is chosen when a batch is made.** A batch follows from `intake.create(..., follow=True)` until `intake.stop()`, its removal, or the making of another batch that follows. A batch that does not follow cannot be made to follow. ### What is kept on disk | File | Content | Writer | |---|---|---| | `definitions/labels/