From caee002be21585709db6627ab79fa77b7ee83933 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 20:36:53 -0800 Subject: [PATCH 1/5] docs(tutorial): plain-language pass over Getting Started and the tutorial (ITL-1459) Co-Authored-By: Claude Opus 5.5 --- .gitignore | 1 + README.md | 4 +- changelog.d/ITL-1459.md | 5 + docs/concepts/notebooks.md | 2 +- docs/dev/documentation-style.md | 62 ++++++++ docs/getting-started.md | 111 +++++--------- docs/index.md | 4 +- docs/troubleshooting.md | 4 +- docs/tutorial/00-setup.md | 21 ++- docs/tutorial/01-first-stream.md | 109 +++++++------- docs/tutorial/02-function-pods.md | 118 ++++++--------- docs/tutorial/03-operators.md | 163 ++++++++------------- docs/tutorial/04-many-rows-into-one.md | 101 +++++-------- docs/tutorial/05-pipeline-job.md | 113 ++++++-------- docs/tutorial/06-reruns-and-caching.md | 115 ++++++--------- docs/tutorial/07-files.md | 127 +++++++--------- docs/tutorial/08-inspecting-and-tracing.md | 8 +- docs/tutorial/09-when-things-go-wrong.md | 139 ++++++++---------- docs/tutorial/10-where-next.md | 47 +++--- docs/tutorial/index.md | 16 +- site/astro.config.mjs | 4 +- 21 files changed, 554 insertions(+), 720 deletions(-) create mode 100644 changelog.d/ITL-1459.md create mode 100644 docs/dev/documentation-style.md diff --git a/.gitignore b/.gitignore index 0f91c5cb0..cb4a61fdc 100644 --- a/.gitignore +++ b/.gitignore @@ -216,6 +216,7 @@ docs/dev/* !docs/dev/notes !docs/dev/orcapod-design.md !docs/dev/security-exceptions.md +!docs/dev/documentation-style.md # General JSON files at project root /*.json diff --git a/README.md b/README.md index b810cfef3..3b0834a14 100644 --- a/README.md +++ b/README.md @@ -21,10 +21,10 @@ Orcapod to a uv project (start one with `uv init` in a new directory), and `uv r your code in that project's environment: ```bash -uv add "orcapod>=0.4.0rc4" +uv add "orcapod>=0.4.0rc7" ``` -In an environment not managed by uv, use `pip install "orcapod>=0.4.0rc4"` instead. For the +In an environment not managed by uv, use `pip install "orcapod>=0.4.0rc7"` instead. For the development version, install from the repository: `uv add git+https://github.com/metamorphic-labs/orcapod-python`. diff --git a/changelog.d/ITL-1459.md b/changelog.d/ITL-1459.md new file mode 100644 index 000000000..b463e937d --- /dev/null +++ b/changelog.d/ITL-1459.md @@ -0,0 +1,5 @@ +### Changed + +- Getting Started and the tutorial are shorter and in plainer language, loop over a stream with + `for tag, data in stream`, and install at least 0.4.0rc7. Part 6 is titled "Re-runs" and + Part 9 "Handling errors". (ITL-1459) diff --git a/docs/concepts/notebooks.md b/docs/concepts/notebooks.md index 4cc4f72ef..f46a88c72 100644 --- a/docs/concepts/notebooks.md +++ b/docs/concepts/notebooks.md @@ -170,7 +170,7 @@ One row per function node: `rows` is every input row the run accounted for in th how many its function computed in this run, `from store` how many it read back from the database instead, `failed` how many raised, and `first error` the first of those errors, with the call that prints its full traceback (`job.last_run.print_traceback("rates")`). Here one `rates` row -was found in the store during the run itself ([Part 5](../tutorial/05-pipeline-job.md#record-then-run) +was found in the store during the run itself ([Part 5](../tutorial/05-pipeline-job.md#run-a-recorded-job) of the tutorial explains why). A load-only run (`job.run(load_only=True)`) shows how many rows each node loaded and how many had no stored result instead. The job keeps the summary as `job.last_run`. A cell that ends with `job.run();` (a semicolon) shows nothing. What a run diff --git a/docs/dev/documentation-style.md b/docs/dev/documentation-style.md new file mode 100644 index 000000000..86475c036 --- /dev/null +++ b/docs/dev/documentation-style.md @@ -0,0 +1,62 @@ +# Documentation style + +How to write the published documentation, the tutorial above all (ITL-1459). CLAUDE.md, +"Documentation samples" and "Documentation site", has the mechanics. + +## Sentences + +Write short declarative sentences that say what happens or what to do. Cut any sentence that +announces, justifies or repeats another one. + +| Avoid | Before | After | +|---|---|---| +| Announcing what comes next | "Now the surprise. Suppose you edit the function:" | "Suppose you edit the function:" | +| Answering a doubt nobody raised | "63 times for 64 units. That is not a mistake: two units have the same inputs." | "63 times for 64 units, because two units have the same inputs." | +| Denying one thing to state another | "identified by the path, not the content" | "identified by the path" | +| "Always" and "never" that change nothing for the reader | "Refer to columns by name, never by position." | "Refer to columns by name." | +| A colon that only delays the sentence | "The habit that makes these quick to fix: print `keys()`." | "Print `keys()`." | +| An aside after a dash | "The schema is unchanged -- pods never modify tags." | "The schema is unchanged: a pod passes tags through." | +| Selling a feature | "Notice that this is why tags matter: you never wrote the lookup." | (cut) | +| Talking about the page | "These samples only serve to produce the clash." | (cut) | +| Emphasis by contrast | "It finishes. It is not finished successfully." | "A job can finish with failed rows." | + +A negative sentence is right when the reader would otherwise act wrongly: "A change after the +dot is **not** enough." + +## Headings + +- Name the subject: "Nodes", "Reuse rule", "Versioning a pod". A heading does not carry the + conclusion ("An edited function: nothing is recomputed"), ask a question, or say that one + thing is another ("A source is a stream"). +- A changed heading changes its anchor. Find every link to it with + `grep -rn '.md#' docs README.md`; the site build checks them. + +## Facts + +- State a fact once, on the page and at the place where the reader needs it. Elsewhere, link to + it. A message that every page can show (`ProvisionalHashWarning`) is explained in Setup only. +- Do not introduce what the page does not use. Link to the concept page instead. +- Check each sentence against the code, or run it. Show the output the library prints. +- Cutting words must not cut a trap. These stay wherever they apply: an edited function returns + its old values; comparisons in a filter need parentheses, and `and` drops a condition without + an error; a node reads empty before `run()`; a finished job can have failed rows; a stored + path outlives a deleted file. +- Show a number only when the reader can compare it with something. + +## Examples + +- Orcapod is general. Describe a feature in general terms, and use the workshop data as the + example. +- An example or exercise gives the domain facts it needs: "Unit numbers restart at 0 on every + probe." A reader must not have to know the field to answer. +- Code and text use the names of the columns they produce: `return temp_fahrenheit` for + `output_keys=["temp_fahrenheit"]`. +- Iterate with `for tag, data in stream`. +- The install lines name a release candidate that has every feature the pages use. + +## Tutorial pages + +- A part opens with what it adds, then a "You will" list. +- "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. diff --git a/docs/getting-started.md b/docs/getting-started.md index c61f9f572..d0a30593e 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -11,15 +11,15 @@ with `uv init` (in a new directory) and add Orcapod to it: ```bash uv init -uv add "orcapod>=0.4.0rc4" +uv add "orcapod>=0.4.0rc7" ``` -In an environment not managed by uv, `pip install "orcapod>=0.4.0rc4"` installs it instead. +In an environment not managed by uv, `pip install "orcapod>=0.4.0rc7"` installs it instead. -The workshop uses the latest 0.4.0 release candidate, which these commands install. The -latest stable release on PyPI is 0.1.4 (0.3.0 was withdrawn), which a plain `uv add orcapod` installs and this guide does not -cover. For the development version, install from the repository: -`uv add git+https://github.com/metamorphic-labs/orcapod-python`. +The workshop uses the latest 0.4.0 release candidate, which these commands install. The latest +stable release on PyPI is 0.1.4 (0.3.0 was withdrawn), which a plain `uv add orcapod` installs +and this guide does not cover. For the development version, install from the repository: `uv +add git+https://github.com/metamorphic-labs/orcapod-python`. ## Creating a source @@ -40,20 +40,15 @@ source = DictSource( ) ``` -There are two important concepts here: +- **Tag columns** (`tag_columns`) are the keys that identify each row, like primary keys in a + database or independent variables in an experiment. Here, `experiment` identifies each + measurement. +- **Data columns** hold the values. Here they are `temperature` and `pressure`. -- **Tag columns** (`tag_columns`) are the keys that identify each row -- like primary keys - in a database or independent variables in an experiment. Here, `experiment` uniquely - identifies each measurement. -- **Data columns** are the actual data payload. In this example, `temperature` and - `pressure` are the data columns. +Here a column is either a tag or data. `tag_only_columns=True` sets that; see +[Data-tags](concepts/data-tags.md) for columns with both roles. -By default a source's tag columns are also data columns: each is a **data-tag**, one -column seen in both roles, so a function can read it. `tag_only_columns=True` keeps the tags -plain (a tag only), which is what this example does, so the data columns are exactly the -columns that are not tags. See [Data-tags](concepts/data-tags.md). - -The `source_id` is a human-readable name used for provenance tracking. +The `source_id` names the source. Orcapod uses it when it records where a value came from. !!! note Orcapod provides several source types beyond `DictSource`: `ListSource`, `CSVSource`, @@ -62,10 +57,10 @@ The `source_id` is a human-readable name used for provenance tracking. ## Inspecting the stream -In Orcapod, a source *is* a stream. You can inspect it immediately without any extra -conversion step. In a notebook, put `source` on the last line of a cell to see a table of -its first rows; [Working in notebooks](concepts/notebooks.md) shows what that table and -Orcapod's other notebook displays show. +Every step in Orcapod takes streams and returns a stream. A source is the stream that brings +data in, so you can inspect it right away. In a notebook, put `source` on the last line of a +cell to see a table of its first rows; [Working in notebooks](concepts/notebooks.md) shows +what that table and Orcapod's other notebook displays show. ### Schema @@ -93,8 +88,7 @@ print(data_keys) ### Iterating over rows -A stream is iterable: a `for` loop walks through each (Tag, Data) pair. Iterating a stream -is the same as calling its `iter_data()` method: +A `for` loop over a stream gives one (tag, data) pair per row: ```python for tag, data in source: @@ -127,24 +121,22 @@ from orcapod import function_pod @function_pod(output_keys=["temp_fahrenheit", "is_high_pressure"]) def analyze_conditions(temperature: float, pressure: float) -> tuple[float, bool]: - temp_f = temperature * 9.0 / 5.0 + 32.0 - is_high = pressure > 1.0 - return temp_f, is_high + temp_fahrenheit = temperature * 9.0 / 5.0 + 32.0 + is_high_pressure = pressure > 1.0 + return temp_fahrenheit, is_high_pressure ``` -A few things to note about function pods: - -- **Parameter names match data column names.** The function's parameter names - (`temperature`, `pressure`) must match the data column names from the input stream - exactly -- one parameter per data column. Data columns the function does not take are - dropped when you call the pod; `pod(stream, strict=True)` and `pod.process(stream)` - reject them instead (see [Function Pods](concepts/function-pods.md#input-columns)). +- **Parameter names match data column names.** Each parameter takes the data column with + exactly its name, here `temperature` and `pressure`. +- **Data columns the function does not take are dropped** when you call the pod. + `pod(stream, strict=True)` and `pod.process(stream)` reject them instead (see + [Function Pods](concepts/function-pods.md#input-columns)). - **Type annotations define the schemas.** Orcapod uses them to build the output schema and to validate compatibility when the pod is applied. A parameter without an annotation needs its type in the decorator's `input_schema` mapping instead. -- **`output_keys` names the output columns.** Since the function returns a tuple of two - values, `output_keys` must be a list of two names. For a function returning a single - value, pass a single string (e.g., `output_keys="result"`). +- **`output_keys` names the output columns.** The function returns a tuple of two + values, so `output_keys` is a list of two names, in the order of the tuple. A function that + returns one value takes a single string, such as `output_keys="result"`. - **The decorator creates a `.pod` attribute.** You call `.pod(stream)` to apply the function to a stream. @@ -154,13 +146,8 @@ Now apply it: result = analyze_conditions.pod(source) ``` -!!! tip - For an operator, `op(stream)` is a shorthand for `op.process(stream)`. For a function - pod, `pod(stream)` also drops the data columns the function does not take, while - `pod.process(stream)` is exact and rejects them. - -The `result` is a new stream. Tags are preserved from the input; the data columns -are replaced with the function's outputs. +`result` is a new stream. It has the tags of the input, and the function's outputs as its +data columns. ## Inspecting the result @@ -174,8 +161,8 @@ print(data_schema) # Schema({'temp_fahrenheit': float, 'is_high_pressure': bool}) ``` -The tag schema is unchanged -- function pods never modify tags. The data schema -now reflects the function's output types. +The tag schema is unchanged: a function pod passes tags through. The data schema holds the +function's outputs. Iterate over the results: @@ -219,9 +206,9 @@ source = DictSource( # Define a transformation @function_pod(output_keys=["temp_fahrenheit", "is_high_pressure"]) def analyze_conditions(temperature: float, pressure: float) -> tuple[float, bool]: - temp_f = temperature * 9.0 / 5.0 + 32.0 - is_high = pressure > 1.0 - return temp_f, is_high + temp_fahrenheit = temperature * 9.0 / 5.0 + 32.0 + is_high_pressure = pressure > 1.0 + return temp_fahrenheit, is_high_pressure # Apply and view results result = analyze_conditions.pod(source) @@ -242,25 +229,7 @@ With `pip`, in the activated environment: `python my_pipeline.py`. ## Keeping results -Everything above runs in memory: nothing is stored, 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. - -## Next steps - -Now that you have the basics, explore these topics: - -- [Sources](concepts/sources.md) -- learn about the different source types and how - provenance tracking works. -- [Streams](concepts/streams.md) -- understand the immutable (Tag, Data) stream model. -- [Working in notebooks](concepts/notebooks.md) -- what streams, run summaries and pipeline - diagrams show at the end of a notebook cell. -- [Function Pods](concepts/function-pods.md) -- advanced function pod usage, including - caching with databases. -- [Operators](concepts/operators.md) -- structural transforms like Join, Batch, and Filter - that work on tags and stream structure without inspecting data content. -- [Identity & Hashing](concepts/identity.md) -- how Orcapod tracks content identity and - pipeline structure for reproducibility. -- [Tutorial](tutorial/index.md) -- a self-paced course with exercises, on one small dataset. -- [Troubleshooting](troubleshooting.md) -- common errors, their causes and fixes. +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. diff --git a/docs/index.md b/docs/index.md index 54f752e38..ef0832bb1 100644 --- a/docs/index.md +++ b/docs/index.md @@ -18,10 +18,10 @@ Orcapod to a uv project (start one with `uv init` in a new directory), and `uv r your code in that project's environment: ```bash -uv add "orcapod>=0.4.0rc4" +uv add "orcapod>=0.4.0rc7" ``` -In an environment not managed by uv, use `pip install "orcapod>=0.4.0rc4"` instead. For the +In an environment not managed by uv, use `pip install "orcapod>=0.4.0rc7"` instead. For the development version, install from the repository: `uv add git+https://github.com/metamorphic-labs/orcapod-python`. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 6e8080776..3c17ee161 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -387,8 +387,8 @@ Reading a Delta table yourself with `deltalake.DeltaTable(...).to_pyarrow_table( are installing a version of Orcapod older than 0.2, which required the Graphviz development headers. The latest stable release on PyPI, which a plain `uv add orcapod` installs, is 0.1.4 (0.3.0 was withdrawn). Install the latest 0.4.0 release candidate: - `uv add "orcapod>=0.4.0rc4"`. + `uv add "orcapod>=0.4.0rc7"`. - **Python version.** Orcapod needs Python 3.11 or newer. - **A release candidate is not installed.** `uv add orcapod` (like `pip install orcapod`) takes the latest stable release and skips pre-releases. Name a candidate version, at least: - `uv add "orcapod>=0.4.0rc4"`. + `uv add "orcapod>=0.4.0rc7"`. diff --git a/docs/tutorial/00-setup.md b/docs/tutorial/00-setup.md index b1442ef7c..78d856a87 100644 --- a/docs/tutorial/00-setup.md +++ b/docs/tutorial/00-setup.md @@ -14,7 +14,7 @@ new directory, and `uv add` adds Orcapod to it): ```bash mkdir orcapod-workshop && cd orcapod-workshop uv init -uv add "orcapod>=0.4.0rc4" +uv add "orcapod>=0.4.0rc7" ``` Without uv, with `pip` in a virtual environment: @@ -23,7 +23,7 @@ Without uv, with `pip` in a virtual environment: mkdir orcapod-workshop && cd orcapod-workshop python -m venv .venv source .venv/bin/activate # on Windows: .venv\Scripts\activate -pip install "orcapod>=0.4.0rc4" +pip install "orcapod>=0.4.0rc7" ``` The workshop uses the latest 0.4.0 release candidate, which these commands install (naming @@ -71,12 +71,12 @@ print("Orcapod is working.") # Orcapod is working. ``` -If you see the two lines above, you are ready. You do not need to understand the script yet; -every piece of it is introduced in the parts that follow. +If you see the two lines above, you are ready. The following parts introduce every piece of +the script. ### Messages you can ignore -You may see these on your screen. They are harmless. +These messages are harmless. - `ProvisionalHashWarning: Filter is provisional: its identity is not frozen ...`, once per Python session for each provisional step you use: `filter`, `group_by`, `batch`, @@ -108,9 +108,9 @@ It prints `Wrote 27 files (... kB) to .../workshop_data` and creates the `worksh directory described on the [tutorial front page](index.md#the-dataset). The data is the same on every machine and every run, so your output will match these pages exactly. -Keep `workshop_data.py` in your working directory. Every part of the tutorial starts with -these two lines. `make_dataset()` writes the original files again on every call, overwriting -any edits you made to them, and gives you their location: +Keep `workshop_data.py` in your working directory. Every part starts by calling +`make_dataset()`. Each call writes the original files again, overwriting any edits you made +to them, and returns their location: ```python from workshop_data import make_dataset @@ -144,8 +144,7 @@ with `pandas.read_csv`. Which column or columns identify a row in each file? # False False ``` - Hold on to this idea. Orcapod calls these identifying columns *tags*, and Part 1 starts - from them. + Orcapod calls these identifying columns *tags*. Part 1 starts from them. **2.** How many spikes are in `workshop_data/sessions/mouse_01_s1/spikes_imec0.csv`? @@ -157,5 +156,3 @@ with `pandas.read_csv`. Which column or columns identify a row in each file? print(len(spikes)) # 1736 ``` - -Next: [Part 1: Your first stream](01-first-stream.md). diff --git a/docs/tutorial/01-first-stream.md b/docs/tutorial/01-first-stream.md index a3b50d493..1f76ad05c 100644 --- a/docs/tutorial/01-first-stream.md +++ b/docs/tutorial/01-first-stream.md @@ -1,14 +1,13 @@ # Part 1: Your first stream -An analysis usually starts with tables: a list of animals, a list of sessions, a table of -measurements. Before Orcapod can compute anything, it needs to know two things about each -table: which columns say *what a row is about*, and which columns hold *the values*. This part -shows how to load a table and tell Orcapod that. +An analysis usually starts with tables. Orcapod needs to know two things about each table: +which columns identify a row, and which columns hold the values. This part shows how to load +a table and tell Orcapod both. You will: - load a CSV file and a list of Python dictionaries as **sources** -- choose **tag columns** and see what is left as **data columns** +- choose **tag columns** and **data columns** - look at a **stream** four ways: its schema, its column names, row by row, and as a DataFrame ```python @@ -17,7 +16,7 @@ from workshop_data import make_dataset data_dir = make_dataset() ``` -## A source is a table with named keys +## Loading a table A **source** is where data enters Orcapod. `CSVSource` reads a CSV file: @@ -37,31 +36,24 @@ print(subjects.as_pandas_df()) # 3 mouse_04 M 13 knockout ``` -Three arguments: -- The file path, **as a string**. `CSVSource` takes a string, not a `pathlib.Path`, hence - the `str(...)`. -- `tag_columns`: the columns that identify a row. More on this below. -- `source_id`: a name for this source. Orcapod uses it when it records where a value came - from. Give every source a short, stable name. -## Tags and data - -Every column of a source is either a tag column or a data column. +- The file path is a string, so a `pathlib.Path` needs `str(...)`. +- `tag_columns` names the columns that identify a row. +- `tag_only_columns=True` makes those columns tags only, as the next section explains. +- `source_id` names the source. Orcapod uses it when it records where a value came from. + Give every source a short, stable name. -- **Tag columns** say what a row is about. They are the keys: the mouse, the session, the - probe. If you have used a relational database, they play the part of a primary key. Orcapod - uses tags to match rows when it combines tables. -- **Data columns** are everything else: the values that were measured or recorded. +## Tags and data -By default a declared tag column is also a data column: `CSVSource`, like every source built -from a table, makes its tags **data-tags**, one column seen both as a tag and as the data -column of the same name (see [Data-tags](../concepts/data-tags.md)). This -tutorial keeps its tags plain with `tag_only_columns=True`: a plain tag is a tag only, never -also a data column, so the data columns below are exactly the columns that are not tags. +- **Tag columns** identify a row, like a primary key in a database. Orcapod uses them to + match rows when it combines tables. +- **Data columns** hold the values. -You choose the tag columns; all remaining columns become data columns. `output_schema()` -returns both groups, with their types: +Here a column is either a tag or data. `tag_only_columns=True` sets that; see +[Data-tags](../concepts/data-tags.md) for columns with both roles. You name the tag columns, +and all remaining columns are data columns. `output_schema()` returns both groups, with their +types: ```python tag_schema, data_schema = subjects.output_schema() @@ -71,7 +63,7 @@ print(data_schema) # Schema({'sex': str, 'age_weeks': int, 'genotype': str}) ``` -A **schema** is the list of column names and their types. Orcapod worked the types out from +A **schema** is the list of column names and their types. `CSVSource` infers the types from the file: `age_weeks` is an `int` because every value in that column is a whole number. `keys()` gives only the names: @@ -84,8 +76,8 @@ print(data_keys) # ('sex', 'age_weeks', 'genotype') ``` -A table can need more than one tag column. A session is identified by the mouse *and* the -session name: +A table can need more than one tag column. Every mouse has a session called `s1`, so a +session is identified by the mouse and the session name together: ```python sessions = CSVSource( @@ -97,14 +89,14 @@ print(sessions.output_schema()) # (Schema({'subject_id': str, 'session': str}), Schema({'date': date, 'duration_s': float})) ``` -## A source is a stream +## Looking at a stream -What a source gives you is a **stream**: an ordered, read-only sequence of rows, each one a -pair of (tag, data). Every step you add later takes streams in and gives a stream back, so -the four ways of looking at a stream shown in this part work at every stage of a pipeline. +A **stream** is a read-only sequence of rows, each one a pair of (tag, data). Every step in +Orcapod takes streams and returns a stream. A source is the stream that brings data in. +`output_schema()` and `keys()`, and everything below, work on every stream. -You have seen `output_schema()` and `keys()`. To walk through the rows, loop over the stream -(the same as calling its `iter_data()` method). Each row comes as two objects; call `.as_dict()` on either to get a plain dictionary: +Loop over a stream to get its rows. Call `.as_dict()` on a tag or a data object to get a +plain dictionary: ```python for tag, data in sessions: @@ -132,13 +124,12 @@ print(sessions.as_table().num_rows) # 8 ``` -A stream cannot be changed. There is no method to edit a row or add a column in place. To -get different data you build a new stream from this one, which is what Parts 2 to 4 are -about. +A stream cannot be changed in place. To get different data, you build a new stream from it, +as Parts 2 to 4 show. ## Sources from Python data -Not everything starts as a file. `DictSource` takes a list of dictionaries, one per row: +`DictSource` takes a list of dictionaries, one per row: ```python from orcapod.sources import DictSource @@ -157,28 +148,29 @@ print(probes.as_pandas_df()) # 1 imec1 CA1 384 ``` -It behaves exactly like the CSV sources above. Orcapod has more source types (pandas and -Polars DataFrames, Delta tables, SQL tables); they differ only in where the rows come from. +Orcapod has more source types, for pandas and Polars DataFrames, Delta tables and SQL tables. See [Sources](../concepts/sources.md). -## What to remember +## Key points -- A **source** brings a table into Orcapod. A source is a **stream** of (tag, data) rows. +- Every step takes **streams** of (tag, data) rows and returns a stream. A **source** is the + stream that brings data in. - **Tag columns** identify a row; **data columns** hold the values. You choose the tags. -- Look at any stream with `output_schema()`, `keys()`, `iter_data()` and `as_pandas_df()`. +- Look at any stream with `output_schema()`, `keys()`, a `for` loop and + `as_pandas_df()`. - Streams are read-only. ## Exercises **1.** `workshop_data/units.csv` has one row per sorted unit, with columns `subject_id`, -`session`, `probe`, `unit`, `region`, `depth_um` and `n_spikes`. Load it as a source called -`units`. Which columns must be tags so that each row is identified? How many rows does it -have? +`session`, `probe`, `unit`, `region`, `depth_um` and `n_spikes`. Unit numbers restart at 0 on +every probe, probe names repeat in every session, and session names repeat for every mouse. +`region`, `depth_um` and `n_spikes` describe the unit. Load the file as a source called +`units`, with the tags that identify a row. How many rows does it have? ??? success "Solution" - Unit numbers restart at 0 on every probe, and probe names repeat in every session, so - all four of `subject_id`, `session`, `probe` and `unit` are needed. `region`, `depth_um` - and `n_spikes` describe the unit; they are data. + All four of `subject_id`, `session`, `probe` and `unit` are needed. The other columns + are data. ```python units = CSVSource( @@ -192,9 +184,8 @@ have? # 64 ``` - You could argue that `region` belongs with the tags, because it says what the row is - about. That is a real choice, and it has consequences: tags are what rows are matched on - in Part 3. Here `region` is fully determined by `probe`, so it adds nothing as a key. + `region` could also be a tag. It depends only on `probe` here, so it is not needed to + identify a row. Part 3 shows how tags decide which rows are combined. **2.** Two mistakes are common when a source is created. Make each one on purpose and read the message: (a) name a tag column that does not exist in `subjects.csv`; (b) make every @@ -220,22 +211,20 @@ column of `subjects.csv` a tag. # No data columns found in the table. At least one data column is required. ``` - The first message lists the columns that do exist, which is usually enough to spot a - typo. The second states a rule: a stream needs at least one data column. + The first message lists the columns that exist. The second states a rule: a stream needs + at least one data column. -**3.** Print the first three rows of `units` using `iter_data()`. +**3.** Print the first three rows of `units` with a loop. ??? success "Solution" - `iter_data()` is an ordinary Python iterator, so `itertools.islice` works on it. + A stream is an ordinary Python iterable, so `itertools.islice` works on it. ```python from itertools import islice - for tag, data in islice(units.iter_data(), 3): + for tag, data in islice(units, 3): print(tag.as_dict(), "->", data.as_dict()) # {'subject_id': 'mouse_01', 'session': 's1', 'probe': 'imec0', 'unit': 0} -> {'region': 'V1', 'depth_um': 1580, 'n_spikes': 149} # {'subject_id': 'mouse_01', 'session': 's1', 'probe': 'imec0', 'unit': 1} -> {'region': 'V1', 'depth_um': 2560, 'n_spikes': 326} # {'subject_id': 'mouse_01', 'session': 's1', 'probe': 'imec0', 'unit': 2} -> {'region': 'V1', 'depth_um': 600, 'n_spikes': 662} ``` - -Next: [Part 2: Computing with function pods](02-function-pods.md). diff --git a/docs/tutorial/02-function-pods.md b/docs/tutorial/02-function-pods.md index fc7361785..032f6b283 100644 --- a/docs/tutorial/02-function-pods.md +++ b/docs/tutorial/02-function-pods.md @@ -1,16 +1,15 @@ # Part 2: Computing with function pods -Loading tables is not analysis. The analysis is the functions you write: convert a unit, -compute a rate, fit a model. In Orcapod you write those as ordinary Python functions and -then let Orcapod apply them to every row of a stream. Because Orcapod is the one calling the -function, it knows exactly which inputs produced which output. Everything in later parts -(stored results, re-runs, tracing) rests on that. +Now that you can load data into Orcapod, the next step is to compute with it. New data +values are computed by **function pods**: ordinary Python functions that Orcapod applies to +each row of a stream. Orcapod calls the function, so it knows which inputs produced which +output. Storing, reusing and tracing results, in later parts, rest on that. You will: - turn a function into a **function pod** and apply it to a stream - learn the two rules a function has to follow -- return more than one value +- return more than one output - compute each unit's firing rate from two tables ```python @@ -31,10 +30,10 @@ sessions = CSVSource( ) ``` -## From a function to a function pod +## Making a function pod -Here is a function that converts a depth from micrometres to millimetres. The only Orcapod -part is the decorator on top: +This function converts a depth from micrometres to millimetres. The decorator makes it a +function pod: ```python from orcapod import function_pod @@ -45,10 +44,8 @@ def to_mm(depth_um: int) -> float: return depth_um / 1000 ``` -A **function pod** is a Python function wrapped so that it can be applied to a stream, one -row at a time. `output_keys` names the data column the result goes into. - -The function is still a normal function. You can call it and test it as usual: +`output_keys` names the data column the result goes into. The function can still be called +and tested as usual: ```python print(to_mm(depth_um=1580)) @@ -70,20 +67,13 @@ print(result.as_pandas_df().head(3)) # 2 mouse_01 s1 imec0 2 0.60 ``` -Look at what happened to the columns: - -- The **tags passed through untouched**. A function pod never sees tags and cannot change - them. Each output row keeps the identity of the input row it was computed from. -- The **data columns were replaced** by the function's output. `depth_um` is gone; - `depth_mm` is there instead. - -`result` is a stream like any other, so everything from Part 1 works on it. +- The **tags passed through unchanged**. The function does not receive them. +- The **data columns were replaced** by the function's output, `depth_mm`. ## Rule 1: annotate every parameter and the return value -Orcapod reads the type annotations to know the function's input and output schema. That is -how it could tell you the type of `depth_mm` above without running the function. A missing -annotation is an error at the moment you decorate the function: +Orcapod reads the function's input and output schema from its type annotations. A missing +annotation is an error when you decorate the function: ```python try: @@ -99,13 +89,12 @@ except ValueError as err: ## Rule 2: every parameter needs a data column with its name and type -A function pod takes each data column of the incoming stream as the parameter of the same -name. Every parameter must find its column, and the column's type must fit the parameter's -annotation. A missing column or a wrong type is an error as soon as the pod is applied; -Exercises 1 and 3 below show both. +Each parameter takes the data column with its name, and the column's type must fit the +parameter's annotation. A missing column or a wrong type is an error as soon as the pod is +applied; Exercises 1 and 3 below show both. -Data columns the function does *not* take are dropped. The sample above narrowed `units` to -`depth_um` with `select_data_columns` first, but the pod does that step for you: +Data columns the function does not take are dropped. The sample above narrowed `units` to +`depth_um` with `select_data_columns` first, but the pod can also do that step for you: ```python whole = to_mm.pod(units) @@ -115,13 +104,11 @@ print(whole.as_pandas_df().equals(result.as_pandas_df())) # True ``` -`region` and `n_spikes` were dropped before the function saw a row. The drop is not hidden: -Orcapod adds the same `select_data_columns` step you would have written by hand, so the two -calls build the same pipeline. +Orcapod adds the same `select_data_columns` step you would write by hand, so the two calls +build the same pipeline. -You can still narrow a stream yourself, and it often makes a pipeline easier to read: it -shows which columns a step uses. `select_data_columns` keeps the columns you name; its -counterpart `drop_data_columns` removes the columns you name and keeps the rest: +Narrowing a stream yourself shows the reader which columns a step uses. `select_data_columns` +keeps the columns you name, and `drop_data_columns` removes them. Both keep every tag: ```python print(units.select_data_columns(["depth_um"]).keys()) @@ -130,17 +117,13 @@ print(units.drop_data_columns(["region", "n_spikes"]).keys()) # (('subject_id', 'session', 'probe', 'unit'), ('depth_um',)) ``` -Neither touches the tags. The rule is about data columns only. - !!! note "Why drop the other columns?" - A pod's result can only depend on the columns its function takes. The unused columns are - dropped before the pod receives a row, so they are not part of the inputs Orcapod - remembers a result by: a change in an unrelated column upstream does not make Orcapod - compute the result again (Part 6 shows this). If you would rather have an extra column - rejected than dropped, pass `strict=True`: `to_mm.pod(units, strict=True)` raises - `ValueError`. See [Input columns](../concepts/function-pods.md#input-columns). + Dropped columns are not part of the inputs Orcapod stores a result under. A change in an + unused column therefore does not make Orcapod compute the result again (Part 6 shows + this). To reject extra columns instead, pass `strict=True`: + `to_mm.pod(units, strict=True)` raises `ValueError`. See [Input columns](../concepts/function-pods.md#input-columns). -## Returning more than one value +## Returning more than one output Give `output_keys` a list, return a tuple, and annotate the return type as a tuple: @@ -160,8 +143,8 @@ print(describe_depth.pod(depths).as_pandas_df().head(3)) ## A function of two tables -A firing rate is a spike count divided by a duration. The count is in `units`; the duration -is in `sessions`. Pass both streams to the pod: +A firing rate is a spike count divided by a duration. The count is in `units` and the +duration is in `sessions`. Pass both streams to the pod: ```python @function_pod(output_keys="rate_hz") @@ -185,21 +168,16 @@ print(rates.as_table().num_rows) # 64 ``` -Given several streams, a pod first combines them by matching rows on the tag columns they -share, here `subject_id` and `session`. Each unit row is paired with the row of its session, -and the function receives `n_spikes` from one and `duration_s` from the other. This matching -is a **join**; Part 3 covers it properly. Rule 2 applies to the combined stream. Narrowing -each input first is not required, since the pod would drop the combined stream's other -columns itself, but it shows at a glance which table each parameter comes from. +Given several streams, a pod first **joins** them: it matches rows on the tag columns the +streams share, here `subject_id` and `session`. Each unit row is paired with the row of its +session. Streams that share no tag column can be combined too: every row of one is then paired +with every row of the other. Rule 2 applies to the joined stream, so narrowing each input is +optional here. Part 3 covers joins. -A join does not promise an order for its rows, so the sample sorts them by their tags -before showing the first five. Sort whenever you look at, or compare, rows that went through -a join. +A join does not promise an order for its rows, so the sample sorts them by their tags. Sort +whenever you look at, or compare, rows that went through a join. -Notice that this is why tags matter: you never wrote the code that looks up a unit's -session. Choosing the tags in Part 1 was enough. - -## What to remember +## Key points - `@function_pod(output_keys=...)` turns a function into a pod; `my_function.pod(stream)` applies it to every row. @@ -207,8 +185,6 @@ session. Choosing the tags in Part 1 was enough. - Rule 1: annotate every parameter and the return value. - Rule 2: every parameter needs a data column with its name and a matching type. Data columns the function does not take are dropped. -- Nothing is stored yet. Every result on this page was computed in memory and is gone when - Python exits. Part 5 changes that. ## Exercises @@ -224,10 +200,9 @@ except ValueError as err: ``` ??? success "Solution" - Read the message as "the stream has these data columns; the function expects those", and - the part after the colon names the first problem. `units` has no `duration_s` column: - the duration is in `sessions`. (The message shows `units` after its unused columns, - `region` and `depth_um`, were dropped.) Pass both streams: + The part after the colon names the problem: the input has no column `duration_s`, which + is in `sessions`. (The message shows `units` after its unused columns, `region` and + `depth_um`, were dropped.) Pass `sessions` as an additional input: ```python rates_again = firing_rate.pod(units, sessions) @@ -242,9 +217,6 @@ except ValueError as err: # True ``` - The pod joins the two streams on `subject_id` and `session` and drops every data column - except the two its function takes, so the rates are the ones computed above. - **2.** Write a pod `rate_and_activity` that returns two values for each unit: its firing rate in Hz, and `True` if that rate is above 5 Hz. Apply it to the same two streams as `firing_rate` and print the output schema. @@ -284,8 +256,8 @@ Change the annotation from `duration_s: float` to `duration_s: int` (give the fu name, `to_minutes_int`) and apply it to `sessions`. What happens, and when? ??? success "Solution" - The column in the stream is a `float`, the parameter says `int`, and the pod refuses the - stream. The error comes when the pod is applied, before any row is computed. + The column is a `float` and the parameter an `int`, so the pod refuses the stream when it + is applied, before any row is computed. ```python @function_pod(output_keys="duration_min") @@ -300,6 +272,4 @@ name, `to_minutes_int`) and apply it to `sessions`. What happens, and when? # Incoming data schema Schema({'duration_s': float}) is not compatible with expected input schema Schema({'duration_s': int}): column 'duration_s' has type float, the function expects int ``` - Types are part of the match. Orcapod does not convert `60.0` to `60` for you. - -Next: [Part 3: Reshaping with operators](03-operators.md). + Orcapod does not convert `60.0` to `60`. diff --git a/docs/tutorial/03-operators.md b/docs/tutorial/03-operators.md index 979b2f7a5..1e4eb689d 100644 --- a/docs/tutorial/03-operators.md +++ b/docs/tutorial/03-operators.md @@ -1,17 +1,15 @@ # Part 3: Reshaping with operators -Function pods compute new values. Everything else you do to a table (combine it with another -one, keep some rows, rename or drop columns) is done by **operators**. An operator -rearranges a stream; it never computes a new value from the data. Keeping the two apart is -deliberate: when a number in your result looks wrong, it can only have come from one of your -functions. +Function pods compute new values. **Operators** rearrange streams: they combine two tables, +keep some rows, and rename or drop columns. When a number in a result looks wrong, it was +computed by one of your functions or was already in the source. You will: - combine tables with `join` - keep a subset of rows with `filter` and `semi_join` - rename columns with `map_data` -- see what to do when two tables have a column of the same name +- combine tables that have a data column of the same name ```python from workshop_data import make_dataset @@ -34,12 +32,11 @@ units = CSVSource( ) ``` -Most operators are available as methods on a stream, and that is the form used here. All of -them exist as classes in `orcapod.operators` (`Join`, `Filter`, ...); see -[Operators](../concepts/operators.md). `MergeJoin`, at the end of this page, is used as a -class. +Most operators are available as methods on a stream, which is the form used here. All of them +are classes in `orcapod.operators` (`Join`, `Filter`, ...); see +[Operators](../concepts/operators.md). -## Join: combine tables on their shared tags +## Join `join` matches rows of two streams that have the same values in the tag columns they share, and puts their data columns side by side: @@ -58,22 +55,14 @@ print(narrow.as_pandas_df().sort_values(unit_tags, ignore_index=True).head(3)) # 2 mouse_01 s1 imec0 2 662 60.0 ``` -You do not say what to join on. `units` has tags `subject_id, session, probe, unit`; -`sessions` has `subject_id, session`; the shared ones are used. The result has the union of -the tags and all data columns of both. This is the step the two-stream function pod in Part 2 -did for you. +The join uses every tag column the two streams share, here `subject_id` and `session`. The +result has the tags and the data columns of both. -The column order is chosen by Orcapod, not by the order you wrote the streams in. Refer to -columns by name, never by position. - -Four things to know: - -- It does not promise a row order. The samples on this page sort by the tags before - showing the first rows; do the same when the order matters to you. - It is an **inner** join: a row with no partner in the other stream is dropped. -- The order of the streams does not matter. `units.join(sessions)` and - `sessions.join(units)` give the same rows and the same columns. - If the streams share **no** tag column, every row is paired with every row. +- `units.join(sessions)` and `sessions.join(units)` give the same rows and columns. +- The order of rows and columns is not promised. Sort the rows when their order matters, as + the samples here do, and refer to columns by name. Joins chain. This attaches both the session and the animal to every unit: @@ -81,16 +70,12 @@ Joins chain. This attaches both the session and the animal to every unit: everything = units.join(sessions).join(subjects) print(everything.keys()[1]) # ('region', 'depth_um', 'n_spikes', 'date', 'duration_s', 'sex', 'age_weeks', 'genotype') -print(everything.as_table().num_rows) -# 64 + ``` -## Filter: keep some rows +## Filter -`filter` keeps the rows that satisfy a condition. The simplest form is equality on one or more -columns, written as keyword arguments. The first filter prints a `ProvisionalHashWarning` -(see [Messages you can ignore](00-setup.md#messages-you-can-ignore)); `polars_filter` and `MergeJoin`, below, print -one each too: +`filter` keeps the rows that satisfy a condition. Keyword arguments test equality: ```python knockouts = subjects.filter(genotype="knockout") @@ -100,8 +85,7 @@ print(knockouts.as_pandas_df()) # 1 mouse_04 M 13 knockout ``` -A filter tests tag columns and data columns alike. Join first, and you can filter on -columns from either table. Several keywords must all hold: +Join first to filter on columns from two tables. Several keywords must all hold: ```python knockout_units = units.join(subjects).filter(genotype="knockout", probe="imec1") @@ -109,7 +93,7 @@ print(knockout_units.as_table().num_rows) # 16 ``` -For anything other than equality, name the column with `col` and compare it: +For any other condition, name the column with `col`: ```python from orcapod import col @@ -122,9 +106,9 @@ print(busy.as_pandas_df().sort_values(unit_tags, ignore_index=True)) # 2 mouse_02 s2 imec1 3 CA1 2360 1233 ``` -`col` offers the comparisons (`==`, `!=`, `<`, `<=`, `>`, `>=`), `is_in` for a set of -values, `between` for a range (both ends included), and `is_null` / `is_not_null`. Give -`filter` several conditions and keywords at once, and every one must hold; combine them with +`col` offers `==`, `!=`, `<`, `<=`, `>`, `>=`, `is_in` for a set of values, `between` for a +range (both ends included), and `is_null` / `is_not_null`. Given several conditions and +keywords, `filter` keeps the rows where all of them hold. Combine conditions with `&` (and), `|` (or) and `~` (not): ```python @@ -140,26 +124,16 @@ print(v1_or_busy.as_table().num_rows) # 34 ``` -The order of the conditions, of the keywords and of the `is_in` values never matters. Write -`&` and `|` between two conditions and `~` before one (`~(col("probe") == "imec0")`), never -`and`, `or` and `not`, and put each comparison in parentheses, as in Polars. +As in Polars, write `&`, `|` and `~` instead of `and`, `or` and `not`, and put each comparison +in parentheses. Python applies `&`, `|` and `~` before a comparison, so leaving the +parentheses out raises `TypeError`. With `and`, the first condition is lost without an error. A value must have its column's type: `n_spikes` holds integers, so `col("n_spikes") > 1200.0` -is refused (`InputValidationError`), and `col("n_spikes") > 1200` is the way to write it. -Orcapod converts no value. +is refused (`InputValidationError`). Write `col("n_spikes") > 1200`. -The filter is a step of the pipeline: its conditions are part of the filtered stream's -identity, so a filtered stream can be used anywhere any other stream can: in a join, before -a function pod, or inside a `PipelineJob` (Part 5). - -```python -print(busy.join(subjects).as_table().num_rows) -# 3 -``` - -`filter` reads every row of its input and then keeps the matching ones. `explain()` (new in -this release) shows what each source applies itself and what is applied after reading; it -computes nothing: +`explain()` shows which conditions each source applies itself and which are applied after +reading. Here the source applies none: the whole table is read, and the `Filter` step then +keeps the matching rows. ```python print(busy.explain()) @@ -180,25 +154,17 @@ print(fast.as_table().num_rows) # 13 ``` -Orcapod has to be able to hash the expression, and it knows the common building blocks: -comparisons, arithmetic, `&`, `|`, `~`, `is_in`, `is_between`, `is_null` and a few string -tests. An expression that calls your own Python code (`map_elements`, `map_batches`) is -refused as soon as Orcapod needs to hash it (in a join, a pod or a job), with an error that -names the expression and lists what can be hashed; compute such a test in a function pod -instead. The full list is in [PolarsFilter](../concepts/operators.md#polarsfilter); `filter` -itself is described in [Filter](../concepts/operators.md#filter). - -One more filter, `drop_nulls`, keeps the rows that have a value in the columns you name. The -workshop data has no missing values, so it is not needed here; see -[DropNulls](../concepts/operators.md#dropnulls) for when it is. - -## Semi-join: keep the rows that appear in another table +The expression can use comparisons, arithmetic, `&`, `|`, `~`, `is_in`, `is_between`, +`is_null` and a few string tests. One that calls your own Python code (`map_elements`, +`map_batches`) is refused when the stream is used in a join, a pod or a job; compute such a +test in a function pod. The full list is in +[PolarsFilter](../concepts/operators.md#polarsfilter). -Sometimes the list of rows to keep is itself a table: a curation sheet, a list of sessions -that passed quality control. `semi_join` keeps the rows of the first stream whose tags appear -in the second, and adds nothing from the second. +## Semi-join -Suppose three sessions passed quality control, and the list is in a CSV file: +`semi_join` keeps the rows of the first stream whose tags appear in the second, and adds no +columns. Use it when the list of rows to keep is itself a table. Suppose three sessions passed +quality control, and the list is in a CSV file: ```python (data_dir / "passed_qc.csv").write_text( @@ -220,15 +186,14 @@ print(good_units.as_table().num_rows) # 24 ``` -Three sessions, eight units each. The columns are those of `units`; `checked_by` was used -for nothing. Unlike `join`, the order matters: the first stream is the one being filtered. +Three sessions, eight units each. Unlike `join`, the order matters: the first stream is the +one being filtered. Rows are matched only on the tag columns the two streams share, here `subject_id` and -`session`. Data columns of the second stream are never read. (If the two streams happen to -share a data column name, that column is not used for matching either, and Orcapod warns -about it with a `SemiJoinIgnoredColumnWarning`.) +`session`. If the two streams share a data column name, that column is not used for matching, +and Orcapod issues a `SemiJoinIgnoredColumnWarning`. -The second stream can be any stream, for example the filtered `knockouts` from above. It +The second stream can be any stream, for example the filtered `knockouts` from above, which shares only `subject_id` with `units`: ```python @@ -249,8 +214,8 @@ print(units.join(subjects).filter(genotype="knockout").keys()[1]) ## Rename and select -`select_data_columns` and `drop_data_columns` you know from Part 2. There are matching -`select_tag_columns` and `drop_tag_columns`. +`select_tag_columns` and `drop_tag_columns` do for tags what `select_data_columns` and +`drop_data_columns` (Part 2) do for data columns. `map_data` renames data columns and `map_tags` renames tag columns. Both take a dictionary of old name to new name: @@ -282,9 +247,8 @@ print(subjects.map_data({"age_weeks": "age"}, drop_unmapped=True).keys()) ## When two tables have the same data column -`join` refuses to combine streams that both have a data column of the same name, because it -cannot keep both under one name. To see this, split the units by probe. Each half has an -`n_spikes` column: +`join` refuses streams that both have a data column of the same name. To see this, split the +units by probe. Each half has an `n_spikes` column: ```python imec0 = ( @@ -307,15 +271,11 @@ except InputValidationError as err: # Input streams are not compatible: Datas should not have overlapping keys, but ['n_spikes'] found in SelectDataColumns and SelectDataColumns. ``` -The split above only serves to produce the clash. Unit numbers restart on each probe -(Part 1), so unit 0 of `imec0` and unit 0 of `imec1` are different cells, and the two joins -below pair unrelated units: run them to see how the operators behave, not as an analysis. -The pairing means something when the two columns describe the same thing, for example the -spike counts of one unit from two spike-sorting runs. +Overlapping data on the same tags can be meaningful, for example the spike counts of one unit +from two analysis runs. In this example it is not: unit 0 of `imec0` and unit 0 of `imec1` are +different units. There are two ways to combine such streams: -There are two ways out, and they mean different things. - -**Rename**, when the two columns are different quantities that happen to share a name: +**Rename** when the two columns are different quantities: ```python side_by_side = imec0.map_data({"n_spikes": "n_imec0"}).join( @@ -329,8 +289,8 @@ print(side_by_side.as_pandas_df().sort_values(pair_tags, ignore_index=True).head # 2 mouse_01 s1 2 135 662 ``` -**`MergeJoin`**, when they are repeated measurements of the same quantity and you want them -collected into a list: +**`MergeJoin`** when they are repeated measurements of one quantity, to collect them into a +list: ```python from orcapod.operators import MergeJoin @@ -345,17 +305,16 @@ print(merged.as_pandas_df().sort_values(pair_tags, ignore_index=True).head(3)) # 2 mouse_01 s1 2 [662, 135] ``` -Each list holds the first input's value, then the second's: `imec0` first, `imec1` second, -on every row. `MergeJoin()(imec1, imec0)` would put `imec1` first, and is a different step -with a different content hash. +Each list holds the first input's value, then the second's. `MergeJoin()(imec1, imec0)` puts +`imec1` first and is a different step. -## What to remember +## Key points -- Operators rearrange streams; they never compute new values. +- Operators rearrange streams. - `join` matches on shared tags, keeps only matching rows, and needs distinct data column - names. + names. Rename, or use `MergeJoin`, when names clash. - `filter` keeps rows by equality (`column=value`) or by conditions built with `col` - (comparisons, `is_in`, `between`, null tests, `&`, `|`, `~`); it is a step of the pipeline. + (comparisons, `is_in`, `between`, null tests, `&`, `|`, `~`), with each comparison in parentheses. `polars_filter` takes a Polars expression for anything else. - `semi_join` filters one stream by the shared tags of another and adds no columns. - `map_data` and `map_tags` rename columns and keep the rest unless you pass @@ -397,9 +356,7 @@ with exactly two data columns: `n_spikes` and `age_weeks`. How many rows does it listed in `passed_qc.csv`. Use `semi_join` and a single-stream call to the pod. ??? success "Solution" - Filter the units first, then join the durations. Narrowing to the function's two - parameters is optional, since the pod would drop the other columns itself, but it shows - at a glance what the function receives. + Filter the units first, then join the durations. ```python from orcapod import function_pod @@ -419,5 +376,3 @@ listed in `passed_qc.csv`. Use `semi_join` and a single-stream call to the pod. print(rates.as_table().num_rows) # 24 ``` - -Next: [Part 4: Many rows into one](04-many-rows-into-one.md). diff --git a/docs/tutorial/04-many-rows-into-one.md b/docs/tutorial/04-many-rows-into-one.md index ff587a28b..2bafe5e97 100644 --- a/docs/tutorial/04-many-rows-into-one.md +++ b/docs/tutorial/04-many-rows-into-one.md @@ -1,15 +1,14 @@ # Part 4: Many rows into one -So far every function has worked on one row and produced one row. A summary is different: -the mean firing rate of a session needs *all* the units of that session at once. In Orcapod -this takes two steps. An operator gathers the rows that belong together into a single row -whose values are lists. Then an ordinary function pod computes over those lists. +A summary is computed from many rows: the mean firing rate of a session needs all the units of +that session. In Orcapod this takes two steps. An operator gathers the rows that belong +together into one row whose values are lists. A function pod then computes over those lists. You will: - gather rows that share tag values with `group_by` - write a function pod that takes lists -- compute the mean firing rate of every session, the result this tutorial is building +- compute the mean firing rate of every session - gather rows by count with `batch` ```python @@ -51,8 +50,7 @@ rates = firing_rate.pod( ## Group by tags `group_by` takes a list of tag columns. All rows with the same values in those columns -become one row. The first call prints a `ProvisionalHashWarning` -(see [Messages you can ignore](00-setup.md#messages-you-can-ignore)): +become one row: ```python per_session = rates.group_by(["subject_id", "session"]) @@ -63,43 +61,34 @@ print(per_session.as_table().num_rows) # 8 ``` -64 unit rows became 8 session rows. Compare the schema with the one you started from: +64 unit rows became 8 session rows: -- The columns you grouped by, `subject_id` and `session`, are the tags of the result. One - row per session. -- The other tags, `probe` and `unit`, are gone. A session row covers many probes and units, - so no single value of them describes the row, and `group_by` drops them. +- The columns you grouped by, `subject_id` and `session`, are the tags of the result. +- The other tags, `probe` and `unit`, are dropped, because a session row covers many probes + and units. - Every data column became a list: `rate_hz` is now `list[float]`, one element per unit of the session. Here is the first row: ```python -tag, data = next(iter(per_session.iter_data())) +tag, data = next(iter(per_session)) print(tag.as_dict()) # {'subject_id': 'mouse_01', 'session': 's1'} print([round(r, 2) for r in data.as_dict()["rate_hz"]]) # [2.48, 5.43, 11.03, 9.98, 3.58, 4.98, 2.25, 8.52] ``` -These are the eight rates of `mouse_01`'s first session, ordered by the tags that were -dropped, taken in name order: by `probe`, then by `unit`. So probe `imec0` units 0 to 3, -then probe `imec1` units 0 to 3 (compare the first rows of `rates` in Part 2). The members -of a group are always in this order, whatever order the input rows arrived in and however -the input's columns are arranged. They are never ordered by a data value. To order them -by other tags first, name those tags: `group_by([...], member_order=["unit"])`. +These are the eight rates of `mouse_01`'s first session. The members of a group are ordered by +the dropped tags in name order, here `probe`, then `unit`. To order them by other tags first, +name those tags: `group_by([...], member_order=["unit"])`. -The list itself no longer says which probe or unit each rate came from. If a later step -needs that, it has to be a data column before you group; see -[GroupBy](../concepts/operators.md#groupby). - -`group_by` is an operator, so it computed nothing. Every number in those lists was already -in `rates`. +The list does not say which probe or unit each rate came from. If a later step needs that, it +has to be a data column before you group; see [GroupBy](../concepts/operators.md#groupby). ## A function pod over lists -A function that takes a list is written like any other. Annotate the parameter as -`list[float]`: +Annotate the parameter as `list[float]`: ```python @function_pod(output_keys="mean_rate_hz") @@ -120,15 +109,7 @@ print(session_means.as_pandas_df()) # 7 mouse_04 s2 5.129167 ``` -That is the result this tutorial set out to compute: the mean firing rate of every session. -The rows come out sorted by the group keys, taken in name order: `session`, then -`subject_id`. That is why every animal's `s1` comes before any `s2`. The order you write -the keys in does not change it: `group_by(["session", "subject_id"])` is the same -operation. -The knockout animals, `mouse_03` and `mouse_04`, fire less, as the generator intended. - -The grouped stream has one data column, `rate_hz`, and that is exactly the parameter of -`mean_rate`, so it goes straight into the pod. +The rows come out sorted by the group keys in name order: `session`, then `subject_id`. The whole analysis so far, written as one chain: @@ -144,10 +125,10 @@ print(session_means.as_table().num_rows) # 8 ``` -## What you can group by +## Grouping uses tags only -Only tag columns that hold a single value per row. Grouping by a data column is an error, -and the message says so: +You can group by tag columns that hold a single value per row. Grouping by a data column +raises an error: ```python from orcapod.errors import InputValidationError @@ -159,15 +140,12 @@ except InputValidationError as err: # GroupBy: ['rate_hz'] are not tag columns of the input stream. Available tag columns: ['subject_id', 'session', 'probe', 'unit']. (Data columns cannot be grouping keys: ['rate_hz']) ``` -This matters when the thing you want to group by is stored as data. `genotype` is a data -column of `subjects`, so after a join it is still data, and you cannot group by it. Parts 1 -and 3 said that choosing tags has consequences; this is the main one. Exercise 3 shows a way -through with what you know so far. +`genotype` is a data column of `subjects`, so you cannot group by it, also not after a join. +This is the main consequence of the choice of tags. Exercise 3 shows what you can do. -## Batch: group by count +## Batch -`batch` gathers rows without looking at their values. With no argument, the whole stream -becomes a single row (with the same warning, once, for `Batch`): +`batch` gathers rows by count. With no argument, the whole stream becomes a single row: ```python everyone = subjects.batch() @@ -178,9 +156,8 @@ for tag, data in everyone: # {'sex': ['F', 'M', 'F', 'M'], 'age_weeks': [12, 14, 11, 13], 'genotype': ['wildtype', 'wildtype', 'knockout', 'knockout']} ``` -Here the tags became lists too, since no column identifies the single row any more. With -`batch_size=N` you get rows of `N` members each; the last one may be smaller, unless you pass -`drop_partial_batch=True`: +The tags became lists too. With `batch_size=N` you get rows of `N` members each. The last one +may be smaller, unless you pass `drop_partial_batch=True`: ```python for tag, data in subjects.batch(batch_size=3): @@ -189,24 +166,22 @@ for tag, data in subjects.batch(batch_size=3): # {'subject_id': ['mouse_04']} ``` -Use `group_by` when rows belong together because of what they are (all units of a session). -Use `batch` when you want everything, or fixed-size chunks, regardless of content: a grand -mean over all rows, or mini-batches for a model. +Use `batch` for everything at once or for chunks of a fixed size, such as a grand mean over all +rows or mini-batches for a model. -If you need both, group first and batch afterwards. A batched stream has list-valued tags, -and `group_by` cannot use those. +If you need both `group_by` and `batch`, use them in that order. The tags of a batched stream +are lists, and `group_by` cannot use those. -## What to remember +## Key points - `group_by([...tags])` turns the rows sharing those tag values into one row of lists. `batch()` does the same by count. -- Neither computes anything. A function pod with `list[...]` parameters does the computing. +- A function pod with `list[...]` parameters computes over the lists. - You can only group by tag columns. - `group_by` keeps only the tags you group by; the other tags are dropped. `batch` keeps every tag, as a list. - The members of a group are ordered by the dropped tags in name order, or by the tags you - name in `member_order`. They are never ordered by a data value. Groups come out sorted by - their keys in name order. + name in `member_order`. Groups come out sorted by their keys in name order. ## Exercises @@ -274,10 +249,6 @@ filter, then narrow, then `batch()`.) # knockout 5.058 ``` - Writing a loop over the genotypes works, but it is a sign that `genotype` wanted to be a - tag. Had the subjects table been loaded with `tag_columns=["subject_id", "genotype"]`, - `genotype` would have travelled through every join as a tag and a single - `group_by(["genotype"])` would have done it. When you design your own sources, make a - column a tag if you expect to group or match by it. - -Next: [Part 5: Keeping results](05-pipeline-job.md). + With `genotype` as a tag, the loop is not needed: load the subjects table with + `tag_columns=["subject_id", "genotype"]`, and one `group_by(["genotype"])` replaces it. + In your own sources, make a column a tag if you expect to group or match by it. diff --git a/docs/tutorial/05-pipeline-job.md b/docs/tutorial/05-pipeline-job.md index 1d3faf2b4..e0fa5df60 100644 --- a/docs/tutorial/05-pipeline-job.md +++ b/docs/tutorial/05-pipeline-job.md @@ -1,12 +1,12 @@ # Part 5: Keeping results -Everything in Parts 1 to 4 was computed in memory. Close Python and the results are gone; -run the script again and every function runs again. That is fine for 64 rows. It is not fine -when one function call takes a minute and you have ten thousand of them. +The results of Parts 1 to 4 were held in memory. They are gone when Python exits, and running +the script again runs every function again. With long computations or many rows, you want to +keep the results. -A **`PipelineJob`** runs the same steps against a database. Each result is stored together -with a record of the inputs it was computed from. The next time the pipeline runs, results -that are already stored are read back instead of being computed again. +A **`PipelineJob`** stores each result in a database, with a record of the inputs it was +computed from. The next time the pipeline runs, results that are already stored are read back +instead of being computed again. You will: @@ -47,12 +47,13 @@ def mean_rate(rate_hz: list[float]) -> float: return sum(rate_hz) / len(rate_hz) ``` -These are the two functions from Part 4. The `calls` list is only there for teaching: it -lets us count how often each function was really called. +These are the two functions from Part 4. The `calls` list counts how often each function was +called. -## Record, then run +## Run a recorded job -A job needs a **database** to put its results in. Start with one that lives in memory. Then write the pipeline exactly as before, inside a `with` block: +A job needs a **database** for its results. Start with one in memory, and write the pipeline +inside a `with` block: ```python from orcapod.databases import InMemoryArrowDatabase @@ -75,12 +76,8 @@ print(len(calls)) # 0 ``` -(`group_by` prints a `ProvisionalHashWarning`, once: see -[Messages you can ignore](00-setup.md#messages-you-can-ignore).) - -Nothing has been computed. Inside the `with` block the job only **records** which operators -and pods are applied to which streams. The one new thing in the code is `label=`: a name for -the step, which you will use to find its results. +No function was called in this block. The job only **records** which operators and pods are +applied to which streams. `label=` names a step, so that you can find its results. `run()` executes what was recorded and writes every result to the database: @@ -93,14 +90,12 @@ print(calls.count("firing_rate"), calls.count("mean_rate")) # 63 8 ``` -`mean_rate` ran 8 times, once per session. `firing_rate` ran 63 times for 64 units. That is -not a mistake: two units happen to have the same spike count and the same session duration. -Orcapod stores a result under the function and the *values* of its inputs, so the second of -those two units found its answer already stored. The count of 63 is that of `job.run()`, which -runs one row after another; with `job.run_async()` two equal inputs can be computed at the same -time, so a first run can make 64 calls, with the same results. +`mean_rate` ran 8 times, once per session. `firing_rate` ran 63 times for 64 units, because two +units have the same spike count and the same session duration. Orcapod stores a result under +the function and the *values* of its inputs, so the second of those two units found its result +already stored. -## Nodes: where the results are +## Nodes Each recorded step is a **node** of the job. `job.nodes` lists them by name: @@ -109,8 +104,7 @@ print(sorted(job.nodes)) # ['GroupBy', 'Join', 'SelectDataColumns_1', 'SelectDataColumns_2', 'SelectDataColumns_3', 'rates', 'session_means', 'sessions', 'units'] ``` -(`sorted` is only there to make this page reproducible: `list(job.nodes)` gives the same -names, in an order that can differ from one Python session to the next.) + - A source is listed under its `source_id`. - A function pod is listed under the `label` you gave it. Without a label it gets the @@ -129,10 +123,8 @@ has a picture of this job's diagram and what each display in a notebook shows. `warnings.filterwarnings("ignore", category=InDevelopmentWarning)` after importing it from `orcapod.errors`. -Drag it to move it, zoom with the `+` and `−` buttons, and click a node to see its schema -(its tag and data columns) and how many rows the last run computed or read. Outside a notebook, -`print(job.diagram())` gives the same graph as text, one node per line with the nodes it -reads from: +Outside a notebook, `print(job.diagram())` gives the same graph as text, one node per line +with the nodes it reads from: ```python print(job.diagram()) @@ -148,11 +140,10 @@ print(job.diagram()) # session_means (function pod · mean_rate · current) <- SelectDataColumns_3 ``` -The `Join` is there because `firing_rate` was given two streams: the pod joins them for you. -`current` means the node holds the rows of the run you just did; before `job.run()` every -node but the sources says `not run`. `job.diagram(collapse=True)` hides the steps that only -choose or join columns, leaving the sources, the function pods and the `GroupBy` (in the -notebook, the `collapse` checkbox above the diagram does the same): +The `Join` is there because the pod joins the two streams given to `firing_rate`. `current` +means the node holds the rows of the latest run. Before `job.run()`, every node but the +sources says `not run`. `job.diagram(collapse=True)` hides the steps that only choose or join +columns. The sources, the function pods and the `GroupBy` remain: ```python print(job.diagram(collapse=True)) @@ -164,7 +155,7 @@ print(job.diagram(collapse=True)) # session_means (function pod · mean_rate · current) <- GroupBy ``` -A node is a stream. Everything from Part 1 works on it: +You read a node like any other stream: ```python means = job.nodes["session_means"] @@ -186,12 +177,12 @@ print(job.nodes["rates"].as_table().num_rows) !!! warning "Read nodes after `run()`" A node shows the rows of the job's run in this Python session. Before `run()`, every node - except the sources gives you an empty table without complaint; only `head()` and the - notebook preview say "not run". If a node looks empty, check that you ran the job. + except the sources gives an empty table and raises no error. Only `head()` and the notebook + preview say "not run". If a node looks empty, check that you ran the job. ## Run it again -Record the same pipeline in a new job over the same database. A small function saves retyping: +Record the same pipeline in a new job over the same database: ```python def build_job(database): @@ -218,13 +209,11 @@ print(job.nodes["session_means"].as_table().num_rows) # 8 ``` -Still 71. The second run called no function at all. Every result was found in the database, -and the node holds the same 8 rows. +Still 71: the second run called no function. Every result was found in the database. ## Keep results on disk -`InMemoryArrowDatabase` disappears with the Python process. `DeltaTableDatabase` writes to a -directory and is what you use for real work: +`InMemoryArrowDatabase` is gone when Python exits. `DeltaTableDatabase` writes to a directory: ```python import shutil @@ -238,10 +227,10 @@ print(len(calls)) # 142 ``` -This is a different, empty database, so everything was computed once more: 71 further calls. +This database was empty, so everything was computed: 71 further calls. -Now do what a new Python session would do: make a new database object for the same directory, -build the job, run it. +Now make a new database object for the same directory, as a new Python session would, and +build and run the job: ```python job = build_job(DeltaTableDatabase("workshop_db")) @@ -256,9 +245,7 @@ print(means.sort_values(["subject_id", "session"], ignore_index=True).head(2)) # 1 mouse_01 s2 6.793750 ``` -No calls. The results came from the files in `workshop_db/`. Rows read back from a database -are not guaranteed to come in the order they were first computed in, which is why the sample -sorts them before printing. Sort whenever the order matters to you. +No calls. The results came from the files in `workshop_db/`: ```python from pathlib import Path @@ -270,12 +257,14 @@ print(sorted(p.name for p in Path("workshop_db/workshop").iterdir())) ``` The first level is the job's `name`. Below it, `_result` holds each function's results, and -the directory named after each function records which inputs the job gave it. Two jobs with -different names over the same directory do not share results. You never need to read -these files yourself, and deleting the whole directory is safe: it only means the next run -computes everything again. +the directory named after each function records which inputs the job gave it. By default, two +jobs with different names over the same directory do not share results. If you delete the +directory, the next run computes everything again. + +Rows read back from a database are not guaranteed to come in the order they were computed in. +Sort them whenever the order matters, as the samples here do. -## What to remember +## Key points - `PipelineJob(name=..., database=...)`, a `with` block to record, `job.run()` to execute. - Give pods a `label`; read results from `job.nodes[label]` after `run()`. @@ -284,9 +273,6 @@ computes everything again. - `InMemoryArrowDatabase` for trying things out; `DeltaTableDatabase("directory")` to keep results between sessions. -The concept page [Pipelines and jobs](../concepts/pipeline-job.md) covers what this part left -out: reusable pipeline blueprints, binding sources later, and saving a job to a file. - ## Exercises **1.** Run a pipeline, quit Python, and run it again. Put the script below in a file @@ -326,16 +312,15 @@ print("function calls in this run:", n_calls) ``` ??? success "Solution" - The first run prints `rows: 64` and `function calls in this run: 54`. Fifty-four, not - 64, because some units share a depth and identical inputs are computed once. + The first run prints `rows: 64` and `function calls in this run: 54`. It is below + 64 because some units share a depth, and identical inputs are computed once. - The second run prints `rows: 64` and `function calls in this run: 0`. It is a new Python - process, with a new job object and a new database object. The only thing it shares with - the first run is the `exercise_db` directory, and that is enough. + The second run prints `rows: 64` and `function calls in this run: 0`. It shares only the + `exercise_db` directory with the first run. Delete `exercise_db/` and run the script once more: 54 calls again. -**2.** In the main example, what would `list(job.nodes)` show if you removed both `label=` +**2.** In the main example, which names would `job.nodes` hold if you removed both `label=` arguments? Predict, then try it with a new job over an `InMemoryArrowDatabase`. ??? success "Solution" @@ -355,7 +340,7 @@ arguments? Predict, then try it with a new job over an `InMemoryArrowDatabase`. # ['GroupBy', 'Join', 'SelectDataColumns_1', 'SelectDataColumns_2', 'SelectDataColumns_3', 'firing_rate', 'mean_rate', 'sessions', 'units'] ``` - Labels become useful when the same function is applied in two places of one pipeline. + Labels tell the nodes apart when one function is applied in two places of a pipeline. **3.** Create a job without a database, record one step, and call `run()`. Read the error and do what it suggests. @@ -381,5 +366,3 @@ what it suggests. print(no_database.nodes["rates"].as_table().num_rows) # 64 ``` - -Next: [Part 6: Re-runs and caching](06-reruns-and-caching.md). diff --git a/docs/tutorial/06-reruns-and-caching.md b/docs/tutorial/06-reruns-and-caching.md index 829d7778b..2fa7c1b57 100644 --- a/docs/tutorial/06-reruns-and-caching.md +++ b/docs/tutorial/06-reruns-and-caching.md @@ -1,17 +1,16 @@ -# Part 6: Re-runs and caching +# Part 6: Re-runs -In Part 5 a second run computed nothing, because nothing had changed. Real work is a loop: -new data arrives, a value gets corrected, you improve a function. This part shows what -Orcapod recomputes in each case, and one case where it does **not** recompute although you -would expect it to. That case is the most common surprise for new users, so take the time to -run it. +In Part 5 a second run computed nothing, because nothing had changed. This part shows what +Orcapod recomputes when new data arrives, when a value is corrected, and when you change a +function. Editing a function's code alone recomputes **nothing**, which is the most common +surprise for new users. You will: - add rows and correct a value, and see only the affected rows computed - edit a function and see the old results come back - force recomputation by bumping the function's version -- learn the rule that explains all three +- learn the rule for reusing a stored result ```python from workshop_data import make_dataset @@ -60,16 +59,13 @@ print(len(rates), len(calls)) # 64 63 ``` -This part uses an in-memory database so that the page runs quickly. Everything shown behaves -the same with a `DeltaTableDatabase`. +`run` builds the job from Part 5 without the per-session mean, runs it over the shared +`database`, and returns the sorted result. The first run computed 63 results for 64 units, as in +Part 5. A `DeltaTableDatabase` behaves the same. -The helper `run` builds the job from Part 5 (without the per-session mean, to keep the -output short), runs it over the one shared `database`, and returns the result sorted. The first -run computed 63 results for 64 units, as before (a count of `job.run()`; see Part 5). +## New rows -## New rows: only the new rows are computed - -Two more units were sorted on one probe. Write a new units file with two extra lines: +Write a new units file with two extra lines: ```python original = (data_dir / "units.csv").read_text() @@ -86,9 +82,9 @@ print(len(rates), len(calls)) 66 rows in the result, and two more calls. The other 64 rows were read from the database. -## A corrected value: only that row is computed +## Changes to the input -A spike count turns out to be wrong: unit 0 of the first probe had 150 spikes, not 149. +Correct one value, the spike count of unit 0 of the first probe, from 149 to 150: ```python (data_dir / "units_fixed.csv").write_text( @@ -104,10 +100,9 @@ print(rates.head(2)) # 1 mouse_01 s1 imec0 1 5.433333 ``` -One call, for the one row whose input changed, and the result shows the new value. +One call, for the row whose input changed. -Now change a value the function does **not** use, the depth of that unit. Start from the -corrected file, so that the spike count stays 150 and only the depth differs: +Now change a value the function does **not** use, for example the depth of that unit: ```python fixed = (data_dir / "units_fixed.csv").read_text() @@ -120,16 +115,11 @@ print(len(calls)) # 66 ``` -No call. `firing_rate` only receives `n_spikes` and `duration_s`, and those are unchanged. -This is why Part 2's Rule 2 drops the data columns a function does not take before the pod -sees a row: a result depends on exactly the columns the function receives, so a change to any -other column leaves it valid. (The `select_data_columns` calls in `run` only make that -explicit; the pod would drop `depth_um` without them.) +No calls. `firing_rate` receives only `n_spikes` and `duration_s` (Part 2, Rule 2). -## An edited function: nothing is recomputed +## Changes to the function -Now the surprise. Suppose you decide rates should be reported to one decimal place, and -edit the function: +Suppose you want rates with one decimal place, and edit the function: ```python @function_pod(output_keys="rate_hz") @@ -147,16 +137,14 @@ print(rates.head(2)) # 1 mouse_01 s1 imec0 1 5.433333 ``` -No call, and the **old** values. There is no error and no warning. +No calls, and the **old** values. Orcapod raises no error and prints no warning. !!! warning "Editing a function's code does not recompute its results" Orcapod does not look at a function's source code. It identifies a function by three things: its **name**, its **output** (each output name with its type, in any order), - and its **major version**. As long as those are the same, stored results are reused, - whatever the body now says, and whichever position of the returned tuple each output - name takes. + and its **major version**. As long as those are the same, stored results are reused. -## Bump the major version +## Versioning a pod Every function pod has a version, `"v0.0"` unless you say otherwise. The number before the dot is the major version. When you change what a function computes, raise it: @@ -177,18 +165,16 @@ print(rates.head(2)) # 1 mouse_01 s1 imec0 1 5.4 ``` -63 new calls and new values. The results of version 0 are still in the database, untouched; -version 1 has its own. If you went back to the `v0.0` function you would get the old numbers -without any computation. +63 new calls and new values. The results of version 0 stay in the database, and going back to +the `v0.0` function returns them without any computation. -A change after the dot is **not** enough. `version="v0.1"` shares its stored results with -`"v0.0"`. Use the minor number for changes that cannot alter results, such as a comment or a -faster implementation of the same calculation. +A change after the dot is **not** enough: `version="v0.1"` shares its stored results with +`"v0.0"`. Use the minor number for changes that cannot alter results, such as a faster +implementation of the same calculation. -Renaming the function, or renaming its output column, also starts from an empty slate, -because those are part of its identity too. +Renaming the function or its output column also makes every row compute again. -## The rule +## Reuse rule A stored result is reused when **all** of these are the same as when it was computed: @@ -196,16 +182,11 @@ A stored result is reused when **all** of these are the same as when it was comp 2. the values of the function's inputs for that row; 3. the job's `name` and database. -Change any one and the affected rows are computed, unless a result is already stored for -the new combination (going back to an earlier version finds that version's results). Change -none and nothing is. Where the -input values came from does not matter: which file, which source, which steps before the -function. +Change any one, and the result is looked up under the new combination. It is computed if none +is stored there. Where the input values came from does not matter. -Orcapod implements this with hashes. A **hash** is a short fingerprint computed from some -content: the same content always gives the same hash, and different content gives, in -practice, a different one. Every stream carries two of them. You do not need them to use -Orcapod, but they explain the rule: +Orcapod implements this rule with hashes. A **hash** is a short fingerprint computed from some +content. Every stream carries two of them, a pipeline hash and a content hash: ```python units = CSVSource( @@ -223,21 +204,20 @@ print(units.pipeline_hash() == units_more.pipeline_hash()) # True ``` -The **pipeline hash** covers structure only: column names and types, and the steps applied. -The two files have different rows but the same columns, so their pipeline hashes are equal. -The job uses it to name the table in which it records which inputs each function node -received, so runs of one pipeline over different files share that record. +The **pipeline hash** covers structure: column names and types, and the steps applied. The two +files have the same columns, so their pipeline hashes are equal. The job uses this hash to name +the table in which it records the inputs of each function node. -The results themselves are filed under the function (its name, output and major version) -and a hash of the input values of each row. That is why the run over `units_more.csv` found -the results computed from `units.csv`, and how two extra rows meant two extra calls. +The **content hash** also covers which sources the data came from. -The second hash, the **content hash**, also covers which sources the data came from. See -[Identity & Hashing](../concepts/identity.md) for the full picture. +Results are stored under the function (its name, output and major version) and a hash of each +row's input values. That is why the run over `units_more.csv` found the results computed from +`units.csv`. See [Identity & Hashing](../concepts/identity.md) for more. -## What to remember +## Key points -- New or changed input rows are computed; everything else is read from the database. +- New rows, and rows whose inputs changed, are computed. Other results are read from the + database. - **Editing a function body does not recompute.** Bump the major version (`"v0.0"` to `"v1.0"`), or rename the function. - A minor version bump (`"v0.0"` to `"v0.1"`) does not recompute. @@ -305,16 +285,15 @@ which of these four changes cause function calls on the next `run(...)`, and how run the pipeline since. Which stored results are wrong, and what do you do? ??? success "Solution" - Rows computed before the fix hold values from the buggy code. Rows that were new after - the fix hold correct values. Both are filed under the same function identity, so you - cannot tell them apart from the results alone. + Rows computed before the fix hold values from the old code. Rows that were new after the + fix hold correct values. Both are stored under the same function identity, so you cannot + tell them apart from the results alone. Bump the major version and run again. Every row is then computed with the current code and stored under the new version. The mixed results stay in the database under the old version and are no longer used. - The habit to build: change the behaviour of a function, change its major version, in - the same edit. + Change a function's major version in the same edit that changes what it computes. **3.** A colleague runs the same pipeline code over the same database directory, but named their job `"analysis"` instead of `"workshop"`. Are your stored results reused? @@ -344,5 +323,3 @@ their job `"analysis"` instead of `"workshop"`. Are your stored results reused? ``` Agree on a job name with the people you share a database with. - -Next: [Part 7: Working with files](07-files.md). diff --git a/docs/tutorial/07-files.md b/docs/tutorial/07-files.md index 2223a564e..4abbd77b8 100644 --- a/docs/tutorial/07-files.md +++ b/docs/tutorial/07-files.md @@ -1,16 +1,15 @@ # Part 7: Working with files -Recordings do not live in CSV cells. They are files: binary dumps, spike tables, images, -one folder per session. A pipeline over such data passes *references to files* from step to -step, and the functions open them. Orcapod supports this with a file type that it identifies -by **content**, so that a result is recomputed when the file it was computed from changes, -and not otherwise. +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. You will: - build a stream whose data column holds files - write function pods that read a file and that write one -- see what makes a file-based result recompute +- see when a file-based result is recomputed - treat a whole folder as one input ```python @@ -32,8 +31,8 @@ spike) and a text file of notes. ## A stream of files -`op.File(path)` marks a value as "this file". Build one row per spike file. There is no -table listing them, so walk the folders and use `DictSource`: +`op.File(path)` refers to a file. Walk the folders and build one row per spike file with +`DictSource`: ```python def spike_file_rows(): @@ -63,16 +62,16 @@ print(spike_files.as_table().num_rows) # 16 ``` -The data column has type `File`. Two things about `op.File`: +The data column has type `File`. -- It checks that the file exists **when you create it**. `op.File("no_such_file.csv")` - raises `FileNotFoundError` on the spot, not later in the middle of a run. -- It behaves like a `pathlib.Path`: `.name`, `.stem`, `.parent`, `.read_text()`, `.open()` - all work, and `str(f)` is the path. +- `op.File` checks that the file exists when you create it: `op.File("no_such_file.csv")` + raises `FileNotFoundError`. +- It behaves like a `pathlib.Path`: `.name`, `.stem`, `.parent`, `.read_text()` and `.open()` + all work. ## A function that reads a file -Annotate the parameter as `op.File` and open it however you like: +Annotate the parameter as `op.File`: ```python import csv @@ -122,9 +121,9 @@ print(len(calls)) # 16 ``` -## What makes a file result recompute +## Changed and moved files -Change the content of one file. Here, one spike is appended to the first file: +Append one spike to the first file: ```python first = data_dir / "sessions" / "mouse_01_s1" / "spikes_imec0.csv" @@ -138,11 +137,10 @@ print(counts.head(1)) # 0 mouse_01 s1 imec0 1737 ``` -One call, for the file that changed. Nobody told Orcapod which file was edited. A `File` is -identified by a hash of its content, so a changed file is a changed input. +One call, for the file that changed. Orcapod identifies a `File` by a hash of its content, so a +changed file is a changed input to the pod. -The reverse also holds. The same content under a different name or location is the *same* -input: +The same content under a different name or location is the same input: ```python import shutil @@ -171,19 +169,16 @@ print(len(calls)) moved.unlink() ``` -No call: the stored result for that content was reused. You can reorganise a data directory -without recomputing anything. +No calls. Moving or renaming files recomputes nothing. -!!! warning "`pathlib.Path` columns are identified by the path, not the content" - You may also put plain `pathlib.Path` values in a source and annotate a parameter as - `Path`. Orcapod then identifies the value by the path *string*. If the file's content - changes and its path does not, **nothing is recomputed**. Use `op.File` for every input - whose content matters, which is nearly always. +!!! warning "`pathlib.Path` columns are identified by the path" + A source can also hold plain `pathlib.Path` values, for a parameter annotated as `Path`. + Orcapod does not read those files: if a file changes and its path stays the same, + **nothing is recomputed**. Use `op.File` for input files. ## A function that writes a file -A function may produce a file. Write it, and return its path. Annotate the return type as -`Path`: +Write the file, return its path, and annotate the return type as `Path`: ```python out_dir = Path("spike_summaries") @@ -221,24 +216,20 @@ print(len(list(out_dir.iterdir()))) # 16 ``` -Three things to keep in mind when a function writes files: - -- **Choose the output name from the inputs**, as above, so that two rows never write to the - same file. Two rows whose files have the same content share one stored result, and so - one output path, which holds the right summary for both. A changed file's new result, - though, overwrites the old output under the same name, while the stored result of the old - content still points there; to keep both, put a digest of the file's content into the - output name. -- **The database remembers the path, not the file.** If you delete `spike_summaries/` and - run again, Orcapod finds the stored results, calls nothing, and hands you paths to files - that no longer exist. Treat output files as part of the database: delete both or neither. -- **Paths are stored as you returned them.** A relative path, as here, only means something - from the directory the script was run in. For work you intend to keep, build output paths - from an absolute directory. +- **Give every different input its own output file.** Build the output name from the inputs, as + above. Rows whose files have the same content share one stored result, and so one output + file. When an input file is edited, its new result overwrites the output file of the same + name, and the stored result of the old content still points to that file. To keep both + outputs, include a hash of the file's content in the output name. +- **The database stores the path, even if the file is deleted.** If you delete + `spike_summaries/` and run again, Orcapod calls nothing and returns paths to files that no + longer exist. Keep or delete output files together with the database. +- **Paths are stored as you returned them.** A relative path, as here, only works from the + directory the script was run in. For results you keep, return absolute paths. ## A folder as one input -Some inputs are a folder, not a file: a session directory, an image stack. `op.Directory` +Some inputs could be a folder, such as a session directory or an image stack. `op.Directory` identifies a folder by the names and content of everything in it: ```python @@ -286,35 +277,24 @@ print(len(calls) - before) # 0 ``` -Without `ignore`, any change to any file in the folder makes it a new input. +Without `ignore`, a change to any file in the folder makes it a new input. See +[File and path types](../concepts/file-types.md) for more on `File`, `Directory` and `Path`. ## Large files -Identifying a file by content means reading it. For files of many gigabytes that takes -longer than you want to wait on every run. Orcapod can remember a file's hash and reuse it -as long as the file's size and modification time are unchanged. To turn this on -(optional), call this once, at the start of your script: +Orcapod reads a file to identify it, which takes a long time for large files. It can instead +remember a file's hash while the file's size and modification time stay the same; see +[File Hash Caching](../concepts/file-hash-caching.md). -```python -op.enable_file_hash_caching(db_path=Path("workshop_hashes.sqlite")) -``` - -This keeps the hashes in a file in your working directory. Without `db_path` they go to -`~/.orcapod/file_hash_cache.db`, in your home directory. - -The details and options are on the [File Hash Caching](../concepts/file-hash-caching.md) -page. With the small files of this tutorial it makes no noticeable difference. - -## What to remember +## Key points - `op.File(path)` in a source, `op.File` as a parameter type. Files are identified by - content: edit a file and its results are recomputed; move it and they are not. + content only. Editing a file recomputes its results; moving it does not. - Plain `Path` values are identified by path only. -- A function that writes a file returns its `Path`. The database keeps the path; keep the file. +- A function that writes a file returns its `Path`. The database stores the path; + it does not track the file itself. - `op.Directory(path, ignore=[...])` treats a folder as one input. -More detail: [File and path types](../concepts/file-types.md). - ## Exercises **1.** The table `units.csv` claims a spike count per unit; the spike files contain the @@ -347,8 +327,7 @@ it. Check your result for `mouse_02, s1, imec1` against `units.csv`. # 237 ``` - This pod was applied directly, without a job, so nothing was stored. That is fine for - a quick check. + This pod was applied without a job, so nothing was stored. **2.** Write one output file **per session**: a text file `__total.txt` containing the total number of spikes over both probes. (Hint: Part 4. After @@ -356,9 +335,8 @@ containing the total number of spikes over both probes. (Hint: Part 4. After ??? success "Solution" Group the spike files by session, then hand the list of files to one function call. - The function has no access to the tags, so it takes the session's name from the folder - the files are in. (The first `group_by`, like the first `filter`, prints a - `ProvisionalHashWarning`: see [Messages you can ignore](00-setup.md#messages-you-can-ignore).) + The function does not receive the tags, so it takes the session's name from the folder + the files are in. ```python totals_dir = Path("session_totals") @@ -395,16 +373,15 @@ containing the total number of spikes over both probes. (Hint: Part 4. After # mouse_04_s2_total.txt 2462 ``` - The rows of a stream have no promised order, so they are sorted by their tags before - printing. + **3.** In `run_folders`, remove `ignore=["notes.txt"]` and run it twice, editing a `notes.txt` in between. How many calls does each run make, and why? ??? success "Solution" - The first run makes 8 calls: without `ignore`, each folder's identity now includes its - notes file, so all eight are inputs that have not been seen before. After the edit, the - second run makes 1 call, for the one folder whose content changed. + The first run makes 8 calls: each folder's identity now includes its notes file, so all + eight are new inputs. After the edit, the second run makes 1 call, for the folder whose + content changed. ```python def run_folders_strict(): @@ -437,5 +414,3 @@ containing the total number of spikes over both probes. (Hint: Part 4. After print(len(calls) - before) # 1 ``` - -Next: [Part 8: Inspecting and tracing](08-inspecting-and-tracing.md). diff --git a/docs/tutorial/08-inspecting-and-tracing.md b/docs/tutorial/08-inspecting-and-tracing.md index 029628513..3bb216b3c 100644 --- a/docs/tutorial/08-inspecting-and-tracing.md +++ b/docs/tutorial/08-inspecting-and-tracing.md @@ -90,7 +90,7 @@ kind, it numbers them (`SelectDataColumns_1`, ...); the numbers tell the steps a 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-where-the-results-are)). +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. @@ -342,7 +342,7 @@ 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-where-the-results-are). + 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 @@ -540,7 +540,7 @@ result of the node, including those of earlier runs over other inputs, like 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. -## What to remember +## 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 @@ -605,5 +605,3 @@ Use the source-info column of the `sessions` node. # 2 mouse_03 4.983160 # 3 mouse_04 5.132812 ``` - -Next: [Part 9: When things go wrong](09-when-things-go-wrong.md). diff --git a/docs/tutorial/09-when-things-go-wrong.md b/docs/tutorial/09-when-things-go-wrong.md index 5653f3b53..b49964eaa 100644 --- a/docs/tutorial/09-when-things-go-wrong.md +++ b/docs/tutorial/09-when-things-go-wrong.md @@ -1,15 +1,14 @@ -# Part 9: When things go wrong +# Part 9: Handling errors -Two kinds of things go wrong. Some mistakes Orcapod catches before any data is touched: a -misspelt column, 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 how -each kind appears and what to do about it. +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. You will: - recognise the errors Orcapod raises while a pipeline is being built - see what a job does when a function raises for some rows -- choose between "carry on" and "stop at the first failure" +- choose whether a run continues or stops at the first failure - find out which rows failed, and why, after a run ```python @@ -34,31 +33,30 @@ sessions = CSVSource( ## Errors while building -Most mistakes are caught at the line that makes them, because Orcapod checks column names -and types as soon as you connect two things. You have met these already: +Orcapod checks column names and types as soon as you connect two steps, so most mistakes raise +at the line that makes them: | You did | Raised | Where you saw it | |---|---|---| -| Named a tag column that does not exist | `ValueError: tag_columns not found in table` | Part 1 | -| Made every column a tag | `ValueError: No data columns found in the table` | Part 1 | -| Left out a type annotation | `ValueError: Parameter '...' has no type annotation` | Part 2 | -| Gave a pod a stream with a missing or differently typed column | `ValueError: Incoming data schema ... is not compatible with expected input schema ...: ...` | Part 2 | -| Joined streams that share a data column | `InputValidationError: ... should not have overlapping keys` | Part 3 | -| Grouped by a data column | `InputValidationError: GroupBy: ... are not tag columns` | Part 4 | -| Ran a job without a database | `ValueError: PipelineJob.run() requires a database` | Part 5 | - -The end of a pod's message names the problem, with the column and both types: +| Named a tag column that does not exist | `ValueError: tag_columns not found in table` | [Part 1](01-first-stream.md) | +| Made every column a tag | `ValueError: No data columns found in the table` | [Part 1](01-first-stream.md) | +| Left out a type annotation | `ValueError: Parameter '...' has no type annotation` | [Part 2](02-function-pods.md) | +| Gave a pod a stream with a missing or differently typed column | `ValueError: Incoming data schema ... is not compatible with expected input schema ...: ...` | [Part 2](02-function-pods.md) | +| Joined streams that share a data column | `InputValidationError: ... should not have overlapping keys` | [Part 3](03-operators.md) | +| Grouped by a data column | `InputValidationError: GroupBy: ... are not tag columns` | [Part 4](04-many-rows-into-one.md) | +| Ran a job without a database | `ValueError: PipelineJob.run() requires a database` | [Part 5](05-pipeline-job.md) | + +The end of a pod's message names the problem: `required parameter 'duration_s' has no matching column`, or -`column 'duration_s' has type float, the function expects int`. Data columns the function -does not take are not a problem: the pod drops them. +`column 'duration_s' has type float, the function expects int`. The pod drops the data columns +it does not take. -The habit that makes these quick to fix: when a pod or operator refuses a stream, print -`stream.keys()` or `stream.output_schema()` for the stream you passed, and compare it with -what the step expects. +When a pod or operator refuses a stream, print `stream.keys()` or `stream.output_schema()` for +the stream you passed, and compare it with what the step expects. -The [Troubleshooting](../troubleshooting.md) page lists every one of these with its cause -and fix, together with the problems that give **no** error, such as stale results after -editing a function (Part 6). +[Troubleshooting](../troubleshooting.md) lists these errors with their causes and fixes, and +the problems that give **no** error, such as old results after editing a function +([Part 6](06-reruns-and-caching.md)). ## A function that fails for some rows @@ -89,8 +87,7 @@ def build_job(database): Three of the 64 units have more than 1200 spikes. -**Without a job**, the exception simply propagates, as it would from any Python function. -The stream cannot be produced: +**Without a job**, the exception propagates and the stream is not produced: ```python in_memory = firing_rate.pod( @@ -104,7 +101,7 @@ except ValueError as err: # implausible spike count: 1221 ``` -**Inside a job**, the default is different. The run carries on: +**Inside a job**, the run continues by default: ```python database = InMemoryArrowDatabase() @@ -122,25 +119,22 @@ print(job.nodes["rates"].as_table().num_rows) # 61 ``` -`run()` did not raise. It skipped the three failing rows, computed and stored the other 61, -and at the end issued one `RowFailuresWarning` and returned a **run summary** (the job also -keeps it as `job.last_run`). `job.last_run.print_traceback("rates")` prints the full -traceback of the first failure. (Why "1 from store" in a first run? Two units have the same -spike count and the same session duration. Their inputs are identical, so the second one -reuses the result computed for the first.) +`run()` did not raise. It skipped the three failing rows, stored the results of the other 61, +issued one `RowFailuresWarning` and returned a **run summary**, which the job keeps as +`job.last_run`. `job.last_run.print_traceback("rates")` prints the full traceback of the first +failure. One row is "from store" because two units have the same inputs (Part 5). -This default suits long runs: one bad file should not throw away a night of computation. -It also means that **a job that finishes is not a job in which everything succeeded**. -Read the warning and the summary; in a script, check `summary.ok`, which is `False` when -any row failed. +In a long run, one bad file should not discard a night of computation. As a result, **a job can +finish with failed rows**. Read the warning and the summary. In a script, check `summary.ok`, +which is `False` when any row failed. A row also fails when the function returns a value of a different type than it declares, for example a `float` from a function annotated `-> int`. That raises an `OutputTypeError` -(from `orcapod.errors`) naming the function, the output and both types; Orcapod does not -convert the value for you. Inside a job it is skipped and reported like any other failure. +(from `orcapod.errors`) naming the function, the output and both types. Inside a job the row is +skipped and reported like any other failure. -Failures are not stored. Run again and the failed rows are tried again, and only those. Expect -the same warning again, 3 of 64 rows failed, from this run: +Failures are not stored. The next run tries the failed rows again, and here they fail again +with the same warning: ```python calls.clear() @@ -152,8 +146,8 @@ print(len(calls)) ## Stop at the first failure -While developing, you usually want the opposite: stop immediately and show me the error. -Pass an orchestrator with `error_policy="fail_fast"`: +While developing, you usually want the first error to stop the run. Pass an orchestrator with +`error_policy="fail_fast"`: ```python from orcapod.pipeline import SyncPipelineOrchestrator @@ -166,16 +160,14 @@ except ValueError as err: # implausible spike count: 1221 ``` -The **orchestrator** is the part of Orcapod that walks through the nodes of a job and -executes them. You have been using the default one all along. `"fail_fast"` re-raises the -first exception a function raises; `"continue"`, the default, skips the row. +The **orchestrator** is the part of Orcapod that executes the nodes of a job. `"fail_fast"` +re-raises the first exception a function raises. The default is `"continue"`. -## Which rows failed, and why? +## Finding the failed rows -Reading tracebacks off the screen does not scale. An **observer** records what happens -during a run in a table you can query afterwards. `StatusObserver` records the state of -every row; `LoggingObserver` records the traceback and captured output of failures. -`CompositeObserver` lets you use both. Expect the same 3-of-64 warning again here: +An **observer** records what happens during a run in a table you can query afterwards. +`StatusObserver` records the state of every row, and `LoggingObserver` the traceback and +captured output of each function call. `CompositeObserver` combines them: ```python import polars as pl @@ -226,9 +218,8 @@ record of every run is kept on disk next to your results. ## Fix and re-run -Once you know what went wrong, fix the function, or the data, and run again. Here the limit -was wrong, so the check is removed. Only the three rows that never got a result are -computed: +Once you know what went wrong, fix it and run again. Here the limit was wrong, so the check is +removed. Only the three rows without a result are computed: ```python @function_pod(output_keys="rate_hz") @@ -244,16 +235,17 @@ print(job.nodes["rates"].as_table().num_rows, len(calls)) # 64 3 ``` -The 61 results stored earlier were reused, although the function body changed. In this case -that is what you want, since the calculation for those rows is the same. If your fix changes -what the function returns for rows that had succeeded, bump the major version (Part 6). +The 61 results stored earlier were reused, although the function body changed. If your fix +changes what the function returns for rows that had succeeded, bump the major version +([Part 6](06-reruns-and-caching.md)). -## What to remember +## Key points - Mistakes in how a pipeline is put together raise at the line that makes them. Print the stream's `keys()` and compare. - Inside a job, a function that raises loses that row and the run continues. At the end a - `RowFailuresWarning` and the run summary say how many rows failed. **Read them.** + `RowFailuresWarning` and the run summary say how many rows failed. **Read them.** In a + script, check `summary.ok`. - `SyncPipelineOrchestrator(error_policy="fail_fast")` stops at the first failure. Use it while developing. - `StatusObserver` and `LoggingObserver` tell you which rows failed and why. @@ -291,14 +283,12 @@ one. # c: Input streams are not compatible: Datas should not have overlapping keys ``` - (a) The column is called `subject_id`. (b) `n_spikes` is in `units`, not `sessions`: - pass both, `firing_rate.pod(units, sessions)`. (c) Both sides have the same data - columns; a stream joined with itself is rarely what you want, but if two tables really - share a column name, rename one side or use `MergeJoin` (Part 3). + (a) The column is called `subject_id`. (b) `n_spikes` is in `units`: + pass both, `firing_rate.pod(units, sessions)`. (c) Both sides have the same data columns. + If two tables share a column name, rename one side or use `MergeJoin` (Part 3). **2.** Run the failing version of `firing_rate` (the one with the 1200 limit) in a job with -only a `StatusObserver`, and print how many rows ended in each state. (Expect the same -3-of-64 warning again.) +only a `StatusObserver`, and print how many rows ended in each state. ??? success "Solution" ```python @@ -323,12 +313,10 @@ fails for one unit under the default policy, what does the session mean of that session contain? ??? success "Solution" - The mean of the units that succeeded. The failed row is absent from `rates`, so - `group_by` gathers seven units for that session where there should be eight, and the - mean is computed over seven. `job.run()` reports failed rows in its warning and its - summary, but raises no exception, and nothing in the mean's row says that a unit is - missing. (The same 3-of-64 warning appears again, and `group_by` prints a - `ProvisionalHashWarning`: see [Messages you can ignore](00-setup.md#messages-you-can-ignore).) + The mean of the units that succeeded. The failed row is absent from `rates`, so the mean + is computed over seven units where there should be eight. `job.run()` reports failed rows + in its warning and its summary, but raises no exception, and nothing in the mean's row + says that a unit is missing. ```python @function_pod(output_keys=["n_units", "mean_rate_hz"]) @@ -362,8 +350,5 @@ session contain? # 7 mouse_04 s2 8 ``` - This is the strongest reason to look at the status table after a run, or to use - `fail_fast`: a partial failure upstream becomes a plausible-looking number downstream. - Returning the group size next to the summary, as here, is a cheap safeguard. - -Next: [Part 10: Where next](10-where-next.md). + A partial failure upstream gives a plausible number downstream. Check the run summary or + use `fail_fast`, and return the group size next to the summary value, as here. diff --git a/docs/tutorial/10-where-next.md b/docs/tutorial/10-where-next.md index f6a2fd761..7f47d6e65 100644 --- a/docs/tutorial/10-where-next.md +++ b/docs/tutorial/10-where-next.md @@ -1,8 +1,7 @@ # Part 10: Where next -Optional. You now know the core of Orcapod: sources, function pods, operators, jobs, and how -results are stored and reused. This part is a short tour of features the tutorial did not -need. Each section is independent; read the ones that match what you want to do next. +This part is optional. It is a short tour of features the tutorial did not need. The sections +are independent. ```python from workshop_data import make_dataset @@ -19,19 +18,18 @@ sessions = CSVSource( durations = sessions.select_data_columns(["duration_s"]) ``` -## Steps that act instead of compute +## Side effects -A function pod returns a value. Some steps exist for their effect: send a notification, -upload a file, write a row to a lab database. These are **side-effect pods**. The most -useful kind is the **sink**, made with `@sink_pod`: it runs once for each row and remembers -which rows it has already handled, so a re-run does not repeat the effect for them. A row -counts as handled once its function has returned and that has been recorded; if the process -stops in between, the next run calls the function for that row again. A row is identified by -its source's name and its position, unless the source names key columns that are unique per -row (`record_id_columns`). Reordering the rows of a source without them can make the sink -handle them again, and so can a source whose name changes: an in-memory source without a -`source_id` is named after its content, so adding a row renames it. For a sink, give the -source both a `source_id` and key columns. +**Side-effect pods** are steps that exist for their effect: send a notification, upload a +file, write a row to another database. One kind is the **sink**, made with `@sink_pod`: it +runs once for each row and remembers which rows it has already handled, so a re-run does not +repeat the effect for them. A row counts as handled once its function has returned and that +has been recorded; if the process stops in between, the next run calls the function for that +row again. A row is identified by its source's name and its position, unless the source names +key columns that are unique per row (`record_id_columns`). Reordering the rows of a source +without them can make the sink handle them again, and so can a source whose name changes: an +in-memory source without a `source_id` is named after its content, so adding a row renames it. +For a sink, give the source both a `source_id` and key columns. ```python from orcapod import InvocationContext, sink_pod @@ -62,9 +60,9 @@ print(len(delivered)) # 8 ``` -Eight sessions, eight deliveries, and none on the second run. +The second run delivered nothing. -Three differences from a function pod. A sink is applied by calling it directly +A sink differs from a function pod in three ways. It is applied by calling it directly (`announce(stream)`, no `.pod`). Its function **must** take a parameter named `ctx`, which receives an `InvocationContext` describing the call; without it the run fails with `TypeError: ... got an unexpected keyword argument 'ctx'`. And it does not drop data columns @@ -124,8 +122,8 @@ print(loaded.nodes["minutes"].as_table().num_rows) # 8 ``` -A loaded job is for **looking at results**. It does not contain your functions, only their -names, so it cannot compute anything: `loaded.run()` raises `RuntimeError`. +A loaded job is for **looking at results**. It holds the names of your functions without their +code, so it cannot compute anything: `loaded.run()` raises `RuntimeError`. `loaded.run(load_only=True)` fills its nodes with the results already in the database and computes nothing. To compute, run the script that defines the pipeline. More in [Pipelines and jobs](../concepts/pipeline-job.md). @@ -173,8 +171,7 @@ the job a new name, and run it twice. How many deliveries are there after each r You can make the decision in the function, or filter the stream before the sink with `filter` (Part 3), which works inside a job like any other operator. Filtering keeps the - sink itself unchanged (it prints a `ProvisionalHashWarning`: see - [Messages you can ignore](00-setup.md#messages-you-can-ignore)): + sink itself unchanged: ```python from orcapod import col @@ -204,8 +201,7 @@ the job a new name, and run it twice. How many deliveries are there after each r # 4 ``` - Four after the first run, still four after the second. The sink saw only the four long - sessions, and the second time it ran for none of them. + Four after the first run, and none more after the second. **2.** Wrap Python's built-in `round` with `FunctionPod.from_fn`? Try it, and explain what happens. @@ -232,6 +228,5 @@ happens. # Schema({'duration_rounded': int}) ``` -That is the end of the tutorial. The [Concepts](../concepts/sources.md) pages go deeper on -each topic, and [Troubleshooting](../troubleshooting.md) is the page to keep open while you -write your first pipeline. +The [Concepts](../concepts/sources.md) pages cover each topic in more detail, and +[Troubleshooting](../troubleshooting.md) lists common errors and their fixes. diff --git a/docs/tutorial/index.md b/docs/tutorial/index.md index 628b5b7d0..270647cd2 100644 --- a/docs/tutorial/index.md +++ b/docs/tutorial/index.md @@ -10,20 +10,22 @@ Orcapod's test suite, so what a page shows is what the library prints. ## What you will build -A pipeline that takes a small extracellular-recording dataset and computes, for every -recording session, the mean firing rate of its units. Along the way you will store the +A pipeline that takes a small synthetic neural dataset and computes, for every recording +session, the mean firing rate of its units. The dataset is only the example: the same steps +apply to any analysis that starts from tables or files. Along the way you will store the results in a database, re-run the pipeline so that only new work is computed, read and write files, and trace a result back to the rows it came from. ## The dataset -The data is synthetic. A short script generates it on your machine; nothing is downloaded and -no real recordings are involved. It imitates a tiny study: +A short script generates the data on your machine. It imitates a small study of neural +recordings in mice. A *probe* is a recording device placed in one brain region, a *unit* is +one neuron detected on a probe, and a *spike* is one event of a unit: - 4 mice, two wildtype and two knockout - 2 recording sessions per mouse - 2 probes per session (`imec0` in V1, `imec1` in CA1) -- 4 sorted units per probe +- 4 units per probe ``` workshop_data/ @@ -52,10 +54,10 @@ workshop_data/ | [3. Reshaping with operators](03-operators.md) | Joining, filtering, renaming | 20 min | | [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 and caching](06-reruns-and-caching.md) | What is recomputed, and what is not | 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. When things go wrong](09-when-things-go-wrong.md) | Reading errors; failures inside a run | 15 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 diff --git a/site/astro.config.mjs b/site/astro.config.mjs index f350d5a9b..6bb8b3cb7 100644 --- a/site/astro.config.mjs +++ b/site/astro.config.mjs @@ -139,10 +139,10 @@ export default defineConfig({ 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 and caching', 'tutorial/06-reruns-and-caching'), + 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. When things go wrong', 'tutorial/09-when-things-go-wrong'), + page('9. Handling errors', 'tutorial/09-when-things-go-wrong'), page('10. Where next', 'tutorial/10-where-next'), ], }, From c006f4363769b5b733f856c4b25c4cee3810c881 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 20:37:12 -0800 Subject: [PATCH 2/5] docs(tutorial): say what the node of a source offers (ITL-1459) Co-Authored-By: Claude Opus 5.5 --- docs/tutorial/05-pipeline-job.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/tutorial/05-pipeline-job.md b/docs/tutorial/05-pipeline-job.md index e0fa5df60..7be269bc2 100644 --- a/docs/tutorial/05-pipeline-job.md +++ b/docs/tutorial/05-pipeline-job.md @@ -155,7 +155,8 @@ print(job.diagram(collapse=True)) # session_means (function pod · mean_rate · current) <- GroupBy ``` -You read a node like any other stream: +Read the node of a function pod or an operator like any other stream. The node of a source has +`as_table()`, `keys()` and `output_schema()`, but no `for` loop and no DataFrame methods: ```python means = job.nodes["session_means"] From 8807817b6226a10f4cb19afab61818d0ef434523 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 20:57:48 -0800 Subject: [PATCH 3/5] docs(tutorial): say what batch gathers after group_by, and the stale output of an undone edit (ITL-1459) Co-Authored-By: Claude Opus 5.5 --- docs/tutorial/04-many-rows-into-one.md | 5 +++-- docs/tutorial/07-files.md | 8 +++++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/docs/tutorial/04-many-rows-into-one.md b/docs/tutorial/04-many-rows-into-one.md index 2bafe5e97..d3af8aaa0 100644 --- a/docs/tutorial/04-many-rows-into-one.md +++ b/docs/tutorial/04-many-rows-into-one.md @@ -169,8 +169,9 @@ for tag, data in subjects.batch(batch_size=3): Use `batch` for everything at once or for chunks of a fixed size, such as a grand mean over all rows or mini-batches for a model. -If you need both `group_by` and `batch`, use them in that order. The tags of a batched stream -are lists, and `group_by` cannot use those. +If you need both `group_by` and `batch`, use them in that order. `batch` then gathers the +grouped rows: here sessions, whose lists of units stay whole. The tags of a batched stream are +lists, and `group_by` cannot use those. ## Key points diff --git a/docs/tutorial/07-files.md b/docs/tutorial/07-files.md index 4abbd77b8..f63c6f94f 100644 --- a/docs/tutorial/07-files.md +++ b/docs/tutorial/07-files.md @@ -218,9 +218,11 @@ print(len(list(out_dir.iterdir()))) - **Give every different input its own output file.** Build the output name from the inputs, as above. Rows whose files have the same content share one stored result, and so one output - file. When an input file is edited, its new result overwrites the output file of the same - name, and the stored result of the old content still points to that file. To keep both - outputs, include a hash of the file's content in the output name. + file. The names above do not change when an input file is edited, so the new result + overwrites the old output file, and the stored result of the old content still points to + it. If the edit is then undone, Orcapod returns that stored path, which now holds the + wrong output. For input files that may change, include a hash of the file's content in the + output name. - **The database stores the path, even if the file is deleted.** If you delete `spike_summaries/` and run again, Orcapod calls nothing and returns paths to files that no longer exist. Keep or delete output files together with the database. From 2c0f0441331a62158a787c7d2bf5b530370e4d5f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 23:40:29 -0800 Subject: [PATCH 4/5] docs(tutorial): split Part 8 into short tutorials and rename the section Tutorials (ITL-1460) Co-Authored-By: Claude Fable 5.2 --- README.md | 7 +- changelog.d/ITL-1460.md | 9 + docs/concepts/file-types.md | 2 +- docs/concepts/notebooks.md | 2 +- docs/concepts/pipeline-job.md | 4 +- docs/concepts/provenance.md | 4 +- docs/dev/scripts/provenance_diagrams.py | 2 +- docs/getting-started.md | 2 +- docs/index.md | 5 +- docs/troubleshooting.md | 4 +- docs/tutorial/08-inspecting-and-tracing.md | 607 ------------------ docs/tutorial/chaining-pipelines.md | 156 +++++ docs/tutorial/{07-files.md => files.md} | 4 +- ...-things-go-wrong.md => handling-errors.md} | 6 +- docs/tutorial/index.md | 36 +- docs/tutorial/inspecting-results.md | 243 +++++++ docs/tutorial/tracing-a-value.md | 370 +++++++++++ .../{10-where-next.md => where-next.md} | 4 +- scripts/docs_site_content.py | 2 +- site/README.md | 2 +- site/astro.config.mjs | 36 +- tests/test_docs/test_doc_samples.py | 10 +- tests/test_docs/test_provenance_diagrams.py | 2 +- tests/test_docs/test_site_content.py | 2 +- 24 files changed, 861 insertions(+), 660 deletions(-) create mode 100644 changelog.d/ITL-1460.md delete mode 100644 docs/tutorial/08-inspecting-and-tracing.md create mode 100644 docs/tutorial/chaining-pipelines.md rename docs/tutorial/{07-files.md => files.md} (99%) rename docs/tutorial/{09-when-things-go-wrong.md => handling-errors.md} (98%) create mode 100644 docs/tutorial/inspecting-results.md create mode 100644 docs/tutorial/tracing-a-value.md rename docs/tutorial/{10-where-next.md => where-next.md} (98%) 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/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", }, From ddf745e3c5925ccab44372c59096619320c66da3 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 23:42:13 -0800 Subject: [PATCH 5/5] docs(dev): style guide rules for short tutorials (ITL-1460) Co-Authored-By: Claude Fable 5.2 --- docs/dev/documentation-style.md | 5 +++++ 1 file changed, 5 insertions(+) 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`.