diff --git a/changelog.d/ITL-1478.md b/changelog.d/ITL-1478.md new file mode 100644 index 000000000..c70e152f0 --- /dev/null +++ b/changelog.d/ITL-1478.md @@ -0,0 +1,10 @@ +### Fixed + +- Documentation corrected where a page said something the library does not do. Part 4 of the + tutorial, Troubleshooting and the Operators page now show `tag_by` as the way to group by a + data column. Commands in the tutorial are run with `uv run python`. The pages on streams, + operators, identity, sources and jobs now agree with the code on what operators read, what a + source's identity holds, what the node of a source offers, which order rules do not hold yet, + and how a derived source over a job node is reloaded. The Operators page calls an operator + instead of its `.process()` method. The Troubleshooting entry about `CSVSource` and a + `PosixPath` now names the error that occurs today, when a job over such a source is saved. (ITL-1478) diff --git a/docs/api/operators.md b/docs/api/operators.md index 8da38f324..7e003ca9b 100644 --- a/docs/api/operators.md +++ b/docs/api/operators.md @@ -6,7 +6,7 @@ introduction. Every signature and docstring on the published page comes from the code. See site/README.md. --> -Operators perform structural transformations on streams without inspecting or synthesizing data values. An operator may add a tag (`AddTags`), never data. +Operators perform structural transformations on streams. They never compute a data value. A few read data values: the filters (`Filter`, `PolarsFilter`, `DropNulls`), to decide which rows exist, and `Pick` and `Index`, to give out a value held inside a data value. An operator may add a tag (`AddTags`), never data. ::: orcapod.core.operators.Join diff --git a/docs/concepts/function-pods.md b/docs/concepts/function-pods.md index 8aebfb95f..868f84fea 100644 --- a/docs/concepts/function-pods.md +++ b/docs/concepts/function-pods.md @@ -400,7 +400,7 @@ type yet: a column of `time64` reads as `Any`, and an output annotated `-> time` Applying a pod directly, as above, computes in memory and keeps nothing. To store results and reuse them on later runs, record the same calls inside a `PipelineJob` that has a database -(`store`): +(its `database` argument): ```python from orcapod import PipelineJob, function_pod diff --git a/docs/concepts/identity.md b/docs/concepts/identity.md index cedf58b29..a454b0e54 100644 --- a/docs/concepts/identity.md +++ b/docs/concepts/identity.md @@ -13,9 +13,25 @@ The content hash captures schema, topology, and the **identity of the sources** pipeline. It is computed recursively: each element's content hash depends on its own identity plus the content hashes of all its upstream elements, all the way back to the sources. -A source's identity is its class, its schema, its `source_id` and its key columns (the -`record_id_columns` that name its rows, or none when rows are named by position). What the -`source_id` is depends on how the source was created: +What a source's identity holds depends on its kind: + +| Kind of source | Its identity | +|---|---| +| A table, file or database source (`ArrowTableSource`, `DictSource`, `ListSource`, `DataFrameSource`, `CSVSource`, `DeltaTableSource`, the SQLite, PostgreSQL and SpiralDB table sources), without `tags_as_data` | its `source_id`, its schema and its key columns | +| `DerivedSource` without `tags_as_data` (`node.as_source()`) | the content hash of the job node it reads, and nothing else: a `source_id` you give changes its name, not its content hash | +| `DerivedSource` or `SpiralDBTableSource` with `tags_as_data` | its `source_id`, its schema, its key columns and the `tags_as_data` mapping | +| `PollingSource` | its `source_id`, what its implementation states as its identity (`impl.identity()`), its tag columns and its key columns; not its schema | +| `SourceProxy` (stands in for a source that a loaded job could not rebuild) | the content hash and the pipeline hash saved with the job | + +- The `source_id` is the kind of source, the version of that kind and the source's name, as + in `csv_v1:subjects`. +- The key columns are the `record_id_columns` that name the rows, or none when rows are named + by position. +- The Python class is not part of any identity. Two sources are one source when everything in + their row of the table is equal, whatever their classes; two kinds of source given one name + differ in their `source_id`. + +What the name in the `source_id` is depends on how the source was created: - If you do not pass `source_id`, an in-memory source such as `DictSource` or `ArrowTableSource` derives it from the data, so two sources with different rows have @@ -23,9 +39,7 @@ A source's identity is its class, its schema, its `source_id` and its key column - File- and table-backed sources default to a name derived from their location (the file path for `CSVSource`, the table folder's path or URI for `DeltaTableSource`), not from the rows. -- If you pass `source_id` yourself, you are naming the source: two sources with the same - class, schema, `source_id` and key columns have the same content hash even when their rows - differ. +- If you pass `source_id` yourself, the table above says what the identity holds. Two sources that differ only in their key columns name the same rows differently, so they are two sources: different content hashes (each gets its own cache), the same pipeline hash @@ -314,7 +328,7 @@ The order counts only where it is the point of the argument: | Order that counts | Why | |---|---| | `record_id_columns` of every source (by default a database table's primary key) | A record id is the canonical JSON of the key columns in key order, so the key order is part of every record id and of the source's identity. It is the explicit argument that states the order. | -| `member_order` of `GroupBy` (ITL-1226; not in a release yet) | The explicit order of the members inside each group's lists, the argument that replaces the input's tag order there. | +| `member_order` of `GroupBy` (ITL-1226) | The explicit order of the members inside each group's lists, the argument that replaces the input's tag order there. | | the inputs of an operator whose `argument_symmetry` is a tuple (`SemiJoin`, `MergeJoin`) | The inputs have roles: `SemiJoin(left, right)` keeps the rows of `left`; `MergeJoin(a, b)` lists `a`'s value first in every merged list (ITL-1281). | | the order of the ROWS given to a source without key columns | Its record ids are the row positions, so a reorder is a change (by decision). Row order, never column order. | | the order of the ROWS given to `Batch` | `Batch` groups consecutive rows: row order, never column order. | @@ -351,10 +365,6 @@ source and stream kind, the function pod forms and a job. Today these cases stil data context v1 is frozen: - the order of `polars_filter`'s predicates is in its identity (ITL-1247, undecided); -- a function pod over data-tags: its content and pipeline hash and its node's stored paths - depend on the input's tag order and table layout (ITL-1246); -- a stream built directly from a table (`ArrowTableStream`): its content hash depends on - the order of its tags (ITL-1227); - which rows `head()` shows, sorted by tags, follows the tag order (ITL-1270); - where the columns are placed is not always the declared order: an operator places its output tags in its input table's column order (ITL-1249, presentation only). diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index 024c09153..a6c2fc19b 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -1,8 +1,9 @@ # Operators -Operators are structural transforms that reshape [streams](streams.md) without inspecting or -synthesizing data values. They join, filter, batch, group, rename, select columns and add tags -- -operations that affect the *structure* of the data (which rows exist, which columns are +Operators are structural transforms that reshape [streams](streams.md). They never compute a +data value. A few read data values: the filters, to decide which rows exist, and `Pick` and +`Index`, to give out a value held inside a data value. They join, filter, batch, group, rename, select +columns and add tags -- operations that affect the *structure* of the data (which rows exist, which columns are present, how columns are named) but never compute new values from data content. This is the key distinction from [function pods](function-pods.md), which do the opposite: they transform data values but never touch tags or stream structure. @@ -13,10 +14,10 @@ This separation is a core Orcapod design principle: | | Operator | Function Pod | |---|---|---| -| Inspects data content | Never, except filters (see below) | Yes | +| Inspects data content | Never, except the filters, `Pick` and `Index` (see below) | Yes | | Inspects / uses tags | Yes | No | | Can rename columns | Yes | No | -| Adds or synthesizes data | Never (may add a tag) | Yes | +| Adds or synthesizes data | Never computes one (may add a tag; `Pick` and `Index` may add a column holding a value from inside another) | Yes | | Stream arity | Configurable (1, 2, or N inputs) | Single in, single out | This boundary ensures that structural operations (joins, filters) and value computations @@ -39,10 +40,14 @@ An operator may add a tag, never data. A tag labels rows; it is not a data value [`AddTags`](#addtags) can add tags with constant values while every data column passes through unchanged. -The filters are the operators that read data columns: `Filter` and `PolarsFilter` evaluate -their conditions on values, and `DropNulls` reads only whether a value is present (its +Two groups of operators read data columns. The first is the filters: `Filter` and +`PolarsFilter` evaluate their conditions on values, and `DropNulls` reads only whether a value is present (its validity), never the value. They decide which rows exist; none synthesizes a value. +The second is `Pick` and `Index`. `Pick` reads inside a dict value and `Index` inside a list +value, and each gives one entry out as a data column. The value given out was already held in +the input's data, so nothing is computed. [Pick and Index](#pick-and-index) has the rules. + No operator carries its inputs' meta columns: the `__`-prefixed columns, such as a cached function pod's `__computed`, that describe how an input row was produced. An operator's output row is produced by the operator, so its `Data` holds none of them and its predicted @@ -124,7 +129,7 @@ measurements = DictSource( ) join = Join() -joined = join.process(subjects, measurements) +joined = join(subjects, measurements) print(joined.as_table().to_pandas()) # subject_id weight age # 0 mouse_01 25.3 12 @@ -409,7 +414,7 @@ source = DictSource( ) batch = Batch() -batched = batch.process(source) +batched = batch(source) for tag, data in batched: print("Tags:", tag.as_dict()) # Tags: {'subject_id': ['mouse_01', 'mouse_02']} @@ -606,7 +611,7 @@ source = DictSource( ) select = SelectDataColumns(columns=["weight"]) -result = select.process(source) +result = select(source) print(result.keys()[1]) # ('weight',) ``` @@ -930,7 +935,7 @@ import polars as pl from orcapod.operators import PolarsFilter filt = PolarsFilter(predicates=[pl.col("age") > 10]) -filtered = filt.process(source) +filtered = filt(source) for tag, pkt in filtered: print(f"{tag.as_dict()} -> {pkt.as_dict()}") # {'subject_id': 'mouse_01'} -> {'age': 12, 'weight': 25.3} @@ -1179,14 +1184,46 @@ one operator. On a stream with [data-tags](data-tags.md), the data-tags stay data-tags and the new tags are plain: a constant tag is never a data value. +### TagBy + +!!! warning "Provisional" + `TagBy` is a [provisional operator](#provisional-operators): its identity is not frozen + with data context v1 and may change in a later release. Building one issues + `ProvisionalHashWarning` once per process. + +`TagBy` gives data columns the tag role, so that a later step can join, group or order by +them. Streams offer it as `tag_by`. `group_by` takes tags only, so this is how you group by a +data column: + +```python +by_age = sessions.tag_by("age", "weight") +print(by_age.keys()) +# (('subject_id', 'session', 'age', 'weight'), ('age', 'weight')) + +grouped = sessions.tag_by("age").group_by(["age"]) +print(grouped.keys()) +# (('age',), ('age', 'weight')) +``` + +No value changes. Each named column is now a tag and is still a data column: a +[data-tag](data-tags.md). The names are a set: `tag_by("weight", "age")` is the same +operator. A column that is already a tag, a column that may hold nulls and a column whose +type cannot be a tag (a list, a struct, your own class) are refused. The full rules are in +[Adding the tag role](data-tags.md#adding-the-tag-role-tag_by). + ### Pick and Index -`Pick(column, key)` extracts one entry from a struct- or dict-typed data column, and +`Pick(column, key)` extracts one entry from a dict-typed data column (`dict[K, V]`), and `Index(column, i)` extracts one element from a list-typed data column (for example, a column -produced by `Batch` or `GroupBy`). See the [API reference](../api/operators.md). +produced by `Batch` or `GroupBy`). `dict[K, V]` is the only built-in type `Pick` reads: it +refuses a struct column and a column of your own class today, with `InputValidationError`. +A custom logical type can take part by defining `pick_field`; see the +[API reference](../api/operators.md). With `out=None` the extracted value replaces the column in place; with `out="name"` it is added -as a new column and the original is kept. A row whose list is too short, or whose dict lacks the +as a new column and the original is kept. When the column is a [data-tag](data-tags.md), +`out` is required: replacing the column in place would change the tag's value, so both +operators refuse it. A row whose list is too short, or whose dict lacks the key, is skipped (or raises `RuntimeError` with `fail_on_miss=True`). Every other column keeps its input Arrow type, and the extracted column takes the input's @@ -1329,20 +1366,23 @@ print(merged.as_table().schema.field("subject_id").type) ## Using operators -All operators follow the same interface. Call `.process()` with one or more input streams: +All operators follow the same interface. Build the operator, then call it with one or more +input streams: ```python operator = Join() -result_stream = operator.process(subjects, measurements) +result_stream = operator(subjects, measurements) ``` -All standard operators also support `__call__` as a shorthand for `.process()`, so you can -write: +Or in one line: ```python result_stream = Join()(subjects, measurements) ``` +Calling an operator is the same as calling its `.process()` method: +`operator.process(subjects, measurements)` gives the same stream. + The result is a new [stream](streams.md) that you can inspect, iterate, or pass to further operators or function pods. @@ -1351,7 +1391,8 @@ operators or function pods. Every stream also exposes the operators as methods, which reads well when chaining: `join`, `semi_join`, `batch`, `group_by`, `select_tag_columns`, `select_data_columns`, `drop_tag_columns`, `drop_data_columns`, `select_columns`, `drop_columns`, `map_tags`, -`map_data`, `map_columns`, `add_tags`, `filter`, `polars_filter`, `drop_nulls`, `pick` and `index`. +`map_data`, `map_columns`, `add_tags`, `tag_by`, `filter`, `polars_filter`, `drop_nulls`, `pick`, +`index` and `rejoin`. ```python adults = subjects.join(measurements).filter(col("age") > 10) diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 41a19df1b..64181196c 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -87,13 +87,15 @@ print(sorted(job.nodes)) The order in which `job.nodes` lists its names is not meaningful and can differ between Python sessions; look nodes up by name. -A node is a stream: `output_schema()`, `keys()`, `iter_data()`, `as_table()` and -`as_pandas_df()` work on it, and show the rows of the job's **current run** in this Python -process. Read nodes after `run()`: before it, every node other than a source is empty +The node of a function pod or an operator is a stream: `output_schema()`, `keys()`, +`iter_data()`, `as_table()` and `as_pandas_df()` work on it, and show the rows of the job's +**current run** in this Python process. The node of a source has `output_schema()`, `keys()`, +`iter_data()` and `as_table()`, but no `for` loop and no DataFrame methods. Read nodes after +`run()`: before it, every node other than a source is empty (`as_table()` returns no rows; `head()` and the notebook preview say the node has not run). A run fills a node also when every result is read from the database and nothing is computed. -Three more things a job node offers: +Three more things a job node offers (the node of a source has only the last): - **`get_all_records()`** returns every record this step of the job has stored, including rows computed by earlier runs of the same job over the same source with other inputs. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 4f6b04177..77f13b571 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -520,7 +520,7 @@ summary = job.run() print(summary.conditions) # {'spikes': Condition.of({'unit_id': 106})} print(summary.restricted_source_ids) -# {'spikes': 'spikes'} +# {'spikes': 'spiraldb_table_v1:spikes'} ``` (This sample needs a SpiralDB project, so it is not run with the documentation; `job` is a @@ -825,9 +825,13 @@ before. Things to know: (ITL-1313); `as_source(tags_as_data=..., source_id=...)` takes it too. The source is identified by that name and the mapping, like any named source: the mapping is part of its `content_hash`, so two mappings never share one. -- A saved job reloads a derived source whenever its origin can be reloaded (a CSV file, a - Delta table, a database table). Over an in-memory source it is saved but not reloaded, like - the in-memory source itself. +- A saved job reloads a derived source over a source whenever that source can be reloaded + (a CSV file, a Delta table, a database table). Over an in-memory source it is saved but not + reloaded, like the in-memory source itself. Over a job node (`as_source()`, with or without + `tags_as_data`) it is saved but not reloaded either: the loaded job lists its slot in + `loaded.unbound_sources`. Build the source again from the job it came from and bind it: + `loaded.bind(sources={slot: other_job.nodes["bmi"].as_source(...)})`, with `slot` taken + from `loaded.unbound_sources`. ```python print(with_start.upstreams) @@ -872,7 +876,7 @@ per source kind per process; filter its class to silence it, as for ## What a source does at a run A job node that has run holds its rows until it is stale, and staleness comes from modified -times only (see [Running one node](function-pods.md)). So every run (`job.run()`, +times only (see [Running again: what a run runs](function-pods.md#running-again-what-a-run-runs)). So every run (`job.run()`, `run_async()`, a job node's `run()`, a load-only run too) first asks each source feeding it, once, whether its data changed: `source.check_for_new_data()` (developer, November 14, 2026, ITL-1102). A source that finds new data takes it in and moves its modified time to that @@ -1019,11 +1023,10 @@ print(len({s.source_id for s in as_given})) # 3 ``` -A source given a `source_id` is an address: its content hash is built from its class, schema, -`source_id` and key columns, never from its rows, so changing the rows changes it only when the -schema changes (a column of another type). This holds for `ListSource` too (developer, -November 21, 2026, ITL-1272): its elements and its tag function enter its identity only through -its default `source_id` and its output schema. +What a source's content hash is built from is listed, for each kind of source, in +[Identity](identity.md#content_hash-recursive-source-inclusive-identity). A `ListSource` +has no rule of its own (developer, November 21, 2026, ITL-1272): its elements and its tag +function enter its identity only through its default `source_id` and its output schema. These columns are hidden by default. You can reveal them using `ColumnConfig`: diff --git a/docs/concepts/streams.md b/docs/concepts/streams.md index 40c13de07..68992aeb2 100644 --- a/docs/concepts/streams.md +++ b/docs/concepts/streams.md @@ -21,7 +21,9 @@ columns as function inputs and write new data columns as outputs. This separation is enforced throughout the framework: -- Operators inspect and restructure tags but never look inside data +- Operators inspect and restructure tags and never compute a data value. A few read data + values: the filters, to decide which rows exist, and `Pick` and `Index`, to give out a + value held inside a data value - Function pods inspect and transform data but never look at tags ## Key classes diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 22282a2f7..b5b0ca48d 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -81,13 +81,13 @@ With polars, keep the frame `with_columns` returns: a pandas or polars `DataFrame` stored whole in one column is a library value, not a dictionary column. See [Arrow types of a source](concepts/sources.md#arrow-types-of-a-source). -### `TypeError: 'PosixPath' object is not iterable` from `CSVSource` +### `TypeError: Object of type PosixPath is not JSON serializable` from `job.save` -**Cause.** `CSVSource` was given a `pathlib.Path` and no `source_id`. The file path is -typed as a string; without a `source_id` it is used to build the default one, which fails -for a `Path`. This is a known defect. +**Cause.** A source in the job was built from a `pathlib.Path`, as in +`CSVSource(Path("units.csv"), ...)`. The source reads, but a job over it cannot be saved +yet. This is a known defect (ITL-1489). -**Fix.** `CSVSource(str(path), ...)`. +**Fix.** Pass the path as a string: `CSVSource(str(path), ...)`. ### `ValueError: Parameter 'x' has no type annotation and is not specified in input_types.` @@ -146,9 +146,13 @@ into a list. **Cause.** `group_by` was given a data column or an unknown name. Only tag columns can be grouping keys. -**Fix.** Group by tags. If the column you want to group by is data, it should have been a -tag: name it in `tag_columns` when you create the source. If the message says the columns -are *list-valued tag columns*, the stream came from `batch`; group before batching. +**Fix.** Group by tags. If the column you want to group by is data, give it the tag role +first: `stream.tag_by("genotype").group_by(["genotype"])`, or with several columns +`stream.tag_by("genotype", "sex").group_by(["genotype", "sex"])`. This also works after a +join and for a column a function pod computed; see +[Adding the tag role](concepts/data-tags.md#adding-the-tag-role-tag_by). You can also name +the column in `tag_columns` when you create the source. If the message says the columns are +*list-valued tag columns*, the stream came from `batch`; group before batching. ### `ValueError: Cannot hash the Polars expression '...' for an Orcapod identity` diff --git a/docs/tutorial/00-setup.md b/docs/tutorial/00-setup.md index 78d856a87..72bd638fe 100644 --- a/docs/tutorial/00-setup.md +++ b/docs/tutorial/00-setup.md @@ -101,9 +101,11 @@ curl -fO https://raw.githubusercontent.com/metamorphic-labs/orcapod-python/main/ Then run it: ```bash -python workshop_data.py +uv run python workshop_data.py ``` +With `pip`, in the activated environment: `python workshop_data.py`. + It prints `Wrote 27 files (... kB) to .../workshop_data` and creates the `workshop_data/` 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. diff --git a/docs/tutorial/04-many-rows-into-one.md b/docs/tutorial/04-many-rows-into-one.md index d3af8aaa0..5c5d77f9b 100644 --- a/docs/tutorial/04-many-rows-into-one.md +++ b/docs/tutorial/04-many-rows-into-one.md @@ -140,8 +140,26 @@ 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']) ``` -`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. +`genotype` and `sex` are data columns of `subjects`, and they stay data columns after a join. +To group by a data column, give it the tag role first, with `tag_by`: + +```python +with_subject = session_means.join(subjects.select_data_columns(["genotype", "sex"])) +by_group = with_subject.tag_by("genotype", "sex").group_by(["genotype", "sex"]) + +print(by_group.output_schema()) +# (Schema({'genotype': str, 'sex': str}), Schema({'genotype': str, 'sex': str, 'mean_rate_hz': list[float]})) +print(by_group.as_table().num_rows) +# 4 +``` + +`tag_by` changes no value. Each column you name is now a tag and is still a data column, so +it shows in both schemas. The same works for a column that a function pod computed. `tag_by` takes +a column with one value per row and no missing value: it refuses a list column and a column +that may hold nulls; see [Adding the tag role](../concepts/data-tags.md#adding-the-tag-role-tag_by). + +If you know from the start that you will group or match by a column, make it a tag in the +source, in `tag_columns`. Exercise 3 uses `tag_by`. ## Batch @@ -178,7 +196,8 @@ lists, and `group_by` cannot use those. - `group_by([...tags])` turns the rows sharing those tag values into one row of lists. `batch()` does the same by count. - A function pod with `list[...]` parameters computes over the lists. -- You can only group by tag columns. +- `group_by` takes tag columns only. To group by a data column, give it the tag role first: + `stream.tag_by("column")`. - `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 @@ -225,9 +244,8 @@ values: the number of units, the mean rate, and the highest rate. Apply it per s ``` **3.** Compute one number for each genotype: the mean of the session means of its animals. -`genotype` is a data column, so you cannot group by it. Instead, for each genotype, keep -that genotype's sessions and `batch` them. (Hint: `session_means.join(...)`, an equality -filter, then narrow, then `batch()`.) +`genotype` is a data column of `subjects`. (Hint: `session_means.join(...)`, then `tag_by`, +then `group_by`.) ??? success "Solution" ```python @@ -236,20 +254,22 @@ filter, then narrow, then `batch()`.) return sum(mean_rate_hz) / len(mean_rate_hz) - with_genotype = session_means.join(subjects.select_data_columns(["genotype"])) - - for genotype in ["wildtype", "knockout"]: - one_genotype = ( - with_genotype.filter(genotype=genotype) - .select_data_columns(["mean_rate_hz"]) - .batch() - ) - for _, data in mean_of_means.pod(one_genotype): - print(genotype, round(data.as_dict()["genotype_mean_hz"], 3)) - # wildtype 6.545 + genotype_means = mean_of_means.pod( + session_means.join(subjects.select_data_columns(["genotype"])) + .tag_by("genotype") + .group_by(["genotype"]) + ) + for tag, data in genotype_means: + print(tag.as_dict()["genotype"], round(data.as_dict()["genotype_mean_hz"], 3)) # knockout 5.058 + # wildtype 6.545 ``` - 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. + The join brings `genotype` in as a data column, `tag_by` makes it a tag, and `group_by` + gathers the four session means of each genotype into one list. + + With `genotype` as a tag of the source, `tag_by` is not needed. Load the subjects table + with `tag_columns=["subject_id", "genotype"]` and join it as it is, + `session_means.join(subjects)`: `genotype` is then no data column, so + `select_data_columns(["genotype"])` would fail. `group_by(["genotype"])` works right after + that join. 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 7be269bc2..0a0c90ffe 100644 --- a/docs/tutorial/05-pipeline-job.md +++ b/docs/tutorial/05-pipeline-job.md @@ -277,7 +277,8 @@ Sort them whenever the order matters, as the samples here do. ## Exercises **1.** Run a pipeline, quit Python, and run it again. Put the script below in a file -`run_pipeline.py` and run `python run_pipeline.py` twice. What does each run print? +`run_pipeline.py` and run `uv run python run_pipeline.py` twice (with `pip`, in the activated +environment: `python run_pipeline.py`). What does each run print? ```python from workshop_data import make_dataset diff --git a/docs/tutorial/where-next.md b/docs/tutorial/where-next.md index d7e0a1e1b..ae25b2bc0 100644 --- a/docs/tutorial/where-next.md +++ b/docs/tutorial/where-next.md @@ -141,7 +141,9 @@ Not covered here, with pointers: [Sources](../concepts/sources.md) and the [API reference](../api/sources.md). - **Running in parallel.** The `orcapod[ray]` extra adds an executor that runs function calls on a [Ray](https://www.ray.io/) cluster. `AsyncPipelineOrchestrator` in - `orcapod.pipeline` runs independent branches of a pipeline concurrently. + `orcapod.pipeline` runs the nodes of a pipeline side by side and a function on several rows + at once: see + [Running asynchronously](../concepts/function-pods.md#running-asynchronously-in-a-script-or-a-notebook). - **Arrays and your own classes as values.** NumPy arrays and tensors can be data values: see [Arrays and Tensors](../concepts/arrays.md). So can your own dataclasses and pydantic models: see [Your Own Data Types](../concepts/your-own-data-types.md). diff --git a/src/orcapod/core/operators/pick.py b/src/orcapod/core/operators/pick.py index 09824160d..57ac92354 100644 --- a/src/orcapod/core/operators/pick.py +++ b/src/orcapod/core/operators/pick.py @@ -1,4 +1,4 @@ -"""Pick operator — keyed projection into dict/struct-typed columns.""" +"""Pick operator — keyed projection into dict-typed columns.""" from __future__ import annotations @@ -25,13 +25,16 @@ class Pick(UnaryOperator): - """Extract a value from a struct- or dict-typed data column by key. + """Extract a value from a dict-typed data column by key. For ``dict[K, V]`` columns the lookup is per-packet; if the key is absent the packet is skipped (or an error is raised when ``fail_on_miss=True``). - For extension-type struct columns (Pydantic, dataclass) the field - existence is validated at build time and guaranteed at runtime. + ``dict[K, V]`` is the only built-in column type ``Pick`` reads. A column of a + logical type is read only when that type defines ``pick_field``, which gives + the type of the named field; no built-in type does. So an Arrow struct column + and a column of a dataclass, an ``orcapod.dataclass`` or a pydantic model are + refused with ``InputValidationError`` when the operator is applied (ITL-1494). The extracted column keeps the value's Arrow type (``dict[str, int16]`` yields ``int16``). Its nullability follows the predicted output type, which @@ -41,7 +44,8 @@ class Pick(UnaryOperator): Args: column: Name of the data column to project into. - key: Dict key or struct field name to extract. + key: Dict key to extract (for a logical type with ``pick_field``, the + field name). out: Output column name. ``None`` (default) replaces ``column`` in-place; a string adds a new column alongside the original. fail_on_miss: If ``True``, raise ``RuntimeError`` when the key is diff --git a/tests/test_core/order_rules.py b/tests/test_core/order_rules.py index be2d8a29c..fd6dce731 100644 --- a/tests/test_core/order_rules.py +++ b/tests/test_core/order_rules.py @@ -46,7 +46,7 @@ class OrderException: ), OrderException( "member_order", - "`member_order` of `GroupBy` (ITL-1226; not in a release yet)", + "`member_order` of `GroupBy` (ITL-1226)", "The explicit order of the members inside each group's lists, the argument that " "replaces the input's tag order there.", ),