-
Notifications
You must be signed in to change notification settings - Fork 0
Task/normalize behavior name resolution #56
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
bergsalex
wants to merge
2
commits into
master
Choose a base branch
from
task/normalize-behavior-name-resolution
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -28,6 +28,28 @@ | |
| BEHAVIOR_CLASSIFY_VERSION = 1 | ||
|
|
||
|
|
||
| def normalize_behavior_name(behavior: str) -> str: | ||
| """Normalize behavior names to align with pipeline behavior path rules.""" | ||
| normalized = behavior.replace(" ", "_") | ||
| normalized = re.sub(r"[()]", "", normalized) | ||
| return normalized.lower() | ||
|
|
||
|
|
||
| def resolve_behavior_key(behavior: str, available_behaviors: List[str]) -> str | None: | ||
| """Resolves a behavior key from available behaviors using normalization.""" | ||
| if behavior in available_behaviors: | ||
| return behavior | ||
| behavior_norm = normalize_behavior_name(behavior) | ||
| matches = [ | ||
| key | ||
| for key in available_behaviors | ||
| if normalize_behavior_name(key) == behavior_norm | ||
| ] | ||
| if len(matches) == 1: | ||
| return matches[0] | ||
| return None | ||
|
|
||
|
|
||
| class MissingBehaviorException(ValueError): | ||
| """Custom error for behavior-related missing data.""" | ||
|
|
||
|
|
@@ -705,10 +727,11 @@ def from_jabs_annotation_file(cls, source_file: Path, behavior: str): | |
| data = json.load(f) | ||
|
|
||
| vid_name = data["file"] | ||
| behavior_norm = normalize_behavior_name(behavior) | ||
| df_list = [] | ||
| for animal_idx, labels in data["labels"].items(): | ||
| for cur_behavior, label_data in labels.items(): | ||
| if cur_behavior == behavior: | ||
| if normalize_behavior_name(cur_behavior) == behavior_norm: | ||
| new_events = [] | ||
| for cur_event in label_data: | ||
| new_df = pd.DataFrame( | ||
|
|
@@ -1340,8 +1363,9 @@ def generate_bout_table(source_file: Path, settings: ClassifierSettings): | |
| MissingBehaviorException if behavior file exists but contains no behavior predictions. | ||
| """ | ||
| with h5py.File(str(source_file), "r") as in_f: | ||
| if settings.behavior not in in_f["predictions/"].keys(): | ||
| available_keys = list(in_f["predictions"].keys()) | ||
| available_keys = list(in_f["predictions"].keys()) | ||
| behavior_key = resolve_behavior_key(settings.behavior, available_keys) | ||
| if behavior_key is None: | ||
|
Comment on lines
+1367
to
+1368
|
||
| if len(available_keys) > 0: | ||
| behavior_pred_shape = in_f[ | ||
| f"predictions/{available_keys[0]}/predicted_class" | ||
|
|
@@ -1353,7 +1377,7 @@ def generate_bout_table(source_file: Path, settings: ClassifierSettings): | |
| raise MissingBehaviorException( | ||
| "Prediction file exists, but no behaviors present to discover shape." | ||
| ) | ||
| class_calls = in_f[f"predictions/{settings.behavior}/predicted_class"][:] | ||
| class_calls = in_f[f"predictions/{behavior_key}/predicted_class"][:] | ||
|
|
||
| # Iterate over the animals | ||
| bout_dfs = [] | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| """Tests for behavior name normalization and resolution.""" | ||
|
|
||
| import json | ||
| from pathlib import Path | ||
|
|
||
| import h5py | ||
| import numpy as np | ||
|
|
||
| from jabs_postprocess.utils.project_utils import ( | ||
| BoutTable, | ||
| ClassifierSettings, | ||
| Prediction, | ||
| normalize_behavior_name, | ||
| resolve_behavior_key, | ||
| ) | ||
|
|
||
|
|
||
| def test_normalize_behavior_name_matches_pipeline_rules(): | ||
| assert normalize_behavior_name("rearing (unsupported)") == "rearing_unsupported" | ||
| assert normalize_behavior_name("Rearing_unsupported") == "rearing_unsupported" | ||
|
|
||
|
|
||
| def test_resolve_behavior_key_normalized_match(): | ||
| available = ["rearing (unsupported)", "grooming"] | ||
| assert ( | ||
| resolve_behavior_key("Rearing_unsupported", available) | ||
| == "rearing (unsupported)" | ||
| ) | ||
|
|
||
|
|
||
| def test_resolve_behavior_key_ambiguous_match(): | ||
| available = ["A B", "A_B"] | ||
| assert resolve_behavior_key("a b", available) is None | ||
|
|
||
|
|
||
| def test_from_jabs_annotation_file_uses_normalized_behavior(tmp_path: Path): | ||
| annotation = { | ||
| "file": "video1.avi", | ||
| "labels": { | ||
| "0": { | ||
| "rearing (unsupported)": [ | ||
| {"start": 0, "end": 2, "present": 1} | ||
| ] | ||
| } | ||
| }, | ||
| } | ||
| annotation_path = tmp_path / "annotation.json" | ||
| annotation_path.write_text(json.dumps(annotation)) | ||
|
|
||
| table = BoutTable.from_jabs_annotation_file( | ||
| annotation_path, "Rearing_unsupported" | ||
| ) | ||
| df = table.data | ||
|
|
||
| assert len(df) == 1 | ||
| row = df.iloc[0] | ||
| assert row["start"] == 0 | ||
| assert row["duration"] == 3 | ||
| assert row["is_behavior"] == 1 | ||
| assert row["video_name"] == "video1" | ||
|
|
||
|
|
||
| def test_generate_bout_table_uses_normalized_behavior(tmp_path: Path): | ||
| pred_path = tmp_path / "predictions.h5" | ||
| with h5py.File(pred_path, "w") as h5f: | ||
| pred_group = h5f.create_group("predictions") | ||
| behavior_group = pred_group.create_group("rearing (unsupported)") | ||
| behavior_group.create_dataset( | ||
| "predicted_class", data=np.array([[0, 1, 1, 0]], dtype=np.int8) | ||
| ) | ||
|
|
||
| settings = ClassifierSettings("Rearing_unsupported", 0, 0, 0) | ||
| df = Prediction.generate_bout_table(pred_path, settings) | ||
|
|
||
| match = df[ | ||
| (df["start"] == 1) & (df["duration"] == 2) & (df["is_behavior"] == 1) | ||
| ] | ||
| assert len(match) == 1 |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The function returns
Nonewhen multiple matches are found (ambiguous case), but this is indistinguishable from the case where no matches are found. Consider returning a more informative result (e.g., raising an exception for ambiguous matches or returning a tuple indicating the error type) to help callers differentiate between these scenarios.