Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions docs/schema/classes/ClassDerivation.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,8 @@ URI: [linkmlmap:class/ClassDerivation](https://w3id.org/linkml/transformer/class

ClassDerivation : populated_from

ClassDerivation : required_slots

ClassDerivation : slot_derivations


Expand Down Expand Up @@ -200,6 +202,7 @@ URI: [linkmlmap:class/ClassDerivation](https://w3id.org/linkml/transformer/class
| [slot_derivations](../slots/slot_derivations.md) | * <br/> [SlotDerivation](../classes/SlotDerivation.md) | Instructions on how to derive the slots of this target class from source data | direct |
| [target_definition](../slots/target_definition.md) | 0..1 <br/> [Any](../classes/Any.md) | LinkML class definition object for this slot | direct |
| [filter_rows](../slots/filter_rows.md) | 0..1 <br/> [String](../types/String.md) | An expression evaluated on each source row, using the LinkML expression langu... | direct |
| [required_slots](../slots/required_slots.md) | * <br/> [String](../types/String.md) | Slot derivations that must come out with a value for the object to be emitted | direct |
| [pivot_operation](../slots/pivot_operation.md) | 0..1 <br/> [PivotOperation](../classes/PivotOperation.md) | Configuration for pivot (unmelt) operations at class level | direct |
| [mint_ids](../slots/mint_ids.md) | 0..1 <br/> [Boolean](../types/Boolean.md) | Overrides the specification's mint_ids, and the target class's entry in class... | direct |
| [name](../slots/name.md) | 1 <br/> [String](../types/String.md) | Name of the element in the target schema | [ElementDerivation](../classes/ElementDerivation.md) |
Expand Down Expand Up @@ -350,6 +353,18 @@ attributes:
domain_of:
- ClassDerivation
range: string
required_slots:
name: required_slots
description: 'Slot derivations that must come out with a value for the object
to be emitted. If any of them is None or an empty list once the slots are derived,
the row yields no object: no record at the top level, and no nested object under
a slot.'
from_schema: https://w3id.org/linkml/transformer
rank: 1000
domain_of:
- ClassDerivation
range: string
multivalued: true
pivot_operation:
name: pivot_operation
description: Configuration for pivot (unmelt) operations at class level
Expand Down Expand Up @@ -462,6 +477,19 @@ attributes:
domain_of:
- ClassDerivation
range: string
required_slots:
name: required_slots
description: 'Slot derivations that must come out with a value for the object
to be emitted. If any of them is None or an empty list once the slots are derived,
the row yields no object: no record at the top level, and no nested object under
a slot.'
from_schema: https://w3id.org/linkml/transformer
rank: 1000
owner: ClassDerivation
domain_of:
- ClassDerivation
range: string
multivalued: true
pivot_operation:
name: pivot_operation
description: Configuration for pivot (unmelt) operations at class level
Expand Down
1 change: 1 addition & 0 deletions docs/schema/datamodel.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ Name: linkml-map
| [publication_date](slots/publication_date.md) | date of publication of this transformation specification |
| [range](slots/range.md) | The range (value type) to assign to the derived target slot, overriding the r... |
| [repository_url](slots/repository_url.md) | URL to a code repository |
| [required_slots](slots/required_slots.md) | Slot derivations that must come out with a value for the object to be emitted |
| [reversed](slots/reversed.md) | If true, reverse the operation, splitting a delimited or serialized string ba... |
| [reviewer](slots/reviewer.md) | A list of reviewers of this transformation specification |
| [ror_id](slots/ror_id.md) | ROR (Research Organization Registry) identifier |
Expand Down
108 changes: 108 additions & 0 deletions docs/schema/slots/required_slots.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
---
search:
boost: 5.0
---

# Slot: required_slots


_Slot derivations that must come out with a value for the object to be emitted. If any of them is None or an empty list once the slots are derived, the row yields no object: no record at the top level, and no nested object under a slot._



<div data-search-exclude markdown="1">



URI: [linkmlmap:slot/required_slots](https://w3id.org/linkml/transformer/slot/required_slots)
<!-- no inheritance hierarchy -->





## Applicable Classes

| Name | Description | Modifies Slot |
| --- | --- | --- |
| [ClassDerivation](../classes/ClassDerivation.md) | A specification of how to derive a target class from a source class | no |






## Properties

### Type and Range

| Property | Value |
| --- | --- |
| Range | [String](../types/String.md) |
| Domain Of | [ClassDerivation](../classes/ClassDerivation.md) |
### Cardinality and Requirements

| Property | Value |
| --- | --- |
| Multivalued | Yes |


### Slot Characteristics

| Property | Value |
| --- | --- |
| Owner | [ClassDerivation](../classes/ClassDerivation.md) |












## Identifier and Mapping Information





### Schema Source


* from schema: https://w3id.org/linkml/transformer




## Mappings

| Mapping Type | Mapped Value |
| --- | --- |
| self | linkmlmap:required_slots |
| native | linkmlmap:required_slots |




## LinkML Source

<details>
```yaml
name: required_slots
description: 'Slot derivations that must come out with a value for the object to be
emitted. If any of them is None or an empty list once the slots are derived, the
row yields no object: no record at the top level, and no nested object under a slot.'
from_schema: https://w3id.org/linkml/transformer
rank: 1000
owner: ClassDerivation
domain_of:
- ClassDerivation
range: string
multivalued: true

```
</details></div>
37 changes: 37 additions & 0 deletions docs/writing-specs.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,43 @@ A filter can read joined tables like any expression (`{people.cohort} == "origin
On a nested class derivation it decides whether the row contributes that object: a
rejected row adds nothing to a multivalued slot and leaves a single-valued one empty.

## Requiring Slots

`filter_rows` decides from the source row. When the test is whether a slot came out with a
value — a status that mapped, a nested list that isn't empty — name the slot in
`required_slots`:

```yaml
class_derivations:
Condition:
populated_from: answers
required_slots: [status]
slot_derivations:
id:
populated_from: pid
kind:
value: smoking
status:
populated_from: smoker
value_mappings:
'Y': PRESENT
'N': ABSENT
```

A row whose `smoker` is empty or isn't `Y` or `N` yields no `Condition`. Without
`required_slots` it would yield one holding an id and `kind: smoking` but no status.

- Every named slot must have a value: one that is None or an empty list drops the object.
- The check runs once the slots are derived, so a `value_if_missing` or `value_if_unmapped`
fill counts as a value, and so does a slot marked `hide`.
- It works on a nested class derivation too. A parent that requires the slot holding its
nested objects is dropped when none of them is left.
- If it keeps none of a class derivation's objects, `map-data` logs a warning when the run
ends, as for `filter_rows`.

Unlike a filter, it derives every slot of a row before dropping it, so a row that fails to
derive is still an error. Use `filter_rows` where the source row alone decides.

## Working with Auto-Generated Schemas

When working with schemas auto-generated from tabular data (e.g., via [schema-automator](https://github.com/linkml/schema-automator)),
Expand Down
5 changes: 4 additions & 1 deletion src/linkml_map/cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,7 @@ def _map_data_single(
click.echo(f" - {err}", err=True)
raise SystemExit(1) from err
if tr_obj is None:
click.echo("The input object fails filter_rows; nothing to write.", err=True)
click.echo("The input object fails filter_rows or required_slots; nothing to write.", err=True)
elif output_format in COLUMNAR_FORMATS:
_dump_columnar(tr_obj, output_format, output, table_name)
else:
Expand Down Expand Up @@ -550,6 +550,9 @@ def report_error(err: TransformationError) -> None:
for (cd_name, filter_rows), (seen, kept) in tr.filter_counts.items():
if seen and not kept:
logger.warning(f"{cd_name}: filter_rows {filter_rows!r} kept none of {seen} rows")
for cd_name, (derived, kept) in tr.required_counts.items():
if derived and not kept:
logger.warning(f"{cd_name}: required_slots kept none of {derived} objects")

# Errors were already printed as they occurred; a mid-stream crash would
# have propagated before reaching here. Reached only on clean completion.
Expand Down
1 change: 1 addition & 0 deletions src/linkml_map/datamodel/transformer_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,7 @@ class ClassDerivation(ElementDerivation):
target_definition: Optional[Any] = Field(default=None, description="""LinkML class definition object for this slot.""", json_schema_extra = { "linkml_meta": {'comments': ['currently defined as Any to avoid coupling with metamodel'],
'domain_of': ['ClassDerivation', 'SlotDerivation']} })
filter_rows: Optional[str] = Field(default=None, description="""An expression evaluated on each source row, using the LinkML expression language. A row for which it is not true yields no object: no record at the top level, and no nested object under a slot.""", json_schema_extra = { "linkml_meta": {'domain_of': ['ClassDerivation'], 'examples': [{'value': '{visit_code} == 3'}]} })
required_slots: Optional[list[str]] = Field(default_factory=list, description="""Slot derivations that must come out with a value for the object to be emitted. If any of them is None or an empty list once the slots are derived, the row yields no object: no record at the top level, and no nested object under a slot.""", json_schema_extra = { "linkml_meta": {'domain_of': ['ClassDerivation']} })
pivot_operation: Optional[PivotOperation] = Field(default=None, description="""Configuration for pivot (unmelt) operations at class level""", json_schema_extra = { "linkml_meta": {'domain_of': ['ClassDerivation', 'SlotDerivation']} })
mint_ids: Optional[bool] = Field(default=None, description="""Overrides the specification's mint_ids, and the target class's entry in class_defaults, for this class derivation. Set to false on classes whose identifiers other records reference, so a missing derivation is an error rather than a content hash.""", json_schema_extra = { "linkml_meta": {'domain_of': ['TransformationSpecification',
'ClassDefault',
Expand Down
8 changes: 8 additions & 0 deletions src/linkml_map/datamodel/transformer_model.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,14 @@ classes:
the top level, and no nested object under a slot.
examples:
- value: "{visit_code} == 3"
required_slots:
range: string
multivalued: true
description: >-
Slot derivations that must come out with a value for the object to be
emitted. If any of them is None or an empty list once the slots are
derived, the row yields no object: no record at the top level, and no
nested object under a slot.
pivot_operation:
range: PivotOperation
description: Configuration for pivot (unmelt) operations at class level
Expand Down
10 changes: 9 additions & 1 deletion src/linkml_map/transformer/object_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,12 @@ def map_object(
tgt_attrs[str(slot_deriv.name)] = self._derive_slot(
slot_deriv, context, target_type or class_deriv.name, bindings, expr_functions
)
if class_deriv.required_slots:
counts = self.required_counts.setdefault(class_deriv.name, [0, 0])
counts[0] += 1
if any(tgt_attrs.get(name) in (None, []) for name in class_deriv.required_slots):
return None
Comment thread
amc-corey-cox marked this conversation as resolved.
Resolved
counts[1] += 1
# Remove hidden slots from output (they exist only for slot() references)
for slot_deriv in class_deriv.slot_derivations.values():
if slot_deriv.hide:
Expand Down Expand Up @@ -1182,7 +1188,9 @@ def _derive_nested_objects(
class_derivation=cls_derivation,
)
if nested_result is None:
logger.debug("Row failed the filter for nested %r; emitting no object", cls_derivation.name)
logger.debug(
"Row failed filter_rows or required_slots for nested %r; emitting no object", cls_derivation.name
)
continue
# An object with every slot None has no content; leave it out as None slot values are.
# A minted id hashes that content rather than adding to it, so it doesn't count.
Expand Down
3 changes: 3 additions & 0 deletions src/linkml_map/transformer/transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,9 @@ class Transformer(ABC):
filter_counts: dict[tuple[str, str], list[int]] = field(default_factory=dict, repr=False)
"""``[seen, kept]`` source rows per ``(class derivation, filter_rows)``, to warn about a filter that keeps none."""

required_counts: dict[str, list[int]] = field(default_factory=dict, repr=False)
"""``[derived, kept]`` objects per class derivation with ``required_slots``, to warn when none is kept."""

spec_messages: list[Any] = field(default_factory=list)
"""Scan messages captured at spec-load time.

Expand Down
11 changes: 11 additions & 0 deletions src/linkml_map/validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -751,6 +751,17 @@ def _validate_class_derivation(
messages,
)

derived_slots = {sd.get("name") for sd in slot_derivation_dicts}
messages.extend(
ValidationMessage(
severity="error",
path=f"{cd_path}.required_slots",
message=f"required_slots names {name!r}, which is not a slot derivation of this class derivation",
)
for name in cd.get("required_slots") or []
if name not in derived_slots
)
Comment thread
amc-corey-cox marked this conversation as resolved.
Resolved

for sd in slot_derivation_dicts:
sd_name = sd.get("name", "?")
sd_path = f"{cd_path}.slot_derivations[{sd_name}]"
Expand Down
Loading
Loading