-
Notifications
You must be signed in to change notification settings - Fork 33
feat: extract brain area anatomy from NWB location fields #1807
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
base: master
Are you sure you want to change the base?
Changes from all commits
d62f427
020ac76
e07f69f
8d06a2b
b6810cb
d6b5be1
322ccfc
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| #!/usr/bin/env python3 | ||
| """Regenerate allen_ccf_structures.json from Allen Brain Map API. | ||
|
|
||
| Run: python -m dandi.data.generate_allen_structures | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| from pathlib import Path | ||
|
|
||
| import requests | ||
|
|
||
|
|
||
| def _flatten(node: dict, out: list[dict]) -> None: | ||
| out.append({"id": node["id"], "acronym": node["acronym"], "name": node["name"]}) | ||
| for child in node.get("children", []): | ||
| _flatten(child, out) | ||
|
|
||
|
|
||
| def main() -> None: | ||
| url = "http://api.brain-map.org/api/v2/structure_graph_download/1.json" | ||
| resp = requests.get(url, timeout=30) | ||
| resp.raise_for_status() | ||
| data = resp.json() | ||
| structures: list[dict] = [] | ||
| root = data["msg"][0] | ||
| _flatten(root, structures) | ||
| structures.sort(key=lambda s: s["id"]) | ||
| out_path = Path(__file__).with_name("allen_ccf_structures.json") | ||
| with open(out_path, "w") as f: | ||
| json.dump(structures, f, separators=(",", ":")) | ||
| print(f"Wrote {len(structures)} structures to {out_path}") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
| Original file line number | Diff line number | Diff line change | |||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,252 @@ | |||||||||||||||||||||||||||||||||||||||||
| from __future__ import annotations | |||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
| import ast | |||||||||||||||||||||||||||||||||||||||||
| from functools import lru_cache | |||||||||||||||||||||||||||||||||||||||||
| import json | |||||||||||||||||||||||||||||||||||||||||
| from pathlib import Path | |||||||||||||||||||||||||||||||||||||||||
| import re | |||||||||||||||||||||||||||||||||||||||||
| from typing import Any | |||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
| from dandischema import models | |||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
| from .. import get_logger | |||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
| lgr = get_logger() | |||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
| MBAO_URI_TEMPLATE = "http://purl.obolibrary.org/obo/MBA_{}" | |||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
| # Values that should be treated as missing / uninformative | |||||||||||||||||||||||||||||||||||||||||
| _TRIVIAL_VALUES = frozenset( | |||||||||||||||||||||||||||||||||||||||||
| { | |||||||||||||||||||||||||||||||||||||||||
| "", | |||||||||||||||||||||||||||||||||||||||||
| "unknown", | |||||||||||||||||||||||||||||||||||||||||
| "none", | |||||||||||||||||||||||||||||||||||||||||
| "n/a", | |||||||||||||||||||||||||||||||||||||||||
| "na", | |||||||||||||||||||||||||||||||||||||||||
| "null", | |||||||||||||||||||||||||||||||||||||||||
| "unspecified", | |||||||||||||||||||||||||||||||||||||||||
| "not available", | |||||||||||||||||||||||||||||||||||||||||
| "not applicable", | |||||||||||||||||||||||||||||||||||||||||
| "brain", | |||||||||||||||||||||||||||||||||||||||||
| } | |||||||||||||||||||||||||||||||||||||||||
| ) | |||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
| @lru_cache(maxsize=1) | |||||||||||||||||||||||||||||||||||||||||
| def _load_allen_structures() -> list[dict[str, Any]]: | |||||||||||||||||||||||||||||||||||||||||
| """Load the bundled Allen CCF structures JSON.""" | |||||||||||||||||||||||||||||||||||||||||
| data_path = ( | |||||||||||||||||||||||||||||||||||||||||
| Path(__file__).resolve().parent.parent / "data" / "allen_ccf_structures.json" | |||||||||||||||||||||||||||||||||||||||||
| ) | |||||||||||||||||||||||||||||||||||||||||
| with open(data_path) as f: | |||||||||||||||||||||||||||||||||||||||||
| structures: list[dict[str, Any]] = json.load(f) | |||||||||||||||||||||||||||||||||||||||||
| return structures | |||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
| @lru_cache(maxsize=1) | |||||||||||||||||||||||||||||||||||||||||
| def _build_lookup_dicts() -> ( | |||||||||||||||||||||||||||||||||||||||||
| tuple[dict[str, dict], dict[str, dict], dict[str, dict], dict[str, dict]] | |||||||||||||||||||||||||||||||||||||||||
| ): | |||||||||||||||||||||||||||||||||||||||||
| """Build lookup dictionaries for Allen CCF structures. | |||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
| Returns | |||||||||||||||||||||||||||||||||||||||||
| ------- | |||||||||||||||||||||||||||||||||||||||||
| tuple of 4 dicts | |||||||||||||||||||||||||||||||||||||||||
| (acronym_exact, acronym_lower, name_exact, name_lower) | |||||||||||||||||||||||||||||||||||||||||
| """ | |||||||||||||||||||||||||||||||||||||||||
| structures = _load_allen_structures() | |||||||||||||||||||||||||||||||||||||||||
| acronym_exact: dict[str, dict] = {} | |||||||||||||||||||||||||||||||||||||||||
| acronym_lower: dict[str, dict] = {} | |||||||||||||||||||||||||||||||||||||||||
| name_exact: dict[str, dict] = {} | |||||||||||||||||||||||||||||||||||||||||
| name_lower: dict[str, dict] = {} | |||||||||||||||||||||||||||||||||||||||||
| for s in structures: | |||||||||||||||||||||||||||||||||||||||||
| acr = s["acronym"] | |||||||||||||||||||||||||||||||||||||||||
| name = s["name"] | |||||||||||||||||||||||||||||||||||||||||
| # First match wins (structures are sorted by id) | |||||||||||||||||||||||||||||||||||||||||
| if acr not in acronym_exact: | |||||||||||||||||||||||||||||||||||||||||
| acronym_exact[acr] = s | |||||||||||||||||||||||||||||||||||||||||
| acr_low = acr.lower() | |||||||||||||||||||||||||||||||||||||||||
| if acr_low not in acronym_lower: | |||||||||||||||||||||||||||||||||||||||||
| acronym_lower[acr_low] = s | |||||||||||||||||||||||||||||||||||||||||
| if name not in name_exact: | |||||||||||||||||||||||||||||||||||||||||
| name_exact[name] = s | |||||||||||||||||||||||||||||||||||||||||
| name_low = name.lower() | |||||||||||||||||||||||||||||||||||||||||
| if name_low not in name_lower: | |||||||||||||||||||||||||||||||||||||||||
| name_lower[name_low] = s | |||||||||||||||||||||||||||||||||||||||||
| return acronym_exact, acronym_lower, name_exact, name_lower | |||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
| def _is_numeric(val: str) -> bool: | |||||||||||||||||||||||||||||||||||||||||
| """Return True if *val* looks like a number (int or float).""" | |||||||||||||||||||||||||||||||||||||||||
| try: | |||||||||||||||||||||||||||||||||||||||||
| float(val) | |||||||||||||||||||||||||||||||||||||||||
| return True | |||||||||||||||||||||||||||||||||||||||||
| except ValueError: | |||||||||||||||||||||||||||||||||||||||||
| return False | |||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
| # Canonicalised area key names recognised in dict-style location strings. | |||||||||||||||||||||||||||||||||||||||||
| # Keys are normalised by lowering, stripping whitespace, and removing hyphens | |||||||||||||||||||||||||||||||||||||||||
| # and underscores so that "brain-area", "brain_area", "BrainArea" all match. | |||||||||||||||||||||||||||||||||||||||||
| _AREA_KEYS = frozenset( | |||||||||||||||||||||||||||||||||||||||||
| { | |||||||||||||||||||||||||||||||||||||||||
| "area", | |||||||||||||||||||||||||||||||||||||||||
| "areaname", | |||||||||||||||||||||||||||||||||||||||||
| "brainarea", | |||||||||||||||||||||||||||||||||||||||||
| "brainregion", | |||||||||||||||||||||||||||||||||||||||||
| "location", | |||||||||||||||||||||||||||||||||||||||||
| "name", | |||||||||||||||||||||||||||||||||||||||||
| "region", | |||||||||||||||||||||||||||||||||||||||||
| "regionname", | |||||||||||||||||||||||||||||||||||||||||
| } | |||||||||||||||||||||||||||||||||||||||||
| ) | |||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
| def _normalise_key(key: str) -> str: | |||||||||||||||||||||||||||||||||||||||||
| """Lower-case and strip spaces, hyphens, underscores from *key*.""" | |||||||||||||||||||||||||||||||||||||||||
| return re.sub(r"[\s_-]", "", key).lower() | |||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
| def _extract_area_from_dict(d: dict) -> str | None: | |||||||||||||||||||||||||||||||||||||||||
| """Return the first non-trivial area value from a dict with flexible key matching.""" | |||||||||||||||||||||||||||||||||||||||||
| for key, val in d.items(): | |||||||||||||||||||||||||||||||||||||||||
| if _normalise_key(str(key)) in _AREA_KEYS: | |||||||||||||||||||||||||||||||||||||||||
| val = str(val).strip() | |||||||||||||||||||||||||||||||||||||||||
| if val and val.lower() not in _TRIVIAL_VALUES: | |||||||||||||||||||||||||||||||||||||||||
| return val | |||||||||||||||||||||||||||||||||||||||||
| return None | |||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
| def _parse_location_string(location: str) -> list[str]: | |||||||||||||||||||||||||||||||||||||||||
| """Parse a raw NWB location string into area tokens ignoring numerics etc. | |||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
| Handles: | |||||||||||||||||||||||||||||||||||||||||
| - Simple strings: ``"VISp"`` | |||||||||||||||||||||||||||||||||||||||||
| - Dict literals: ``"{'area': 'VISp', 'depth': '20'}"`` | |||||||||||||||||||||||||||||||||||||||||
| - Key-value pairs: ``"area: VISp, depth: 175"`` | |||||||||||||||||||||||||||||||||||||||||
| - Comma-separated lists: ``"VISp,VISrl,VISlm"`` | |||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
| In examples above, depth numerical values are getting ignored. | |||||||||||||||||||||||||||||||||||||||||
| """ | |||||||||||||||||||||||||||||||||||||||||
| location = location.strip() | |||||||||||||||||||||||||||||||||||||||||
| if not location or location.lower() in _TRIVIAL_VALUES: | |||||||||||||||||||||||||||||||||||||||||
| return [] | |||||||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||||||
| # Try dict literal (e.g. "{'area': 'VISp', 'depth': 20}") | |||||||||||||||||||||||||||||||||||||||||
| if location.startswith("{"): | |||||||||||||||||||||||||||||||||||||||||
| try: | |||||||||||||||||||||||||||||||||||||||||
| d = ast.literal_eval(location) | |||||||||||||||||||||||||||||||||||||||||
| if isinstance(d, dict): | |||||||||||||||||||||||||||||||||||||||||
| val = _extract_area_from_dict(d) | |||||||||||||||||||||||||||||||||||||||||
| if val is not None: | |||||||||||||||||||||||||||||||||||||||||
| return [val] | |||||||||||||||||||||||||||||||||||||||||
| # If no known key, return all non-trivial, non-numeric values | |||||||||||||||||||||||||||||||||||||||||
| tokens = [] | |||||||||||||||||||||||||||||||||||||||||
| for v in d.values(): | |||||||||||||||||||||||||||||||||||||||||
| v = str(v).strip() | |||||||||||||||||||||||||||||||||||||||||
| if v and v.lower() not in _TRIVIAL_VALUES and not _is_numeric(v): | |||||||||||||||||||||||||||||||||||||||||
| tokens.append(v) | |||||||||||||||||||||||||||||||||||||||||
| return tokens | |||||||||||||||||||||||||||||||||||||||||
| except (ValueError, SyntaxError): | |||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||
| @@ -112,7 +112,11 @@ | ||
| tokens.append(val) | ||
| return tokens | ||
| except (ValueError, SyntaxError): | ||
| pass | ||
| lgr.debug( | ||
| "Failed to parse brain location as dict literal %r; " | ||
| "falling back to alternative parsing strategies", | ||
| location, | ||
| ) | ||
|
|
||
| # Try key-value format (e.g. "area: VISp, depth: 175") | ||
| if re.search(r"\w+\s*:", location) and "://" not in location: |
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.
@bendichter something should be at least logged here or best to give example on when is it happening -- is that a broken structure from allen (report upstream?) or expected and unhandled explicitly above ? may be it would signal need to just add one more _TRIVIAL_VALUES ?
overall -- unclear
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 idea here is to try our best to process the variety of different forms of the location string.
I disagree with your reviewer bot- there is a clear explanation on the next line.
Above, Claude is trying to parse the string as a dict literal. If it can't it proceeds to other parsers. It is using try/except here instead of if/else. It's easier to try to parse a string as a dict literal and handle failure than it is to have a test for a dict literal. It's not how I usually code, but it's valid and understandable. Would you rather we always used if/else for flow control?
False positives are not a problem, because in the end all tokens will be matched against the CCF.
If you want, we can get rid of this and just reduce the variety of edge cases we can handle here. It just means we will miss area extraction on a few outlier datasets.
At the same time, I am working on a PR to NWB Inspector to try to clamp down on this variety.
Uh oh!
There was an error while loading. Please reload this page.