예제 #1
0
def test_entity_matches(tmpdir):
    filename = "aardvark-4-reporting-for-duty.txt"
    tmpdir.mkdir("tmp").join(filename).write("###")
    f = BIDSFile(os.path.join(str(tmpdir), filename))
    e = Entity('avaricious', r'aardvark-(\d+)')
    result = e.match_file(f)
    assert result == '4'
예제 #2
0
def writable_file(tmpdir):
    engine = create_engine('sqlite://')
    Base.metadata.create_all(engine)
    Session = sessionmaker(bind=engine)
    session = Session()

    testfile = 'sub-03_ses-2_task-rest_acq-fullbrain_run-2_bold.nii.gz'
    fn = tmpdir.mkdir("tmp").join(testfile)
    fn.write('###')
    bf = BIDSFile(os.path.join(str(fn)))

    tag_dict = {'task': 'rest', 'run': 2, 'subject': '3'}
    ents = {name: Entity(name) for name in tag_dict.keys()}
    tags = [Tag(bf, ents[k], value=v) for k, v in tag_dict.items()]

    session.add_all(list(ents.values()) + tags + [bf])
    session.commit()
    return bf
예제 #3
0
def test_file_associations():
    session = create_session()
    img = BIDSFile('sub-03/func/sub-03_task-rest_run-2_bold.nii.gz')
    md1 = BIDSFile('sub-03/func/sub-03_task-rest_run-2_bold.json')
    md2 = BIDSFile('task-rest_run-2_bold.json')
    assocs = [
        FileAssociation(src=md1.path, dst=img.path, kind="MetadataFor"),
        FileAssociation(src=img.path, dst=md1.path, kind="MetadataIn"),
        FileAssociation(src=md1.path, dst=md2.path, kind="Child"),
        FileAssociation(src=md2.path, dst=md1.path, kind="Parent"),
        FileAssociation(src=md2.path, dst=img.path, kind="Informs")
    ]
    session.add_all([img, md1, md2] + assocs)
    session.commit()
    assert img._associations == [md1, md2] == img.get_associations()
    assert md2._associations == [md1]
    assert img.get_associations(kind='MetadataFor') == []
    assert img.get_associations(kind='MetadataIn') == [md1]
    results = img.get_associations(kind='MetadataIn', include_parents=True)
    assert set(results) == {md1, md2}
예제 #4
0
def sample_bidsfile(tmpdir):
    testfile = 'sub-03_ses-2_task-rest_acq-fullbrain_run-2_bold.nii.gz'
    fn = tmpdir.mkdir("tmp").join(testfile)
    fn.write('###')
    return BIDSFile(os.path.join(str(fn)))
예제 #5
0
def to_fileobj(obj: BIDSFile, basemetadata: dict) -> File | None:
    entitydict: dict = obj.get_entities()

    datatype: str | None = entitydict.get("datatype")
    suffix: str | None = entitydict.get("suffix")
    extension: str | None = entitydict.get("extension")

    if datatype is None:
        return None  # exclude README and dataset_description.json etc

    if extension is not None:
        if not extension.startswith("."):
            extension = f".{extension}"

    if not isinstance(obj.path, str):
        return None  # need path

    path: str = obj.path

    metadata: dict = dict(**basemetadata)
    metadata.update(obj.get_metadata())

    tags: dict = dict()
    for k, v in entitydict.items():
        entity = entity_shortnames[k] if k in entity_shortnames else k
        if entity in entities:
            tags[entity] = str(v)

    filedict: dict[str, Any] = dict(
        datatype=datatype,
        suffix=suffix,
        extension=extension,
        path=path,
        tags=tags,
        metadata=metadata,
    )

    try:
        fileobj = file_schema.load(filedict, unknown=EXCLUDE)
        if isinstance(fileobj, File):
            return fileobj
    except marshmallow.exceptions.ValidationError as e:
        log_method = logger.warning

        if extension == ".json":
            log_method = logger.debug  # silence
        elif datatype == "dwi":
            log_method = logger.debug  # silence
        elif datatype == "anat":
            log_method = logger.info  # T2w and FLAIR
        elif basename(path).startswith("."):  # is hidden
            log_method = logger.debug  # silence

        log_method(
            f'Skipping unsupported file "{path}" because %s',
            e,
            exc_info=False,
            stack_info=False,
        )

    return None