|
| 1 | +import yaml |
| 2 | + |
| 3 | +spyglass_error = ( |
| 4 | + "This functional is optional and requires the spyglass package. It is only relevant" |
| 5 | + + " for those using spyglass for data management and requires spyglass be installed." |
| 6 | +) |
| 7 | + |
| 8 | + |
| 9 | +def check_for_brain_region(data: dict): |
| 10 | + from spyglass.common import BrainRegion |
| 11 | + |
| 12 | + missing_regions = [] |
| 13 | + for k, v in data.items(): |
| 14 | + if isinstance(v, dict): |
| 15 | + missing_regions.extend(check_for_brain_region(v)) |
| 16 | + continue |
| 17 | + if isinstance(v, list): |
| 18 | + for item in v: |
| 19 | + if isinstance(item, dict): |
| 20 | + missing_regions.extend(check_for_brain_region(item)) |
| 21 | + continue |
| 22 | + if "location" in k: |
| 23 | + key = {"region_name": v} |
| 24 | + if not (BrainRegion & key): |
| 25 | + missing_regions.append(v) |
| 26 | + return list(set(missing_regions)) |
| 27 | + |
| 28 | + |
| 29 | +def yaml_database_validation(yaml_path: str): |
| 30 | + """Validate the YAML file against the database tables to reduce duplication and errors. |
| 31 | +
|
| 32 | + Parameters |
| 33 | + ---------- |
| 34 | + yaml_path : str |
| 35 | + Path to the YAML file. |
| 36 | + """ |
| 37 | + |
| 38 | + yaml_data = yaml.safe_load(open(yaml_path)) |
| 39 | + try: |
| 40 | + from spyglass.common import CameraDevice, Task |
| 41 | + except ImportError: |
| 42 | + raise ImportError(spyglass_error) |
| 43 | + |
| 44 | + # check entries for tables in the database for consistency with the yaml file |
| 45 | + yaml_to_table = { |
| 46 | + "tasks": Task(), |
| 47 | + "cameras": CameraDevice(), |
| 48 | + } |
| 49 | + for yaml_key, table in yaml_to_table.items(): |
| 50 | + if yaml_key not in yaml_data: |
| 51 | + continue |
| 52 | + print(f"Checking table `{table.camel_name}` against yaml key `{yaml_key}`") |
| 53 | + for key in yaml_data[yaml_key]: |
| 54 | + _primary = {k: v for k, v in key.items() if k in table.primary_key} |
| 55 | + if not (query := (table & _primary)): |
| 56 | + continue |
| 57 | + |
| 58 | + table_entry = query.fetch1() |
| 59 | + for k, v in key.items(): |
| 60 | + if k not in table_entry: |
| 61 | + continue |
| 62 | + if table_entry[k] != v: |
| 63 | + print( |
| 64 | + f"\tFor entry {_primary} in table {table.camel_name} \n" |
| 65 | + + f"\t\t Mismatch in {k}: {table_entry[k]} != {v}" |
| 66 | + ) |
| 67 | + if new_regions := check_for_brain_region(yaml_data): |
| 68 | + print( |
| 69 | + "The following brain regions are missing from the BrainRegion table.\n" |
| 70 | + + " Consider using existing BrainRegion entries:" |
| 71 | + ) |
| 72 | + for region in new_regions: |
| 73 | + print(f"\t{region}") |
0 commit comments