diff --git a/docs/developer/README.md b/docs/developer/README.md
index ef89f6b0..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': Source(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..378abf30 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=...)`) |
@@ -78,8 +78,7 @@ So the records of a removed batch never show as results of another batch.
```
definitions/labels/20261118-130204/header.json {"title": "Afternoon, 2 mm cells", "description": "..."}
-definitions/labels/20261118-130204/... the settings and the table (ADR 0012), the source (ADR 0013)
-definitions/following.json {"label": "20261118-130204"}, or {"label": null}
+definitions/labels/20261118-130204/... the settings and the table (ADR 0012), the source and whether the batch follows (ADR 0013)
definitions/corrections.json metadata of runs set by hand
```
@@ -92,18 +91,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:
+`Intake` keeps which batch follows, if any:
```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.
+- Making a batch that follows stops the batch that followed before, first, so at most one batch follows.
+- `Intake` keeps it in the definitions of the batch (`"follows"` in its `source.json`), so a restart resumes, and removing the batch that follows ends Follow, also for a batch made again with the label.
+- Whoever serves the pages owns the timer that calls `step`. `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 14d53244..abadc934 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
@@ -42,8 +42,7 @@ def step(batch, source, considered):
### What is kept
```
-definitions/labels/20261118-130204/source.json {"source": "sample-runs", "considered": ["60337", "60338", "60339"]}
-definitions/following.json the label of the batch that follows, or none (ADR 0011)
+definitions/labels/20261118-130204/source.json {"source": "sample-runs", "considered": ["60337", "60338", "60339"], "follows": true}
```
- A key is *considered* by a batch once a row of that key was put into the batch from the source, or was filled and left out when the batch was made.
@@ -72,7 +71,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.
@@ -84,8 +83,8 @@ A source says which columns it fills (`Source.fills`, such as `sample` and `samp
`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 +115,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 +126,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,15 +135,15 @@ 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.
-- 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.
+- At most one batch follows, as in ADR 0011: `Intake` keeps whether a batch follows in its `source.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 `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 its `source.json` says that it does not follow, and no call writes that it follows 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.
@@ -175,7 +174,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..e58381d0 100644
--- a/docs/developer/tours/layers.html
+++ b/docs/developer/tours/layers.html
@@ -180,12 +180,12 @@
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'))
-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` },
+source = RowSource(angles, fills=('runs',), selector=Selector(role='sample'))
+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/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..0289410f 100644
--- a/packages/essapps/docs/batch.md
+++ b/packages/essapps/docs/batch.md
@@ -19,21 +19,26 @@ flowchart TD
notebook["notebook, test"]
end
subgraph layer ["batch layer"]
+ intake["Intake"]
manager["manager: BatchManager"]
subgraph batch ["Batch"]
settings
table["batch table"]
end
step["step: auto.step"]
- source["source: Source"]
+ source["source: RowSource"]
end
definitions["definitions"]
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
@@ -49,11 +54,12 @@ 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 |
-| 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,9 @@ 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, unique in a workspace: its folder in the definitions, the label of its records, its address on the page and for the command; `batch.label` |
+| `Batch` | the object that holds the settings and the batch table of one label, and changes and reduces them |
+| `Intake` | the object that holds the manager and the row sources, by name, and brings rows of a source into a batch; it keeps which batch follows |
| 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) |
@@ -71,11 +79,14 @@ 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 |
+`manager.create` and `intake.create` return the `Batch`, and `manager.batch(label)` gives it again.
+Every other method that names a batch takes its label.
+
The batch table of the example below, as `batch.frame()` gives it:
```python
@@ -88,7 +99,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 |
@@ -126,61 +137,70 @@ Other tables are always named with what they are of:
3. **The state is computed, never kept.** It is read from the records each time. Each rule (`ready`, `not_reduced`, `left_to_reduce`, `earlier_settings`, `to_reduce`) is a function from the states to keys.
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.
+6. **The rules are in the batch layer.** A refusal is a `ValueError`. The page and the command show it and copy no rule of the batch layer. The page refuses only a request that no call of the batch layer can express, such as Follow without a row source. The batch layer has no lock and no timer.
+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//header.json` | `{"title": ..., "description": ...}` | manager |
-| `definitions/labels//settings.json` | the spec, and the settings in `params`, also those of a parameter that has a column | `Batch` |
+| `definitions/labels//settings.json` | a template: the spec; the settings in `params`, also those of a parameter that has a column; `batch.fills` as its `blanks` | `Batch` |
| `definitions/labels//rows.json` | the batch table: `{"schema": ..., "data": [{"key": "60339", "sample": "run:60339", ...}]}` | `Batch.put` |
-| `definitions/labels//source.json` | `{"source": "sample-runs", "considered": ["60337", ...]}`; only for a batch made from a source | manager |
-| `definitions/following.json` | `{"label": ...}` or `{"label": null}` | manager |
+| `definitions/labels//source.json` | `{"source": "sample-runs", "considered": ["60337", ...], "follows": true}`; only for a batch made from a source | `Intake` |
| `definitions/corrections.json` | metadata of files set by hand | `CorrectedFiles` |
+| `definitions/format.json` | `{"format": 1}`: the format of the files above | `FolderDefinitions`, before its first write |
| `store/`, the log | the records | the workspace |
A label is a batch if and only if `header.json` exists.
-`create` writes settings, rows and source, then the header, then `following.json` if the batch follows.
-`remove` writes `following.json` first if the batch follows, then deletes the header, then the rest.
+`manager.create` writes rows and settings, then the header.
+`intake.create` then, if the batch follows, writes `"follows": false` to the `source.json` of the batch that followed, then writes the `source.json` of the batch; if the definitions refuse a write, it removes the batch again.
+So a batch of `intake.create` is not always made as asked or not at all: a process that stops between the header and the batch's `source.json` leaves a batch made without a source, which neither offers rows nor follows, and no batch that follows.
+`manager.remove` deletes the header, then every other file of the label, `source.json` too.
+So whether a batch follows goes with its label: a batch made again with the label does not follow unless made so.
Each file has one writer.
+`FolderDefinitions` refuses, with a `ValueError` that says "make a new folder", a folder with labels and no `format.json`, or another format.
+What the files mean changes with the format, such as where the fills of a batch are kept, and a folder read with the wrong meaning would reduce rows with wrong values; no folder is migrated.
+
`rows.json` has the shape that pandas writes with `to_json(orient='table')`: a schema with the dtype of each column, and one record per row.
The records are written and read as Python values and not by `to_json` and `read_json`, which round floats: `0.1 + 0.2` comes back as `0.3`.
A table file is written and read by pandas (`to_csv`, `read_csv`, `to_excel`, `read_excel`).
-`settings.json` has the form of a template file of the client; its `blanks` are not read, since the batch table says which parameters have a column.
+`settings.json` has the form of a template file of the client.
+Its `blanks` are the parameters that the row source of the batch fills (`batch.fills`): a template gives a blank no value, and each row must fill it.
+Which parameters have a column is said by the batch table; they are the blanks of `batch.template()`.
+A `source.json` is refused when read unless its entries are `source`, `considered` and `follows`.
## One example followed through
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.
```python
-manager.rows_of('sample-runs') # what the source makes now
+intake = Intake(manager, sources={'sample-runs': SAMPLE_RUNS})
+intake.rows_of('sample-runs') # what the source makes now
# run name sample sample_transmission
# key
# 60337 60337 water run:60337 run:60305
# ...
# 60340 60340 sample A run:60340 run:60306
-label = manager.create('loki-iofq', title='Afternoon', source='sample-runs',
- choose=Range(first='60339'), label='afternoon',
- follow=True)
+batch = intake.create('loki-iofq', title='Afternoon', source='sample-runs',
+ choose=Range(first='60339'), label='afternoon',
+ follow=True)
```
-`create` lists the source once and gives `choose` the rows that are filled; a `Range` picks those from 60339 on. In code, `choose` may be any function that picks rows and adds columns.
-On disk: `header.json`, `settings.json`, `rows.json` with rows 60339 and 60340, `source.json` with `considered` = 60337 to 60340, and `following.json` with `afternoon`.
+`intake.create` lists the source once and gives `choose` the rows that are filled; a `Range` picks those from 60339 on. In code, `choose` may be any function that picks rows and adds columns.
+On disk: `header.json`, `settings.json`, `rows.json` with rows 60339 and 60340, and `source.json` with `considered` = 60337 to 60340 and `"follows": true`.
Rows 60337 and 60338 are considered and not in the table: they were left out when the batch was made, so Follow never adds them.
A row that waits when the batch is made, such as a sample run whose transmission run is not listed yet, is neither taken nor considered: Follow adds it once it is filled.
**2. A person edits a cell and reduces.**
```python
-batch = manager.batch(label)
-table = batch.frame() # a copy of the table
+table = batch.frame() # a copy of the table; later: manager.batch('afternoon')
table.loc['60340', 'sample_transmission'] = 'run:60307'
batch.put(table)
batch.reduce(['60339', '60340']) # {key: Record}
@@ -202,7 +222,7 @@ batch.put(table) # row 60340 is outdated; 60339 still takes
A row added later, by a step of Follow, by `take` or by hand, takes 1.5 until its cell is set.
`batch.put(table.drop(columns='thickness'))` drops the column, and every row takes 1.5 again.
-**4. Follow adds a row once its transmission run is listed.** The page calls `manager.step()` every few seconds.
+**4. Follow adds a row once its transmission run is listed.** The page calls `intake.step()` every few seconds.
| | What happens | Table | `considered` |
|---|---|---|---|
@@ -212,7 +232,7 @@ A row added later, by a step of Follow, by `take` or by hand, takes 1.5 until it
| d | the transmission of sample 60339 is measured again | unchanged: row 60339 keeps its cell | unchanged |
```python
-done = manager.step() # a Step, or None if no batch follows
+done = intake.step() # a Step, or None if no batch follows
done.waiting # the keys of the rows that wait
done.refused # why rows of this step were refused, by key
done.records # the records of the rows reduced, by key
@@ -223,38 +243,39 @@ In step b, `rows.json` is written first, then `source.json`.
**5. A restart.** The process stops; sample run 60343 and its transmission run arrive meanwhile.
```python
-manager = BatchManager(client, sources={'sample-runs': SAMPLE_RUNS}, definitions=definitions)
-manager.following # 'afternoon'
-manager.step() # adds 60343 and reduces it
+manager = BatchManager(client, definitions=definitions)
+intake = Intake(manager, sources={'sample-runs': SAMPLE_RUNS})
+intake.following # 'afternoon'
+intake.step() # adds 60343 and reduces it
```
-The manager reads the headers and `following.json`.
-`manager.batch(label)` reads `settings.json` and `rows.json` and makes the `Batch`.
+The manager reads the headers; the `Intake` finds the batch that follows in their `source.json`.
+`manager.batch('afternoon')` reads `settings.json` and `rows.json` and makes the `Batch`.
The results are read from the records, so no row is reduced twice.
**6. The next batch.** In the evening a person wants the runs from 60400 on in a batch of their own.
They make it from the source, with the settings of the afternoon, and with Follow:
```python
-label = manager.create('loki-iofq', title='Evening', source='sample-runs',
- choose=Range(first='60400'),
- settings=manager.batch('afternoon').settings, label='evening',
- follow=True) # 'afternoon' stops following, and cannot follow again
+evening = intake.create('loki-iofq', title='Evening', source='sample-runs',
+ choose=Range(first='60400'),
+ settings=manager.batch('afternoon').settings, label='evening',
+ follow=True) # 'afternoon' stops following, and cannot follow again
```
No row moves between batches.
`afternoon` keeps its rows, also those from 60400 on that it added before, until a person removes them.
A batch that follows has no last row: the rows filled between a last row and the making would never be added.
-`create` refuses `follow=True` with a `Range` that has a `last` (see [The batches of a workspace](#the-batches-of-a-workspace)); a function as `choose` may pick any rows, and the filled rows it leaves out are considered.
+`intake.create` refuses `follow=True` with a `Range` that has a `last` (see [From a row source](#from-a-row-source)); a function as `choose` may pick any rows, and the filled rows it leaves out are considered.
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 +288,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)`.
@@ -275,7 +296,7 @@ SAMPLE_RUNS = Source(pair_by_sample, fills=('sample', 'sample_transmission'))
- `selector` (optional) chooses the files the source is given; raw files if not given.
- `rows_of(client, source)` calls the source on the files listed now. It adds an empty column for each of `fills` that the table lacks, so a batch made on an empty folder still has its columns.
- The page names a row by its note column `name` if the batch table has one, else by its key.
-- A source knows no spec. `fits(spec, source)` of `ess.apps.batch.manager` checks that each of `fills` is a parameter of the spec.
+- A source knows no spec. `fits(spec, source)` of `ess.apps.batch.intake` checks that each of `fills` is a parameter of the spec.
A source is plain code on plain data: test it on a list of `FileInfo`.
@@ -380,7 +401,7 @@ If that row's cell holds a value, the setting becomes it; if the cell is empty,
Without `key`, every row must take the same value; a batch whose cells are all empty, or that has no rows, keeps its setting.
It writes `settings.json`, if the setting changes, before `rows.json` without the column; a stop between the two leaves the column, whose empty cells take the value chosen.
-A batch made from a source keeps the parameters that its source fills, `batch.fills`, in `source.json` with the name of the source.
+A batch made from a row source keeps the parameters that its source fills, `batch.fills`, as the `blanks` of `settings.json`.
The manager gives them to the batch when it makes or reads it; it does not look up the source, so the command without `-s` reads them too.
The table keeps a column for each, since a row waits until its cell there is filled.
By the rule above, a setting there is never read; one that the definitions hold is left out when the batch is read, and gone at the next write of the settings.
@@ -439,7 +460,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.
@@ -471,48 +492,58 @@ It raises `SubmitError` naming the row and the column.
## The batches of a workspace
```python
-manager = BatchManager(client, sources={'sample-runs': SAMPLE_RUNS},
- definitions=FolderDefinitions(folder),
+manager = BatchManager(client, definitions=FolderDefinitions(folder),
settings={'loki-iofq': {...}}, # the first settings of a batch, by spec
staged=('loki-iofq',)) # the specs that run through a stage
-label = manager.create('loki-iofq', title='Water', rows=table) # label: the time if not given
+batch = manager.create('loki-iofq', title='Water', rows=table) # the Batch
+label = batch.label # the time of making if not given
manager.headers() # {label: Header(title, description)}
-manager.batch(label) # the one Batch of the label, made at the first call
-manager.source(label) # the name of its source, or None: it cannot follow
+manager.batch(label) # the one Batch of the label, made from the definitions at the first call
manager.change(label, title='Water, second try')
-manager.remove(label) # the definitions go; the records stay
+manager.remove(label) # every file of the label goes; the records stay
```
-`create` with `source=` takes its rows from the source, in one listing:
+`columns` are parameters that are columns of empty cells, besides those of the table.
-```python
-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
-```
+- `create` refuses an empty title, a label that has definitions or records, a spec that the workspace does not bind, and rows that `put` refuses. `manager.check(spec, title=..., label=...)` refuses the first three without rows, and `create` calls it first.
+- `fills=` names the parameters that a row source fills (`batch.fills`). `create` keeps them as the `blanks` of `settings.json`, refuses a table without one of their columns, and leaves out the settings there (`batch.settable`). Every other setting stays, at a column too. `Intake.create` gives them; code that makes a batch from a table leaves them out.
+- `manager.batch(label)` reads `settings.json`, with the fills as its blanks, and `rows.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.
+- A `Batch` made in code, `Batch(client, spec, label=..., settings=..., rows=...)`, is the same class without definitions: it keeps nothing.
+
+### From a row source
-A range of the rows that arrived, as a person picks it, is a `Range`, open at an end not given:
+An `Intake` holds the manager and the row sources, by name, and brings rows of a source into a batch:
```python
-manager.create('loki-iofq', title='Afternoon', source='sample-runs',
- choose=Range(first='60339'), columns=['thickness'])
-manager.marked('sample-runs', Range(first='60339'))
+intake = Intake(manager, sources={'sample-runs': SAMPLE_RUNS})
+batch = intake.create('loki-iofq', title='Afternoon', source='sample-runs',
+ choose=Range(first='60339'), columns=['thickness'])
+intake.rows_of('sample-runs') # what the source makes now
+intake.marked('sample-runs', Range(first='60339'))
# rows_of, with columns waits and taken
-manager.create(..., choose=Range(later=True), follow=True)
+intake.create(..., choose=Range(later=True), follow=True)
# no row now: Follow adds the rows that arrive later
+intake.source(batch.label) # 'sample-runs'; None for a batch made without a source: it cannot follow
```
-`Range` refuses an end that is not a key of the rows that arrived (a row that waits is not one), a first row after the last, and an end with `later=True`.
-`create` refuses a `Range` with a `last` and `follow=True`; a function as `choose` picks any rows, also with `follow=True`, and the filled rows it leaves out are considered.
-`columns` are parameters that are columns of empty cells, besides those of the table.
+`intake.create` takes the rows from the source, in one listing, then makes the batch with the manager:
-- `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.
-- 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.
-- A `Batch` made in code, `Batch(client, spec, label=..., settings=..., rows=...)`, is the same class without definitions: it keeps nothing.
+```python
+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
+batch = manager.create(spec, rows=table, fills=source.fills, ...)
+# with follow: "follows": false to the batch that followed
+# then source.json: the source, considered, and whether it follows
+```
+
+`Range` refuses an end that is not a key of the rows that arrived (a row that waits is not one), a first row after the last, and an end with `later=True`.
+`intake.create` refuses a `Range` with a `last` and `follow=True`; a function as `choose` picks any rows, also with `follow=True`, and the filled rows it leaves out are considered.
+It refuses a source that is not registered and a key from `choose` that is not in `arrived`, and refuses as `manager.create` does.
+It checks the label, the title and the spec first, with `manager.check`, so these refusals come before any of the source.
+If the process stops while a batch that follows is made, the batch may be there and no batch follow (see [What is kept on disk](#what-is-kept-on-disk)).
## Follow
@@ -524,19 +555,19 @@ stateDiagram-v2
follows: follows
still: does not follow
[*] --> still: create(...)
- [*] --> follows: create(source=..., follow=True)
+ [*] --> follows: intake.create(..., follow=True)
follows --> still: stop(), or another batch made with Follow
still --> removed: remove()
follows --> removed: remove()
```
```python
-manager.create(..., source='sample-runs', follow=True) # follows; the batch that followed stops
-manager.following # its label, or None
-manager.stop() # none follows; the batch that followed cannot follow again
-done = manager.step() # a Step, or None if none follows
-manager.offered(label) # the rows of the source that the table lacks, with a boolean column `waits`
-manager.take(label, keys) # put these rows as the source gives them now, then consider them
+intake.create(..., source='sample-runs', follow=True) # follows; the batch that followed stops
+intake.following # its label, or None
+intake.stop() # none follows; the batch that followed cannot follow again
+done = intake.step() # a Step, or None if none follows
+intake.offered(label) # the rows of the source that the table lacks, with a boolean column `waits`
+intake.take(label, keys) # put these rows as the source gives them now, then consider them
```
A step (`auto.step(batch, source, considered)`), as code:
@@ -556,14 +587,14 @@ One step of Follow, from the timer to `considered` kept:
```mermaid
sequenceDiagram
participant timer as timer: Pages.tick
- participant manager as manager: BatchManager
+ participant intake as intake: Intake
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()
- manager->>definitions: read source.json: the source, considered
- manager->>step: step(batch, source, considered)
+ timer->>intake: step()
+ intake->>definitions: read source.json: the source, considered
+ intake->>step: step(batch, source, considered)
step->>batch: frame()
step->>source: rows_of(client, source)
Note over source: lists the files
@@ -574,9 +605,9 @@ sequenceDiagram
batch->>definitions: write rows.json
end
step->>batch: reduce(rows ready and without a result)
- step-->>manager: Step: considered, refused, waiting, records
- manager->>definitions: write source.json: considered, if it changed
- manager-->>timer: Step
+ step-->>intake: Step: considered, refused, waiting, records
+ intake->>definitions: write source.json: considered, if it changed
+ intake-->>timer: Step
```
- A row is new if its key is neither considered nor in the table. A key of the source that the table has is considered, so a row added by hand, or by a step cut off before `source.json` is written, stays away once removed.
@@ -585,6 +616,7 @@ sequenceDiagram
- A row with a result is never reduced by a step, also when it is outdated, failed or cancelled.
- A row whose request is refused does not hold back the others; `done.refused` says why, and the next step tries again.
- A batch of the manager persists what it submits.
+- `manager.remove(label)` of the batch that follows ends Follow, since `source.json` goes with the label: `intake.following` is then `None`, and `intake.step()` does nothing. A batch made again with the label does not follow unless made so.
A source whose row grows, such as the runs of a sample so far, gives the grown list a new key:
@@ -597,9 +629,10 @@ after run 3: si@2,3,4 runs=[2, 3, 4] # listed after run 4: a new key too
Each list is a new row, which a step adds and reduces; the earlier rows keep their results.
The key names the whole list, since a step adds a row only under a key that is not considered.
-`step`, `offered` and `take` raise `ValueError` " was not made from a source of rows" for a batch without `source.json`.
+`offered` and `take` raise `ValueError` " was not made from a row source" for a batch without `source.json`.
+`step` takes no label: it steps the batch that follows, whose `source.json` says so.
`auto.step(batch, source, considered)` runs the same step on a `Batch` made in code, with `considered` in memory: give the next step `done.considered`.
-Whoever serves calls `manager.step()` on a timer, such as `every` of `ess.apps.batch.web.api`.
+Whoever serves calls `intake.step()` on a timer, such as `every` of `ess.apps.batch.web.api`.
## Table files and the command
@@ -654,15 +687,15 @@ A cell may name a record that still runs. If that record failed or was cancelled
## Where the definitions are kept
`DefinitionStore` is a protocol: `load(key, read)`, `save(key, data)`, `delete(key)`, `labels()`.
-A key is a tuple, such as `('labels', label, 'rows')` or `('following',)`.
+A key is a tuple, such as `('labels', label, 'rows')` or `('corrections',)`.
`FolderDefinitions(folder)` keeps each table of the definitions as a JSON file under `definitions/`, written whole through a temporary file.
`rows.json` holds `data_of(table)`, and `frame_of(data)` reads it back equal, dtypes and floats included; both are in `ess.apps.batch.table`.
A refused write raises `NotKept`.
## The page
-`ess.apps.batch.web` serves the manager as a page.
-`Pages` holds one lock over the manager; the app calls `Pages.tick`, and so `manager.step()`, on a timer.
+`ess.apps.batch.web` serves the batches of a manager as a page.
+`Pages(intake, ...)` takes the `Intake` and reaches the manager as `intake.manager`; it holds one lock over both, and the app calls `Pages.tick`, and so `intake.step()`, on a timer.
`Page` is the presenter of one batch: each action that changes rows builds a table and calls `put`.
The actions are described in [`batch/web/README.md`](../src/ess/apps/batch/web/README.md).
Each action of the page is one call of the batch layer:
@@ -672,21 +705,21 @@ Each action of the page is one call of the batch layer:
| an edit of cells, **+ Add row**, **Remove selected**, **Load table** | `batch.put(table)` |
| **Apply** | `batch.settings = settings` |
| **Reduce** and its ways | `batch.reduce(keys)` |
-| **+ New batch** | `manager.create(..., choose=Range(first, last, later), columns=...)` |
-| the range's marks | `manager.marked(source, choose)` |
-| **+ Add rows from the runs** | `manager.offered(label)`, then `manager.take(label, keys)` |
+| **+ New batch** | from a source `intake.create(..., choose=Range(first, last, later), columns=...)`; from a table file or without rows `manager.create(rows=..., columns=...)` |
+| the range's marks | `intake.marked(source, choose)` |
+| **+ Add rows from the runs** | `intake.offered(label)`, then `intake.take(label, keys)` |
| "Make this a column" | `batch.make_column(name)` |
| "Make this a setting" | `batch.values(name)`, then `batch.make_setting(name, key)` |
| the grey text of an empty cell | `batch.settings[name]`, else the default of the parameter |
-| **Follow** in **+ New batch** | `manager.create(..., follow=True)`; the timer calls `manager.step()` |
-| **Stop following** | `manager.stop()` |
+| **Follow** in **+ New batch** | `intake.create(..., follow=True)`; the timer calls `intake.step()` |
+| **Stop following** | `intake.stop()` |
| the column **Batches** of the Runs view | `batch.files()` of each batch, joined to the runs by identity |
## Testing an application
- Test the source on a list of `FileInfo`, without a workspace.
- Test the batch on `ess.apps.local()` or a folder workspace with fake workflows (`ess.apps.testing`). They start in milliseconds, and refuse and fail as real ones do.
-- Use `FolderDefinitions(tmp_path)`, and make the manager again to test a restart.
+- Use `FolderDefinitions(tmp_path)`, and make the manager and the `Intake` again to test a restart.
- `packages/essapps/tests/batch/toys.py` and `conftest.py` show the pattern.
## What it does not do
diff --git a/packages/essapps/src/ess/apps/batch/__init__.py b/packages/essapps/src/ess/apps/batch/__init__.py
index f7e939d1..8cfd9846 100644
--- a/packages/essapps/src/ess/apps/batch/__init__.py
+++ b/packages/essapps/src/ess/apps/batch/__init__.py
@@ -10,9 +10,10 @@
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, RowSource, Source, rows_of
+from .source import FileInfo, Range, RowFunction, RowSource, rows_of
from .state import (
RowState,
earlier_settings,
@@ -30,11 +31,12 @@
'FileInfo',
'FolderDefinitions',
'Header',
+ 'Intake',
'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..6469c844 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 (``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
@@ -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..1138d4dd 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,8 +81,9 @@
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 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 +94,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 +201,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
@@ -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 # 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
)
@@ -319,10 +320,10 @@ def main(argv: Sequence[str] | None = None) -> int:
f'--source {args.source} is not a name in --sources: '
f'{", ".join(args.sources) or "none given"}'
)
- definitions = FolderDefinitions(args.workspace)
try:
+ definitions = FolderDefinitions(args.workspace)
files = CorrectedFiles(folder_files(args.workspace), definitions=definitions)
- except ValueError as error:
+ except ValueError as error: # also definitions of another format
sys.stderr.write(f'{error}\n')
return 2
try:
diff --git a/packages/essapps/src/ess/apps/batch/definition.py b/packages/essapps/src/ess/apps/batch/definition.py
index 233293d8..0a7491ec 100644
--- a/packages/essapps/src/ess/apps/batch/definition.py
+++ b/packages/essapps/src/ess/apps/batch/definition.py
@@ -8,22 +8,21 @@
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, the Intake
+ keys of it that the batch has considered,
+ and whether the batch follows
The corrections are about files, and every batch of a workspace reads the
files through one :class:`~.corrections.CorrectedFiles`, so a workspace has
-one table of them. The following label is the workspace's too. The others are
-of a label. A :class:`DefinitionStore`, *the definitions*, keeps each table as
-plain data under a key::
+one table of them. The others are of a label, so removing a label removes
+them all, also whether its batch follows. A :class:`DefinitionStore`, *the
+definitions*, keeps each table as plain data under a key::
('corrections',)
- ('following',)
('labels', label, 'header')
('labels', label, 'settings')
('labels', label, 'rows')
@@ -38,16 +37,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`).
+ source {'source': 'sample-runs', 'considered': ['60337', '60338'],
+ 'follows': True}
+
+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 +65,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
@@ -75,7 +76,6 @@
"""Names a table: ``('corrections',)``, or ``('labels', label, part)``."""
CORRECTIONS: Key = ('corrections',)
-FOLLOWING: Key = ('following',)
def header_key(label: str) -> Key:
@@ -94,6 +94,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."""
@@ -124,18 +129,33 @@ def labels(self) -> list[str]:
_NAME_MAX = 255
"""The bytes of a file name, on the file systems of Linux and macOS."""
+# Moves with every change of what the kept files mean, such as where the fills
+# of a batch are kept, so that a folder of another format is refused, not read
+# wrong. No folder is migrated.
+FORMAT = 1
+"""The format of the files of :class:`FolderDefinitions`, in ``format.json``."""
+
+_FORMAT_KEY: Key = ('format',)
+
+
+class _Format(TypedDict):
+ format: int
+
+
+_FORMAT = TypeAdapter(_Format)
+
class FolderDefinitions:
"""
A :class:`DefinitionStore` of JSON files in ``definitions/`` of a
workspace's folder (see :mod:`ess.apps.folder`)::
+ definitions/format.json
definitions/corrections.json
definitions/labels/auto%2Fiofq/header.json
definitions/labels/auto%2Fiofq/settings.json
definitions/labels/auto%2Fiofq/rows.json
definitions/labels/auto%2Fiofq/source.json
- definitions/following.json
Each name of a key is a folder or a file, with ``/``, ``%`` and ``.``
written as ``%2F``, ``%25`` and ``%2E``, so that no label reaches out of
@@ -145,10 +165,27 @@ class FolderDefinitions:
file left by a write that was cut off stays, a few bytes, until its table
is deleted: a reader cannot tell it from that of a write of another
process that runs.
+
+ ``format.json`` holds ``{"format": FORMAT}`` (:data:`FORMAT`), written
+ before the first table of a folder without labels. Made on a folder with
+ labels and no ``format.json``, or another format, it raises
+ ``ValueError``: what the files mean may have changed, and no folder is
+ migrated.
"""
def __init__(self, directory: Path) -> None:
self._root = directory / 'definitions'
+ self._formatted = False # format.json is written before the first table
+ if not self.labels():
+ return
+ found = self.load(_FORMAT_KEY, lambda data: _checked(_FORMAT, data)['format'])
+ if found != FORMAT:
+ given = 'none (no format.json)' if found is None else found
+ raise ValueError(
+ f'{self._root}: the definitions are of format {given}, and this '
+ f'version reads format {FORMAT}; make a new folder'
+ )
+ self._formatted = True
def __str__(self) -> str:
return str(self._root)
@@ -180,7 +217,13 @@ def load[T](self, key: Key, read: Callable[[Any], T]) -> T | None:
raise ValueError(f'{path}: {error}') from None
def save(self, key: Key, data: Any) -> None:
- path = self.path(key)
+ if not self._formatted:
+ self._write(self.path(_FORMAT_KEY), {'format': FORMAT})
+ self._formatted = True
+ self._write(self.path(key), data)
+
+ def _write(self, path: Path, data: Any) -> None:
+ """Write ``data`` to ``path`` whole; :class:`NotKept` if refused."""
content = to_json(data, indent=1)
try:
path.parent.mkdir(parents=True, exist_ok=True)
@@ -258,25 +301,22 @@ 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;
+ 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 whether
+ the batch follows its source. Data with other entries, or without one of
+ these, is refused when read.
"""
+ __pydantic_config__ = ConfigDict(extra='forbid')
+
source: str
considered: frozenset[str]
- fills: tuple[str, ...]
-
-
-class _Following(TypedDict):
- label: str | None
+ follows: bool
_HEADER = TypeAdapter(Header)
_FROM_SOURCE = TypeAdapter(FromSource)
-_FOLLOWING = TypeAdapter(_Following)
_CORRECTIONS = TypeAdapter(dict[str, dict[str, Any]])
_TEMPLATE = TypeAdapter(Template)
@@ -323,20 +363,10 @@ def source_data(made: FromSource) -> dict[str, Any]:
return {
'source': made.source,
'considered': sorted(made.considered),
- 'fills': list(made.fills),
+ 'follows': made.follows,
}
def source_of(data: Any) -> FromSource:
"""The source of :func:`source_data`; ``ValueError`` names an entry."""
return _checked(_FROM_SOURCE, data)
-
-
-def following_data(label: str | None) -> dict[str, Any]:
- """The label that follows, or ``None`` if none does, as plain data."""
- return {'label': label}
-
-
-def following_of(data: Any) -> str | None:
- """The label of :func:`following_data`; ``ValueError`` names an entry."""
- return _checked(_FOLLOWING, data)['label']
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/intake.py b/packages/essapps/src/ess/apps/batch/intake.py
new file mode 100644
index 00000000..59cd234a
--- /dev/null
+++ b/packages/essapps/src/ess/apps/batch/intake.py
@@ -0,0 +1,446 @@
+# 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 one table of the definitions
+(:mod:`.definition`) for each batch made from a source::
+
+ source the source, the keys considered, and whether the batch follows
+
+Whether a batch follows is kept with its label, so a removal through the
+manager, which deletes every table of the label, ends Follow, and a batch
+made again with the label does not follow unless made so.
+:meth:`Intake.create` makes the batch with the manager, which writes its
+settings, rows and header; with ``follow``, it then ends Follow on the batch
+that followed; then it writes ``source``. So no two batches follow, also
+when a process stops in between. 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. :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 (
+ FromSource,
+ NotKept,
+ 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 change through the manager, such as a
+ removal, moves :attr:`.manager.BatchManager.version` instead, and
+ :attr:`following` is read again from the definitions after it.
+
+ 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._version = 0
+ # The batch that follows, as read when the manager had this version.
+ self._read: tuple[int, str | None] | None = None
+
+ @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 whose ``source.json`` says that it follows,
+ ``None`` if none does. It is read from the definitions at the first
+ call and whenever :attr:`.manager.BatchManager.version` moved since.
+ If several say so, which no call of ``Intake`` makes, it is the first
+ in the order of :meth:`~.manager.BatchManager.headers`.
+ """
+ version = self.manager.version
+ if self._read is None or self._read[0] != version:
+ self._read = (version, self._kept_following())
+ return self._read[1]
+
+ def _kept_following(self) -> str | None:
+ """
+ The first label whose ``source.json`` says that its batch follows. A
+ ``source.json`` that cannot be read is passed over: :meth:`source`
+ says why at the page of its batch, and the other pages still work.
+ """
+ for label in self.manager.headers():
+ try:
+ made = self._from(label)
+ except ValueError:
+ continue
+ if made is not None and made.follows:
+ return label
+ return None
+
+ def _set_following(self, label: str | None) -> None:
+ """Hold ``label`` as the batch that follows, as now written."""
+ self._read = (self.manager.version, label)
+ self._version += 1
+
+ def _write_follows(self, label: str, follows: bool) -> None:
+ """Write whether the batch of ``label`` follows."""
+ made = replace(self._made(label), follows=follows)
+ self.manager.definitions.save(source_key(label), source_data(made))
+
+ 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 (label := self.following) is None:
+ return
+ self._write_follows(label, False)
+ self._set_following(None)
+
+ 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 label and the spec are checked before the source is listed. The
+ manager writes the settings, the rows and the header; then, with
+ ``follow``, the ``source.json`` of the batch that followed says that
+ it follows no more; then the ``source.json`` of the batch is written.
+ If the definitions refuse one of these writes, the batch is removed
+ again (:meth:`~.manager.BatchManager.remove`), and the batch that
+ followed is written to follow again, if its Follow was ended. A process
+ that stops between the header and the batch's ``source.json`` leaves
+ a batch made without a source, which neither offers rows nor
+ follows, and no batch that 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'
+ )
+ # Checked before the source is listed, which may be slow or raise.
+ self.manager.check(spec, title=title, label=label)
+ 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)
+ before = self.following
+ batch = self.manager.create(
+ spec,
+ title=title,
+ rows=rows,
+ fills=found.fills,
+ columns=columns,
+ description=description,
+ settings=settings,
+ label=label,
+ )
+ made = FromSource(source, frozenset(arrived.index), follows=follow)
+ ended = None # the batch whose Follow was ended, to follow again
+ try:
+ if follow and before is not None:
+ self._write_follows(before, False)
+ ended = before
+ self.manager.definitions.save(source_key(batch.label), source_data(made))
+ except NotKept:
+ # The first error is what to say.
+ with suppress(NotKept):
+ self.manager.remove(batch.label)
+ if ended is not None:
+ with suppress(NotKept):
+ self._write_follows(ended, True)
+ raise
+ if follow:
+ self._set_following(batch.label)
+ 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 row source')
+ 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 1990f7a3..f003d005 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, the keys considered, and Intake; only for a
+ whether the batch follows 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, Source, filled, rows_of
from .table import frame_of, typed
-def fits(spec: WorkflowSpec[Any, Any], source: Source | 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, Source],
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,35 @@ 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: Source, 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; :meth:`check` comes first. 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,124 +172,81 @@ 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'
- )
+ self.check(spec, title=title, label=label)
if label is None:
stamp = time.strftime('%Y%m%d-%H%M%S')
label, n = stamp, 1
while self._taken(label):
n += 1
label = f'{stamp}-{n}'
- else:
- _check_label(label)
- if self._taken(label):
- raise ValueError(f'{label}: the label has definitions or records')
header = Header(title, description)
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
+ return batch
- def _source(self, name: str) -> Source:
- """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 check(self, spec: str, *, title: str, label: str | None) -> None:
+ """
+ Raise ``ValueError`` as :meth:`create` refuses ``spec``, ``title``
+ and ``label``, without rows: so a caller that lists rows first, such
+ as :meth:`.intake.Intake.create`, refuses in the same order.
+ """
+ if label is not None:
+ _check_label(label)
+ if self._taken(label):
+ raise ValueError(f'{label}: the label has definitions or records')
+ Header(title)
+ self.spec_named(spec)
def spec_named(self, spec: str) -> WorkflowSpec[Any, Any]:
"""
@@ -430,38 +260,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 +281,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 +316,7 @@ def _kept(
rows=rows,
staged=spec.name in self._staged,
persist=True,
- definitions=self._definitions,
+ definitions=self.definitions,
fills=fills,
)
@@ -534,126 +333,30 @@ 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.
+ Whether the batch follows is kept with the label, so it goes too.
"""
- 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 2581077b..754d4e84 100644
--- a/packages/essapps/src/ess/apps/batch/reduction.py
+++ b/packages/essapps/src/ess/apps/batch/reduction.py
@@ -159,19 +159,20 @@ 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.Source.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
----------
- columns:
+ parameter_columns:
The parameter columns of the table, in its order: the blanks of the
template.
settings_fields:
@@ -254,13 +255,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 +354,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 +391,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 +418,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()):
@@ -427,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:
@@ -451,7 +458,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 +476,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 +579,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 +654,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 +769,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..921ab6b0 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 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
@@ -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,
@@ -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/README.md b/packages/essapps/src/ess/apps/batch/web/README.md
index b9aa80b2..e14e4269 100644
--- a/packages/essapps/src/ess/apps/batch/web/README.md
+++ b/packages/essapps/src/ess/apps/batch/web/README.md
@@ -38,8 +38,8 @@ Each change of rows on the page, an edit of cells, **+ Add row**, **Remove selec
A run chosen in a cell is kept as the text of its file (`table.cell_of`).
**Load table** replaces the whole table, its columns too; the page then shows the cells and the settings form of the columns loaded.
It is refused while the settings form holds a change, which the new form would drop, as "Make this a column" and "Make this a setting" are.
-**+ Add rows from the runs**, on the page of a batch made from a source, lists the rows of the source that the table lacks (`BatchManager.offered`): those left out when the batch was made, those removed, those that wait for a run, marked, and, in a batch that does not follow, those filled after it was made or after it stopped.
-The rows a person picks are added as the source makes them now (`BatchManager.take`), and Follow does not add them again once removed; so a removed row comes back this way.
+**+ Add rows from the runs**, on the page of a batch made from a source, lists the rows of the source that the table lacks (`Intake.offered`): those left out when the batch was made, those removed, those that wait for a run, marked, and, in a batch that does not follow, those filled after it was made or after it stopped.
+The rows a person picks are added as the source makes them now (`Intake.take`), and Follow does not add them again once removed; so a removed row comes back this way.
"Make this a column", at a setting in the Settings tab, makes the parameter a column with an empty cell in each row (`Batch.make_column`); it is offered only for a parameter that is no column and whose cell the page edits.
The setting stays: a row whose cell is empty takes it, also a row added later, by Follow or by a person, until its cell is set.
@@ -79,13 +79,13 @@ Each state replaces the form, but not while the focused input holds a value type
A batch follows from the time it is made, if **Follow** is ticked in **+ New batch** (see [Making a batch](#making-a-batch)), until it is stopped.
At most one batch follows: making one with Follow stops the batch that followed before, and the list of batches marks the one that follows.
-The page of the batch that follows has **Stop following** next to **List runs again** (`POST api/follow/stop`, `BatchManager.stop`). It asks once, since the batch cannot follow again; rows that arrive later are then added with **+ Add rows from the runs**, or go to a new batch.
+The page of the batch that follows has **Stop following** next to **List runs again** (`POST api/follow/stop`, `Intake.stop`). It asks once, since the batch cannot follow again; rows that arrive later are then added with **+ Add rows from the runs**, or go to a new batch.
The page of a batch that does not follow has no Follow control.
-While a batch follows, a timer in the server runs a step every `interval` seconds (5 by default; `Pages(manager, interval=...)`, or `--interval SECONDS`), under the lock of every request, with or without a page open.
-A step is `BatchManager.step`:
+While a batch follows, a timer in the server runs a step every `interval` seconds (5 by default; `Pages(intake, interval=...)`, or `--interval SECONDS`), under the lock of every request, with or without a page open.
+A step is `Intake.step`:
```python
-done = manager.step() # a Step, None if no batch follows
+done = intake.step() # a Step, None if no batch follows
done.refused # why a row could not be submitted, by key
done.waiting # the keys of the rows of the source not filled yet
```
@@ -159,12 +159,12 @@ The page remembers in the session of the browser, so that a reload or a return t
| Field | What it is |
|---|---|
| Title, Description | the header of the batch; the title is required |
-| Rows | from a source that the application registers (`BatchManager(sources=...)`), from a table file, or "none: no rows" |
+| Rows | from a source that the application registers (`Intake(sources=...)`), from a table file, or "none: no rows" |
| Range | with a source: the first and the last row to take, each open if not chosen, among the rows that the source has filled now (`Range`); or, as the last choice of "From", no row now (`later`): the batch gets only the rows added later, by Follow if ticked, else with **+ Add rows from the runs**; the table below lists every row the source makes, marked by the server as taken, left out, or waiting (`GET api/sources/rows?name=...&first=...&last=...&later=...`) |
| Table file | from a table file: a `.csv`, `.tsv` or `.xlsx` file with a column `key` (`table.read_table`) |
| Workflow | a spec that the workspace binds and that has a parameter for each column that the source fills; any spec without a source |
| Settings | on the page of a batch: start with the settings of that batch, else with those that the application gives; a setting at a column ticked stays, and each row whose cell is empty takes it, also a row that Follow adds; a column that the source fills gets no setting |
-| Follow | with a source: add the rows that arrive later, and reduce them; off unless ticked. While ticked, the end of the range is open and cannot be chosen, since a last row would leave out the rows filled between it and the making for good; the manager refuses a last row with Follow (`BatchManager.create`). Beside it, how many rows taken are reduced at once, and the batch that follows now, which stops following if ticked |
+| Follow | with a source: add the rows that arrive later, and reduce them; off unless ticked. While ticked, the end of the range is open and cannot be chosen, since a last row would leave out the rows filled between it and the making for good; the `Intake` refuses a last row with Follow (`Intake.create`). Beside it, how many rows taken are reduced at once, and the batch that follows now, which stops following if ticked |
| Columns | the columns that the source fills, fixed; the other parameters of the spec whose cell the page edits, to tick (a group of fields, such as a Q binning, stays a setting); none for a table file, whose columns are those of the file |
**Make** sends the form to `POST api/batches`, or the file to `POST api/batches/table`, and the page shows the new batch in the Rows view.
@@ -176,21 +176,23 @@ In code:
```python
settings = manager.batch(other).settings # thickness among them
-label = manager.create(spec, title=title, source=source,
- choose=Range(first, last, later),
- columns=['thickness'], # ticked: an empty column
- settings=settings, # less those of source.fills
- follow=follow) # Follow ticked
+batch = intake.create(spec, title=title, source=source,
+ choose=Range(first, last, later),
+ columns=['thickness'], # ticked: an empty column
+ settings=settings, # less those of source.fills
+ follow=follow) # Follow ticked
+batch = manager.create(spec, title=title, rows=table, # from a table file, or rows=None
+ columns=['thickness'], settings=settings)
```
-The batch is made in one call, so it is made as asked or not at all; a batch that follows replaces the one before only if it is made.
+The batch is made in one call: a call that is refused leaves no batch, and a batch that follows replaces the one before only if it is made. A process that stops while a batch that follows is made may leave the batch made and no batch that follows ([What is kept on disk](../../../../../docs/batch.md#what-is-kept-on-disk)).
Opened on the page of a batch, the form starts at that batch's source, workflow, columns and settings, so the next batch is this form with a range that starts later, and Follow ticked by the person.
"From" starts at the first row, so a batch with Follow reduces every row taken again; "no row now" with Follow makes a batch of only the rows that arrive from now on.
A batch that follows and has no row yet says so where its rows would be.
Follow is off unless ticked, since it stops the batch that follows, for good, and reduces the rows taken within seconds, with the settings chosen.
-The choices come from `GET api/sources`; what can be made is decided by `BatchManager.create`, and what it refuses, such as an empty title, shows at the form, with nothing made.
+The choices come from `GET api/sources`; what can be made is decided by `Intake.create` and `BatchManager.create`, and what they refuse, such as an empty title, shows at the form, with nothing made.
**Make** is disabled while it is sent, so a double click makes one batch.
The new batch starts with the settings that the application gives its spec (`BatchManager(settings=...)`).
A source that no spec fits is not offered.
@@ -218,7 +220,7 @@ The page then shows `/` in place of the batch in the history of the browser: the
The web layer follows eight rules. Each says where a reader finds a kind of thing, so a change that breaks one needs a reason.
-1. **The batch layer decides.** Every rule of rows, settings, sources, reduction and Follow is in `ess.apps.batch`. The web layer says what the batch layer refuses in words for a person and copies no rule. The form in the browser may know a rule to be helpful, such as that a batch that follows has no last row, but the server does not decide it here.
+1. **The batch layer decides.** Every rule of rows, settings, sources, reduction and Follow is in `ess.apps.batch`. The web layer says what the batch layer refuses in words for a person and copies no rule of the batch layer. It refuses only a request that no call of the batch layer can express, such as Follow without a row source (`NewBatch`). The form in the browser may know a rule to be helpful, such as that a batch that follows has no last row, but the server does not decide it here.
2. **One lock.** `Pages.lock` is around every request, every step of Follow and every count. Each public method of `Pages` takes it, and a caller may hold it already; a property of `Pages` (`listing`, `files_version`, `runs_version`, `corrects_runs`) reads one value without it.
3. **Each piece of state has one owner, which alone writes it.**
@@ -246,15 +248,19 @@ flowchart TD
api["api: create_app, the timer"]
pages["Pages: one lock, the listing of the files, files_version"]
page["Page, one per batch: poll compares the versions"]
+ intake["Intake: version"]
manager["BatchManager: version"]
batch["Batch: version"]
browser -->|HTTP| api
api -->|"tick(), page(label), routes of the workspace"| pages
api -->|routes of a batch| page
- pages -->|"step(), create, remove, counts"| manager
+ pages -->|"step(), create from a source"| intake
+ pages -->|"create, remove, counts"| manager
page -->|"listing, what Follow said"| pages
- page -->|"batch(label), stop()"| manager
+ page -->|"offered, take, stop()"| intake
+ page -->|"batch(label), change"| manager
page -->|"put, reduce"| batch
+ intake --> manager
manager -->|one per label| batch
```
@@ -262,10 +268,10 @@ flowchart TD
|---|---|
| `static/` | the page: `index.html`, `app.js`, `tables.js`, `form.js`; what is shown: selection, filter, view, tab, sort, axes |
| `api.py` | HTTP: `create_app(pages)`; each action is a POST that answers with the new `State` (`models.py`), 422 `{message}`, or 404 for a label that is no batch |
-| `pages.py` | `Pages`: what the pages share, without HTTP: the manager, one lock around every request and step, the list of batches and its counts, making and removing a batch. It alone writes the listing of the files and its version, the corrections of runs, and the step of Follow (`tick`) and what it said |
-| `page.py` | `Page`: what the page of one batch does, without HTTP. It alone writes the settings form (a draft until Apply), the refusals and its version. Through the manager it writes its batch: the rows (each change a frame put to the batch), the settings at Apply, its header, Follow's stop. It asks `Pages` for the listing and for what to show of Follow |
+| `pages.py` | `Pages`: what the pages share, without HTTP: the `Intake` and its manager, one lock around every request and step, the list of batches and its counts, making and removing a batch. It alone writes the listing of the files and its version, the corrections of runs, and the step of Follow (`tick`) and what it said |
+| `page.py` | `Page`: what the page of one batch does, without HTTP. It alone writes the settings form (a draft until Apply), the refusals and its version. Through the manager and the `Intake` it writes its batch: the rows (each change a frame put to the batch), the settings at Apply, its header, the rows taken, Follow's stop. It asks `Pages` for the listing and for what to show of Follow |
| `refusals.py` | how `Pages` and `Page` refuse a request: `Problem` (422) or `Missing` (404); how an exception of the batch layer reads as a message (`why`, `kept`), and which exceptions of a source are said (`refused`: `ValueError`, `KeyError`, `OSError`; anything else is a defect) |
-| `ess.apps.batch` | the logic: `BatchManager`, `step`, `Batch`, `table`, states, `CorrectedFiles`; shared with the command `essapps-batch` |
+| `ess.apps.batch` | the logic: `BatchManager`, `Intake`, `step`, `Batch`, `table`, states, `CorrectedFiles`; shared with the command `essapps-batch` |
`/docs` on a running server lists the API.
@@ -332,8 +338,8 @@ parent.mount('/batch', batch)
## Where the definition is kept
-The headers, the tables, the settings, the batch that follows, and the corrections of runs are the definitions of the workspace.
-The demo and the LoKI page give the manager and the file source the folder's definitions, `FOLDER/definitions/` (`ess.apps.batch.FolderDefinitions`), so a restart shows the batches, their definitions and the batch that follows again.
+The headers, the tables, the settings, the batch that follows, and the corrections of runs are the definitions of the workspace. A folder whose definitions are of another format is refused when the page starts (`FolderDefinitions`).
+The demo and the LoKI page give the manager, and so the `Intake`, and the file source the folder's definitions, `FOLDER/definitions/` (`ess.apps.batch.FolderDefinitions`), so a restart shows the batches, their definitions and the batch that follows again.
The settings form is a draft of the batch's settings: **Apply** writes it to the batch, and so to the definitions. A draft not applied is lost when the server stops.
Results are records of the workspace, in `FOLDER/store/`.
See [Where the definitions are kept](../../../../../docs/batch.md#where-the-definitions-are-kept).
diff --git a/packages/essapps/src/ess/apps/batch/web/demo.py b/packages/essapps/src/ess/apps/batch/web/demo.py
index 5d9ddc6b..add047d4 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, Source
+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
@@ -206,7 +213,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."""
@@ -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},
@@ -409,7 +416,10 @@ def arrive(group: list[Run]) -> None:
def _serve(directory: Path, port: int, *, interval: float, samples: int) -> None:
import uvicorn
- client, files, definitions = open_demo(directory, samples=samples)
+ try:
+ client, files, definitions = open_demo(directory, samples=samples)
+ except ValueError as error: # such as definitions of another format
+ raise SystemExit(str(error)) from None
with client:
folder = directory.name
app = build(client, files, definitions, folder=folder, interval=interval)
diff --git a/packages/essapps/src/ess/apps/batch/web/models.py b/packages/essapps/src/ess/apps/batch/web/models.py
index 2d022b73..333cc48a 100644
--- a/packages/essapps/src/ess/apps/batch/web/models.py
+++ b/packages/essapps/src/ess/apps/batch/web/models.py
@@ -14,9 +14,9 @@
from __future__ import annotations
from datetime import datetime
-from typing import Any, Literal
+from typing import Any, Literal, Self
-from pydantic import BaseModel
+from pydantic import BaseModel, model_validator
class Way(BaseModel):
@@ -422,8 +422,10 @@ class NewBatch(BaseModel):
those that the application gives ``spec``; a setting at a column stays,
the value of each row whose cell is empty, but at a column that the
source fills. With ``follow``, the batch follows its source from then
- on, in place of the batch that followed before; the manager refuses it
- with a ``last``.
+ on, in place of the batch that followed before; the
+ :class:`~ess.apps.batch.Intake`
+ refuses it with a ``last``. A ``follow`` without a ``source`` is refused
+ here, since no call of the batch layer can express it.
"""
title: str
@@ -437,6 +439,12 @@ class NewBatch(BaseModel):
later: bool = False
follow: bool = False
+ @model_validator(mode='after')
+ def _follows_a_source(self) -> Self:
+ if self.follow and self.source is None:
+ raise ValueError('a batch follows its source, and none is given')
+ return self
+
class Value(BaseModel):
"""A value of a column, as ``text``, and the ``key`` of a row that has it."""
diff --git a/packages/essapps/src/ess/apps/batch/web/page.py b/packages/essapps/src/ess/apps/batch/web/page.py
index 2bd30be6..2f3a02d0 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]:
@@ -393,18 +393,18 @@ 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()
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),
)
@@ -455,7 +456,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 +522,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)
@@ -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,
@@ -705,7 +706,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 +749,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:
@@ -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 ``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))}.'
@@ -921,7 +922,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
@@ -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:
@@ -1010,7 +1011,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 +1021,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}
@@ -1039,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:
@@ -1102,7 +1107,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..2d5a69ff 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
+``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,8 +69,8 @@
from ...listing import Listing
from ..auto import Step
from ..corrections import CorrectedFiles
-from ..manager import BatchManager, fits
-from ..source import Range, Source
+from ..intake import Intake, fits
+from ..source import Range, RowSource
from ..state import RowState, not_reduced
from ..table import read_table
from . import forms
@@ -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,12 +494,12 @@ 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
- 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,
@@ -509,7 +511,7 @@ def choice(name: str | None, source: Source | 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,21 +525,22 @@ 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
- (: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
+ Make the batch of ``new`` in one call, with the :class:`Intake` if it
+ has a source (:meth:`~ess.apps.batch.Intake.create`), else with the
+ manager (:meth:`~ess.apps.batch.BatchManager.create`), so that a
+ refusal leaves no batch: with a source, of the rows of the
:class:`~ess.apps.batch.Range` of ``new.first``, ``new.last`` and
``new.later`` of those that the source has filled now, with an empty
column for each other of ``new.columns``; with a table ``file``, its
@@ -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,
- whose cells are those of the source.
+ the :class:`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 :class:`Intake` 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`).
"""
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,28 @@ 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)
+ 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 +613,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 +632,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 822914ad..97c71480 100644
--- a/packages/essapps/tests/batch/auto_test.py
+++ b/packages/essapps/tests/batch/auto_test.py
@@ -21,9 +21,10 @@
CorrectedFiles,
FileInfo,
FolderDefinitions,
+ Intake,
NotKept,
+ RowFunction,
RowSource,
- Source,
rows_of,
)
from ess.apps.batch.auto import Step, added, step
@@ -62,7 +63,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 +83,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 +127,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 +183,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 +487,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)]
@@ -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'}
@@ -689,40 +693,46 @@ 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)
- manager = BatchManager(client, sources={'pairs': thick}, definitions=definitions)
- from_pairs(manager, PLAIN.name, title='A', label='a', follow=True)
+ thick = RowSource(_changed(pair, **{'1': {'thickness': 'thick'}}), PAIRS.fills)
+ 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 6a1d2bd1..605422fc 100644
--- a/packages/essapps/tests/batch/definition_test.py
+++ b/packages/essapps/tests/batch/definition_test.py
@@ -2,6 +2,7 @@
# Copyright (c) 2026 Scipp contributors (https://github.com/scipp)
"""The definition of batches kept in a folder workspace, opened twice."""
+import json
import re
from collections.abc import Callable, Iterator, Sequence
from contextlib import AbstractContextManager, contextmanager
@@ -19,16 +20,15 @@
FileInfo,
FolderDefinitions,
Header,
+ Intake,
NotKept,
- Source,
+ RowSource,
)
from ess.apps.batch.definition import (
CORRECTIONS,
- FOLLOWING,
+ FORMAT,
FromSource,
Key,
- following_data,
- following_of,
header_data,
header_key,
header_of,
@@ -63,22 +63,25 @@ 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]]]
+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 +89,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 +107,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 +117,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 +134,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 +174,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 +206,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 +249,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 +259,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()
@@ -342,7 +345,7 @@ def test_deleting_a_part_never_kept_does_nothing(folder: Path) -> None:
store.save(rows_key('a'), {})
store.delete(rows_key('b'))
- store.delete(FOLLOWING)
+ store.delete(source_key('a'))
assert store.labels() == ['a']
@@ -369,24 +372,40 @@ 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'}), follows=True)
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', 'follows': False})
with pytest.raises(ValueError, match=r'source\.json: considered: '):
store.load(key, source_of)
+ store.save(key, {'source': 'pairs', 'considered': ['60339']})
+ with pytest.raises(ValueError, match=r'source\.json: follows: Field required'):
+ store.load(key, source_of)
-@pytest.mark.parametrize('label', ['20261118-130204', None])
-def test_the_label_that_follows_is_kept_and_read_back(
- folder: Path, label: str | None
-) -> None:
+def test_a_folder_gets_the_format_with_its_first_definitions(folder: Path) -> None:
store = FolderDefinitions(folder)
+ store.save(rows_key('a'), {})
- store.save(FOLLOWING, following_data(label))
+ format_file = folder / 'definitions' / 'format.json'
+ assert json.loads(format_file.read_text()) == {'format': FORMAT}
+ assert FolderDefinitions(folder).labels() == ['a']
- assert store.load(FOLLOWING, following_of) == label
+
+@pytest.mark.parametrize(('kept', 'said'), [(None, 'none'), (FORMAT + 1, FORMAT + 1)])
+def test_a_folder_of_definitions_of_another_format_is_refused(
+ folder: Path, kept: int | None, said: object
+) -> None:
+ FolderDefinitions(folder).save(rows_key('a'), {})
+ format_file = folder / 'definitions' / 'format.json'
+ if kept is None:
+ format_file.unlink()
+ else:
+ format_file.write_text(json.dumps({'format': kept}))
+
+ with pytest.raises(ValueError, match=f'format {said}.*make a new folder'):
+ FolderDefinitions(folder)
diff --git a/packages/essapps/tests/batch/files_test.py b/packages/essapps/tests/batch/files_test.py
index 749f1227..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,
)
@@ -58,7 +59,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 +128,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}
'''
@@ -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(
@@ -835,10 +837,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/intake_test.py b/packages/essapps/tests/batch/intake_test.py
new file mode 100644
index 00000000..753cb9d1
--- /dev/null
+++ b/packages/essapps/tests/batch/intake_test.py
@@ -0,0 +1,649 @@
+# 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,
+ RowSource,
+)
+from ess.apps.batch.definition import (
+ 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 row source'):
+ intake.offered('a')
+ with pytest.raises(ValueError, match='a was not made from a row 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 _broken(files: Any) -> pd.DataFrame:
+ raise AssertionError('the source is listed')
+
+
+@pytest.mark.parametrize(
+ ('spec', 'title', 'label', 'said'),
+ [
+ ('iofq', 'A', None, 'no spec iofq'),
+ ('plain', ' ', None, 'a title that is not empty'),
+ ('plain', 'A', 'a/b', 'a label is'),
+ ],
+)
+def test_a_spec_title_or_label_is_refused_before_the_source_is_looked_up(
+ manager: BatchManager, spec: str, title: str, label: str | None, said: str
+) -> None:
+ intake = Intake(manager, sources={'broken': RowSource(_broken, fills=())})
+
+ for source in ('broken', 'nope'):
+ with pytest.raises(ValueError, match=said):
+ intake.create(spec, title=title, source=source, label=label)
+
+
+# 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 _follows(definitions: FolderDefinitions) -> list[str]:
+ """The labels whose ``source.json`` says that they follow."""
+ return [
+ label
+ for label in definitions.labels()
+ if (made := definitions.load(source_key(label), source_of)) is not None
+ and made.follows
+ ]
+
+
+def test_a_source_json_that_cannot_be_read_hides_neither_follow_nor_other_batches(
+ two: Intake, client: Client, definitions: FolderDefinitions
+) -> None:
+ two.create('plain', title='C', source='pairs', label='c', follow=True)
+ definitions.save(source_key('a'), {'source': 'pairs'})
+ again = _again(client, definitions)
+
+ assert again.following == 'c'
+ assert again.source('b') == 'pairs'
+ with pytest.raises(ValueError, match=r'source\.json: considered: '):
+ again.source('a')
+
+
+def test_a_batch_made_to_follow_ends_follow_on_the_one_before_then_writes_its_own(
+ two: Intake, refusing: Refusing, definitions: FolderDefinitions
+) -> None:
+ two.create('plain', title='C', source='pairs', label='c', follow=True)
+
+ assert refusing.saved[-3:] == [header_key('c'), source_key('a'), source_key('c')]
+ assert _follows(definitions) == ['c']
+
+
+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
+
+
+@pytest.mark.parametrize(
+ 'remake',
+ [
+ lambda i: i.manager.create('plain', title='A again', label='a'),
+ lambda i: i.create('plain', title='A again', source='pairs', label='a'),
+ ],
+ ids=['manager', 'intake'],
+)
+def test_a_label_removed_and_made_again_without_follow_does_not_follow(
+ two: Intake,
+ client: Client,
+ definitions: FolderDefinitions,
+ remake: Callable[[Intake], object],
+) -> None:
+ two.manager.remove('a')
+ remake(two)
+
+ assert two.following is None
+ assert _again(client, definitions).following is None
+
+
+class _Counting(Refusing):
+ """:class:`Refusing` that counts the tables loaded."""
+
+ def __init__(self, definitions: FolderDefinitions) -> None:
+ super().__init__(definitions)
+ self.loads = 0
+
+ def load[T](self, key: Key, read: Callable[[Any], T]) -> T | None:
+ self.loads += 1
+ return super().load(key, read)
+
+
+def test_which_batch_follows_is_read_again_only_after_a_change_of_the_headers(
+ two: Intake, client: Client, definitions: FolderDefinitions
+) -> None:
+ counting = _Counting(definitions)
+ intake = Intake(BatchManager(client, definitions=counting), sources=SOURCES)
+ assert intake.following == 'a'
+ loads = counting.loads
+
+ assert intake.following == 'a'
+ assert counting.loads == loads
+ intake.manager.change('b', title='B again')
+ assert intake.following == 'a'
+ assert counting.loads > loads
+
+
+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 = source_key('a')
+
+ 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 06ee9f65..31fe5a73 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,16 +71,15 @@ 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.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 +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).columns == ('thickness', 'transmission', 'sample')
- assert manager.batch(empty).columns == ()
+ assert chosen.parameter_columns == ('thickness', 'transmission', 'sample')
+ assert empty.parameter_columns == ()
@pytest.mark.parametrize(
@@ -141,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
@@ -164,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 with_defaults.batch(label).settings == {'thickness': 3.0}
+ 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 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(
@@ -204,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:
@@ -246,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:
@@ -267,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
@@ -278,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(
@@ -289,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]
@@ -304,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')
@@ -315,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']))
@@ -356,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(
@@ -399,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(
@@ -416,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)
@@ -434,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)
@@ -444,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):
@@ -457,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(
@@ -967,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
@@ -1015,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',
@@ -1027,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:
@@ -1035,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(
@@ -1049,22 +564,22 @@ 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'}
- assert again.following == 'z'
+ # No batch a, or one made without a source; z follows still, or
+ # none does if the cut came after Follow on z ended.
+ again = _intake(client, definitions)
+ assert set(again.manager.headers()) - {'z'} <= {'a'}
+ assert again.following in ('z', None)
_made_again(client, definitions, follow=True)
else:
break
- assert at > 5 # settings, rows, source, header, following
+ assert at > 5 # rows, settings, header, source of z, source of a
def test_a_remove_cut_off_at_any_write_leaves_what_remove_removes(
@@ -1073,13 +588,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=True)
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/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..7aaedb3a 100644
--- a/packages/essapps/tests/batch/toys.py
+++ b/packages/essapps/tests/batch/toys.py
@@ -15,11 +15,11 @@
from ess.apps import Client
from ess.apps.batch import (
Batch,
- BatchManager,
DefinitionStore,
FileInfo,
+ Intake,
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."""
@@ -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 b813c636..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')
@@ -1505,8 +1505,12 @@ 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.following is None # Follow is off unless ticked
+ assert manager.batch(label).parameter_columns == (
+ 'sample',
+ 'transmission',
+ 'thickness',
+ )
+ assert intake.following is None # Follow is off unless ticked
assert page.is_hidden('#stop-follow')
@@ -1531,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.")')
@@ -1553,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:
@@ -1576,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')
@@ -1596,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}")')
@@ -1787,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/')
@@ -1843,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]')
@@ -1865,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 ce1ff4d6..8bef4072 100644
--- a/packages/essapps/tests/batch/web_test.py
+++ b/packages/essapps/tests/batch/web_test.py
@@ -29,7 +29,8 @@
DefinitionStore,
FolderDefinitions,
Header,
- Source,
+ Intake,
+ 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
@@ -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
@@ -818,7 +822,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.'}
@@ -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')
@@ -1426,7 +1432,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']]
@@ -1454,8 +1460,8 @@ 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')
- assert batch.columns == ('sample', 'transmission', 'thickness')
+ 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]
@@ -1488,7 +1494,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 +1525,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 +1546,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
@@ -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')
@@ -2091,10 +2096,10 @@ 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'))
- manager = BatchManager(client, sources={'odd': odd}, definitions=definitions)
+ odd = RowSource(pair, fills=('sample', 'background'))
+ 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,40 +2127,34 @@ 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 (refused.status_code, refused.json()) == (
- 422,
- {
- 'message': 'The batch was not made: '
- 'a batch follows its source, and none is given.'
- },
- )
+ assert intake.following == made['label']
+ assert refused.status_code == 422
+ [error] = refused.json()['detail']
+ assert error['msg'].endswith('a batch follows its source, and none is given')
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())
@@ -2171,7 +2170,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,
@@ -2224,7 +2223,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 +2232,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 +2297,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 +2306,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(
@@ -2358,7 +2362,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]
@@ -2366,7 +2370,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,16 +2418,16 @@ 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'
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 intake.source(made['label']) is None
assert manager.headers()[made['label']].title == 'From a file'
@@ -2512,12 +2515,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 +2547,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,17 +2641,18 @@ 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'
+ refusing.part = 'source'
answer = http.post('/api/batches', json=new_batch(follow=True))
- assert (answer.status_code, answer.json()) == (
- 422,
- {'message': "The change was not kept: ('following',): refused"},
+ assert answer.status_code == 422
+ assert re.fullmatch(
+ r"The change was not kept: \('labels', '[\d-]+', 'source'\): refused",
+ answer.json()['message'],
)
- 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 +2698,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 +2719,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 +2756,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/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/docs/loki-batch.ipynb b/packages/essinstruments/docs/loki-batch.ipynb
index a2fd7e85..238308fe 100644
--- a/packages/essinstruments/docs/loki-batch.ipynb
+++ b/packages/essinstruments/docs/loki-batch.ipynb
@@ -191,7 +191,7 @@
"source": [
"## The table of rows\n",
"\n",
- "`rows_of` gives the table that LoKI's source of rows makes from the files: `pair_by_sample` makes a row for each sample run, with the transmission run of the same sample.\n",
+ "`rows_of` gives the table that LoKI's row source makes from the files: `pair_by_sample` makes a row for each sample run, with the transmission run of the same sample.\n",
"The key of a row is its run, and is the index of the table.\n",
"A cell names a file as the workspace identifies it, here by its path."
]
diff --git a/packages/essinstruments/src/ess/instruments/loki/batch.py b/packages/essinstruments/src/ess/instruments/loki/batch.py
index 5bb97be9..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)
@@ -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/src/ess/instruments/loki/web.py b/packages/essinstruments/src/ess/instruments/loki/web.py
index 651d4faa..e39b1198 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)},
@@ -167,7 +167,10 @@ def main() -> None:
args = parser.parse_args()
if not (STATIC / 'vendor').is_dir():
parser.exit(1, f'The page needs its libraries: sh {STATIC / "vendor.sh"}\n')
- client, files, definitions = open_loki(args.folder)
+ try:
+ client, files, definitions = open_loki(args.folder)
+ except ValueError as error: # such as definitions of another format
+ parser.exit(1, f'{error}\n')
with client:
folder = args.folder.resolve().name
app = build(client, files, definitions, folder=folder, interval=args.interval)
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
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']]