<commit_before># emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import os
from tempfile import mkdtemp
from shutil import rmtree

import numpy as np

from nipype.testing import (assert_equal, assert_false, assert_true, 
                            assert_raises, skipif)
import nipype.interfaces.spm as spm
import nipype.interfaces.matlab as mlab

try:
    matlab_cmd = os.environ['MATLABCMD']
except:
    matlab_cmd = 'matlab -nodesktop -nosplash'

mlab.MatlabCommand.matlab_cmd = matlab_cmd

def cannot_find_spm():
    # See if we can find spm or not.
    try:
        spm.Info.spm_path()
        return False
    except IOError:
        return True

def test_scan_for_fnames():
    a = ['a.nii','b.nii']
    names = spm.scans_for_fnames(a,keep4d=True)
    yield assert_equal, names[0], 'a.nii'
    yield assert_equal, names[1], 'b.nii'

save_time = True
if not save_time:
    def test_spm_path():
        spm_path = spm.Info.spm_path
        if spm_path is not None:
            yield assert_equal, type(spm_path), type('')
            yield assert_true, 'spm' in spm_path

def test_use_mfile():
    mlab = spm.SPMCommand()
    yield assert_true, mlab.mfile
    mlab._use_mfile(False)
    yield assert_false, mlab.mfile

@skipif(cannot_find_spm, "SPM not found")
def test_run():
    #mlab = spm.SpmMatlabCommandLine()
    #yield assert_raises, NotImplementedError, mlab.run

    class mlabsub(spm.SPMCommand):
        def _compile_command(self):
            return self._gen_matlab_command('',mfile=self.mfile) 
    mlab = mlabsub()
    mlab._use_mfile(False)
    yield assert_raises, NotImplementedError, mlab.run
    class mlabsub2(mlabsub):
        def aggregate_outputs(self):
            pass
    mlab = mlabsub2()
    mlab._use_mfile(False)
    results = mlab.run()
    yield assert_equal, results.runtime.returncode, 0
    
def test_reformat_dict_for_savemat():
    mlab = spm.SPMCommand()
    out = mlab._reformat_dict_for_savemat({'a':{'b':{'c':[]}}})
    yield assert_equal, out, [{'a': [{'b': [{'c': []}]}]}]
    
def test_generate_job():
    mlab = spm.SPMCommand()
    out = mlab._generate_job()
    yield assert_equal, out, ''
    # struct array
    contents = {'contents':[1,2,3,4]}
    out = mlab._generate_job(contents=contents)
    yield assert_equal, out, '.contents(1) = 1;\n.contents(2) = 2;\n.contents(3) = 3;\n.contents(4) = 4;\n'
    # cell array of strings
    a = ['a.nii','b.nii']
    names = spm.scans_for_fnames(a,keep4d=True)
    contents = {'files':names}
    out = mlab._generate_job(prefix='test',contents=contents)
    yield assert_equal, out, "test.files = {...\n'a.nii';...\n'b.nii';...\n};\n"
    # string assignment
    contents = 'foo'
    out = mlab._generate_job(prefix='test',contents=contents)
    yield assert_equal, out, "test = 'foo';\n"
    # cell array of vectors
    contents = {'onsets':np.array((1,),dtype=object)}
    contents['onsets'][0] = [1,2,3,4]
    out = mlab._generate_job(prefix='test',contents=contents)
    yield assert_equal, out, 'test.onsets = {...\n[1, 2, 3, 4];...\n};\n'
    
def test_make_matlab_command():
    mlab = spm.SPMCommand()
    outdir = mkdtemp()
    old_wd = os.getcwd()
    os.chdir(outdir)
    contents = {'contents':[1,2,3,4]}
    cmdline,script = mlab._make_matlab_command([contents])
    yield assert_equal, cmdline, \
        ' '.join((matlab_cmd, '-r "pyscript_jobname;exit" '))
    yield assert_true, 'jobs{1}.jobtype{1}.jobname{1}.contents(3) = 3;' in script
    yield assert_true, os.path.exists(os.path.join(os.getcwd(),'pyscript_jobname.m'))
    if os.path.exists(outdir):
        rmtree(outdir)
    os.chdir(old_wd)<commit_msg>fixed spm base tests<commit_after># emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
import os
from tempfile import mkdtemp
from shutil import rmtree

import numpy as np

from nipype.testing import (assert_equal, assert_false, assert_true, 
                            assert_raises, skipif)
import nipype.externals.pynifti as nif
import nipype.interfaces.spm.base as spm
import nipype.interfaces.matlab as mlab

try:
    matlab_cmd = os.environ['MATLABCMD']
except:
    matlab_cmd = 'matlab -nodesktop -nosplash'

mlab.MatlabCommand.set_default_matlab_cmd(matlab_cmd)

