""" Container for a BIDS sidecar file. """importosimportioimportjsonfromhed.models.sidecarimportSidecarfromhed.tools.bids.bids_fileimportBidsFile
[docs]classBidsSidecarFile(BidsFile):""" A BIDS sidecar file. """
[docs]def__init__(self,file_path):""" Constructs a bids sidecar from a file. Parameters: file_path (str): The real path of the sidecar. """super().__init__(file_path)
[docs]defis_sidecar_for(self,obj):""" Return True if this is a sidecar for obj. Parameters: obj (BidsFile): A BidsFile object to check. Returns: bool: True if this is a BIDS parent of obj and False otherwise. Notes: - A sidecar is a sidecar for itself. """ifobj.suffix!=self.suffix:returnFalseelifos.path.dirname(self.file_path)!=os.path.commonpath([obj.file_path,self.file_path]):returnFalseforkey,iteminself.entity_dict.items():ifkeynotinobj.entity_dictorobj.entity_dict[key]!=item:returnFalsereturnTrue
[docs]defset_contents(self,content_info=None,name='unknown',overwrite=False):""" Set the contents of the sidecar. Parameters: content_info (dict, or None): If None, create a Sidecar from the object's file-path. name (str): The name of the sidecar. overwrite (bool): If True, overwrite contents if already set. Notes: - The handling of content_info is as follows: - None: This object's file_path is used. - dict: This is interpreted as a JSON dictionary. """ifnotoverwriteandself.contents:returntry:ifnotcontent_info:self._contents=Sidecar(self.file_path,name=os.path.basename(self.file_path))else:self._contents=Sidecar(io.StringIO(json.dumps(content_info)),name=name)self.has_hed=self.is_hed(self.contents.loaded_dict)exceptExceptionase:self._contents=Noneself.has_hed=False
[docs]@staticmethoddefis_hed(json_dict):""" Return True if the json has HED. Parameters: json_dict (dict): A dictionary representing a JSON file or merged file. Returns: bool: True if the dictionary has HED or HED_assembled as a first or second-level key. """ifnotjson_dictornotisinstance(json_dict,dict):returnFalsejson_keys=json_dict.keys()if'HED'injson_keysor'HED_assembled'injson_keys:returnTrueforkey,valueinjson_dict.items():ifnotisinstance(value,dict):continueval_keys=value.keys()if'HED'inval_keysor'HED_assembled'inval_keys:returnTruereturnFalse
[docs]@staticmethoddefmerge_sidecar_list(sidecar_list,name='merged_sidecar.json'):""" Merge a list of sidecars into a single sidecar. Parameters: sidecar_list (list): A list of Sidecar objects. name (str): The name of the merged sidecar. Returns: Union[Sidecar, None]: A sidecar constructed from the merged list. """merged_dict={}forsidecarinsidecar_list:ifnotsidecar:continuemerged_dict.update(sidecar.contents.loaded_dict)ifmerged_dict:returnSidecar(files=io.StringIO(json.dumps(merged_dict)),name=name)returnNone