zombie-squirrel 0.7.4__py3-none-any.whl → 0.8.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,12 +3,10 @@
3
3
  Provides functions to fetch and cache project names, subject IDs, and asset
4
4
  metadata from the AIND metadata database with support for multiple backends."""
5
5
 
6
- __version__ = "0.7.4"
6
+ __version__ = "0.8.1"
7
7
 
8
- from zombie_squirrel.squirrels import ( # noqa: F401
9
- asset_basics,
10
- raw_to_derived,
11
- source_data,
12
- unique_project_names,
13
- unique_subject_ids,
14
- )
8
+ from zombie_squirrel.acorn_contents.asset_basics import asset_basics # noqa: F401
9
+ from zombie_squirrel.acorn_contents.raw_to_derived import raw_to_derived # noqa: F401
10
+ from zombie_squirrel.acorn_contents.source_data import source_data # noqa: F401
11
+ from zombie_squirrel.acorn_contents.unique_project_names import unique_project_names # noqa: F401
12
+ from zombie_squirrel.acorn_contents.unique_subject_ids import unique_subject_ids # noqa: F401
@@ -0,0 +1,10 @@
1
+ """Acorns module: individual data fetching functions."""
2
+
3
+ # Import the acorn modules to trigger decorator registration
4
+ from zombie_squirrel.acorn_contents import ( # noqa: F401
5
+ asset_basics,
6
+ raw_to_derived,
7
+ source_data,
8
+ unique_project_names,
9
+ unique_subject_ids,
10
+ )
@@ -0,0 +1,135 @@
1
+ """Asset basics acorn."""
2
+
3
+ import logging
4
+
5
+ import pandas as pd
6
+ from aind_data_access_api.document_db import MetadataDbClient
7
+
8
+ import zombie_squirrel.acorns as acorns
9
+
10
+
11
+ @acorns.register_acorn(acorns.NAMES["basics"])
12
+ def asset_basics(force_update: bool = False) -> pd.DataFrame:
13
+ """Fetch basic asset metadata including modalities, projects, and subject info.
14
+
15
+ Returns a DataFrame with columns: _id, _last_modified, modalities,
16
+ project_name, data_level, subject_id, acquisition_start_time, and
17
+ acquisition_end_time. Uses incremental updates based on _last_modified
18
+ timestamps to avoid re-fetching unchanged records.
19
+
20
+ Args:
21
+ force_update: If True, bypass cache and fetch fresh data from database.
22
+
23
+ Returns:
24
+ DataFrame with basic asset metadata."""
25
+ df = acorns.TREE.scurry(acorns.NAMES["basics"])
26
+
27
+ FIELDS = [
28
+ "data_description.modalities",
29
+ "data_description.project_name",
30
+ "data_description.data_level",
31
+ "subject.subject_id",
32
+ "acquisition.acquisition_start_time",
33
+ "acquisition.acquisition_end_time",
34
+ "processing.data_processes.start_date_time",
35
+ "subject.subject_details.genotype",
36
+ "other_identifiers",
37
+ "location",
38
+ ]
39
+
40
+ if df.empty or force_update:
41
+ logging.info("Updating cache for asset basics")
42
+ df = pd.DataFrame(
43
+ columns=[
44
+ "_id",
45
+ "_last_modified",
46
+ "modalities",
47
+ "project_name",
48
+ "data_level",
49
+ "subject_id",
50
+ "acquisition_start_time",
51
+ "acquisition_end_time",
52
+ "code_ocean",
53
+ "process_date",
54
+ "genotype",
55
+ "location",
56
+ ]
57
+ )
58
+ client = MetadataDbClient(
59
+ host=acorns.API_GATEWAY_HOST,
60
+ version="v2",
61
+ )
62
+ # It's a bit complex to get multiple fields that aren't indexed in a database
63
+ # as large as DocDB. We'll also try to limit ourselves to only updating fields
64
+ # that are necessary
65
+ record_ids = client.retrieve_docdb_records(
66
+ filter_query={},
67
+ projection={"_id": 1, "_last_modified": 1},
68
+ limit=0,
69
+ )
70
+ keep_ids = []
71
+ # Drop all _ids where _last_modified matches cache
72
+ for record in record_ids:
73
+ cached_row = df[df["_id"] == record["_id"]]
74
+ if cached_row.empty or cached_row["_last_modified"].values[0] != record["_last_modified"]:
75
+ keep_ids.append(record["_id"])
76
+
77
+ # Now batch by 100 IDs at a time to avoid overloading server, and fetch all the fields
78
+ BATCH_SIZE = 100
79
+ asset_records = []
80
+ for i in range(0, len(keep_ids), BATCH_SIZE):
81
+ logging.info(f"Fetching asset basics batch {i // BATCH_SIZE + 1}...")
82
+ batch_ids = keep_ids[i: i + BATCH_SIZE]
83
+ batch_records = client.retrieve_docdb_records(
84
+ filter_query={"_id": {"$in": batch_ids}},
85
+ projection={field: 1 for field in FIELDS + ["_id", "_last_modified"]},
86
+ limit=0,
87
+ )
88
+ asset_records.extend(batch_records)
89
+
90
+ # Unwrap nested fields
91
+ records = []
92
+ for record in asset_records:
93
+ modalities = record.get("data_description", {}).get("modalities", [])
94
+ modality_abbreviations = [modality["abbreviation"] for modality in modalities if "abbreviation" in modality]
95
+ modality_abbreviations_str = ", ".join(modality_abbreviations)
96
+
97
+ # Get the process date, convert to YYYY-MM-DD if present
98
+ data_processes = record.get("processing", {}).get("data_processes", [])
99
+ if data_processes:
100
+ latest_process = data_processes[-1]
101
+ process_datetime = latest_process.get("start_date_time", None)
102
+ process_date = process_datetime.split("T")[0]
103
+ else:
104
+ process_date = None
105
+
106
+ # Get the CO asset ID
107
+ other_identifiers = record.get("other_identifiers", {})
108
+ if other_identifiers:
109
+ code_ocean = other_identifiers.get("Code Ocean", None)
110
+ else:
111
+ code_ocean = None
112
+
113
+ flat_record = {
114
+ "_id": record["_id"],
115
+ "_last_modified": record.get("_last_modified", None),
116
+ "modalities": modality_abbreviations_str,
117
+ "project_name": record.get("data_description", {}).get("project_name", None),
118
+ "data_level": record.get("data_description", {}).get("data_level", None),
119
+ "subject_id": record.get("subject", {}).get("subject_id", None),
120
+ "acquisition_start_time": record.get("acquisition", {}).get("acquisition_start_time", None),
121
+ "acquisition_end_time": record.get("acquisition", {}).get("acquisition_end_time", None),
122
+ "code_ocean": code_ocean,
123
+ "process_date": process_date,
124
+ "genotype": record.get("subject", {}).get("subject_details", {}).get("genotype", None),
125
+ "location": record.get("location", None),
126
+ }
127
+ records.append(flat_record)
128
+
129
+ # Combine new records with the old df and store in cache
130
+ new_df = pd.DataFrame(records)
131
+ df = pd.concat([df[~df["_id"].isin(keep_ids)], new_df], ignore_index=True)
132
+
133
+ acorns.TREE.hide(acorns.NAMES["basics"], df)
134
+
135
+ return df
@@ -0,0 +1,71 @@
1
+ """Raw to derived mapping acorn."""
2
+
3
+ import logging
4
+
5
+ import pandas as pd
6
+ from aind_data_access_api.document_db import MetadataDbClient
7
+
8
+ import zombie_squirrel.acorns as acorns
9
+
10
+
11
+ @acorns.register_acorn(acorns.NAMES["r2d"])
12
+ def raw_to_derived(force_update: bool = False) -> pd.DataFrame:
13
+ """Fetch mapping of raw records to their derived records.
14
+
15
+ Returns a DataFrame mapping raw record IDs to lists of derived record IDs
16
+ that depend on them as source data.
17
+
18
+ Args:
19
+ force_update: If True, bypass cache and fetch fresh data from database.
20
+
21
+ Returns:
22
+ DataFrame with _id and derived_records columns."""
23
+ df = acorns.TREE.scurry(acorns.NAMES["r2d"])
24
+
25
+ if df.empty or force_update:
26
+ logging.info("Updating cache for raw to derived mapping")
27
+ client = MetadataDbClient(
28
+ host=acorns.API_GATEWAY_HOST,
29
+ version="v2",
30
+ )
31
+
32
+ # Get all raw record IDs
33
+ raw_records = client.retrieve_docdb_records(
34
+ filter_query={"data_description.data_level": "raw"},
35
+ projection={"_id": 1},
36
+ limit=0,
37
+ )
38
+ raw_ids = {record["_id"] for record in raw_records}
39
+
40
+ # Get all derived records with their _id and source_data
41
+ derived_records = client.retrieve_docdb_records(
42
+ filter_query={"data_description.data_level": "derived"},
43
+ projection={"_id": 1, "data_description.source_data": 1},
44
+ limit=0,
45
+ )
46
+
47
+ # Build mapping: raw_id -> list of derived _ids
48
+ raw_to_derived_map = {raw_id: [] for raw_id in raw_ids}
49
+ for derived_record in derived_records:
50
+ source_data_list = derived_record.get("data_description", {}).get("source_data", [])
51
+ derived_id = derived_record["_id"]
52
+ # Add this derived record to each raw record it depends on
53
+ for source_id in source_data_list:
54
+ if source_id in raw_to_derived_map:
55
+ raw_to_derived_map[source_id].append(derived_id)
56
+
57
+ # Convert to DataFrame
58
+ data = []
59
+ for raw_id, derived_ids in raw_to_derived_map.items():
60
+ derived_ids_str = ", ".join(derived_ids)
61
+ data.append(
62
+ {
63
+ "_id": raw_id,
64
+ "derived_records": derived_ids_str,
65
+ }
66
+ )
67
+
68
+ df = pd.DataFrame(data)
69
+ acorns.TREE.hide(acorns.NAMES["r2d"], df)
70
+
71
+ return df
@@ -0,0 +1,50 @@
1
+ """Source data acorn."""
2
+
3
+ import logging
4
+
5
+ import pandas as pd
6
+ from aind_data_access_api.document_db import MetadataDbClient
7
+
8
+ import zombie_squirrel.acorns as acorns
9
+
10
+
11
+ @acorns.register_acorn(acorns.NAMES["d2r"])
12
+ def source_data(force_update: bool = False) -> pd.DataFrame:
13
+ """Fetch source data references for derived records.
14
+
15
+ Returns a DataFrame mapping record IDs to their upstream source data
16
+ dependencies as comma-separated lists.
17
+
18
+ Args:
19
+ force_update: If True, bypass cache and fetch fresh data from database.
20
+
21
+ Returns:
22
+ DataFrame with _id and source_data columns."""
23
+ df = acorns.TREE.scurry(acorns.NAMES["d2r"])
24
+
25
+ if df.empty or force_update:
26
+ logging.info("Updating cache for source data")
27
+ client = MetadataDbClient(
28
+ host=acorns.API_GATEWAY_HOST,
29
+ version="v2",
30
+ )
31
+ records = client.retrieve_docdb_records(
32
+ filter_query={},
33
+ projection={"_id": 1, "data_description.source_data": 1},
34
+ limit=0,
35
+ )
36
+ data = []
37
+ for record in records:
38
+ source_data_list = record.get("data_description", {}).get("source_data", [])
39
+ source_data_str = ", ".join(source_data_list) if source_data_list else ""
40
+ data.append(
41
+ {
42
+ "_id": record["_id"],
43
+ "source_data": source_data_str,
44
+ }
45
+ )
46
+
47
+ df = pd.DataFrame(data)
48
+ acorns.TREE.hide(acorns.NAMES["d2r"], df)
49
+
50
+ return df
@@ -0,0 +1,41 @@
1
+ """Unique project names acorn."""
2
+
3
+ import logging
4
+
5
+ import pandas as pd
6
+ from aind_data_access_api.document_db import MetadataDbClient
7
+
8
+ import zombie_squirrel.acorns as acorns
9
+
10
+
11
+ @acorns.register_acorn(acorns.NAMES["upn"])
12
+ def unique_project_names(force_update: bool = False) -> list[str]:
13
+ """Fetch unique project names from metadata database.
14
+
15
+ Returns cached results if available, fetches from database if cache is empty
16
+ or force_update is True.
17
+
18
+ Args:
19
+ force_update: If True, bypass cache and fetch fresh data from database.
20
+
21
+ Returns:
22
+ List of unique project names."""
23
+ df = acorns.TREE.scurry(acorns.NAMES["upn"])
24
+
25
+ if df.empty or force_update:
26
+ # If cache is missing, fetch data
27
+ logging.info("Updating cache for unique project names")
28
+ client = MetadataDbClient(
29
+ host=acorns.API_GATEWAY_HOST,
30
+ version="v2",
31
+ )
32
+ unique_project_names = client.aggregate_docdb_records(
33
+ pipeline=[
34
+ {"$group": {"_id": "$data_description.project_name"}},
35
+ {"$project": {"project_name": "$_id", "_id": 0}},
36
+ ]
37
+ )
38
+ df = pd.DataFrame(unique_project_names)
39
+ acorns.TREE.hide(acorns.NAMES["upn"], df)
40
+
41
+ return df["project_name"].tolist()
@@ -0,0 +1,41 @@
1
+ """Unique subject IDs acorn."""
2
+
3
+ import logging
4
+
5
+ import pandas as pd
6
+ from aind_data_access_api.document_db import MetadataDbClient
7
+
8
+ import zombie_squirrel.acorns as acorns
9
+
10
+
11
+ @acorns.register_acorn(acorns.NAMES["usi"])
12
+ def unique_subject_ids(force_update: bool = False) -> list[str]:
13
+ """Fetch unique subject IDs from metadata database.
14
+
15
+ Returns cached results if available, fetches from database if cache is empty
16
+ or force_update is True.
17
+
18
+ Args:
19
+ force_update: If True, bypass cache and fetch fresh data from database.
20
+
21
+ Returns:
22
+ List of unique subject IDs."""
23
+ df = acorns.TREE.scurry(acorns.NAMES["usi"])
24
+
25
+ if df.empty or force_update:
26
+ # If cache is missing, fetch data
27
+ logging.info("Updating cache for unique subject IDs")
28
+ client = MetadataDbClient(
29
+ host=acorns.API_GATEWAY_HOST,
30
+ version="v2",
31
+ )
32
+ unique_subject_ids = client.aggregate_docdb_records(
33
+ pipeline=[
34
+ {"$group": {"_id": "$subject.subject_id"}},
35
+ {"$project": {"subject_id": "$_id", "_id": 0}},
36
+ ]
37
+ )
38
+ df = pd.DataFrame(unique_subject_ids)
39
+ acorns.TREE.hide(acorns.NAMES["usi"], df)
40
+
41
+ return df["subject_id"].tolist()
zombie_squirrel/acorns.py CHANGED
@@ -1,96 +1,47 @@
1
- """Storage backend interfaces for caching data."""
1
+ """Acorns: functions to fetch and cache data from MongoDB."""
2
2
 
3
- import io
4
3
  import logging
5
- from abc import ABC, abstractmethod
4
+ import os
5
+ from collections.abc import Callable
6
+ from typing import Any
6
7
 
7
- import boto3
8
- import duckdb
9
- import pandas as pd
8
+ from zombie_squirrel.forest import (
9
+ MemoryTree,
10
+ S3Tree,
11
+ )
10
12
 
11
- from zombie_squirrel.utils import get_s3_cache_path, prefix_table_name
13
+ # --- Backend setup ---------------------------------------------------
12
14
 
15
+ API_GATEWAY_HOST = "api.allenneuraldynamics.org"
13
16
 
14
- class Acorn(ABC):
15
- """Base class for a storage backend (the cache)."""
17
+ forest_type = os.getenv("FOREST_TYPE", "memory").lower()
16
18
 
17
- def __init__(self) -> None:
18
- """Initialize the Acorn."""
19
- super().__init__()
19
+ if forest_type == "S3": # pragma: no cover
20
+ logging.info("Using S3 forest for caching")
21
+ TREE = S3Tree()
22
+ else:
23
+ logging.info("Using in-memory forest for caching")
24
+ TREE = MemoryTree()
20
25
 
21
- @abstractmethod
22
- def hide(self, table_name: str, data: pd.DataFrame) -> None:
23
- """Store records in the cache."""
24
- pass # pragma: no cover
26
+ # --- Acorn registry and names -----------------------------------------------------
25
27
 
26
- @abstractmethod
27
- def scurry(self, table_name: str) -> pd.DataFrame:
28
- """Fetch records from the cache."""
29
- pass # pragma: no cover
28
+ NAMES = {
29
+ "upn": "unique_project_names",
30
+ "usi": "unique_subject_ids",
31
+ "basics": "asset_basics",
32
+ "d2r": "source_data",
33
+ "r2d": "raw_to_derived",
34
+ }
30
35
 
36
+ ACORN_REGISTRY: dict[str, Callable[[], Any]] = {}
31
37
 
32
- class S3Acorn(Acorn):
33
- """Stores and retrieves caches using AWS S3 with parquet files."""
34
38
 
35
- def __init__(self) -> None:
36
- """Initialize S3Acorn with S3 client."""
37
- self.bucket = "aind-scratch-data"
38
- self.s3_client = boto3.client("s3")
39
+ def register_acorn(name: str):
40
+ """Decorator for registering new acorns."""
39
41
 
40
- def hide(self, table_name: str, data: pd.DataFrame) -> None:
41
- """Store DataFrame as parquet file in S3."""
42
- filename = prefix_table_name(table_name)
43
- s3_key = get_s3_cache_path(filename)
42
+ def decorator(func):
43
+ """Register function in acorn registry."""
44
+ ACORN_REGISTRY[name] = func
45
+ return func
44
46
 
45
- # Convert DataFrame to parquet bytes
46
- parquet_buffer = io.BytesIO()
47
- data.to_parquet(parquet_buffer, index=False)
48
- parquet_buffer.seek(0)
49
-
50
- # Upload to S3
51
- self.s3_client.put_object(
52
- Bucket=self.bucket,
53
- Key=s3_key,
54
- Body=parquet_buffer.getvalue(),
55
- )
56
- logging.info(f"Stored cache to S3: s3://{self.bucket}/{s3_key}")
57
-
58
- def scurry(self, table_name: str) -> pd.DataFrame:
59
- """Fetch DataFrame from S3 parquet file."""
60
- filename = prefix_table_name(table_name)
61
- s3_key = get_s3_cache_path(filename)
62
-
63
- try:
64
- # Read directly from S3 using DuckDB
65
- query = f"""
66
- SELECT * FROM read_parquet(
67
- 's3://{self.bucket}/{s3_key}'
68
- )
69
- """
70
- result = duckdb.query(query).to_df()
71
- logging.info(
72
- f"Retrieved cache from S3: s3://{self.bucket}/{s3_key}"
73
- )
74
- return result
75
- except Exception as e:
76
- logging.warning(
77
- f"Error fetching from cache {s3_key}: {e}"
78
- )
79
- return pd.DataFrame()
80
-
81
-
82
- class MemoryAcorn(Acorn):
83
- """A simple in-memory backend for testing or local development."""
84
-
85
- def __init__(self) -> None:
86
- """Initialize MemoryAcorn with empty store."""
87
- super().__init__()
88
- self._store: dict[str, pd.DataFrame] = {}
89
-
90
- def hide(self, table_name: str, data: pd.DataFrame) -> None:
91
- """Store DataFrame in memory."""
92
- self._store[table_name] = data
93
-
94
- def scurry(self, table_name: str) -> pd.DataFrame:
95
- """Fetch DataFrame from memory."""
96
- return self._store.get(table_name, pd.DataFrame())
47
+ return decorator
@@ -0,0 +1,96 @@
1
+ """Storage backend interfaces for caching data."""
2
+
3
+ import io
4
+ import logging
5
+ from abc import ABC, abstractmethod
6
+
7
+ import boto3
8
+ import duckdb
9
+ import pandas as pd
10
+
11
+ from zombie_squirrel.utils import get_s3_cache_path, prefix_table_name
12
+
13
+
14
+ class Tree(ABC):
15
+ """Base class for a storage backend (the cache)."""
16
+
17
+ def __init__(self) -> None:
18
+ """Initialize the Tree."""
19
+ super().__init__()
20
+
21
+ @abstractmethod
22
+ def hide(self, table_name: str, data: pd.DataFrame) -> None:
23
+ """Store records in the cache."""
24
+ pass # pragma: no cover
25
+
26
+ @abstractmethod
27
+ def scurry(self, table_name: str) -> pd.DataFrame:
28
+ """Fetch records from the cache."""
29
+ pass # pragma: no cover
30
+
31
+
32
+ class S3Tree(Tree):
33
+ """Stores and retrieves caches using AWS S3 with parquet files."""
34
+
35
+ def __init__(self) -> None:
36
+ """Initialize S3Acorn with S3 client."""
37
+ self.bucket = "aind-scratch-data"
38
+ self.s3_client = boto3.client("s3")
39
+
40
+ def hide(self, table_name: str, data: pd.DataFrame) -> None:
41
+ """Store DataFrame as parquet file in S3."""
42
+ filename = prefix_table_name(table_name)
43
+ s3_key = get_s3_cache_path(filename)
44
+
45
+ # Convert DataFrame to parquet bytes
46
+ parquet_buffer = io.BytesIO()
47
+ data.to_parquet(parquet_buffer, index=False)
48
+ parquet_buffer.seek(0)
49
+
50
+ # Upload to S3
51
+ self.s3_client.put_object(
52
+ Bucket=self.bucket,
53
+ Key=s3_key,
54
+ Body=parquet_buffer.getvalue(),
55
+ )
56
+ logging.info(f"Stored cache to S3: s3://{self.bucket}/{s3_key}")
57
+
58
+ def scurry(self, table_name: str) -> pd.DataFrame:
59
+ """Fetch DataFrame from S3 parquet file."""
60
+ filename = prefix_table_name(table_name)
61
+ s3_key = get_s3_cache_path(filename)
62
+
63
+ try:
64
+ # Read directly from S3 using DuckDB
65
+ query = f"""
66
+ SELECT * FROM read_parquet(
67
+ 's3://{self.bucket}/{s3_key}'
68
+ )
69
+ """
70
+ result = duckdb.query(query).to_df()
71
+ logging.info(
72
+ f"Retrieved cache from S3: s3://{self.bucket}/{s3_key}"
73
+ )
74
+ return result
75
+ except Exception as e:
76
+ logging.warning(
77
+ f"Error fetching from cache {s3_key}: {e}"
78
+ )
79
+ return pd.DataFrame()
80
+
81
+
82
+ class MemoryTree(Tree):
83
+ """A simple in-memory backend for testing or local development."""
84
+
85
+ def __init__(self) -> None:
86
+ """Initialize MemoryAcorn with empty store."""
87
+ super().__init__()
88
+ self._store: dict[str, pd.DataFrame] = {}
89
+
90
+ def hide(self, table_name: str, data: pd.DataFrame) -> None:
91
+ """Store DataFrame in memory."""
92
+ self._store[table_name] = data
93
+
94
+ def scurry(self, table_name: str) -> pd.DataFrame:
95
+ """Fetch DataFrame from memory."""
96
+ return self._store.get(table_name, pd.DataFrame())
zombie_squirrel/sync.py CHANGED
@@ -2,17 +2,17 @@
2
2
 
3
3
  import logging
4
4
 
5
- from .squirrels import SQUIRREL_REGISTRY
5
+ from .acorns import ACORN_REGISTRY
6
6
 
7
7
 
8
8
  def hide_acorns():
9
- """Trigger force update of all registered squirrel functions.
9
+ """Trigger force update of all registered acorn functions.
10
10
 
11
- Calls each squirrel function with force_update=True to refresh
12
- all cached data in the acorn backend."""
11
+ Calls each acorn function with force_update=True to refresh
12
+ all cached data in the tree backend."""
13
13
  logging.basicConfig(
14
14
  level=logging.INFO,
15
15
  format="%(asctime)s %(levelname)s %(message)s"
16
16
  )
17
- for squirrel in SQUIRREL_REGISTRY.values():
18
- squirrel(force_update=True)
17
+ for acorn in ACORN_REGISTRY.values():
18
+ acorn(force_update=True)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: zombie-squirrel
3
- Version: 0.7.4
3
+ Version: 0.8.1
4
4
  Summary: Generated from aind-library-template
5
5
  Author: Allen Institute for Neural Dynamics
6
6
  License: MIT
@@ -21,7 +21,7 @@ Dynamic: license-file
21
21
  ![Code Style](https://img.shields.io/badge/code%20style-black-black)
22
22
  [![semantic-release: angular](https://img.shields.io/badge/semantic--release-angular-e10079?logo=semantic-release)](https://github.com/semantic-release/semantic-release)
23
23
  ![Interrogate](https://img.shields.io/badge/interrogate-100.0%25-brightgreen)
24
- ![Coverage](https://img.shields.io/badge/coverage-99%25-brightgreen)
24
+ ![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen)
25
25
  ![Python](https://img.shields.io/badge/python->=3.10-blue?logo=python)
26
26
 
27
27
  <img src="zombie-squirrel_logo.png" width="400" alt="Logo (image from ChatGPT)">
@@ -37,10 +37,10 @@ pip install zombie-squirrel
37
37
  ### Set backend
38
38
 
39
39
  ```bash
40
- export TREE_SPECIES='s3'
40
+ export FOREST_TYPE='S3'
41
41
  ```
42
42
 
43
- Options are 's3', 'MEMORY'.
43
+ Options are 'S3', 'MEMORY'.
44
44
 
45
45
  ### Scurry (fetch) data
46
46
 
@@ -0,0 +1,16 @@
1
+ zombie_squirrel/__init__.py,sha256=sPD8B2awlREi8c33mhKoGw0khdE5u1XQmU_3hWiVH9A,693
2
+ zombie_squirrel/acorns.py,sha256=BLhySoLfb7D6IfbNMOhxbLJba-8Wp-L9e1w_2KozjjM,1134
3
+ zombie_squirrel/forest.py,sha256=v0K1u0EA0OptzxocFC-fPEi6xYcnJ9SoWJ6aiPF4jLg,2939
4
+ zombie_squirrel/sync.py,sha256=9cpfSzTj0cQz4-d3glMAOejCZgekMirLc-dwEFFQhlg,496
5
+ zombie_squirrel/utils.py,sha256=kojQpHUKlRJD7WEZDfcpQIZTj9iUrtX5_6F-gWWzJW0,628
6
+ zombie_squirrel/acorn_contents/__init__.py,sha256=LsNy5xjlJS981SVxRLD4yPhUg__fuY8-HbPDapOhH-o,285
7
+ zombie_squirrel/acorn_contents/asset_basics.py,sha256=cTg016sZbrJH5_As7CqnirumR1hSMn4GiYX0IReoou0,5513
8
+ zombie_squirrel/acorn_contents/raw_to_derived.py,sha256=EFjLP9szzk3Q6jNhyDwxx8rqhG1bFTVmxeCpCAsv6yg,2445
9
+ zombie_squirrel/acorn_contents/source_data.py,sha256=zbw3DnTwXo6xDTZ1uCoIbcYrVBH2r2xZN3trKtxT8cg,1527
10
+ zombie_squirrel/acorn_contents/unique_project_names.py,sha256=Fu0P2DyI91W7xhx1uRk2YVMyFG8WPihDCj7n_A7zL2E,1289
11
+ zombie_squirrel/acorn_contents/unique_subject_ids.py,sha256=dOVn1ObDF86p8S8US__hlyjTGxT0vz01oeGzjoWGFIc,1260
12
+ zombie_squirrel-0.8.1.dist-info/licenses/LICENSE,sha256=U0Y7B3gZJHXpjJVLgTQjM8e_c8w4JJpLgGhIdsoFR1Y,1092
13
+ zombie_squirrel-0.8.1.dist-info/METADATA,sha256=xEQ04ahuoz0XhbxLpAUCYFLG1kj6VSV2RFMfRtAq1PY,1898
14
+ zombie_squirrel-0.8.1.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
15
+ zombie_squirrel-0.8.1.dist-info/top_level.txt,sha256=FmM0coe4AangURZLjM4JwwRv2B8H6oINYCoZLKLDCKA,16
16
+ zombie_squirrel-0.8.1.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (80.9.0)
2
+ Generator: setuptools (80.10.2)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,355 +0,0 @@
1
- """Squirrels: functions to fetch and cache data from MongoDB."""
2
-
3
- import logging
4
- import os
5
- from collections.abc import Callable
6
- from typing import Any
7
-
8
- import pandas as pd
9
- from aind_data_access_api.document_db import MetadataDbClient
10
-
11
- from zombie_squirrel.acorns import (
12
- MemoryAcorn,
13
- S3Acorn,
14
- )
15
-
16
- # --- Backend setup ---------------------------------------------------
17
-
18
- API_GATEWAY_HOST = "api.allenneuraldynamics.org"
19
-
20
- tree_type = os.getenv("TREE_SPECIES", "memory").lower()
21
-
22
- if tree_type == "s3": # pragma: no cover
23
- logging.info("Using S3 acorn for caching")
24
- ACORN = S3Acorn()
25
- else:
26
- logging.info("Using in-memory acorn for caching")
27
- ACORN = MemoryAcorn()
28
-
29
- # --- Squirrel registry -----------------------------------------------------
30
-
31
- SQUIRREL_REGISTRY: dict[str, Callable[[], Any]] = {}
32
-
33
-
34
- def register_squirrel(name: str):
35
- """Decorator for registering new squirrels."""
36
-
37
- def decorator(func):
38
- """Register function in squirrel registry."""
39
- SQUIRREL_REGISTRY[name] = func
40
- return func
41
-
42
- return decorator
43
-
44
-
45
- # --- Squirrels -----------------------------------------------------
46
-
47
- NAMES = {
48
- "upn": "unique_project_names",
49
- "usi": "unique_subject_ids",
50
- "basics": "asset_basics",
51
- "d2r": "source_data",
52
- "r2d": "raw_to_derived",
53
- }
54
-
55
-
56
- @register_squirrel(NAMES["upn"])
57
- def unique_project_names(force_update: bool = False) -> list[str]:
58
- """Fetch unique project names from metadata database.
59
-
60
- Returns cached results if available, fetches from database if cache is empty
61
- or force_update is True.
62
-
63
- Args:
64
- force_update: If True, bypass cache and fetch fresh data from database.
65
-
66
- Returns:
67
- List of unique project names."""
68
- df = ACORN.scurry(NAMES["upn"])
69
-
70
- if df.empty or force_update:
71
- # If cache is missing, fetch data
72
- logging.info("Updating cache for unique project names")
73
- client = MetadataDbClient(
74
- host=API_GATEWAY_HOST,
75
- version="v2",
76
- )
77
- unique_project_names = client.aggregate_docdb_records(
78
- pipeline=[
79
- {"$group": {"_id": "$data_description.project_name"}},
80
- {"$project": {"project_name": "$_id", "_id": 0}},
81
- ]
82
- )
83
- df = pd.DataFrame(unique_project_names)
84
- ACORN.hide(NAMES["upn"], df)
85
-
86
- return df["project_name"].tolist()
87
-
88
-
89
- @register_squirrel(NAMES["usi"])
90
- def unique_subject_ids(force_update: bool = False) -> list[str]:
91
- """Fetch unique subject IDs from metadata database.
92
-
93
- Returns cached results if available, fetches from database if cache is empty
94
- or force_update is True.
95
-
96
- Args:
97
- force_update: If True, bypass cache and fetch fresh data from database.
98
-
99
- Returns:
100
- List of unique subject IDs."""
101
- df = ACORN.scurry(NAMES["usi"])
102
-
103
- if df.empty or force_update:
104
- # If cache is missing, fetch data
105
- logging.info("Updating cache for unique subject IDs")
106
- client = MetadataDbClient(
107
- host=API_GATEWAY_HOST,
108
- version="v2",
109
- )
110
- unique_subject_ids = client.aggregate_docdb_records(
111
- pipeline=[
112
- {"$group": {"_id": "$subject.subject_id"}},
113
- {"$project": {"subject_id": "$_id", "_id": 0}},
114
- ]
115
- )
116
- df = pd.DataFrame(unique_subject_ids)
117
- ACORN.hide(NAMES["usi"], df)
118
-
119
- return df["subject_id"].tolist()
120
-
121
-
122
- @register_squirrel(NAMES["basics"])
123
- def asset_basics(force_update: bool = False) -> pd.DataFrame:
124
- """Fetch basic asset metadata including modalities, projects, and subject info.
125
-
126
- Returns a DataFrame with columns: _id, _last_modified, modalities,
127
- project_name, data_level, subject_id, acquisition_start_time, and
128
- acquisition_end_time. Uses incremental updates based on _last_modified
129
- timestamps to avoid re-fetching unchanged records.
130
-
131
- Args:
132
- force_update: If True, bypass cache and fetch fresh data from database.
133
-
134
- Returns:
135
- DataFrame with basic asset metadata."""
136
- df = ACORN.scurry(NAMES["basics"])
137
-
138
- FIELDS = [
139
- "data_description.modalities",
140
- "data_description.project_name",
141
- "data_description.data_level",
142
- "subject.subject_id",
143
- "acquisition.acquisition_start_time",
144
- "acquisition.acquisition_end_time",
145
- "processing.data_processes.start_date_time",
146
- "subject.subject_details.genotype",
147
- "other_identifiers",
148
- "location",
149
- "name",
150
- ]
151
-
152
- if df.empty or force_update:
153
- logging.info("Updating cache for asset basics")
154
- df = pd.DataFrame(
155
- columns=[
156
- "_id",
157
- "_last_modified",
158
- "modalities",
159
- "project_name",
160
- "data_level",
161
- "subject_id",
162
- "acquisition_start_time",
163
- "acquisition_end_time",
164
- "code_ocean",
165
- "process_date",
166
- "genotype",
167
- "location",
168
- "name",
169
- ]
170
- )
171
- client = MetadataDbClient(
172
- host=API_GATEWAY_HOST,
173
- version="v2",
174
- )
175
- # It's a bit complex to get multiple fields that aren't indexed in a database
176
- # as large as DocDB. We'll also try to limit ourselves to only updating fields
177
- # that are necessary
178
- record_ids = client.retrieve_docdb_records(
179
- filter_query={},
180
- projection={"_id": 1, "_last_modified": 1},
181
- limit=0,
182
- )
183
- keep_ids = []
184
- # Drop all _ids where _last_modified matches cache
185
- for record in record_ids:
186
- cached_row = df[df["_id"] == record["_id"]]
187
- if cached_row.empty or cached_row["_last_modified"].values[0] != record["_last_modified"]:
188
- keep_ids.append(record["_id"])
189
-
190
- # Now batch by 100 IDs at a time to avoid overloading server, and fetch all the fields
191
- BATCH_SIZE = 100
192
- asset_records = []
193
- for i in range(0, len(keep_ids), BATCH_SIZE):
194
- logging.info(f"Fetching asset basics batch {i // BATCH_SIZE + 1}...")
195
- batch_ids = keep_ids[i: i + BATCH_SIZE]
196
- batch_records = client.retrieve_docdb_records(
197
- filter_query={"_id": {"$in": batch_ids}},
198
- projection={field: 1 for field in FIELDS + ["_id", "_last_modified"]},
199
- limit=0,
200
- )
201
- asset_records.extend(batch_records)
202
-
203
- # Unwrap nested fields
204
- records = []
205
- for record in asset_records:
206
- modalities = record.get("data_description", {}).get("modalities", [])
207
- modality_abbreviations = [modality["abbreviation"] for modality in modalities if "abbreviation" in modality]
208
- modality_abbreviations_str = ", ".join(modality_abbreviations)
209
-
210
- # Get the process date, convert to YYYY-MM-DD if present
211
- data_processes = record.get("processing", {}).get("data_processes", [])
212
- if data_processes:
213
- latest_process = data_processes[-1]
214
- process_datetime = latest_process.get("start_date_time", None)
215
- process_date = process_datetime.split("T")[0]
216
- else:
217
- process_date = None
218
-
219
- # Get the CO asset ID
220
- other_identifiers = record.get("other_identifiers", {})
221
- code_ocean = None
222
- if other_identifiers:
223
- co_list = other_identifiers.get("Code Ocean", None)
224
- if co_list:
225
- code_ocean = co_list[0]
226
-
227
- flat_record = {
228
- "_id": record["_id"],
229
- "_last_modified": record.get("_last_modified", None),
230
- "modalities": modality_abbreviations_str,
231
- "project_name": record.get("data_description", {}).get("project_name", None),
232
- "data_level": record.get("data_description", {}).get("data_level", None),
233
- "subject_id": record.get("subject", {}).get("subject_id", None),
234
- "acquisition_start_time": record.get("acquisition", {}).get("acquisition_start_time", None),
235
- "acquisition_end_time": record.get("acquisition", {}).get("acquisition_end_time", None),
236
- "code_ocean": code_ocean,
237
- "process_date": process_date,
238
- "genotype": record.get("subject", {}).get("subject_details", {}).get("genotype", None),
239
- "location": record.get("location", None),
240
- "name": record.get("name", None),
241
- }
242
- records.append(flat_record)
243
-
244
- # Combine new records with the old df and store in cache
245
- new_df = pd.DataFrame(records)
246
- df = pd.concat([df[~df["_id"].isin(keep_ids)], new_df], ignore_index=True)
247
-
248
- ACORN.hide(NAMES["basics"], df)
249
-
250
- return df
251
-
252
-
253
- @register_squirrel(NAMES["d2r"])
254
- def source_data(force_update: bool = False) -> pd.DataFrame:
255
- """Fetch source data references for derived records.
256
-
257
- Returns a DataFrame mapping record IDs to their upstream source data
258
- dependencies as comma-separated lists.
259
-
260
- Args:
261
- force_update: If True, bypass cache and fetch fresh data from database.
262
-
263
- Returns:
264
- DataFrame with _id and source_data columns."""
265
- df = ACORN.scurry(NAMES["d2r"])
266
-
267
- if df.empty or force_update:
268
- logging.info("Updating cache for source data")
269
- client = MetadataDbClient(
270
- host=API_GATEWAY_HOST,
271
- version="v2",
272
- )
273
- records = client.retrieve_docdb_records(
274
- filter_query={},
275
- projection={"_id": 1, "data_description.source_data": 1},
276
- limit=0,
277
- )
278
- data = []
279
- for record in records:
280
- source_data_list = record.get("data_description", {}).get("source_data", [])
281
- source_data_str = ", ".join(source_data_list) if source_data_list else ""
282
- data.append(
283
- {
284
- "_id": record["_id"],
285
- "source_data": source_data_str,
286
- }
287
- )
288
-
289
- df = pd.DataFrame(data)
290
- ACORN.hide(NAMES["d2r"], df)
291
-
292
- return df
293
-
294
-
295
- @register_squirrel(NAMES["r2d"])
296
- def raw_to_derived(force_update: bool = False) -> pd.DataFrame:
297
- """Fetch mapping of raw records to their derived records.
298
-
299
- Returns a DataFrame mapping raw record IDs to lists of derived record IDs
300
- that depend on them as source data.
301
-
302
- Args:
303
- force_update: If True, bypass cache and fetch fresh data from database.
304
-
305
- Returns:
306
- DataFrame with _id and derived_records columns."""
307
- df = ACORN.scurry(NAMES["r2d"])
308
-
309
- if df.empty or force_update:
310
- logging.info("Updating cache for raw to derived mapping")
311
- client = MetadataDbClient(
312
- host=API_GATEWAY_HOST,
313
- version="v2",
314
- )
315
-
316
- # Get all raw record IDs
317
- raw_records = client.retrieve_docdb_records(
318
- filter_query={"data_description.data_level": "raw"},
319
- projection={"_id": 1},
320
- limit=0,
321
- )
322
- raw_ids = {record["_id"] for record in raw_records}
323
-
324
- # Get all derived records with their _id and source_data
325
- derived_records = client.retrieve_docdb_records(
326
- filter_query={"data_description.data_level": "derived"},
327
- projection={"_id": 1, "data_description.source_data": 1},
328
- limit=0,
329
- )
330
-
331
- # Build mapping: raw_id -> list of derived _ids
332
- raw_to_derived_map = {raw_id: [] for raw_id in raw_ids}
333
- for derived_record in derived_records:
334
- source_data_list = derived_record.get("data_description", {}).get("source_data", [])
335
- derived_id = derived_record["_id"]
336
- # Add this derived record to each raw record it depends on
337
- for source_id in source_data_list:
338
- if source_id in raw_to_derived_map:
339
- raw_to_derived_map[source_id].append(derived_id)
340
-
341
- # Convert to DataFrame
342
- data = []
343
- for raw_id, derived_ids in raw_to_derived_map.items():
344
- derived_ids_str = ", ".join(derived_ids)
345
- data.append(
346
- {
347
- "_id": raw_id,
348
- "derived_records": derived_ids_str,
349
- }
350
- )
351
-
352
- df = pd.DataFrame(data)
353
- ACORN.hide(NAMES["r2d"], df)
354
-
355
- return df
@@ -1,10 +0,0 @@
1
- zombie_squirrel/__init__.py,sha256=NEzSvrO6WxDaetYvZ7EoSWRQqnTnNxe5XKoKPHt8XGk,409
2
- zombie_squirrel/acorns.py,sha256=mpinFacaN9BM6CvRy0M76JMb6n3oVPZLJxn8O4J9Wlw,2945
3
- zombie_squirrel/squirrels.py,sha256=1leLr5gA3gPa39NSLNmTOVFjxC29caciPwEcTNCgj6Y,12399
4
- zombie_squirrel/sync.py,sha256=84Ta5beHiPuGBVzp9SCo7G1b4McTUohcUIf_TJbNIV8,518
5
- zombie_squirrel/utils.py,sha256=kojQpHUKlRJD7WEZDfcpQIZTj9iUrtX5_6F-gWWzJW0,628
6
- zombie_squirrel-0.7.4.dist-info/licenses/LICENSE,sha256=U0Y7B3gZJHXpjJVLgTQjM8e_c8w4JJpLgGhIdsoFR1Y,1092
7
- zombie_squirrel-0.7.4.dist-info/METADATA,sha256=kVo8V2VH1YpNwJOh9TqQJ2vN780BwQ8Jk6QgjTy3y1o,1898
8
- zombie_squirrel-0.7.4.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
9
- zombie_squirrel-0.7.4.dist-info/top_level.txt,sha256=FmM0coe4AangURZLjM4JwwRv2B8H6oINYCoZLKLDCKA,16
10
- zombie_squirrel-0.7.4.dist-info/RECORD,,