diff --git a/README.md b/README.md index 3b0834a14..a774f33bf 100644 --- a/README.md +++ b/README.md @@ -99,9 +99,10 @@ session. - [Getting Started](https://github.com/metamorphic-labs/orcapod-python/blob/main/docs/getting-started.md): sources, streams and function pods, step by step. -- [Tutorial](https://github.com/metamorphic-labs/orcapod-python/blob/main/docs/tutorial/index.md): - a self-paced course in eleven short parts, from a first stream to a stored, re-runnable - pipeline over files, with exercises. +- [Tutorials](https://github.com/metamorphic-labs/orcapod-python/blob/main/docs/tutorial/index.md): + a self-paced core course in seven parts, from a first stream to a stored, re-runnable + pipeline, and short tutorials on files, inspecting results, tracing a value, chaining + pipelines and handling errors, with exercises. - [Concepts](https://github.com/metamorphic-labs/orcapod-python/tree/main/docs/concepts): sources, streams, function pods, operators, pipelines and jobs, identity and hashing, file types, arrays and your own data types. diff --git a/changelog.d/ITL-1460.md b/changelog.d/ITL-1460.md new file mode 100644 index 000000000..4430c0602 --- /dev/null +++ b/changelog.d/ITL-1460.md @@ -0,0 +1,9 @@ +### Changed + +- The tutorial section is "Tutorials": a core course (Parts 0 to 6) and short tutorials that + each cover one subject and can be read in any order afterwards. Part 8 is split into + "Inspecting results", "Tracing a value" and "Chaining pipelines"; Parts 7, 9 and 10 are + "Working with files", "Handling errors" and "Where next". Their pages have new addresses + (`docs/tutorial/files.md`, `inspecting-results.md`, `tracing-a-value.md`, + `chaining-pipelines.md`, `handling-errors.md`, `where-next.md`). The pages list a job's + steps with `print(job.diagram())`. (ITL-1460) diff --git a/docs/concepts/file-types.md b/docs/concepts/file-types.md index 7b435d582..73de2c2f3 100644 --- a/docs/concepts/file-types.md +++ b/docs/concepts/file-types.md @@ -4,7 +4,7 @@ Pipelines over scientific data pass references to files between steps. Orcapod h for this, and the choice of type decides **what a result's validity depends on**: the content of the file, or only its location. -For a guided introduction see the tutorial, [Part 7](../tutorial/07-files.md). +For a guided introduction see the tutorial [Working with files](../tutorial/files.md). ## The types diff --git a/docs/concepts/notebooks.md b/docs/concepts/notebooks.md index f46a88c72..4a8f4e9c1 100644 --- a/docs/concepts/notebooks.md +++ b/docs/concepts/notebooks.md @@ -218,7 +218,7 @@ print(job.nodes["rates"].run().header()) A view holds the default columns only (tags and data). For system tags, source info and the other hidden columns, ask the node: `as_table(columns=...)`, as in -[Part 8 of the tutorial](../tutorial/08-inspecting-and-tracing.md). `run()` on each kind of +the tutorial [Inspecting results](../tutorial/inspecting-results.md#tracing-rows). `run()` on each kind of object is the table "What `run()` does on each kind of object" in [Streams](streams.md#computing-a-stream-outside-a-job-run). diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index a8f19817a..41a19df1b 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -58,8 +58,8 @@ The three stages: and failed; see [Reading the run summary](function-pods.md#reading-the-run-summary). -Among `job.run()`'s optional arguments, the tutorial's -[Part 9](../tutorial/09-when-things-go-wrong.md) demonstrates `orchestrator=` (for example +Among `job.run()`'s optional arguments, the tutorial +[Handling errors](../tutorial/handling-errors.md) demonstrates `orchestrator=` (for example `SyncPipelineOrchestrator(error_policy="fail_fast")` to stop at the first failing row; the default policy skips failed rows and continues) and `observer=` (`StatusObserver`, `LoggingObserver`) to record what happened during the run. An observer only watches: one diff --git a/docs/concepts/provenance.md b/docs/concepts/provenance.md index 36c0d1878..8bc650427 100644 --- a/docs/concepts/provenance.md +++ b/docs/concepts/provenance.md @@ -192,7 +192,7 @@ The result is an `Absence`. Its fields hold: - `removed_by`: the step that removed it, a `Step`; - `because`: the reason, in words. -Tutorial [Part 8](../tutorial/08-inspecting-and-tracing.md) shows a row removed by a filter +The tutorial [Tracing a value](../tutorial/tracing-a-value.md#missing-rows) shows a row removed by a filter and one removed by a join. ## On the diagram @@ -247,7 +247,7 @@ print(warm.highlight().marks == trace.highlight().marks) ``` In a notebook the diagram is drawn as a picture, the mark as a bold line on its node. Here -is the job of tutorial [Part 8](../tutorial/08-inspecting-and-tracing.md), first plain, +is the job of the tutorial [Tracing a value](../tutorial/tracing-a-value.md), first plain, then with the trace of one firing rate highlighted. Its path stops at `rates`: the grouping after it is dimmed. That rate reused the result an equal input had computed, so `rates` is marked `reused`: diff --git a/docs/dev/documentation-style.md b/docs/dev/documentation-style.md index 86475c036..3b6d71abc 100644 --- a/docs/dev/documentation-style.md +++ b/docs/dev/documentation-style.md @@ -60,3 +60,8 @@ dot is **not** enough." - "Key points" ends the text, before the exercises. It repeats what the part taught and adds nothing: no new term, link or feature, and no preview of the next part. - No "Next: ..." line. The site has its own next-page link. +- The section is a core course (Parts 0 to 6, read in order) and short tutorials on one subject + each (ITL-1460). A short tutorial has no part number, says which core parts it needs in a + "**Before you start:**" line after its opening, and runs on its own from `make_dataset()`. +- List a job's steps with `print(job.diagram())`; do not write a helper that walks + `node.upstreams`. diff --git a/docs/dev/scripts/provenance_diagrams.py b/docs/dev/scripts/provenance_diagrams.py index b51dd9338..7955214db 100644 --- a/docs/dev/scripts/provenance_diagrams.py +++ b/docs/dev/scripts/provenance_diagrams.py @@ -2,7 +2,7 @@ The pictures are drawn by Orcapod itself (``job.diagram(highlight=...)``) from the tutorial's synthetic dataset (``docs/tutorial/workshop_data.py``), over the pipelines of -tutorial Part 8. Each is the diagram's standalone SVG (the image a notebook shows: on its +the tutorial "Tracing a value". Each is the diagram's standalone SVG (the image a notebook shows: on its own white background, so it reads on a light and a dark page alike). Run it to rewrite the pictures after a change to the diagram:: diff --git a/docs/getting-started.md b/docs/getting-started.md index d0a30593e..af8141a46 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -232,4 +232,4 @@ With `pip`, in the activated environment: `python my_pipeline.py`. The results above are held in memory, so each new run computes everything again. To save results in a database and have later runs compute only what is new, record the same steps inside a `PipelineJob`. See [Pipelines and Jobs](concepts/pipeline-job.md), or work through -the [Tutorial](tutorial/index.md), which builds up to it step by step. +the [Tutorials](tutorial/index.md), which build up to it step by step. diff --git a/docs/index.md b/docs/index.md index ef0832bb1..a28dfc6af 100644 --- a/docs/index.md +++ b/docs/index.md @@ -66,8 +66,9 @@ for tag, data in result: - [Getting Started](getting-started.md) -- a hands-on walkthrough of sources, streams, function pods, and operators. -- [Tutorial](tutorial/index.md) -- a self-paced course in eleven short parts, from a first - stream to a stored, re-runnable pipeline over files, with exercises and solutions. +- [Tutorials](tutorial/index.md) -- a self-paced core course in seven parts, from a first + stream to a stored, re-runnable pipeline, and short tutorials on files, inspecting results, + tracing a value, chaining pipelines and handling errors, with exercises and solutions. - [Concepts](concepts/sources.md) -- deeper explanations of Orcapod's core abstractions. - [Troubleshooting](troubleshooting.md) -- common errors, their causes and fixes. - [API Reference](api/index.md) -- complete reference for all public classes and functions. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 3c17ee161..20350f3a9 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -184,8 +184,8 @@ same (`Run of job '...': 1 row failed.`). **Fix.** The message says how to see the full traceback: `job.last_run.print_traceback("label")`. While developing, run with `job.run(orchestrator=SyncPipelineOrchestrator(error_policy="fail_fast"))` (from -`orcapod.pipeline`) so that the first failure stops the run and raises. See the tutorial, -[Part 9](tutorial/09-when-things-go-wrong.md). +`orcapod.pipeline`) so that the first failure stops the run and raises. See the tutorial +[Handling errors](tutorial/handling-errors.md). ### `TypeError: ...() got an unexpected keyword argument 'ctx'` from a `sink_pod` diff --git a/docs/tutorial/08-inspecting-and-tracing.md b/docs/tutorial/08-inspecting-and-tracing.md deleted file mode 100644 index 3bb216b3c..000000000 --- a/docs/tutorial/08-inspecting-and-tracing.md +++ /dev/null @@ -1,607 +0,0 @@ -# Part 8: Inspecting and tracing - -A number in a figure raises questions. Which steps produced it? From which rows of which -table? When was it computed, and with what? Because Orcapod runs every step itself, it -keeps the answers. This part shows where to find them. - -You will: - -- walk backwards from a result to the sources it came from -- trace one value to the source cells it was made from, and find why a row is missing -- reveal the provenance columns that every stream carries -- read the record Orcapod keeps of each function call -- start a second pipeline from the stored results of the first - -```python -from workshop_data import make_dataset -from orcapod import PipelineJob, function_pod -from orcapod.databases import InMemoryArrowDatabase -from orcapod.sources import CSVSource - -data_dir = make_dataset() -database = InMemoryArrowDatabase() - - -@function_pod(output_keys="rate_hz") -def firing_rate(n_spikes: int, duration_s: float) -> float: - return n_spikes / duration_s - - -@function_pod(output_keys="mean_rate_hz") -def mean_rate(rate_hz: list[float]) -> float: - return sum(rate_hz) / len(rate_hz) - - -job = PipelineJob(name="workshop", database=database) -with job: - units = CSVSource( - str(data_dir / "units.csv"), - tag_columns=["subject_id", "session", "probe", "unit"], tag_only_columns=True, - source_id="units", - ) - sessions = CSVSource( - str(data_dir / "sessions.csv"), - tag_columns=["subject_id", "session"], tag_only_columns=True, - source_id="sessions", - ) - rates = firing_rate.pod( - units.select_data_columns(["n_spikes"]), - sessions.select_data_columns(["duration_s"]), - label="rates", - ) - mean_rate.pod( - rates.group_by(["subject_id", "session"]).select_data_columns(["rate_hz"]), - label="session_means", - ) -job.run() -``` - -This is the full pipeline from Part 5. `group_by`, and `filter` further down, each print a -`ProvisionalHashWarning` once (see [Messages you can ignore](00-setup.md#messages-you-can-ignore)). - -## Which steps produced this? - -Every node knows the nodes it reads from, in `node.upstreams`, and its own name, in -`node.label`. Following `upstreams` until there are none left takes you from a result back -to the sources: - -```python -def print_lineage(node, depth=0): - print(" " * depth + node.label) - for upstream in node.upstreams: - print_lineage(upstream, depth + 1) - - -print_lineage(job.nodes["session_means"]) -# session_means -# SelectDataColumns_3 -# GroupBy -# rates -# Join -# SelectDataColumns_1 -# units -# SelectDataColumns_2 -# sessions -``` - -Read from the bottom up, this is the pipeline as you wrote it, including the join that the -two-stream call to `firing_rate` added for you. When a job has several steps of the same -kind, it numbers them (`SelectDataColumns_1`, ...); the numbers tell the steps apart but do -not follow the order you wrote them in. - -The whole graph, rather than one node's lineage, is what the job draws when it is the last -line of a notebook cell (see [Part 5](05-pipeline-job.md#nodes)). -Clicking a node there shows its columns and its row counts in the last run. -`job.diagram(direction="TB")` lays it out top to bottom (in the notebook, the `vertical` -checkbox above the diagram does the same), and `print(job.diagram())` lists it as text. -[Working in notebooks](../concepts/notebooks.md) shows the diagram, the table preview of a -node and the run summary as they appear in a notebook. - -## Which rows did a value come from? - -Every stream carries hidden columns that record where its rows and values came from. They -are left out by default. Ask for them with the `columns` argument of `as_table`. - -**Source-info columns.** For each data column there is a companion column named -`_source_`. On the `units` source it holds the source id, the row's record id -(its position, counted from zero) and the column: - -```python -table = job.nodes["units"].as_table(columns={"source": True}) -print(table.column_names) -# ['subject_id', 'session', 'probe', 'unit', 'region', 'depth_um', 'n_spikes', '_source_region', '_source_depth_um', '_source_n_spikes'] -print(table.column("_source_n_spikes").to_pylist()[5]) -# csv_v1:units::row_5::n_spikes -``` - -Row 5 of the source you named `units`, column `n_spikes`, read by the CSV source -(`csv_v1`: the kind of source and the version of its reader come first in every source id). -This is what the `source_id` you have been passing since Part 1 is for. - -**System tags.** Each source also adds two hidden tag columns to every row: one with the -source's name, one with an identifier of the row. They travel with the row through every -operator and function pod. When two streams are joined, the joined row carries the system -tags of both. So for any row of `rates` you can read off which sources it depends on: - -```python -import polars as pl - -table = pl.from_arrow(job.nodes["rates"].as_table(columns={"system_tags": True})) -source_columns = [c for c in table.columns if c.startswith("_tag_source_id")] -print(len(source_columns)) -# 2 -print(table.select(source_columns).unique().rows()) -# [('csv_v1:sessions', 'csv_v1:units')] -``` - -Two system-tag columns, because two sources feed `rates`; every row depends on one row of -`sessions` and one row of `units`. The column names end in a long hash that identifies the -source's position in the pipeline, which is why the sample selects them by prefix. - -The companion `_tag_record_id::...` columns identify the individual source row within its -source, as text. By default a record id is the row's position, counted from zero: - -```python -units_table = job.nodes["units"].as_table(columns={"system_tags": True}) -record_id_column = next( - name for name in units_table.column_names if name.startswith("_tag_record_id::") -) -print(units_table.column(record_id_column)[5].as_py()) -# row_5 -``` - -For a source with key columns (`record_id_columns`), the record id is instead a JSON object -of the key columns and their values, in the order you declared them. - -!!! note "After `group_by`" - A grouped row comes from many source rows. Its system tags are folded into a single - digest per column, so they still distinguish one group from another but no longer name - the individual rows. To see which rows went into a group, look at the stream before the - grouping (`job.nodes["rates"]`): every row there with the group's `subject_id` and - `session` is a member, and the list elements are in the order of their `probe` and - `unit`, as you saw in Part 4. - -`as_table(all_info=True)` shows every hidden column at once. - -## How was it computed? - -For each function, the database holds one record per computed result, with details of the -call. `get_all_records` returns them; ask for the `meta` columns to see the details: - -```python -records = pl.from_arrow(job.nodes["rates"].get_all_records(columns={"meta": True})) -meta = [c for c in records.columns if c.startswith("__")] -print(meta) -# ['__data_id', '__input_data_hash', '__output_data_hash', '__data_context', '__computed', '__is_ephemeral', '__pipeline_run_id', '__recorded_at', '__input_data_hash_right', '__pf_var_function_name', '__pf_var_function_version', '__pf_var_function_module', '__pf_var_function_signature_hash', '__pf_var_function_content_hash', '__pf_var_git_hash', '__pf_exec_executor_type', '__pf_exec_executor_info', '__pf_exec_python_version', '__pf_exec_extra_info', '__pod_ts'] -``` - -The ones you are most likely to want: - -| Column | Meaning | -|---|---| -| `__pf_var_function_name` | The function that produced the result | -| `__pod_ts` | When the result was computed | -| `__pf_exec_python_version` | The Python version it ran under | -| `__pf_var_git_hash` | The git commit of the code, when run inside a git repository | -| `__computed` | `True` if this row was computed, `False` if it reused the result of an identical input | -| `__pipeline_run_id` | The job run that recorded the pipeline entry | -| `__recorded_at` | When the pipeline entry was recorded, in UTC | -| `__input_data_hash` | The hash of the input values: the key the result is stored under (Part 6) | - -```python -print(records.select("__pf_var_function_name", "__pf_exec_executor_type").unique().rows()) -# [('firing_rate', 'local')] -print(records["__computed"].sum(), "of", len(records)) -# 63 of 64 -print(records["__pod_ts"].dtype) -# Datetime(time_unit='us', time_zone='UTC') -``` - -63 of 64: the count from Part 5 again, now visible in the records. One row reused the -result of another row with the same inputs. (Like there, it is the count of `job.run()`.) - -### `as_table` versus `get_all_records` - -They answer different questions. - -- `node.as_table()` is the node's output **for the inputs of this job's run**: 64 rows here. - Before the job has run in this Python session it has no rows at all, even when the - database already holds results. -- `node.get_all_records()` is **everything stored** for this function in this job's part of - the database, including results from earlier runs over other inputs. It does not need a - run. - -After the "two more units" run of Part 6, a job over the original file, once run, has 64 -rows in `as_table()`, while `get_all_records()` has 66. - -## Tracing one value to its sources - -The columns above hold every link from a result back to its sources. `trace` follows them -for you, for one cell: give the node, the tags of the row and the column. - -```python -means = job.nodes["session_means"] -trace = means.trace({"subject_id": "mouse_03", "session": "s2"}, "mean_rate_hz") -print(trace) -# trace of mean_rate_hz at node session_means, for subject_id='mouse_03', session='s2': 1 row matches -# session_means (subject_id='mouse_03', session='s2'): mean_rate_hz = 5.059375 -# mean_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... -# GroupBy (subject_id='mouse_03', session='s2'): rate_hz = [4.791666666666667, 5.058333333333334, 7.366666666666666, 4.683333333333334, 5.0, 3.3333333333333335, 6.916666666666667, 3.325] (via SelectDataColumns) -# [0] rates (subject_id='mouse_03', session='s2', probe='imec0', unit=0): rate_hz = 4.791666666666667 -# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... -# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) -# csv_v1:units row_40 n_spikes = 575 (via Join, SelectDataColumns) -# [1] rates (subject_id='mouse_03', session='s2', probe='imec0', unit=1): rate_hz = 5.058333333333334 -# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... -# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) -# csv_v1:units row_41 n_spikes = 607 (via Join, SelectDataColumns) -# [2] rates (subject_id='mouse_03', session='s2', probe='imec0', unit=2): rate_hz = 7.366666666666666 -# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... -# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) -# csv_v1:units row_42 n_spikes = 884 (via Join, SelectDataColumns) -# [3] rates (subject_id='mouse_03', session='s2', probe='imec0', unit=3): rate_hz = 4.683333333333334 -# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... -# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) -# csv_v1:units row_43 n_spikes = 562 (via Join, SelectDataColumns) -# [4] rates (subject_id='mouse_03', session='s2', probe='imec1', unit=0): rate_hz = 5.0 -# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... -# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) -# csv_v1:units row_44 n_spikes = 600 (via Join, SelectDataColumns) -# [5] rates (subject_id='mouse_03', session='s2', probe='imec1', unit=1): rate_hz = 3.3333333333333335 -# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... -# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) -# csv_v1:units row_45 n_spikes = 400 (via Join, SelectDataColumns) -# [6] rates (subject_id='mouse_03', session='s2', probe='imec1', unit=2): rate_hz = 6.916666666666667 -# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... -# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) -# csv_v1:units row_46 n_spikes = 830 (via Join, SelectDataColumns) -# [7] rates (subject_id='mouse_03', session='s2', probe='imec1', unit=3): rate_hz = 3.325 -# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... -# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) -# csv_v1:units row_47 n_spikes = 399 (via Join, SelectDataColumns) -``` - -The first line repeats the question: the column traced, the node it was asked at and the -row selector, and how many held rows match it. Read the rest from the top. The mean of -`mouse_03`, session `s2`, was computed by `mean_rate` -(its version, the hash of its body, when and where it ran, and the job run that -recorded the entry, with when). Its input was the grouped row -of eight rates. Each rate was computed by `firing_rate` from one row of `units.csv` and the -one row of `sessions.csv` for that session; the operators it passed through are listed -after `via`. - -Each step is found from what the job holds and stores, not guessed: - -- A function's row is matched to its stored record (Part 8, "How was it computed?") by - its system tags, the hidden tags that name the source rows it came from. -- The members of a group are the rows before the grouping with the group's - `subject_id` and `session`, in `probe`, `unit` order (Part 4). Orcapod checks them - against the group's folded system tags and raises an error if they do not agree. -- The last step reads the source-info columns: `csv_v1:units row_40` is row 40 of the - source named `units` (its id names the kind of reader, a CSV file read by version 1, - then its name). - -Nothing is computed: the trace only reads. - -`source_cells()` lists the source cells alone, each once: - -```python -for cell in trace.source_cells(): - print(cell.text()) -# csv_v1:sessions row_5 duration_s = 120.0 -# csv_v1:units row_40 n_spikes = 575 -# csv_v1:units row_41 n_spikes = 607 -# csv_v1:units row_42 n_spikes = 884 -# csv_v1:units row_43 n_spikes = 562 -# csv_v1:units row_44 n_spikes = 600 -# csv_v1:units row_45 n_spikes = 400 -# csv_v1:units row_46 n_spikes = 830 -# csv_v1:units row_47 n_spikes = 399 -``` - -**Computed here, or reused.** In session `s1` of `mouse_02`, two units have the same spike -count, so `firing_rate` received equal inputs twice and ran once (the "63 of 64" above). -The trace still tells the two units apart, and says which of them computed the result and -which reused it: - -```python -shared = means.trace({"subject_id": "mouse_02", "session": "s1"}, "mean_rate_hz") -for step in shared.root.walk(): - if step.node == "rates": - tags = dict(step.tags) - print(tags["probe"], tags["unit"], step.function.computed_here) -# imec0 0 True -# imec0 1 True -# imec0 2 True -# imec0 3 True -# imec1 0 True -# imec1 1 True -# imec1 2 False -# imec1 3 True -``` - -`imec1` unit 2 reused the result that `imec0` unit 0 computed: one stored result, two -rows, both traced to their own row of `units.csv`. - -**Several rows at once.** The selector need not pick one row: every held row whose columns -equal the values given is traced, and `{}` traces every row. Each matching row has its own -tree, in `trace.roots`, in tag order; `source_cells()` and the highlight cover them all: - -```python -both = means.trace({"subject_id": "mouse_02"}, "mean_rate_hz") -print(both.header()) -# trace of mean_rate_hz at node session_means, for subject_id='mouse_02': 2 rows match -print([dict(root.tags) for root in both.roots]) -# [{'subject_id': 'mouse_02', 'session': 's1'}, {'subject_id': 'mouse_02', 'session': 's2'}] -print(len(both.source_cells())) -# 18 -``` - -A selector that matches no held row gives a trace that says so (`no held row matches`, -status `no_match`); one that names a column the node does not have is an error. - -!!! note "The first diagram" - The first diagram in a Python session issues `InDevelopmentWarning`, once. It is - harmless: see the note in [Part 5](05-pipeline-job.md#nodes). - -**On the diagram.** `trace.highlight()` marks the trace's path on the job's diagram. The -listing shows the provenance question only, with no run status. It marks the nodes on the -path with `*`, the node the trace was asked at with `>` and `[traced from here]`, and each -function node on the path with how its rows on the path got their results: `[computed]`, -`[reused]` (a result stored for equal inputs), or `[computed + reused]` (some rows each): - -```python -print(job.diagram(highlight=trace.highlight())) -# Job 'workshop': 9 nodes -# highlight (*): trace of mean_rate_hz at node session_means, for subject_id='mouse_03', session='s2': 1 row matches -# * sessions (source · CSVSource) -# * SelectDataColumns_2 (operator) <- sessions -# * units (source · CSVSource) -# * SelectDataColumns_1 (operator) <- units -# * Join (operator) <- SelectDataColumns_2, SelectDataColumns_1 -# * rates (function pod · firing_rate) [computed] <- Join -# * GroupBy (operator) <- rates -# * SelectDataColumns_3 (operator) <- GroupBy -# >* session_means (function pod · mean_rate) [computed] [traced from here] <- SelectDataColumns_3 -``` - -A mean is made through every step of the job, so its path covers the whole diagram. The -trace of one firing rate covers only part of it: the two sources, their column selections, -the join and `rates`. Take the unit that reused a stored result: - -```python -rate = job.nodes["rates"].trace( - {"subject_id": "mouse_02", "session": "s1", "probe": "imec1", "unit": 2}, "rate_hz" -) -print(job.diagram(highlight=rate.highlight())) -# Job 'workshop': 9 nodes -# highlight (*): trace of rate_hz at node rates, for subject_id='mouse_02', session='s1', probe='imec1', unit=2: 1 row matches -# * sessions (source · CSVSource) -# * SelectDataColumns_2 (operator) <- sessions -# * units (source · CSVSource) -# * SelectDataColumns_1 (operator) <- units -# * Join (operator) <- SelectDataColumns_2, SelectDataColumns_1 -# >* rates (function pod · firing_rate) [reused] [traced from here] <- Join -# GroupBy (operator) <- rates -# SelectDataColumns_3 (operator) <- GroupBy -# session_means (function pod · mean_rate) <- SelectDataColumns_3 -``` - -In a notebook the same call draws the picture. The caption is the question; the path is -outlined in the text colour and the rest is dimmed (no status of a node is shown in that -colour: red is kept for failed). The node it was asked at has a second outline and the -bold line "traced from here"; the mark is the bold line "reused": - -![The diagram of the workshop job, captioned "highlighted: trace of rate_hz at node rates, for subject_id='mouse_02', session='s1', probe='imec1', unit=2: 1 row matches": the sources sessions and units, their column selections, the Join and the function pod rates outlined in a dark line; rates has a second outline and the bold lines "reused" and "traced from here"; GroupBy, its selection and the function pod session_means dimmed](provenance-diagram-trace.svg) - -**Computed when?** `computed here`, `[computed]` and `[reused]` describe the **stored -entry**, in the run that recorded it. They do not describe the run you just made. For that, -read the run summary. Build the same job again over the same database, as a new Python session -would, and run it: - -```python -again = PipelineJob(name="workshop", database=database) -with again: - rates = firing_rate.pod( - units.select_data_columns(["n_spikes"]), - sessions.select_data_columns(["duration_s"]), - label="rates", - ) - mean_rate.pod( - rates.group_by(["subject_id", "session"]).select_data_columns(["rate_hz"]), - label="session_means", - ) -print(again.run()) -# Run of job 'workshop': all rows succeeded. -# rates: 64 rows: 0 computed, 64 from store, 0 failed -# session_means: 8 rows: 0 computed, 8 from store, 0 failed -warm = again.nodes["session_means"].trace( - {"subject_id": "mouse_03", "session": "s2"}, "mean_rate_hz" -) -print([run.computed_here for label, run in warm.function_runs() if label == "session_means"]) -# [True] -print(warm.highlight().marks == trace.highlight().marks) -# True -``` - -This run computed nothing: the summary counts 0 computed and 72 from the store. The trace and -its marks are those of the first job, because the entries are: they were recorded by the first run, -whose id and time the trace shows. A loaded job (`PipelineJob.load`) shows the same. - -**Why is a row missing?** A second job keeps only the `imec0` probe and leaves out the -sessions of `mouse_04`. Row 4 of `units.csv` is an `imec1` unit, and row 48 is a unit of -`mouse_04`. Neither has a firing rate. `why_missing` says which step removed each: - -```python -from orcapod.types import col - -imec0 = PipelineJob(name="imec0", database=database) -with imec0: - units = CSVSource( - str(data_dir / "units.csv"), - tag_columns=["subject_id", "session", "probe", "unit"], tag_only_columns=True, - source_id="units", - ) - sessions = CSVSource( - str(data_dir / "sessions.csv"), - tag_columns=["subject_id", "session"], tag_only_columns=True, - source_id="sessions", - ) - firing_rate.pod( - units.filter({"probe": "imec0"}).select_data_columns(["n_spikes"]), - sessions.filter(col("subject_id") != "mouse_04").select_data_columns( - ["duration_s"] - ), - label="imec0_rates", - ) -imec0.run() -print(imec0.nodes["imec0_rates"].why_missing("units", "row_4")) -# why record row_4 of units is missing at node imec0_rates -# units row_4 is removed by Filter[...]: probe='imec0' -# no successful entry of function node 'imec0_rates' is stored for it (the function raised on it, or never received it) -# present in: units -print(imec0.nodes["imec0_rates"].why_missing("units", "row_48")) -# why record row_48 of units is missing at node imec0_rates -# units row_48 is removed by Join: rows without a match in 'sessions' are dropped -# no successful entry of function node 'imec0_rates' is stored for it (the function raised on it, or never received it) -# present in: units, ... -# because: no row with session='s1', subject_id='mouse_04' in ... (reads sessions) -``` - -The first line repeats the question. The second answers it: which step removed the row. -The third is read from the stored records of `imec0_rates`: no run of this job stored a -result for the row. On its own that does not prove the function never saw it (a function -that raised on a row stores no result for it); the second line says why it did not. -`why_missing(...).highlight()` marks the path up to the step that removed the row; the -other nodes are dimmed, except the node asked at, marked "asked here". For `units row_4`, -the path ends at the filter on `probe`: - -![The diagram of the imec0 job, captioned "highlighted: why record row_4 of units is missing at node imec0_rates: ...": the source units and the node Filter_2 outlined in a dark line; the sessions branch and the Join dimmed; the function pod imec0_rates with a second outline and the bold line "asked here"](provenance-diagram-missing-filter.svg) - -For `units row_48`, the row passes the filter and its column selection and ends at the -Join, which has no session `s1` of `mouse_04` to match it with: - -![The diagram of the imec0 job, captioned "highlighted: why record row_48 of units is missing at node imec0_rates: ...": the source units, Filter_2, SelectDataColumns_1 and the Join outlined in a dark line; the sessions branch dimmed; the function pod imec0_rates with a second outline and the bold line "asked here"](provenance-diagram-missing-join.svg) - -The pictures are drawn by `job.diagram(...)` itself, from the job above. - -## Starting a second pipeline from stored results - -A finished analysis is often the input of the next one. `as_source()` turns the stored -results of a node into a source: - -```python -session_means = job.nodes["session_means"].as_source() -print(type(session_means).__name__) -# DerivedSource -print(session_means.keys()) -# (('subject_id', 'session'), ('mean_rate_hz',)) -``` - -A `DerivedSource` is a source like those of Part 1, so it can be joined, filtered and fed to -pods. The first one you build prints a `ProvisionalHashWarning`, once: its identity is not -frozen yet, so a later release of Orcapod may compute the stages built on it again instead of -reusing what they stored (see [Provisional sources](../concepts/sources.md#provisional-sources)). -Here the next stage flags sessions with a low mean rate: - -```python -@function_pod(output_keys="is_low") -def is_low(mean_rate_hz: float) -> bool: - return mean_rate_hz < 5.5 - - -flags = is_low.pod(session_means).as_pandas_df() -print(flags.sort_values(["subject_id", "session"], ignore_index=True)) -# subject_id session is_low -# 0 mouse_01 s1 False -# 1 mouse_01 s2 False -# 2 mouse_02 s1 False -# 3 mouse_02 s2 False -# 4 mouse_03 s1 True -# 5 mouse_03 s2 True -# 6 mouse_04 s1 True -# 7 mouse_04 s2 True -``` - -The next stage does not re-run the first. It reads what the first one stored. This is how -you split a large analysis into stages that different people, or different days, can own. -`as_source()` reads what the database holds, whether or not the node has run in this Python -session; for a node whose results were never stored, it has no rows. It reads every stored -result of the node, including those of earlier runs over other inputs, like -`get_all_records()` above; when you want only this run's output, use `as_table()`. - -!!! warning "Not yet: a stored joined result as the source of a new job" - The stage above runs in memory, so its own results are not stored. Recording it in a new - `PipelineJob` does not work yet for `session_means`, or for any node downstream of a - `Join` or `MergeJoin` of two sources. An input of a job must declare exactly one - source-id and one record-id system tag. The source `session_means` has the schema - of its node, which declares a pair for each joined source, so a job refuses it with - `SourceSpecMismatchError` when it is bound. (Its rows hold only the stored tag and data - columns: no system tags, and null source-info tokens.) Support is planned (ITL-1127). - Until then, to store a later stage, add it to the first job. - -## Key points - -- `node.upstreams` and `node.label` walk the pipeline backwards from any result. -- `as_table(columns={"source": True})` and `columns={"system_tags": True}` reveal where - values and rows came from; `all_info=True` shows everything. -- `get_all_records(columns={"meta": True})` shows how and when each result was computed. -- `as_table()` is the output of this job's run; `get_all_records()` is everything stored. -- `node.trace(row, column)` follows one value back to its source cells, and says which - function computed each step and whether it reused a stored result. -- `node.why_missing(source, record_id)` says which step removed a row. -- `job.diagram(highlight=...)` marks a trace's or a missing row's path. -- `node.as_source()` starts a new pipeline from stored results. - -## Exercises - -**1.** Print the lineage of the `rates` node. How many sources does it depend on? - -??? success "Solution" - ```python - print_lineage(job.nodes["rates"]) - # rates - # Join - # SelectDataColumns_1 - # units - # SelectDataColumns_2 - # sessions - ``` - - Two: `units` and `sessions`. - -**2.** Which row of `sessions.csv` did the duration of `mouse_03`, session `s2` come from? -Use the source-info column of the `sessions` node. - -??? success "Solution" - ```python - table = pl.from_arrow(job.nodes["sessions"].as_table(columns={"source": True})) - row = table.filter((pl.col("subject_id") == "mouse_03") & (pl.col("session") == "s2")) - print(row["_source_duration_s"].to_list()) - # ['csv_v1:sessions::row_5::duration_s'] - ``` - - Row 5, counting data rows from 0: the sixth line after the header. - - Note the plain Polars filter on a table you have already taken out of Orcapod. Inside a - pipeline you would write the same test as `stream.filter(...)` (Part 3). - -**3.** Using `as_source()`, compute the mean of the session means per animal (one row per -`subject_id`). Reuse `group_by` from Part 4. - -??? success "Solution" - ```python - @function_pod(output_keys="animal_mean_hz") - def mean_of_means(mean_rate_hz: list[float]) -> float: - return sum(mean_rate_hz) / len(mean_rate_hz) - - - means = job.nodes["session_means"].as_source() - result = mean_of_means.pod(means.group_by(["subject_id"])).as_pandas_df() - print(result.sort_values("subject_id", ignore_index=True)) - # subject_id animal_mean_hz - # 0 mouse_01 6.413542 - # 1 mouse_02 6.676042 - # 2 mouse_03 4.983160 - # 3 mouse_04 5.132812 - ``` diff --git a/docs/tutorial/chaining-pipelines.md b/docs/tutorial/chaining-pipelines.md new file mode 100644 index 000000000..9c899a0fa --- /dev/null +++ b/docs/tutorial/chaining-pipelines.md @@ -0,0 +1,156 @@ +# Chaining pipelines + +The results of one pipeline are often the input of the next. `as_source()` turns the stored +results of a node into a source, so a later stage reads them without running the first stage +again. + +**Before you start:** Parts 0 to 5 of the [core course](index.md#core-course). + +You will: + +- make a source from the stored results of a node +- build a second stage on it +- see which stored results a new job cannot use yet + +```python +from workshop_data import make_dataset +from orcapod import PipelineJob, function_pod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.sources import CSVSource + +data_dir = make_dataset() +database = InMemoryArrowDatabase() + + +@function_pod(output_keys="rate_hz") +def firing_rate(n_spikes: int, duration_s: float) -> float: + return n_spikes / duration_s + + +@function_pod(output_keys="mean_rate_hz") +def mean_rate(rate_hz: list[float]) -> float: + return sum(rate_hz) / len(rate_hz) + + +job = PipelineJob(name="workshop", database=database) +with job: + units = CSVSource( + str(data_dir / "units.csv"), + tag_columns=["subject_id", "session", "probe", "unit"], tag_only_columns=True, + source_id="units", + ) + sessions = CSVSource( + str(data_dir / "sessions.csv"), + tag_columns=["subject_id", "session"], tag_only_columns=True, + source_id="sessions", + ) + rates = firing_rate.pod( + units.select_data_columns(["n_spikes"]), + sessions.select_data_columns(["duration_s"]), + label="rates", + ) + mean_rate.pod( + rates.group_by(["subject_id", "session"]).select_data_columns(["rate_hz"]), + label="session_means", + ) +job.run() +``` + +This is the pipeline of [Part 5](05-pipeline-job.md): the first stage. + +## A source from stored results + +```python +session_means = job.nodes["session_means"].as_source() +print(type(session_means).__name__) +# DerivedSource +print(session_means.keys()) +# (('subject_id', 'session'), ('mean_rate_hz',)) +``` + +A `DerivedSource` is a source like those of Part 1, so it can be joined, filtered and given to +pods. The first one you build prints a `ProvisionalHashWarning`, once (see +[Messages you can ignore](00-setup.md#messages-you-can-ignore)). + +`as_source()` reads what the database holds, whether or not the node has run in this Python +session. For a node whose results were never stored, it has no rows. It reads every stored +result of the node, including those of earlier runs over other inputs. When you want only +this run's output, use `as_table()`. + +## The next stage + +The next stage flags sessions with a low mean rate: + +```python +@function_pod(output_keys="is_low") +def is_low(mean_rate_hz: float) -> bool: + return mean_rate_hz < 5.5 + + +flags = is_low.pod(session_means).as_pandas_df() +print(flags.sort_values(["subject_id", "session"], ignore_index=True)) +# subject_id session is_low +# 0 mouse_01 s1 False +# 1 mouse_01 s2 False +# 2 mouse_02 s1 False +# 3 mouse_02 s2 False +# 4 mouse_03 s1 True +# 5 mouse_03 s2 True +# 6 mouse_04 s1 True +# 7 mouse_04 s2 True +``` + +The next stage reads what the first one stored. This is how you split a large analysis into +stages that can be owned by different people. + +!!! warning "A new job cannot use this source yet" + The stage above runs in memory, so its own results are not stored. Recording it in a new + `PipelineJob` does not work yet for `session_means`, or for any node downstream of a + `Join` or `MergeJoin` of two sources: the job refuses the source with + `SourceSpecMismatchError` when it is bound. An input of a job must declare one source-id + and one record-id system tag, and this source declares a pair for each joined source. + Support is planned (ITL-1127). Until then, to store a later stage, add it to the first + job. + +## Key points + +- `node.as_source()` makes a source from the stored results of a node. +- A stage built on it reads the stored results and does not run the first stage. +- `as_source()` reads everything stored for the node; `as_table()` returns this run's output. +- A new job cannot yet use the stored results of a node downstream of a join of two sources. + +## Exercises + +**1.** Using `as_source()`, compute the mean of the session means per animal (one row per +`subject_id`). Reuse `group_by` from Part 4. + +??? success "Solution" + ```python + @function_pod(output_keys="animal_mean_hz") + def mean_of_means(mean_rate_hz: list[float]) -> float: + return sum(mean_rate_hz) / len(mean_rate_hz) + + + means = job.nodes["session_means"].as_source() + result = mean_of_means.pod(means.group_by(["subject_id"])).as_pandas_df() + print(result.sort_values("subject_id", ignore_index=True)) + # subject_id animal_mean_hz + # 0 mouse_01 6.413542 + # 1 mouse_02 6.676042 + # 2 mouse_03 4.983160 + # 3 mouse_04 5.132812 + ``` + +**2.** The `rates` node is also downstream of the join. How many rows and which columns does +`job.nodes["rates"].as_source()` have? + +??? success "Solution" + ```python + rates_source = job.nodes["rates"].as_source() + print(rates_source.keys()) + # (('subject_id', 'session', 'probe', 'unit'), ('rate_hz',)) + print(rates_source.as_table().num_rows) + # 64 + ``` + + One row per unit, with the tags and the data column of the node. diff --git a/docs/tutorial/07-files.md b/docs/tutorial/files.md similarity index 99% rename from docs/tutorial/07-files.md rename to docs/tutorial/files.md index f63c6f94f..29c9ced88 100644 --- a/docs/tutorial/07-files.md +++ b/docs/tutorial/files.md @@ -1,10 +1,12 @@ -# Part 7: Working with files +# Working with files Much data is kept in files: images, binary recordings, tables, often with one folder per recording. A pipeline over such data passes *references to files* from step to step, and the functions open them. Orcapod identifies a file by its **content**, so a result is recomputed when the file it was computed from changes. +**Before you start:** Parts 0 to 5 of the [core course](index.md#core-course). + You will: - build a stream whose data column holds files diff --git a/docs/tutorial/09-when-things-go-wrong.md b/docs/tutorial/handling-errors.md similarity index 98% rename from docs/tutorial/09-when-things-go-wrong.md rename to docs/tutorial/handling-errors.md index b49964eaa..1fdc3ee6a 100644 --- a/docs/tutorial/09-when-things-go-wrong.md +++ b/docs/tutorial/handling-errors.md @@ -1,8 +1,10 @@ -# Part 9: Handling errors +# Handling errors Orcapod catches some mistakes before any function runs: a misspelt column, or a function that does not fit its input. Others happen in the middle of a run: one file out of a thousand is -corrupt, and your function raises. This part shows what to do about both. +corrupt, and your function raises. This tutorial shows what to do about both. + +**Before you start:** Parts 0 to 6 of the [core course](index.md#core-course). You will: diff --git a/docs/tutorial/index.md b/docs/tutorial/index.md index 270647cd2..166eafc60 100644 --- a/docs/tutorial/index.md +++ b/docs/tutorial/index.md @@ -1,10 +1,11 @@ -# Tutorial +# Tutorials -This tutorial teaches Orcapod by building one small analysis from start to finish. It is -written for scientists who are comfortable with Python and have not used Orcapod before. You -can work through it on your own, at your own pace, on a laptop. +These tutorials teach Orcapod on one small analysis. The core course builds it from start to +finish, and the short tutorials each add one subject. They are written for scientists who are +comfortable with Python and have not used Orcapod before. You can work through them on your +own, at your own pace, on a laptop. -Each part takes about 20 minutes: a few minutes of reading, samples to run, and two or three +A page takes about 20 minutes: a few minutes of reading, samples to run, and two or three exercises. Every exercise has a solution you can unfold. Every sample on these pages is run by Orcapod's test suite, so what a page shows is what the library prints. @@ -44,7 +45,9 @@ workshop_data/ 27 files, about 0.4 MB. [Part 0](00-setup.md) shows how to generate it. -## The parts +## Core course + +Do these parts in order. | Part | You learn | Time | |---|---|---| @@ -55,19 +58,26 @@ workshop_data/ | [4. Many rows into one](04-many-rows-into-one.md) | Grouping rows and computing over the group | 20 min | | [5. Keeping results](05-pipeline-job.md) | `PipelineJob`: run a pipeline against a database | 20 min | | [6. Re-runs](06-reruns-and-caching.md) | What is recomputed, and what is not | 20 min | -| [7. Working with files](07-files.md) | Functions that read and write files | 20 min | -| [8. Inspecting and tracing](08-inspecting-and-tracing.md) | Where a result came from | 20 min | -| [9. Handling errors](09-when-things-go-wrong.md) | Errors while building a pipeline; failed rows in a run | 15 min | -| [10. Where next](10-where-next.md) | Features this tutorial did not cover | optional | -Parts 0 to 6 are the core and should be done in order. Parts 7 to 10 can be read in any -order afterwards. +## Short tutorials + +Each is on one subject and can be read in any order after the parts it names. + +| Tutorial | You learn | Before you start | Time | +|---|---|---|---| +| [Working with files](files.md) | Functions that read and write files | Parts 0 to 5 | 20 min | +| [Inspecting results](inspecting-results.md) | The steps of a job, where a row came from, the record of each call | Parts 0 to 6 | 15 min | +| [Tracing a value](tracing-a-value.md) | One value back to its source cells; why a row is missing | Parts 0 to 6 | 20 min | +| [Chaining pipelines](chaining-pipelines.md) | A second pipeline over the stored results of the first | Parts 0 to 5 | 10 min | +| [Handling errors](handling-errors.md) | Errors while building a pipeline; failed rows in a run | Parts 0 to 6 | 15 min | + +[Where next](where-next.md) is a short tour of features these pages did not cover. ## How to use these pages Type or paste each sample into a Python session, a notebook, or a script, in the order shown. Within one page, later samples use names defined by earlier ones. Each page starts from -scratch, so you can stop after any part and pick up at the next one later. +scratch, so you can stop after any page and pick up at the next one later. Lines starting with `#` directly under a `print(...)` show what it prints. Where a value differs from run to run (a hash, a timestamp), the page shows `...` in its place. diff --git a/docs/tutorial/inspecting-results.md b/docs/tutorial/inspecting-results.md new file mode 100644 index 000000000..33f4259a3 --- /dev/null +++ b/docs/tutorial/inspecting-results.md @@ -0,0 +1,243 @@ +# Inspecting results + +After a run, a job holds the result of every step, and the database holds a record of every +function call. This tutorial shows where to read them. + +**Before you start:** Parts 0 to 6 of the [core course](index.md#core-course). + +You will: + +- list the steps of a job and what each one reads +- show the hidden columns that say which source rows a row came from +- read the record Orcapod keeps of each function call +- tell a node's output from everything stored for it + +```python +from workshop_data import make_dataset +from orcapod import PipelineJob, function_pod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.sources import CSVSource + +data_dir = make_dataset() +database = InMemoryArrowDatabase() + + +@function_pod(output_keys="rate_hz") +def firing_rate(n_spikes: int, duration_s: float) -> float: + return n_spikes / duration_s + + +@function_pod(output_keys="mean_rate_hz") +def mean_rate(rate_hz: list[float]) -> float: + return sum(rate_hz) / len(rate_hz) + + +job = PipelineJob(name="workshop", database=database) +with job: + units = CSVSource( + str(data_dir / "units.csv"), + tag_columns=["subject_id", "session", "probe", "unit"], tag_only_columns=True, + source_id="units", + ) + sessions = CSVSource( + str(data_dir / "sessions.csv"), + tag_columns=["subject_id", "session"], tag_only_columns=True, + source_id="sessions", + ) + rates = firing_rate.pod( + units.select_data_columns(["n_spikes"]), + sessions.select_data_columns(["duration_s"]), + label="rates", + ) + mean_rate.pod( + rates.group_by(["subject_id", "session"]).select_data_columns(["rate_hz"]), + label="session_means", + ) +job.run() +``` + +This is the pipeline of [Part 5](05-pipeline-job.md). + +## Tracing the steps + +`print(job.diagram())` lists the steps of the job, one node per line. After `<-` come the nodes +a node reads from: + +```python +print(job.diagram()) +# Job 'workshop': 9 nodes +# sessions (source · CSVSource · bound) +# SelectDataColumns_2 (operator · current) <- sessions +# units (source · CSVSource · bound) +# SelectDataColumns_1 (operator · current) <- units +# Join (operator · current) <- SelectDataColumns_2, SelectDataColumns_1 +# rates (function pod · firing_rate · current) <- Join +# GroupBy (operator · current) <- rates +# SelectDataColumns_3 (operator · current) <- GroupBy +# session_means (function pod · mean_rate · current) <- SelectDataColumns_3 +``` + +To find the steps that produced a result, start at its node and follow `<-` until you reach +the sources: `session_means` reads `SelectDataColumns_3`, which reads `GroupBy`, and so on back +to `units` and `sessions`. When a job has several steps of the same kind, it numbers them +(`SelectDataColumns_1`, ...). The numbers tell the steps apart and do not follow the order you +wrote them in. + +In a notebook, `job` as the last line of a cell draws the same graph as a picture. Clicking a +node there shows its columns and its row counts in the last run. +[Working in notebooks](../concepts/notebooks.md) shows it, and +[Tracing a value](tracing-a-value.md#on-the-diagram) marks the path of one value on it. + +## Tracing rows + +Every stream carries hidden columns that record where its rows and values came from. Ask for +them with the `columns` argument of `as_table`. + +**Source-info columns.** For each data column there is a column named `_source_`. On +the `units` source it holds the source id, the row's record id (its position, counted from +zero) and the column: + +```python +table = job.nodes["units"].as_table(columns={"source": True}) +print(table.column_names) +# ['subject_id', 'session', 'probe', 'unit', 'region', 'depth_um', 'n_spikes', '_source_region', '_source_depth_um', '_source_n_spikes'] +print(table.column("_source_n_spikes").to_pylist()[5]) +# csv_v1:units::row_5::n_spikes +``` + +This is row 5 of the source you named `units`, column `n_spikes`. Every source id starts with +the kind of source and the version of its reader, here `csv_v1`. + +**System tags.** Each source also adds two hidden tag columns to every row: one with the +source's id, one with the row's record id. They travel with the row through every operator and +function pod, and a joined row carries the system tags of both inputs: + +```python +import polars as pl + +table = pl.from_arrow(job.nodes["rates"].as_table(columns={"system_tags": True})) +source_columns = [c for c in table.columns if c.startswith("_tag_source_id")] +print(len(source_columns)) +# 2 +print(table.select(source_columns).unique().rows()) +# [('csv_v1:sessions', 'csv_v1:units')] +``` + +Since two sources feed `rates`, every row depends on one row of `sessions` and one row of +`units`. The column names end in a long hash that identifies the source's position in the +pipeline, so the sample selects them by prefix. + +The `_tag_record_id::...` columns hold the record id of the source row, as text: + +```python +units_table = job.nodes["units"].as_table(columns={"system_tags": True}) +record_id_column = next( + name for name in units_table.column_names if name.startswith("_tag_record_id::") +) +print(units_table.column(record_id_column)[5].as_py()) +# row_5 +``` + +For a source with key columns (`record_id_columns`), the record id is a JSON object of the key +columns and their values, in the order you declared them. + +!!! note "After `group_by`" + A grouped row comes from many source rows. Its system tags are folded into one digest per + column, so they tell one group from another and no longer name the individual rows. To see + which rows went into a group, look at the stream before the grouping + (`job.nodes["rates"]`). The list is made up of every row with the same `subject_id` and + `session`. + +`as_table(all_info=True)` shows every hidden column at once. + +## Call records + +For each function, the database holds one record per computed result. +`get_all_records(columns={"meta": True})` returns them with the details of the call: + +```python +records = pl.from_arrow(job.nodes["rates"].get_all_records(columns={"meta": True})) +meta = [c for c in records.columns if c.startswith("__")] +print(meta) +# ['__data_id', '__input_data_hash', '__output_data_hash', '__data_context', '__computed', '__is_ephemeral', '__pipeline_run_id', '__recorded_at', '__input_data_hash_right', '__pf_var_function_name', '__pf_var_function_version', '__pf_var_function_module', '__pf_var_function_signature_hash', '__pf_var_function_content_hash', '__pf_var_git_hash', '__pf_exec_executor_type', '__pf_exec_executor_info', '__pf_exec_python_version', '__pf_exec_extra_info', '__pod_ts'] +``` + +Some important columns: + +| Column | Meaning | +|---|---| +| `__pf_var_function_name` | The function that produced the result | +| `__pod_ts` | When the result was computed | +| `__pf_exec_python_version` | The Python version it ran under | +| `__pf_var_git_hash` | The git commit of the code, when run inside a git repository | +| `__computed` | `True` if this row was computed, `False` if it reused the result of an identical input | +| `__pipeline_run_id` | The job run that recorded the entry | +| `__recorded_at` | When the entry was recorded, in UTC | +| `__input_data_hash` | The hash of the input values: the key the result is stored under ([Part 6](06-reruns-and-caching.md#reuse-rule)) | + +```python +print(records.select("__pf_var_function_name", "__pf_exec_executor_type").unique().rows()) +# [('firing_rate', 'local')] +print(records["__computed"].sum(), "of", len(records)) +# 63 of 64 +print(records["__pod_ts"].dtype) +# Datetime(time_unit='us', time_zone='UTC') +``` + +63 of 64 rows were computed: one row reused the result of another row with the same inputs, +as in Part 5. + +### `as_table` and `get_all_records` + +- `node.as_table()` returns the node's output **for the inputs of this job's run**: 64 rows + here. Before the job has run in this Python session it returns no rows, even when the + database already holds results. +- `node.get_all_records()` returns **everything stored** for this function in this job's part + of the database, including results from earlier runs over other inputs. It does not need a + run. + +After the run with two more units in Part 6, a job over the original file has 64 rows in +`as_table()` once it has run, while `get_all_records()` has 66. + +## Key points + +- `print(job.diagram())` lists the steps of a job and what each one reads. +- `as_table(columns={"source": True})` and `columns={"system_tags": True}` show where values + and rows came from; `all_info=True` shows every hidden column. +- `get_all_records(columns={"meta": True})` shows how and when each result was computed. +- `as_table()` returns the output of this job's run; `get_all_records()` returns everything + stored. + +## Exercises + +**1.** Print the diagram with `collapse=True`, which hides the joins and column selections. +Which sources does `rates` read? + +??? success "Solution" + ```python + print(job.diagram(collapse=True)) + # Job 'workshop': 5 nodes + # sessions (source · CSVSource · bound) + # units (source · CSVSource · bound) + # rates (function pod · firing_rate · current) <- sessions, units + # GroupBy (operator · current) <- rates + # session_means (function pod · mean_rate · current) <- GroupBy + ``` + + Two: `sessions` and `units`. + +**2.** Which row of `sessions.csv` did the duration of `mouse_03`, session `s2` come from? +Use the source-info column of the `sessions` node. + +??? success "Solution" + ```python + table = pl.from_arrow(job.nodes["sessions"].as_table(columns={"source": True})) + row = table.filter((pl.col("subject_id") == "mouse_03") & (pl.col("session") == "s2")) + print(row["_source_duration_s"].to_list()) + # ['csv_v1:sessions::row_5::duration_s'] + ``` + + Row 5, counting data rows from 0: the sixth line after the header. + + This is a Polars filter on a table taken out of Orcapod. Inside a pipeline, write the same + test as `stream.filter(...)` (Part 3). diff --git a/docs/tutorial/tracing-a-value.md b/docs/tutorial/tracing-a-value.md new file mode 100644 index 000000000..af2321969 --- /dev/null +++ b/docs/tutorial/tracing-a-value.md @@ -0,0 +1,370 @@ +# Tracing a value + +`node.trace` follows one value of a result back to the source cells it was made from, and +names the function call behind every step. `node.why_missing` says which step removed a row +that has no result. Both read what the job holds and the database stores, and compute nothing. + +**Before you start:** Parts 0 to 6 of the [core course](index.md#core-course). +[Inspecting results](inspecting-results.md) shows the columns and records a trace reads. + +You will: + +- trace one value to its source cells +- see which rows computed their result and which reused a stored one +- mark the path of a trace on the job's diagram +- find the step that removed a row + +```python +from workshop_data import make_dataset +from orcapod import PipelineJob, function_pod +from orcapod.databases import InMemoryArrowDatabase +from orcapod.sources import CSVSource + +data_dir = make_dataset() +database = InMemoryArrowDatabase() + + +@function_pod(output_keys="rate_hz") +def firing_rate(n_spikes: int, duration_s: float) -> float: + return n_spikes / duration_s + + +@function_pod(output_keys="mean_rate_hz") +def mean_rate(rate_hz: list[float]) -> float: + return sum(rate_hz) / len(rate_hz) + + +job = PipelineJob(name="workshop", database=database) +with job: + units = CSVSource( + str(data_dir / "units.csv"), + tag_columns=["subject_id", "session", "probe", "unit"], tag_only_columns=True, + source_id="units", + ) + sessions = CSVSource( + str(data_dir / "sessions.csv"), + tag_columns=["subject_id", "session"], tag_only_columns=True, + source_id="sessions", + ) + rates = firing_rate.pod( + units.select_data_columns(["n_spikes"]), + sessions.select_data_columns(["duration_s"]), + label="rates", + ) + mean_rate.pod( + rates.group_by(["subject_id", "session"]).select_data_columns(["rate_hz"]), + label="session_means", + ) +job.run() +``` + +This is the pipeline of [Part 5](05-pipeline-job.md). + +## Tracing one value + +Give `trace` the tags of the row and the column: + +```python +means = job.nodes["session_means"] +trace = means.trace({"subject_id": "mouse_03", "session": "s2"}, "mean_rate_hz") +print(trace) +# trace of mean_rate_hz at node session_means, for subject_id='mouse_03', session='s2': 1 row matches +# session_means (subject_id='mouse_03', session='s2'): mean_rate_hz = 5.059375 +# mean_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... +# GroupBy (subject_id='mouse_03', session='s2'): rate_hz = [4.791666666666667, 5.058333333333334, 7.366666666666666, 4.683333333333334, 5.0, 3.3333333333333335, 6.916666666666667, 3.325] (via SelectDataColumns) +# [0] rates (subject_id='mouse_03', session='s2', probe='imec0', unit=0): rate_hz = 4.791666666666667 +# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... +# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) +# csv_v1:units row_40 n_spikes = 575 (via Join, SelectDataColumns) +# [1] rates (subject_id='mouse_03', session='s2', probe='imec0', unit=1): rate_hz = 5.058333333333334 +# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... +# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) +# csv_v1:units row_41 n_spikes = 607 (via Join, SelectDataColumns) +# [2] rates (subject_id='mouse_03', session='s2', probe='imec0', unit=2): rate_hz = 7.366666666666666 +# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... +# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) +# csv_v1:units row_42 n_spikes = 884 (via Join, SelectDataColumns) +# [3] rates (subject_id='mouse_03', session='s2', probe='imec0', unit=3): rate_hz = 4.683333333333334 +# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... +# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) +# csv_v1:units row_43 n_spikes = 562 (via Join, SelectDataColumns) +# [4] rates (subject_id='mouse_03', session='s2', probe='imec1', unit=0): rate_hz = 5.0 +# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... +# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) +# csv_v1:units row_44 n_spikes = 600 (via Join, SelectDataColumns) +# [5] rates (subject_id='mouse_03', session='s2', probe='imec1', unit=1): rate_hz = 3.3333333333333335 +# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... +# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) +# csv_v1:units row_45 n_spikes = 400 (via Join, SelectDataColumns) +# [6] rates (subject_id='mouse_03', session='s2', probe='imec1', unit=2): rate_hz = 6.916666666666667 +# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... +# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) +# csv_v1:units row_46 n_spikes = 830 (via Join, SelectDataColumns) +# [7] rates (subject_id='mouse_03', session='s2', probe='imec1', unit=3): rate_hz = 3.325 +# firing_rate v0.0 (body function_content_v1:...), computed here, computed ... on local, run ..., recorded ... +# csv_v1:sessions row_5 duration_s = 120.0 (via Join, SelectDataColumns) +# csv_v1:units row_47 n_spikes = 399 (via Join, SelectDataColumns) +``` + +The first line is the question: the column, the node, the row selector, and how many rows +match. Below it, the mean of `mouse_03`, session `s2`, was computed by `mean_rate`: the line +gives its version, the hash of its body, when and where it ran, and the job run that recorded +the entry. Its input was the grouped row of eight rates. Each rate was computed by +`firing_rate` from one row of `units.csv` and the row of `sessions.csv` for that session. The +operators a value passed through are listed after `via`. + +- A function's row is matched to its stored record by its system tags, the hidden tags that + name the source rows it came from. +- The members of a group are the rows before the grouping with the group's `subject_id` and + `session`. Orcapod checks them against the group's folded system tags and raises an error + if they do not agree. +- The last step reads the source-info columns: `csv_v1:units row_40` is row 40 of the source + named `units`. + +`source_cells()` lists the source cells, each once: + +```python +for cell in trace.source_cells(): + print(cell.text()) +# csv_v1:sessions row_5 duration_s = 120.0 +# csv_v1:units row_40 n_spikes = 575 +# csv_v1:units row_41 n_spikes = 607 +# csv_v1:units row_42 n_spikes = 884 +# csv_v1:units row_43 n_spikes = 562 +# csv_v1:units row_44 n_spikes = 600 +# csv_v1:units row_45 n_spikes = 400 +# csv_v1:units row_46 n_spikes = 830 +# csv_v1:units row_47 n_spikes = 399 +``` + +## Reused results + +In session `s1` of `mouse_02`, two units have the same spike count, so `firing_rate` received +equal inputs twice and ran once. The trace says which of the two rows computed the result and +which reused it: + +```python +shared = means.trace({"subject_id": "mouse_02", "session": "s1"}, "mean_rate_hz") +for step in shared.root.walk(): + if step.node == "rates": + tags = dict(step.tags) + print(tags["probe"], tags["unit"], step.function.computed_here) +# imec0 0 True +# imec0 1 True +# imec0 2 True +# imec0 3 True +# imec1 0 True +# imec1 1 True +# imec1 2 False +# imec1 3 True +``` + +`imec1` unit 2 reused the result that `imec0` unit 0 computed. One stored result serves two +rows, and each is traced to its own row of `units.csv`. + +## Several rows + +Every row whose columns equal the values given is traced, and `{}` traces every row. Each +matching row has its own tree, in `trace.roots`, in tag order. `source_cells()` and the +highlight cover all of them: + +```python +both = means.trace({"subject_id": "mouse_02"}, "mean_rate_hz") +print(both.header()) +# trace of mean_rate_hz at node session_means, for subject_id='mouse_02': 2 rows match +print([dict(root.tags) for root in both.roots]) +# [{'subject_id': 'mouse_02', 'session': 's1'}, {'subject_id': 'mouse_02', 'session': 's2'}] +print(len(both.source_cells())) +# 18 +``` + +A selector that matches no row gives a trace that says so (`no held row matches`, status +`no_match`). A selector that names a column the node does not have is an error. + +## On the diagram + +`trace.highlight()` marks the path of a trace on the job's diagram. The listing marks the +nodes on the path with `*` and the node the trace was asked at with `>` and +`[traced from here]`. Each function node on the path says how its rows on the path got their +results: `[computed]`, `[reused]` (a result stored for equal inputs), or +`[computed + reused]`. It shows no run status. The first diagram in a Python session issues +`InDevelopmentWarning` once (see [Part 5](05-pipeline-job.md#nodes)). + +```python +print(job.diagram(highlight=trace.highlight())) +# Job 'workshop': 9 nodes +# highlight (*): trace of mean_rate_hz at node session_means, for subject_id='mouse_03', session='s2': 1 row matches +# * sessions (source · CSVSource) +# * SelectDataColumns_2 (operator) <- sessions +# * units (source · CSVSource) +# * SelectDataColumns_1 (operator) <- units +# * Join (operator) <- SelectDataColumns_2, SelectDataColumns_1 +# * rates (function pod · firing_rate) [computed] <- Join +# * GroupBy (operator) <- rates +# * SelectDataColumns_3 (operator) <- GroupBy +# >* session_means (function pod · mean_rate) [computed] [traced from here] <- SelectDataColumns_3 +``` + +A mean is made through every step of the job, so its path covers the whole diagram. The trace +of one firing rate covers the two sources, their column selections, the join and `rates`. Take +the unit that reused a stored result: + +```python +rate = job.nodes["rates"].trace( + {"subject_id": "mouse_02", "session": "s1", "probe": "imec1", "unit": 2}, "rate_hz" +) +print(job.diagram(highlight=rate.highlight())) +# Job 'workshop': 9 nodes +# highlight (*): trace of rate_hz at node rates, for subject_id='mouse_02', session='s1', probe='imec1', unit=2: 1 row matches +# * sessions (source · CSVSource) +# * SelectDataColumns_2 (operator) <- sessions +# * units (source · CSVSource) +# * SelectDataColumns_1 (operator) <- units +# * Join (operator) <- SelectDataColumns_2, SelectDataColumns_1 +# >* rates (function pod · firing_rate) [reused] [traced from here] <- Join +# GroupBy (operator) <- rates +# SelectDataColumns_3 (operator) <- GroupBy +# session_means (function pod · mean_rate) <- SelectDataColumns_3 +``` + +In a notebook the same call draws the picture. The caption is the question. The path is +outlined and the rest is dimmed. The node the trace was asked at has a second outline and the +line "traced from here", and `rates` has the line "reused": + +![The diagram of the workshop job, captioned "highlighted: trace of rate_hz at node rates, for subject_id='mouse_02', session='s1', probe='imec1', unit=2: 1 row matches": the sources sessions and units, their column selections, the Join and the function pod rates outlined in a dark line; rates has a second outline and the bold lines "reused" and "traced from here"; GroupBy, its selection and the function pod session_means dimmed](provenance-diagram-trace.svg) + +## Stored entries and the last run + +`computed here`, `[computed]` and `[reused]` describe the **stored entry**, in the run that +recorded it. What the last run computed is in its run summary. Build the same job again over +the same database, as a new Python session would, and run it: + +```python +again = PipelineJob(name="workshop", database=database) +with again: + rates = firing_rate.pod( + units.select_data_columns(["n_spikes"]), + sessions.select_data_columns(["duration_s"]), + label="rates", + ) + mean_rate.pod( + rates.group_by(["subject_id", "session"]).select_data_columns(["rate_hz"]), + label="session_means", + ) +print(again.run()) +# Run of job 'workshop': all rows succeeded. +# rates: 64 rows: 0 computed, 64 from store, 0 failed +# session_means: 8 rows: 0 computed, 8 from store, 0 failed +warm = again.nodes["session_means"].trace( + {"subject_id": "mouse_03", "session": "s2"}, "mean_rate_hz" +) +print([run.computed_here for label, run in warm.function_runs() if label == "session_means"]) +# [True] +print(warm.highlight().marks == trace.highlight().marks) +# True +``` + +This run computed nothing: the summary counts 0 computed and 72 from the store. The trace and +its marks are those of the first job, because the entries were recorded by the first run. A +loaded job (`PipelineJob.load`) shows the same. + +## Missing rows + +A second job keeps only the `imec0` probe and leaves out the sessions of `mouse_04`. Row 4 of +`units.csv` is an `imec1` unit, and row 48 is a unit of `mouse_04`. Neither has a firing rate. +`why_missing` says which step removed each: + +```python +from orcapod.types import col + +imec0 = PipelineJob(name="imec0", database=database) +with imec0: + units = CSVSource( + str(data_dir / "units.csv"), + tag_columns=["subject_id", "session", "probe", "unit"], tag_only_columns=True, + source_id="units", + ) + sessions = CSVSource( + str(data_dir / "sessions.csv"), + tag_columns=["subject_id", "session"], tag_only_columns=True, + source_id="sessions", + ) + firing_rate.pod( + units.filter({"probe": "imec0"}).select_data_columns(["n_spikes"]), + sessions.filter(col("subject_id") != "mouse_04").select_data_columns( + ["duration_s"] + ), + label="imec0_rates", + ) +imec0.run() +print(imec0.nodes["imec0_rates"].why_missing("units", "row_4")) +# why record row_4 of units is missing at node imec0_rates +# units row_4 is removed by Filter[...]: probe='imec0' +# no successful entry of function node 'imec0_rates' is stored for it (the function raised on it, or never received it) +# present in: units +print(imec0.nodes["imec0_rates"].why_missing("units", "row_48")) +# why record row_48 of units is missing at node imec0_rates +# units row_48 is removed by Join: rows without a match in 'sessions' are dropped +# no successful entry of function node 'imec0_rates' is stored for it (the function raised on it, or never received it) +# present in: units, ... +# because: no row with session='s1', subject_id='mouse_04' in ... (reads sessions) +``` + +The first line is the question. The second names the step that removed the row. The third is +read from the stored records of `imec0_rates`: no run of this job stored a result for the row. +A function that raised on a row stores no result for it either, so the third line alone does +not say the function never received the row; the second line does. + +`why_missing(...).highlight()` marks the path up to the step that removed the row. The other +nodes are dimmed, except the node asked at, marked "asked here". For `units row_4`, the path +ends at the filter on `probe`: + +![The diagram of the imec0 job, captioned "highlighted: why record row_4 of units is missing at node imec0_rates: ...": the source units and the node Filter_2 outlined in a dark line; the sessions branch and the Join dimmed; the function pod imec0_rates with a second outline and the bold line "asked here"](provenance-diagram-missing-filter.svg) + +`units row_48` passes the filter and its column selection and ends at the Join, which has no +session `s1` of `mouse_04` to match it with: + +![The diagram of the imec0 job, captioned "highlighted: why record row_48 of units is missing at node imec0_rates: ...": the source units, Filter_2, SelectDataColumns_1 and the Join outlined in a dark line; the sessions branch dimmed; the function pod imec0_rates with a second outline and the bold line "asked here"](provenance-diagram-missing-join.svg) + +## Key points + +- `node.trace(row, column)` follows one value back to its source cells, and says which + function computed each step and whether it reused a stored result. +- `trace.source_cells()` lists the source cells. +- `computed` and `reused` describe the stored entry; the run summary describes the last run. +- `node.why_missing(source, record_id)` says which step removed a row. +- `job.diagram(highlight=...)` marks the path of a trace or of a missing row. + +## Exercises + +**1.** Trace the firing rate of unit 0 on probe `imec0` in session `s1` of `mouse_01`, at the +`rates` node. Which source cells was it computed from? + +??? success "Solution" + ```python + first = job.nodes["rates"].trace( + {"subject_id": "mouse_01", "session": "s1", "probe": "imec0", "unit": 0}, "rate_hz" + ) + for cell in first.source_cells(): + print(cell.text()) + # csv_v1:sessions row_0 duration_s = 60.0 + # csv_v1:units row_0 n_spikes = 149 + ``` + + One cell of each source: the session's duration and the unit's spike count. + +**2.** Row 56 of `units.csv` is an `imec0` unit of `mouse_04`, session `s2`. Which step of the +`imec0` job removes it? + +??? success "Solution" + ```python + print(imec0.nodes["imec0_rates"].why_missing("units", "row_56")) + # why record row_56 of units is missing at node imec0_rates + # units row_56 is removed by Join: rows without a match in 'sessions' are dropped + # no successful entry of function node 'imec0_rates' is stored for it (the function raised on it, or never received it) + # present in: units, ... + # because: no row with session='s2', subject_id='mouse_04' in ... (reads sessions) + ``` + + The row passes the filter on `probe`. The Join removes it, because the filter on + `sessions` left no session of `mouse_04` to match it with. diff --git a/docs/tutorial/10-where-next.md b/docs/tutorial/where-next.md similarity index 98% rename from docs/tutorial/10-where-next.md rename to docs/tutorial/where-next.md index 7f47d6e65..d7e0a1e1b 100644 --- a/docs/tutorial/10-where-next.md +++ b/docs/tutorial/where-next.md @@ -1,6 +1,6 @@ -# Part 10: Where next +# Where next -This part is optional. It is a short tour of features the tutorial did not need. The sections +This page is optional. It is a short tour of features the tutorials did not need. The sections are independent. ```python diff --git a/scripts/docs_site_content.py b/scripts/docs_site_content.py index c0e083fe5..59aede8ea 100644 --- a/scripts/docs_site_content.py +++ b/scripts/docs_site_content.py @@ -241,7 +241,7 @@ class Hero: image=SITE_DIR / "src" / "assets" / "orcapod-icon.png", actions=( HeroAction("Get started", "getting-started.md", "primary", "right-arrow"), - HeroAction("Tutorial", "tutorial/index.md", "secondary"), + HeroAction("Tutorials", "tutorial/index.md", "secondary"), HeroAction( "GitHub", "https://github.com/metamorphic-labs/orcapod-python", diff --git a/site/README.md b/site/README.md index 4f1f5bb5c..dea29b1a9 100644 --- a/site/README.md +++ b/site/README.md @@ -123,7 +123,7 @@ accent of its own: Every text colour meets WCAG AA against its background. The home page opens with a hero (Starlight's `splash` template, so it has no sidebar): -the logo, the name in Lexend Exa, a tagline and three buttons (Get started, Tutorial, +the logo, the name in Lexend Exa, a tagline and three buttons (Get started, Tutorials, GitHub). `docs/index.md` stays a plain page; the content build adds the hero as its front matter (`HOME_HERO` in `../scripts/docs_site_content.py`), and its buttons are links checked like any other. The hero's logo is the header's file: Astro could only resize diff --git a/site/astro.config.mjs b/site/astro.config.mjs index 6bb8b3cb7..56075569e 100644 --- a/site/astro.config.mjs +++ b/site/astro.config.mjs @@ -130,20 +130,32 @@ export default defineConfig({ { label: 'Home', link: '/' }, page('Getting Started', 'getting-started'), { - label: 'Tutorial', + label: 'Tutorials', items: [ page('Overview', 'tutorial'), - page('0. Setup', 'tutorial/00-setup'), - page('1. Your first stream', 'tutorial/01-first-stream'), - page('2. Computing with function pods', 'tutorial/02-function-pods'), - page('3. Reshaping with operators', 'tutorial/03-operators'), - page('4. Many rows into one', 'tutorial/04-many-rows-into-one'), - page('5. Keeping results', 'tutorial/05-pipeline-job'), - page('6. Re-runs', 'tutorial/06-reruns-and-caching'), - page('7. Working with files', 'tutorial/07-files'), - page('8. Inspecting and tracing', 'tutorial/08-inspecting-and-tracing'), - page('9. Handling errors', 'tutorial/09-when-things-go-wrong'), - page('10. Where next', 'tutorial/10-where-next'), + { + label: 'Core course', + items: [ + page('0. Setup', 'tutorial/00-setup'), + page('1. Your first stream', 'tutorial/01-first-stream'), + page('2. Computing with function pods', 'tutorial/02-function-pods'), + page('3. Reshaping with operators', 'tutorial/03-operators'), + page('4. Many rows into one', 'tutorial/04-many-rows-into-one'), + page('5. Keeping results', 'tutorial/05-pipeline-job'), + page('6. Re-runs', 'tutorial/06-reruns-and-caching'), + ], + }, + { + label: 'Short tutorials', + items: [ + page('Working with files', 'tutorial/files'), + page('Inspecting results', 'tutorial/inspecting-results'), + page('Tracing a value', 'tutorial/tracing-a-value'), + page('Chaining pipelines', 'tutorial/chaining-pipelines'), + page('Handling errors', 'tutorial/handling-errors'), + ], + }, + page('Where next', 'tutorial/where-next'), ], }, { diff --git a/tests/test_docs/test_doc_samples.py b/tests/test_docs/test_doc_samples.py index 8f89d728e..e9925bdf0 100644 --- a/tests/test_docs/test_doc_samples.py +++ b/tests/test_docs/test_doc_samples.py @@ -267,10 +267,12 @@ def test_doc_pages_are_discovered(): "docs/tutorial/04-many-rows-into-one.md", "docs/tutorial/05-pipeline-job.md", "docs/tutorial/06-reruns-and-caching.md", - "docs/tutorial/07-files.md", - "docs/tutorial/08-inspecting-and-tracing.md", - "docs/tutorial/09-when-things-go-wrong.md", - "docs/tutorial/10-where-next.md", + "docs/tutorial/files.md", + "docs/tutorial/inspecting-results.md", + "docs/tutorial/tracing-a-value.md", + "docs/tutorial/chaining-pipelines.md", + "docs/tutorial/handling-errors.md", + "docs/tutorial/where-next.md", ): assert expected in DOC_PAGES diff --git a/tests/test_docs/test_provenance_diagrams.py b/tests/test_docs/test_provenance_diagrams.py index ab6150ea1..1c2feaa27 100644 --- a/tests/test_docs/test_provenance_diagrams.py +++ b/tests/test_docs/test_provenance_diagrams.py @@ -57,7 +57,7 @@ def test_a_picture_is_self_contained_and_on_its_own_background(name: str) -> Non @pytest.mark.parametrize( "page", - ["docs/tutorial/08-inspecting-and-tracing.md", "docs/concepts/provenance.md"], + ["docs/tutorial/tracing-a-value.md", "docs/concepts/provenance.md"], ) def test_the_pages_show_the_pictures(page: str) -> None: text = (REPOSITORY / page).read_text(encoding="utf-8") diff --git a/tests/test_docs/test_site_content.py b/tests/test_docs/test_site_content.py index 04f519435..a8fd281f6 100644 --- a/tests/test_docs/test_site_content.py +++ b/tests/test_docs/test_site_content.py @@ -171,7 +171,7 @@ def test_the_home_page_gets_the_hero(tmp_path: Path): "icon": "right-arrow", }, { - "text": "Tutorial", + "text": "Tutorials", "link": "/orcapod-python/tutorial/", "variant": "secondary", },