def cannot_find_spm():
    # See if we can find spm or not.
    try:
        spm.Info.spm_path()
        return False
    except IOError:
        return True

def create_files_in_directory():
    outdir = mkdtemp()
    cwd = os.getcwd()
    os.chdir(outdir)
    filelist = ['a.nii','b.nii']
    for f in filelist:
        hdr = nif.Nifti1Header()
        shape = (3,3,3,4)
        hdr.set_data_shape(shape)
        img = np.random.random(shape)
        nif.save(nif.Nifti1Image(img,np.eye(4),hdr),
                 os.path.join(outdir,f))
    return filelist, outdir, cwd
    
def clean_directory(outdir, old_wd):
    if os.path.exists(outdir):
        rmtree(outdir)
    os.chdir(old_wd)

def test_scan_for_fnames():
    filelist, outdir, cwd = create_files_in_directory()
    names = spm.scans_for_fnames(filelist, keep4d=True)
    yield assert_equal, names[0], filelist[0]
    yield assert_equal, names[1], filelist[1]
    clean_directory(outdir, cwd)

save_time = False
if not save_time:
    def test_spm_path():
        spm_path = spm.Info.spm_path()
        if spm_path is not None:
            yield assert_equal, type(spm_path), type('')
            yield assert_true, 'spm' in spm_path

def test_use_mfile():
    class TestClass(spm.SPMCommand):
        input_spec = spm.SPMCommandInputSpec
    dc = TestClass() # dc = derived_class
    yield assert_true, dc.inputs.mfile
    dc.use_mfile(False)
    yield assert_false, dc.inputs.mfile

@skipif(cannot_find_spm, "SPM not found")
def test_cmd_update():
    class TestClass(spm.SPMCommand):
        input_spec = spm.SPMCommandInputSpec
    dc = TestClass() # dc = derived_class
    dc.inputs.matlab_cmd = 'foo'
    yield assert_equal, dc.mlab._cmd, 'foo'

def test_cmd_update():
    class TestClass(spm.SPMCommand):
        _jobtype = 'jobtype'
        _jobname = 'jobname'
        input_spec = spm.SPMCommandInputSpec
    dc = TestClass() # dc = derived_class
    yield assert_equal, dc.jobtype, 'jobtype'
    yield assert_equal, dc.jobname, 'jobname'

def test_reformat_dict_for_savemat():
    class TestClass(spm.SPMCommand):
        input_spec = spm.SPMCommandInputSpec
    dc = TestClass() # dc = derived_class
    out = dc._reformat_dict_for_savemat({'a':{'b':{'c':[]}}})
    yield assert_equal, out, [{'a': [{'b': [{'c': []}]}]}]
    
def test_generate_job():
    class TestClass(spm.SPMCommand):
        input_spec = spm.SPMCommandInputSpec
    dc = TestClass() # dc = derived_class
    out = dc._generate_job()
    yield assert_equal, out, ''
    # struct array
    contents = {'contents':[1,2,3,4]}
    out = dc._generate_job(contents=contents)
    yield assert_equal, out, '.contents(1) = 1;\n.contents(2) = 2;\n.contents(3) = 3;\n.contents(4) = 4;\n'
    # cell array of strings
    filelist, outdir, cwd = create_files_in_directory()
    names = spm.scans_for_fnames(filelist,keep4d=True)
    contents = {'files':names}
    out = dc._generate_job(prefix='test',contents=contents)
    yield assert_equal, out, "test.files = {...\n'a.nii';...\n'b.nii';...\n};\n"
    clean_directory(outdir, cwd)
    # string assignment
    contents = 'foo'
    out = dc._generate_job(prefix='test',contents=contents)
    yield assert_equal, out, "test = 'foo';\n"
    # cell array of vectors
    contents = {'onsets':np.array((1,),dtype=object)}
    contents['onsets'][0] = [1,2,3,4]
    out = dc._generate_job(prefix='test',contents=contents)
    yield assert_equal, out, 'test.onsets = {...\n[1, 2, 3, 4];...\n};\n'
    
def test_make_matlab_command():
    class TestClass(spm.SPMCommand):
        _jobtype = 'jobtype'
        _jobname = 'jobname'
        input_spec = spm.SPMCommandInputSpec
    dc = TestClass() # dc = derived_class
    filelist, outdir, cwd = create_files_in_directory()
    contents = {'contents':[1,2,3,4]}
    script = dc._make_matlab_command([contents])
    yield assert_true, 'jobs{1}.jobtype{1}.jobname{1}.contents(3) = 3;' in script
    clean_directory(outdir, cwd)
{'fraction_non_alphanumeric': 0.13955738299673479, 'fraction_numerical': 0.010884024670455919, 'mean_word_length': 3.3207941483803554, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7473978', 'n_tokens_mistral': 3075, 'n_tokens_neox': 3028, 'n_words': 612}