Create flexible function to use inside connect

Following this post, I have been trying to create a function that allows me to select a file on-the-fly within connect.

def concatenate_files(files_list, file):
    files_list.append(file)
    return files_list

def getFile(files,n):
    return files[n]

fast = Node(FAST(in_files="structural.nii"), node="fast")

concatenate = Node(Function(input_names=["files_list", "file"], output_names=["all_files"], function=concatenate_files), name="concat_files")

convert = MapNode(Gunzip(),name="convert",iterfield="in_file")

get_file = Node(Function(input_names=["files","n"], output_names=["out_file"], function=getFile), name="get_file")

masker = Node(ApplyMask(mask_file="mask.nii"), name=masker)

wf.connect([(fast, concatenate, [("probability_maps", "files_list"), ("partial_volume_map", "file")]),
            (concatenate, convert, [("files_list", "in_file")]),
            (convert, get_file, [("out_file","files"), ("out_file",1)]), # here I'd like get_file to select the file from convert with index 1
            (get_file, masker, [("out_file", "in_file")]) # get_file is supposed to pass the file from convert with index 1 to masker
            ])

wf.run()

So fast outputs a list of files which get concatenated (concatenate), and compressed (convert). I would like to be able to select some of the compressed files and pass it to masker. I know I can just do

def getFile(files):
    return files[1]

to get a specific file, but I was trying to make getFile more general so that I can select different files without having to specify a getFile function for each of them. Is that possible in nipype?

@mri - I’m not completely sure what do you mean by “select a file on-the-fly”.

If you’re asking whether get_file node can return more outputs (so you don’t have to create a new one for each of them), the answer is - it can. You can return more elements, e.g.:

def getFile(files):
    return files[1], files[2]

and specify the second output in output_names when creating the node.

1 Like

Thank you again @djarecka. I’d been trying to solve this problem for days now without success, but your solution works great!