-
Notifications
You must be signed in to change notification settings - Fork 3
/
manage_neuroconv.py
2050 lines (1562 loc) · 91.6 KB
/
manage_neuroconv.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Collection of utility functions used by the NeuroConv Flask API."""
import copy
import hashlib
import inspect
import json
import math
import os
import re
import traceback
import zoneinfo
from datetime import datetime, timedelta
from pathlib import Path
from shutil import copytree, rmtree
from typing import Any, Dict, List, Optional, Union
from pynwb import NWBFile
from tqdm_publisher import TQDMProgressHandler
from .info import (
CONVERSION_SAVE_FOLDER_PATH,
GUIDE_ROOT_FOLDER,
STUB_SAVE_FOLDER_PATH,
is_packaged,
resource_path,
)
from .info.sse import format_sse
progress_handler = TQDMProgressHandler()
EXCLUDED_RECORDING_INTERFACE_PROPERTIES = ["contact_vector", "contact_shapes", "group", "location"]
EXTRA_INTERFACE_PROPERTIES = {
"brain_area": {
"data_type": "str",
"default": "unknown",
}
}
EXTRA_RECORDING_INTERFACE_PROPERTIES = list(EXTRA_INTERFACE_PROPERTIES.keys())
RECORDING_INTERFACE_PROPERTY_OVERRIDES = {
"brain_area": {
"description": "The brain area where the electrode is located.",
**EXTRA_INTERFACE_PROPERTIES["brain_area"],
}
}
EXTRA_SORTING_INTERFACE_PROPERTIES = ["unit_id", *EXTRA_INTERFACE_PROPERTIES.keys()]
SORTING_INTERFACE_PROPERTIES_TO_RECAST = {
"quality": {
"data_type": "str",
},
"KSLabel": {
"data_type": "str",
},
"KSLabel_repeat": {
"data_type": "str",
},
}
SORTING_INTERFACE_PROPERTY_OVERRIDES = {
"unit_id": {"description": "The unique ID for this unit", "data_type": "str"},
"brain_area": {
"description": "The brain area where the unit is located.",
**EXTRA_INTERFACE_PROPERTIES["brain_area"],
},
**SORTING_INTERFACE_PROPERTIES_TO_RECAST,
}
# NOTE: No need to show this if it isn't editable
del SORTING_INTERFACE_PROPERTY_OVERRIDES["brain_area"]
brain_area_idx = EXTRA_SORTING_INTERFACE_PROPERTIES.index("brain_area")
EXTRA_SORTING_INTERFACE_PROPERTIES.pop(brain_area_idx)
EXCLUDED_SORTING_INTERFACE_PROPERTIES = ["location", "spike_times", "electrodes"] # Not validated
# NOTE: These are the only accepted dtypes...
DTYPE_DESCRIPTIONS = {
"bool": "logical",
"str": "string",
"ndarray": "n-dimensional array",
"float8": "8-bit number",
"float16": "16-bit number",
"float32": "32-bit number",
"float64": "64-bit number",
"int8": "8-bit integer",
"int16": "16-bit integer",
"int32": "32-bit integer",
"int64": "64-bit integer",
}
DTYPE_SCHEMA = {
"type": "string",
# "strict": False,
"enum": list(DTYPE_DESCRIPTIONS.keys()),
"enumLabels": DTYPE_DESCRIPTIONS,
}
def is_path_contained(child, parent):
parent = Path(parent)
child = Path(child)
# Attempt to construct a relative path from parent to child
try:
child.relative_to(parent)
return True
except ValueError:
return False
def replace_nan_with_none(data):
if isinstance(data, dict):
# If it's a dictionary, iterate over its items and replace NaN values with None
return {key: replace_nan_with_none(value) for key, value in data.items()}
elif isinstance(data, list):
# If it's a list, iterate over its elements and replace NaN values with None
return [replace_nan_with_none(item) for item in data]
elif isinstance(data, (float, int)) and (data != data):
return None # Replace NaN with None
else:
return data
def resolve_references(schema: dict, root_schema: Optional[dict] = None) -> dict:
"""
Recursively resolve references in a JSON schema based on the root schema.
Args:
schema (dict): The JSON schema to resolve.
root_schema (dict): The root JSON schema.
Returns:
dict: The resolved JSON schema.
"""
from jsonschema import RefResolver
if root_schema is None:
root_schema = schema
if "$ref" in schema:
resolver = RefResolver.from_schema(root_schema)
return resolver.resolve(schema["$ref"])[1]
if "properties" in schema:
for key, prop_schema in schema["properties"].items():
schema["properties"][key] = resolve_references(prop_schema, root_schema)
if "items" in schema:
schema["items"] = resolve_references(schema["items"], root_schema)
return schema
def replace_none_with_nan(json_object: dict, json_schema: dict) -> dict:
"""
Recursively search a JSON object and replace None values with NaN where appropriate.
Args:
json_object (dict): The JSON object to search and modify.
json_schema (dict): The JSON schema to validate against.
Returns:
dict: The modified JSON object with None values replaced by NaN.
"""
def coerce_schema_compliance_recursive(obj, schema):
if isinstance(obj, dict):
for key, value in obj.items():
# Coerce on pattern properties as well
pattern_properties = schema.get("patternProperties")
if pattern_properties:
for pattern, pattern_schema in pattern_properties.items():
regex = re.compile(pattern)
if regex.match(key):
coerce_schema_compliance_recursive(value, pattern_schema)
elif key in schema.get("properties", {}):
prop_schema = schema["properties"][key]
if prop_schema.get("type") == "number" and (value is None or value == "NaN"):
obj[key] = (
math.nan
) # Turn None into NaN if a number is expected (JavaScript JSON.stringify turns NaN into None)
elif prop_schema.get("type") == "number" and isinstance(value, int):
obj[key] = float(
value
) # Turn integer into float if a number, the JSON Schema equivalent to float, is expected (JavaScript coerces floats with trailing zeros to integers)
else:
coerce_schema_compliance_recursive(value, prop_schema)
elif isinstance(obj, list):
for item in obj:
coerce_schema_compliance_recursive(
item, schema.get("items", schema if "properties" else {})
) # NEUROCONV PATCH
return obj
return coerce_schema_compliance_recursive(
copy.deepcopy(json_object), resolve_references(copy.deepcopy(json_schema))
)
def autocomplete_format_string(info: dict) -> str:
from neuroconv.tools.path_expansion import construct_path_template
from neuroconv.utils.json_schema import NWBMetaDataEncoder
base_directory = info["base_directory"]
filesystem_entry_path = info["path"]
if not is_path_contained(filesystem_entry_path, base_directory):
raise ValueError("Path is not contained in the provided base directory.")
full_format_string = construct_path_template(
filesystem_entry_path,
subject_id=info["subject_id"],
session_id=info["session_id"],
**info["additional_metadata"],
)
parent = Path(base_directory).resolve()
child = Path(full_format_string).resolve()
format_string = str(child.relative_to(parent))
to_locate_info = dict(base_directory=base_directory)
if Path(filesystem_entry_path).is_dir():
to_locate_info["folder_path"] = format_string
else:
to_locate_info["file_path"] = format_string
all_matched = locate_data(dict(autocomplete=to_locate_info))
return json.loads(json.dumps(obj=dict(matched=all_matched, format_string=format_string), cls=NWBMetaDataEncoder))
def locate_data(info: dict) -> dict:
"""Locate data from the specifies directories using fstrings."""
from neuroconv.tools import LocalPathExpander
from neuroconv.utils.json_schema import NWBMetaDataEncoder
expander = LocalPathExpander()
# Transform the input into a list of dictionaries
for value in info.values():
if (value.get("base_directory") is not None) and (value.get("base_directory") != ""):
value["base_directory"] = Path(value["base_directory"])
out = expander.expand_paths(info)
# Organize results by subject, session, and data type
organized_output = {}
for item in out:
subject_id = item["metadata"]["Subject"]["subject_id"]
session_id = item["metadata"]["NWBFile"]["session_id"]
if subject_id not in organized_output:
organized_output[subject_id] = {}
if session_id not in organized_output[subject_id]:
organized_output[subject_id][session_id] = {}
organized_output[subject_id][session_id] = item
return json.loads(json.dumps(obj=organized_output, cls=NWBMetaDataEncoder))
def module_to_dict(my_module) -> dict:
# Create an empty dictionary
module_dict = {}
# Iterate through the module's attributes
for attr_name in dir(my_module):
if not attr_name.startswith("__"): # Exclude special attributes
attr_value = getattr(my_module, attr_name)
module_dict[attr_name] = attr_value
return module_dict
doc_pattern = r":py:class:`\~.+\..+\.(\w+)`"
remove_extra_spaces_pattern = r"\s+"
def get_class_ref_in_docstring(input_string):
match = re.search(doc_pattern, input_string)
if match:
return match.group(1)
def derive_interface_info(interface) -> dict:
info = {"keywords": getattr(interface, "keywords", []), "description": ""}
if hasattr(interface, "associated_suffixes"):
info["suffixes"] = interface.associated_suffixes
if hasattr(interface, "info"):
info["description"] = interface.info
elif interface.__doc__:
info["description"] = re.sub(
remove_extra_spaces_pattern, " ", re.sub(doc_pattern, r"<code>\1</code>", interface.__doc__)
)
info["name"] = interface.__name__
return info
def get_all_converter_info() -> dict:
from neuroconv.converters import converter_list
return {
getattr(converter, "display_name", converter.__name__) or converter.__name__: derive_interface_info(converter)
for converter in converter_list
}
def get_all_interface_info() -> dict:
"""Format an information structure to be used for selecting interfaces based on modality and technique."""
from neuroconv.datainterfaces import interface_list
exclude_interfaces_from_selection = [
# Deprecated
"SpikeGLXLFPInterface",
# Aliased
"CEDRecordingInterface",
"OpenEphysBinaryRecordingInterface",
"OpenEphysLegacyRecordingInterface",
# Ignored
"AxonaPositionDataInterface",
"AxonaUnitRecordingInterface",
"CsvTimeIntervalsInterface",
"ExcelTimeIntervalsInterface",
"Hdf5ImagingInterface",
"MaxOneRecordingInterface",
"OpenEphysSortingInterface",
"SimaSegmentationInterface",
]
return {
getattr(interface, "display_name", interface.__name__) or interface.__name__: derive_interface_info(interface)
for interface in interface_list
if not interface.__name__ in exclude_interfaces_from_selection
}
# Combine Multiple Interfaces
def get_custom_converter(interface_class_dict: dict, alignment_info: Union[dict, None] = None) -> "NWBConverter":
from neuroconv import NWBConverter, converters, datainterfaces
alignment_info = alignment_info or dict()
class CustomNWBConverter(NWBConverter):
data_interface_classes = {
custom_name: getattr(datainterfaces, interface_name, getattr(converters, interface_name, None))
for custom_name, interface_name in interface_class_dict.items()
}
# Handle temporal alignment inside the converter
# TODO: this currently works off of cross-scoping injection of `alignment_info` - refactor to be more explicit
def temporally_align_data_interfaces(self):
set_interface_alignment(self, alignment_info=alignment_info)
# From previous issue regarding SpikeGLX not generating previews of correct size
def add_to_nwbfile(self, nwbfile: NWBFile, metadata, conversion_options: Optional[dict] = None) -> None:
conversion_options = conversion_options or dict()
for interface_key, data_interface in self.data_interface_objects.items():
if isinstance(data_interface, NWBConverter):
subconverter_kwargs = dict(nwbfile=nwbfile, metadata=metadata)
# Certain subconverters fully expose control over their interfaces conversion options
# (such as iterator options, including progress bar details)
subconverter_keyword_arguments = list(
inspect.signature(data_interface.add_to_nwbfile).parameters.keys()
)
if "conversion_options" in subconverter_keyword_arguments:
subconverter_kwargs["conversion_options"] = conversion_options.get(interface_key, None)
# Others do not, and instead expose simplified global keywords similar to a classic interface
else:
subconverter_kwargs.update(conversion_options.get(interface_key, dict()))
data_interface.add_to_nwbfile(**subconverter_kwargs)
else:
data_interface.add_to_nwbfile(
nwbfile=nwbfile, metadata=metadata, **conversion_options.get(interface_key, dict())
)
return CustomNWBConverter
def instantiate_custom_converter(
source_data: Dict, interface_class_dict: Dict, alignment_info: Union[Dict, None] = None
) -> "NWBConverter":
alignment_info = alignment_info or dict()
CustomNWBConverter = get_custom_converter(interface_class_dict=interface_class_dict, alignment_info=alignment_info)
return CustomNWBConverter(source_data=source_data)
def get_source_schema(interface_class_dict: dict) -> dict:
"""Function used to get schema from a CustomNWBConverter that can handle multiple interfaces."""
CustomNWBConverter = get_custom_converter(interface_class_dict)
return CustomNWBConverter.get_source_schema()
def map_interfaces(callback, converter, to_match: Union["BaseDataInterface", None] = None, parent_name=None) -> list:
from neuroconv import NWBConverter
output = []
for name, interface in converter.data_interface_objects.items():
associated_name = f"{parent_name} — {name}" if parent_name else name
if isinstance(interface, NWBConverter):
result = map_interfaces(
callback=callback, converter=interface, to_match=to_match, parent_name=associated_name
)
output.extend(result)
elif to_match is None or isinstance(interface, to_match):
result = callback(associated_name, interface)
output.append(result)
return output
def get_metadata_schema(source_data: Dict[str, dict], interfaces: dict) -> Dict[str, dict]:
"""Function used to fetch the metadata schema from a CustomNWBConverter instantiated from the source_data."""
from neuroconv.utils import NWBMetaDataEncoder
resolved_source_data = replace_none_with_nan(
source_data, resolve_references(get_custom_converter(interfaces).get_source_schema())
)
converter = instantiate_custom_converter(resolved_source_data, interfaces)
schema = converter.get_metadata_schema()
metadata = converter.get_metadata()
# Clear the Electrodes information for being set as a collection of Interfaces
has_ecephys = "Ecephys" in metadata
has_units = False
ecephys_metadata = metadata.get("Ecephys")
ecephys_schema = schema["properties"].get("Ecephys", {"properties": {}})
if not ecephys_schema.get("required"):
ecephys_schema["required"] = []
ecephys_properties = ecephys_schema["properties"]
original_electrodes_schema = ecephys_properties.get("Electrodes")
resolved_electrodes = {}
resolved_units = {}
resolved_electrodes_schema = {"type": "object", "properties": {}, "required": []}
resolved_units_schema = {"type": "object", "properties": {}, "required": []}
def on_sorting_interface(name, sorting_interface):
unit_columns = get_unit_columns_json(sorting_interface)
# Aggregate unit column information across sorting interfaces
existing_unit_columns = metadata["Ecephys"].get("UnitColumns")
if existing_unit_columns:
for entry in unit_columns:
if any(obj["name"] == entry["name"] for obj in existing_unit_columns):
continue
else:
existing_unit_columns.append(entry)
else:
metadata["Ecephys"]["UnitColumns"] = unit_columns
units_data = resolved_units[name] = get_unit_table_json(sorting_interface)
n_units = len(units_data)
resolved_units_schema["properties"][name] = {
"type": "array",
"minItems": n_units,
"maxItems": n_units,
"items": {
"allOf": [
{"$ref": "#/properties/Ecephys/definitions/Unit"},
{"required": list(map(lambda info: info["name"], unit_columns))},
]
},
}
resolved_units_schema["required"].append(name)
return sorting_interface
def on_recording_interface(name, recording_interface):
electrode_columns = get_electrode_columns_json(recording_interface)
# Aggregate electrode column information across recording interfaces
existing_electrode_columns = ecephys_metadata.get("ElectrodeColumns")
if existing_electrode_columns:
for entry in electrode_columns:
if any(obj["name"] == entry["name"] for obj in existing_electrode_columns):
continue
else:
existing_electrode_columns.append(entry)
else:
ecephys_metadata["ElectrodeColumns"] = electrode_columns
electrode_data = resolved_electrodes[name] = get_electrode_table_json(recording_interface)
n_electrodes = len(electrode_data)
resolved_electrodes_schema["properties"][name] = {
"type": "array",
"minItems": n_electrodes,
"maxItems": n_electrodes,
"items": {
"allOf": [
{"$ref": "#/properties/Ecephys/definitions/Electrode"},
{"required": list(map(lambda info: info["name"], electrode_columns))},
]
},
}
resolved_electrodes_schema["required"].append(name)
return recording_interface
from neuroconv.datainterfaces.ecephys.baserecordingextractorinterface import (
BaseRecordingExtractorInterface,
)
from neuroconv.datainterfaces.ecephys.basesortingextractorinterface import (
BaseSortingExtractorInterface,
)
# Map recording interfaces to metadata
map_interfaces(on_recording_interface, converter=converter, to_match=BaseRecordingExtractorInterface)
# Map sorting interfaces to metadata
map_interfaces(on_sorting_interface, converter=converter, to_match=BaseSortingExtractorInterface)
if has_ecephys:
if "definitions" not in ecephys_schema:
ecephys_schema["definitions"] = ecephys_properties["definitions"]
has_electrodes = "ElectrodeColumns" in ecephys_metadata
original_units_schema = ecephys_properties.pop("UnitProperties", None)
ecephys_metadata.pop("UnitProperties", None) # Always remove top-level UnitProperties from metadata
has_units = original_units_schema is not None
# Populate Electrodes metadata
if has_electrodes:
# Add Electrodes to the schema
ecephys_metadata["Electrodes"] = resolved_electrodes
ecephys_schema["required"].append("Electrodes")
ecephys_properties["ElectrodeColumns"] = {
"type": "array",
"minItems": 0,
"items": {"$ref": "#/properties/Ecephys/definitions/ElectrodeColumn"},
}
ecephys_schema["required"].append("ElectrodeColumns")
ecephys_properties["Electrodes"] = resolved_electrodes_schema
else:
ecephys_properties.pop("Electrodes", None)
# Populate Units metadata
if has_units:
ecephys_properties["UnitColumns"] = {
"type": "array",
"minItems": 0,
"items": {"$ref": "#/properties/Ecephys/definitions/UnitColumn"},
}
schema["properties"]["Ecephys"]["required"].append("UnitColumns")
ecephys_properties["Units"] = resolved_units_schema
ecephys_metadata["Units"] = resolved_units
schema["properties"]["Ecephys"]["required"].append("Units")
# Delete Ecephys metadata if no interfaces processed
defs = ecephys_schema["definitions"]
electrode_def = defs["Electrodes"]
# NOTE: Update to output from NeuroConv
electrode_def["properties"]["data_type"] = DTYPE_SCHEMA
# Configure electrode columns
defs["ElectrodeColumn"] = electrode_def
defs["ElectrodeColumn"]["required"] = list(electrode_def["properties"].keys())
new_electrodes_properties = {
properties["name"]: {key: value for key, value in properties.items() if key != "name"}
for properties in original_electrodes_schema.get("default", {})
if properties["name"] not in EXCLUDED_RECORDING_INTERFACE_PROPERTIES
}
defs["Electrode"] = {
"type": "object",
"properties": new_electrodes_properties,
"additionalProperties": True, # Allow for new columns
}
if has_units:
unitprops_def = defs["UnitProperties"]
# NOTE: Update to output from NeuroConv
unitprops_def["properties"]["data_type"] = DTYPE_SCHEMA
# Configure electrode columns
defs["UnitColumn"] = unitprops_def
defs["UnitColumn"]["required"] = list(unitprops_def["properties"].keys())
new_units_properties = {
properties["name"]: {key: value for key, value in properties.items() if key != "name"}
for properties in original_units_schema.get("default", {})
if properties["name"] not in EXCLUDED_SORTING_INTERFACE_PROPERTIES
}
defs["Unit"] = {
"type": "object",
"properties": new_units_properties,
"additionalProperties": True, # Allow for new columns
}
# TODO: generalize logging stuff
log_base = GUIDE_ROOT_FOLDER / "logs"
log_base.mkdir(exist_ok=True)
with open(file=log_base / "file_metadata_page_schema.json", mode="w") as fp:
json.dump(obj=dict(schema=schema), fp=fp, cls=NWBMetaDataEncoder, indent=2)
with open(file=log_base / "file_metadata_page_results.json", mode="w") as fp:
json.dump(obj=dict(results=metadata), fp=fp, cls=NWBMetaDataEncoder, indent=2)
return json.loads(
json.dumps(obj=replace_nan_with_none(dict(results=metadata, schema=schema)), cls=NWBMetaDataEncoder)
)
def get_check_function(check_function_name: str) -> callable:
"""Function used to fetch an arbitrary NWB Inspector function."""
from nwbinspector import configure_checks, load_config
dandi_check_list = configure_checks(config=load_config(filepath_or_keyword="dandi"))
dandi_check_registry = {check.__name__: check for check in dandi_check_list}
check_function: callable = dandi_check_registry.get(check_function_name)
if check_function is None:
raise ValueError(f"Function {check_function_name} not found in nwbinspector")
return check_function
def run_check_function(check_function: callable, arg: dict) -> dict:
""".Function used to run an arbitrary NWB Inspector function."""
from nwbinspector import Importance, InspectorMessage
output = check_function(arg)
if isinstance(output, InspectorMessage):
if output.importance != Importance.ERROR:
output.importance = check_function.importance
elif output is not None:
for x in output:
x.importance = check_function.importance
return output
def validate_subject_metadata(
subject_metadata: dict, check_function_name: str, timezone: Optional[str] = None
): # -> Union[None, InspectorMessage, List[InspectorMessage]]:
"""Function used to validate subject metadata."""
import pytz
from pynwb.file import Subject
check_function = get_check_function(check_function_name)
if isinstance(subject_metadata.get("date_of_birth"), str):
subject_metadata["date_of_birth"] = datetime.fromisoformat(subject_metadata["date_of_birth"])
if timezone is not None:
subject_metadata["date_of_birth"] = subject_metadata["date_of_birth"].replace(
tzinfo=zoneinfo.ZoneInfo(timezone)
)
return run_check_function(check_function, Subject(**subject_metadata))
def validate_nwbfile_metadata(
nwbfile_metadata: dict, check_function_name: str, timezone: Optional[str] = None
): # -> Union[None, InspectorMessage, List[InspectorMessage]]:
"""Function used to validate NWBFile metadata."""
from pynwb.testing.mock.file import mock_NWBFile
check_function = get_check_function(check_function_name)
if isinstance(nwbfile_metadata.get("session_start_time"), str):
nwbfile_metadata["session_start_time"] = datetime.fromisoformat(nwbfile_metadata["session_start_time"])
if timezone is not None:
nwbfile_metadata["session_start_time"] = nwbfile_metadata["session_start_time"].replace(
tzinfo=zoneinfo.ZoneInfo(timezone)
)
return run_check_function(check_function, mock_NWBFile(**nwbfile_metadata))
def validate_metadata(
metadata: dict,
check_function_name: str,
timezone: Optional[str] = None,
) -> dict:
"""Function used to validate data using an arbitrary NWB Inspector function."""
from nwbinspector import InspectorOutputJSONEncoder
from pynwb.file import NWBFile, Subject
check_function = get_check_function(check_function_name)
if issubclass(check_function.neurodata_type, Subject):
result = validate_subject_metadata(metadata, check_function_name, timezone)
elif issubclass(check_function.neurodata_type, NWBFile):
result = validate_nwbfile_metadata(metadata, check_function_name, timezone)
else:
raise ValueError(
f"Function {check_function_name} with neurodata_type {check_function.neurodata_type} "
"is not supported by this function!"
)
return json.loads(json.dumps(result, cls=InspectorOutputJSONEncoder))
def set_interface_alignment(converter: dict, alignment_info: dict) -> dict:
import numpy as np
from neuroconv.datainterfaces.ecephys.basesortingextractorinterface import (
BaseSortingExtractorInterface,
)
from neuroconv.tools.testing.mock_interfaces import MockRecordingInterface
errors = {}
for name, interface in converter.data_interface_objects.items():
interface = converter.data_interface_objects[name]
info = alignment_info.get(name, {})
# Set alignment
method = info.get("selected", None)
if method is None:
continue
value = info["values"].get(method, None)
if value is None:
continue
try:
if method == "timestamps":
# Open the input file for reading
# Can be .txt, .csv, .tsv, etc.
# But timestamps must be scalars separated by newline characters
with open(file=value, mode="r") as io:
aligned_timestamps = np.array([float(line.strip()) for line in io.readlines()])
# Special case for sorting interfaces; to set timestamps they must have a recording registered
must_set_mock_recording = (
isinstance(interface, BaseSortingExtractorInterface)
and not interface.sorting_extractor.has_recording()
)
if must_set_mock_recording is True:
sorting_extractor = interface.sorting_extractor
sampling_frequency = sorting_extractor.get_sampling_frequency()
end_frame = timestamps_array.shape[0]
mock_recording_interface = MockRecordingInterface(
sampling_frequency=sampling_frequency,
durations=[end_frame / sampling_frequency],
num_channels=1,
)
interface.register_recording(recording_interface=mock_recording_interface)
interface.set_aligned_timestamps(aligned_timestamps=aligned_timestamps)
# Special case for sorting interfaces; a recording interface to be converted may be registered/linked
elif method == "linked":
interface.register_recording(converter.data_interface_objects[value])
elif method == "start":
interface.set_aligned_starting_time(aligned_starting_time=value)
except Exception as e:
errors[name] = str(e)
return errors
def get_compatible_interfaces(info: dict) -> dict:
from neuroconv.datainterfaces.ecephys.baserecordingextractorinterface import (
BaseRecordingExtractorInterface,
)
from neuroconv.datainterfaces.ecephys.basesortingextractorinterface import (
BaseSortingExtractorInterface,
)
converter = instantiate_custom_converter(source_data=info["source_data"], interface_class_dict=info["interfaces"])
compatible = {}
for name, interface in converter.data_interface_objects.items():
is_sorting = isinstance(interface, BaseSortingExtractorInterface)
if is_sorting is True:
compatible[name] = []
# If at least one recording and sorting interface is selected on the formats page
# Then it is possible the two could be linked (the sorting was applied to the recording)
# But there are very strict conditions from SpikeInterface determining compatibility
# Those conditions are not easily exposed so we just 'try' to register them and skip on error
sibling_recording_interfaces = {
interface_key: interface
for interface_key, interface in converter.data_interface_objects.items()
if isinstance(interface, BaseRecordingExtractorInterface)
}
for recording_interface_key, recording_interface in sibling_recording_interfaces.items():
try:
interface.register_recording(recording_interface=recording_interface)
compatible[name].append(recording_interface_key)
except Exception:
pass
return compatible
def get_interface_alignment(info: dict) -> dict:
from neuroconv.basetemporalalignmentinterface import BaseTemporalAlignmentInterface
from neuroconv.datainterfaces.ecephys.basesortingextractorinterface import (
BaseSortingExtractorInterface,
)
alignment_info = info.get("alignment", dict())
converter = instantiate_custom_converter(source_data=info["source_data"], interface_class_dict=info["interfaces"])
compatibility = get_compatible_interfaces(info)
errors = set_interface_alignment(converter=converter, alignment_info=alignment_info)
metadata = dict()
timestamps = dict()
for name, interface in converter.data_interface_objects.items():
metadata[name] = dict()
is_sorting = isinstance(interface, BaseSortingExtractorInterface)
metadata[name]["sorting"] = is_sorting
if is_sorting is True:
metadata[name]["compatible"] = compatibility.get(name, None)
if not isinstance(interface, BaseTemporalAlignmentInterface):
timestamps[name] = []
continue
# Note: it is technically possible to have a BaseTemporalAlignmentInterface that has not yet implemented
# the `get_timestamps` method; try to get this but skip on error
try:
interface_timestamps = interface.get_timestamps()
if len(interface_timestamps) == 1:
interface_timestamps = interface_timestamps[0]
# Some interfaces, such as video or audio, may return a list of arrays
# corresponding to each file of their `file_paths` input
# Note: GUIDE only currently supports single files for these interfaces
# Thus, unpack only the first array
if isinstance(interface_timestamps, list):
interface_timestamps = interface_timestamps[0]
timestamps[name] = interface_timestamps.tolist()
except Exception:
timestamps[name] = []
return dict(
metadata=metadata,
timestamps=timestamps,
errors=errors,
)
def create_file(
info: dict,
log_url: Optional[str] = None,
) -> dict:
import neuroconv
import requests
from tqdm_publisher import TQDMProgressSubscriber
project_name = info.get("project_name")
run_stub_test = info.get("stub_test", False)
overwrite = info.get("overwrite", False)
# Progress update info
url = info.get("url")
request_id = info.get("request_id")
# Backend configuration info
backend_configuration = info.get("configuration", {})
backend = backend_configuration.get("backend", "hdf5")
converter, metadata, path_info = get_conversion_info(info)
nwbfile_path = path_info["file"]
try:
# Delete files manually if using Zarr
if overwrite:
if nwbfile_path.exists():
if nwbfile_path.is_dir():
rmtree(nwbfile_path)
else:
nwbfile_path.unlink()
def update_conversion_progress(message):
update_dict = dict(request_id=request_id, **message)
if url or not run_stub_test:
requests.post(url=url, json=update_dict)
else:
progress_handler.announce(update_dict)
progress_bar_options = dict(
mininterval=0,
on_progress_update=update_conversion_progress,
)
# Assume all interfaces have the same conversion options for now
conversion_options_schema = converter.get_conversion_options_schema()
conversion_options = {interface: dict() for interface in info["source_data"]}
for interface_or_subconverter in conversion_options:
conversion_options_schema_per_interface_or_converter = conversion_options_schema.get(
"properties", dict()
).get(interface_or_subconverter, dict())
# Object is a nested converter
if conversion_options_schema_per_interface_or_converter.get("title", "") == "Conversion options schema":
subconverter = interface_or_subconverter
conversion_options_schema_per_subinterface = conversion_options_schema_per_interface_or_converter.get(
"properties", dict()
)
for subinterface, subschema in conversion_options_schema_per_subinterface.items():
conversion_options[subconverter][subinterface] = dict()
options_to_update = conversion_options[subconverter][subinterface]
properties_per_subinterface = subschema.get("properties", dict())
if run_stub_test is True and "stub_test" in properties_per_subinterface:
options_to_update["stub_test"] = True
# Only display per-file progress updates if not running a preview
if run_stub_test is False and "iterator_opts" in properties_per_subinterface:
options_to_update["iterator_opts"] = dict(
display_progress=True,
progress_bar_class=TQDMProgressSubscriber,
progress_bar_options=progress_bar_options,
)
# Object is a standard interface
else:
interface = interface_or_subconverter
conversion_options_schema_per_interface = conversion_options_schema.get("properties", dict())
options_to_update = conversion_options[interface]
if run_stub_test is True and "stub_test" in conversion_options_schema_per_interface:
options_to_update[interface]["stub_test"] = True
# Only display per-file progress updates if not running a preview
if run_stub_test is False and "iterator_opts" in conversion_options_schema_per_interface:
options_to_update[interface]["iterator_opts"] = dict(
display_progress=True,
progress_bar_class=TQDMProgressSubscriber,
progress_bar_options=progress_bar_options,
)
# Add GUIDE watermark