def test_fslmaths(): std_dir = op.join(platform.fsldir, 'data', 'standard') mask = op.join(std_dir, 'MNI152_T1_2mm_brain_mask.nii.gz') assert op.isfile(mask) img1 = op.join(std_dir, 'MNI152_T1_2mm_b0.nii.gz') assert op.isfile(img1) img2 = op.join(std_dir, 'MNI152_T1_2mm.nii.gz') assert op.isfile(img2) with tempdir(): cmd = [ 'fslmaths', img1, '-add', img2, '-mul', mask, 'reference.nii.gz' ] runfsl(cmd) assert op.isfile('reference.nii.gz') cmd[-2] = 'MASK' cmd[-1] = 'splitJOBID.nii.gz' parser = ArgumentParser() submit.add_to_parser(parser) args = parser.parse_args(('3', mask, ' '.join(cmd))) _environ = dict(os.environ) try: if 'SGE_ROOT' in os.environ: del os.environ['SGE_ROOT'] submit.run_from_args(args) finally: os.environ.clear() os.environ.update(_environ) assert op.isfile('split.nii.gz') ref = nib.load('reference.nii.gz') split = nib.load('split.nii.gz') assert_allclose(ref.get_fdata(), split.get_fdata()) assert (ref.affine == split.affine).all() assert ref.header == split.header
def robustfov(self): """Call ``robustfov`` for the current overlay and set the :attr:`cropBox` based on the result. """ if self.__overlay is None: return try: result = fslrun.runfsl( 'robustfov', '-i', self.__overlay.dataSource) # robustfov returns two lines, the last # of which contains the limits, as: # # xmin xlen ymin ylen zmin zlen limits = list(result.strip().split('\n')[-1].split()) limits = [float(l) for l in limits] # Convert the lens to maxes limits[1] += limits[0] limits[3] += limits[2] limits[5] += limits[4] self.cropBox[:] = limits except Exception as e: log.warning('Call to robustfov failed: {}'.format(str(e)))
def add_to_parser(cls, parser: argparse.ArgumentParser, as_group='fsl_sub commands', include=('wait_for', 'logdir', 'email', 'mail_options')): """ Adds submission parameters to the parser :param parser: parser that should understand submission commands :param as_group: add as a new group :param include: sequence of argument flags/names that should be added to the parser (set to None to include everything) :return: the group the arguments got added to """ from fsl.utils.run import runfsl, FSLNotPresent try: fsl_sub_run, _ = runfsl('fsl_sub', exitcode=True) except (FileNotFoundError, FSLNotPresent): warnings.warn('fsl_sub was not found') return doc_lines = fsl_sub_run.splitlines() nspaces = 1 for line in doc_lines: if len(line.strip()) > 0: while line.startswith(' ' * nspaces): nspaces += 1 nspaces -= 1 if as_group: group = parser.add_argument_group(as_group) else: group = parser def get_explanation(flag): explanation = None for line in doc_lines: if explanation is not None and len(line.strip()) > 0 and line.strip()[0] != '-': explanation.append(line[nspaces:].strip()) elif explanation is not None: break elif line.strip().startswith(flag): explanation = [line[nspaces:].strip()] if (explanation is None) or (len(explanation) == 0): return 'documentation not found' return ' '.join(explanation) for flag, value in cls.cmd_line_flags.items(): if include is not None and value not in include and flag not in include: continue as_type = {'minutes': float, 'priority': int, 'ram': int, 'verbose': None} action = 'store_true' if value == 'verbose' else 'store' group.add_argument(flag, dest='_sub_' + value, help=get_explanation(flag), action=action, metavar='<' + value + '>', type=as_type.get(value, str)) group.add_argument('-F', dest='_sub_flags', help=get_explanation('-F'), action='store_true') group.add_argument('-v', dest='_sub_verbose', help=get_explanation('-v'), action='store_true') group.add_argument('-s', dest='_sub_multi_threaded', help=get_explanation('-s'), metavar='<pename>,<threads>') group.add_argument('-j', dest='_sub_wait_for', help=get_explanation('-j'), metavar='<jid>') return group
def __call__(self, *command, **kwargs): """ Submits the command to the cluster. :param command: string or tuple of strings with the command to submit :param kwargs: Keyword arguments can override any parameters set in self :return: job ID """ from fsl.utils.run import prepareArgs, runfsl runner = self.update(**kwargs) command = prepareArgs(command) fsl_sub_cmd = ' '.join(('fsl_sub', ) + tuple(runner.as_flags()) + tuple(command)) log.debug(fsl_sub_cmd) jobid = runfsl(fsl_sub_cmd, env=runner.env).strip() log.debug('Job submitted as {}'.format(jobid)) return jobid
def robustfov(self): """Call ``robustfov`` for the current overlay and set the :attr:`cropBox` based on the result. """ overlay = self.__overlay if overlay is None: return try: with tempdir.tempdir(): # in-memory image - create and # save a copy - use a copy # otherwise the original will # think that is has been saved # to disk. if overlay.dataSource is None: overlay = fslimage.Image(overlay) overlay.save('image') result = fslrun.runfsl('robustfov', '-i', overlay.dataSource) # robustfov returns two lines, the last # of which contains the limits, as: # # xmin xlen ymin ylen zmin zlen limits = list(result.strip().split('\n')[-1].split()) limits = [float(l) for l in limits] # Convert the lens to maxes limits[1] += limits[0] limits[3] += limits[2] limits[5] += limits[4] self.cropBox[:] = limits except Exception as e: log.warning('Call to robustfov failed: {}'.format(str(e)))
import os import fsl.data.featanalysis as FA import fsl.utils.run as RUN # get number of time points using fslinfo (in case of non-uniform runs) info = RUN.runfsl('fslinfo', snakemake.input.func_file) info_temp = info.split() info_dct = { info_temp[i]: info_temp[i + 1] for i in range(0, len(info_temp), 2) } num_pts = int(info_dct['dim4']) # get full path to $FSLDIR FSLDIR = os.path.expandvars('$FSLDIR') # get path of output design.fsf file feat_subdir = os.path.split(snakemake.output.design_fsf)[0] # set variables # load in design.fsf design = FA.loadSettings(snakemake.input.feat_dir) for ev in range(len(snakemake.input.event_files)): evTemp = ev + 1 evName = design['evtitle%d' % evTemp] evFile = snakemake.input.event_files[ev] #evFile = [evf for evf in snakemake.input.event_files if evf == 'trial-%s_onsets.txt'%evName] custom = [('custom%d' % evTemp, '"%s"' % evFile)] design.update(custom)
def test_runfsl(): test_script = textwrap.dedent(""" #!/bin/bash echo {} exit 0 """).strip() old_fsldir = fslplatform.fsldir old_fsldevdir = fslplatform.fsldevdir try: with tempdir.tempdir(): make_random_image('image.nii.gz') # no FSLDIR - should error fslplatform.fsldir = None fslplatform.fsldevdir = None with pytest.raises(run.FSLNotPresent): run.runfsl('fslhd') # FSLDIR/bin exists - should be good fsldir = op.abspath('./fsl') fslhd = op.join(fsldir, 'bin', 'fslhd') os.makedirs(op.join(fsldir, 'bin')) mkexec(fslhd, test_script.format('fsldir')) fslplatform.fsldir = fsldir assert run.runfsl('fslhd').strip() == 'fsldir' # non-FSL command - should error with pytest.raises(FileNotFoundError): run.runfsl('ls') # FSLDEVDIR should take precedence fsldevdir = './fsldev' fslhd = op.join(fsldevdir, 'bin', 'fslhd') shutil.copytree(fsldir, fsldevdir) mkexec(fslhd, test_script.format('fsldevdir')) fslplatform.fsldevdir = fsldevdir fslplatform.fsldir = None assert run.runfsl('fslhd').strip() == 'fsldevdir' # FSL_PREFIX should override all override = './override' fslhd = op.join(override, 'fslhd') os.makedirs(override) mkexec(fslhd, test_script.format('override')) fslplatform.fsldir = None fslplatform.fsldevdir = None run.FSL_PREFIX = override assert run.runfsl('fslhd').strip() == 'override' finally: fslplatform.fsldir = old_fsldir fslplatform.fsldevdir = old_fsldevdir run.FSL_PREFIX = None