""" Models a BIDS file. """importosfromhed.tools.bidsimportbids_util
[docs]classBidsFile:""" A BIDS file with entity dictionary. Attributes: file_path (str): Real path of the file. suffix (str): Suffix part of the filename. ext (str): Extension (including the .). entity_dict (dict): Dictionary of entity-names (keys) and entity-values (values). Notes: - This class may hold the merged sidecar giving metadata for this file as well as contents. """
[docs]def__init__(self,file_path):""" Constructor for a file path. Parameters: file_path(str): Full path of the file. """self.file_path=os.path.realpath(file_path)name_dict=bids_util.parse_bids_filename(self.file_path)self.basename=name_dict.get("basename")self.suffix=name_dict.get("suffix")self.ext=name_dict.get("ext")self.entity_dict=name_dict.get("entities")self.bad=name_dict.get("bad")self._contents=Noneself.has_hed=False
@propertydefcontents(self):""" Return the current contents of this object. """returnself._contents
[docs]defclear_contents(self):""" Set the contents attribute of this object to None. """self._contents=None
[docs]defget_entity(self,entity_name):""" Return the entity value for the specified entity. Parameters: entity_name (str): Name of the BIDS entity, for example task, run, or sub. Returns: Union[str, None]: Entity value if any, otherwise None. """returnself.entity_dict.get(entity_name,None)
[docs]defget_key(self,entities=None):""" Return a key for this BIDS file given a list of entities. Parameters: entities (tuple): A tuple of strings representing entities. Returns: str: A key based on this object. Notes: If entities is None, then the file path is used as the key. """ifnotentities:returnself.file_pathkey_list=[]forentityinentities:ifentityinself.entity_dict:key_list.append(f"{entity}-{self.entity_dict[entity]}")key='_'.join(key_list)returnkey
[docs]defset_contents(self,content_info=None,overwrite=False):""" Set the contents of this object. Parameters: content_info (Any): JSON dictionary The contents appropriate for this object. overwrite (bool): If False and the contents are not empty, do nothing. Notes: - Do not set if the contents are already set and no_overwrite is True. """ifself._contentsandnotoverwrite:returnself._contents=content_infoself.has_hed=False
[docs]def__str__(self):""" Return a string representation of this object. """my_str=self.file_path+":\n\tname_suffix="+self.suffix+" ext="+self.ext+ \
" entity_dict="+str(self.entity_dict)returnmy_str