Example #1
0
def test_logging(ac='pyglet'):
    """Test logging to file (Pyglet)
    """
    tempdir = _TempDir()
    orig_dir = os.getcwd()
    os.chdir(tempdir)
    try:
        with ExperimentController(*std_args, audio_controller=ac,
                                  response_device='keyboard',
                                  **std_kwargs) as ec:
            test_name = ec._log_file
            stamp = ec.current_time
            ec.wait_until(stamp)  # wait_until called w/already passed timest.
            with warnings.catch_warnings(record=True):
                warnings.simplefilter('always')
                ec.load_buffer([1., -1., 1., -1., 1., -1.])  # RMS warning

        with open(test_name) as fid:
            data = '\n'.join(fid.readlines())

        # check for various expected log messages (TODO: add more)
        should_have = ['Subject: foo', 'Session: 01', 'wait_until was called',
                       'Stimulus max RMS (']
        if ac == 'pyglet':
            should_have.append('Pyglet')
        else:
            should_have.append('TDT')

        for s in should_have:
            if s not in data:
                raise ValueError('Missing data: "{0}" in:\n{1}'
                                 ''.format(s, data))
    finally:
        os.chdir(orig_dir)
Example #2
0
def test_logging(ac='pyglet'):
    """Test logging to file (Pyglet)."""
    tempdir = _TempDir()
    orig_dir = os.getcwd()
    os.chdir(tempdir)
    try:
        with ExperimentController(*std_args, audio_controller=ac,
                                  response_device='keyboard',
                                  trigger_controller='dummy',
                                  **std_kwargs) as ec:
            test_name = ec._log_file
            stamp = ec.current_time
            ec.wait_until(stamp)  # wait_until called w/already passed timest.
            with warnings.catch_warnings(record=True):
                warnings.simplefilter('always')
                ec.load_buffer([1., -1., 1., -1., 1., -1.])  # RMS warning

        with open(test_name) as fid:
            data = '\n'.join(fid.readlines())

        # check for various expected log messages (TODO: add more)
        should_have = ['Participant: foo', 'Session: 01',
                       'wait_until was called',
                       'Stimulus max RMS (']
        if ac == 'pyglet':
            should_have.append('Pyglet')
        else:
            should_have.append('TDT')

        for s in should_have:
            if s not in data:
                raise ValueError('Missing data: "{0}" in:\n{1}'
                                 ''.format(s, data))
    finally:
        os.chdir(orig_dir)
Example #3
0
def test_version_assertions():
    """Test version assertions."""
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        pytest.raises(TypeError, assert_version, 1)
        pytest.raises(TypeError, assert_version, '1' * 8)
        pytest.raises(AssertionError, assert_version, 'x' * 7)
        assert_version(__version__[-7:])
    assert all('actual' in str(ww.message) for ww in w)

    # old, broken, new
    for wi, want_version in enumerate(('090948e', 'cae6bc3', 'b6e8a81')):
        print('Running %s' % want_version)
        tempdir = _TempDir()
        if not _has_git:
            pytest.raises(ImportError, download_version, want_version, tempdir)
        else:
            pytest.raises(IOError, download_version, want_version,
                          op.join(tempdir, 'foo'))
            pytest.raises(RuntimeError, download_version, 'x' * 7, tempdir)
            ex_dir = op.join(tempdir, 'expyfun')
            assert not op.isdir(ex_dir)
            download_version(want_version, tempdir)
            assert op.isdir(ex_dir)
            assert op.isfile(op.join(ex_dir, '__init__.py'))
            got_fname = op.join(ex_dir, '_version.py')
            with open(got_fname) as fid:
                line1 = fid.readline().strip()
            got_version = line1.split(' = ')[1][-8:-1]
            ex = want_version
            if want_version == 'cae6bc3':
                ex = (ex, '.dev0+c')
            assert got_version in ex, got_fname

            # auto dir determination
            orig_dir = os.getcwd()
            os.chdir(tempdir)
            try:
                assert op.isdir('expyfun')
                pytest.raises(IOError, download_version, want_version)
            finally:
                os.chdir(orig_dir)
    # make sure we can get latest version
    tempdir_2 = _TempDir()
    if _has_git:
        pytest.raises(IOError, download_version, dest_dir=tempdir)
        download_version(dest_dir=tempdir_2)
Example #4
0
def test_version():
    """Test version assertions."""
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        assert_raises(TypeError, assert_version, 1)
        assert_raises(TypeError, assert_version, '1' * 8)
        assert_raises(AssertionError, assert_version, 'x' * 7)
        assert_version(__version__[-7:])
    assert_true(all('actual' in str(ww.message) for ww in w))

    for want_version in ('090948e', 'cae6bc3', 'b6e8a81'):  # old, broken, new
        tempdir = _TempDir()
        if not _has_git:
            assert_raises(ImportError, download_version, want_version, tempdir)
        else:
            assert_raises(IOError, download_version, want_version,
                          op.join(tempdir, 'foo'))
            assert_raises(RuntimeError, download_version, 'x' * 7, tempdir)
            ex_dir = op.join(tempdir, 'expyfun')
            assert_true(not op.isdir(ex_dir))
            download_version(want_version, tempdir)
            assert_true(op.isdir(ex_dir))
            assert_true(op.isfile(op.join(ex_dir, '__init__.py')))
            got_fname = op.join(ex_dir, '_version.py')
            with open(got_fname) as fid:
                line1 = fid.readline().strip()
            got_version = line1.split(' = ')[1][-8:-1]
            ex = want_version if want_version != 'cae6bc3' else '.dev0+c'
            assert_equal(got_version, ex,
                         msg='File {0}: {1} != {2}'.format(got_fname,
                                                           got_version, ex))

            # auto dir determination
            orig_dir = os.getcwd()
            os.chdir(tempdir)
            try:
                assert_true(op.isdir('expyfun'))
                assert_raises(IOError, download_version, want_version)
            finally:
                os.chdir(orig_dir)
    # make sure we can get latest version
    tempdir_2 = _TempDir()
    if _has_git:
        assert_raises(IOError, download_version, dest_dir=tempdir)
        download_version(dest_dir=tempdir_2)
Example #5
0
def test_version_assertions():
    """Test version assertions."""
    pytest.raises(TypeError, assert_version, 1)
    pytest.raises(TypeError, assert_version, '1' * 8)
    pytest.raises(AssertionError, assert_version, 'x' * 7)
    assert_version(__version__[-7:])

    # old, broken, new
    for wi, want_version in enumerate(('090948e', 'cae6bc3', 'b6e8a81')):
        print('Running %s' % want_version)
        tempdir = _TempDir()
        if not _has_git:
            pytest.raises(ImportError, download_version, want_version, tempdir)
        else:
            pytest.raises(IOError, download_version, want_version,
                          op.join(tempdir, 'foo'))
            pytest.raises(RuntimeError, download_version, 'x' * 7, tempdir)
            ex_dir = op.join(tempdir, 'expyfun')
            assert not op.isdir(ex_dir)
            with pytest.warns(None):  # Sometimes warns
                download_version(want_version, tempdir)
            assert op.isdir(ex_dir)
            assert op.isfile(op.join(ex_dir, '__init__.py'))
            got_fname = op.join(ex_dir, '_version.py')
            with open(got_fname) as fid:
                line1 = fid.readline().strip()
            got_version = line1.split(' = ')[1][-8:-1]
            ex = want_version
            if want_version == 'cae6bc3':
                ex = (ex, '.dev0+c')
            assert got_version in ex, got_fname

            # auto dir determination
            orig_dir = os.getcwd()
            os.chdir(tempdir)
            try:
                assert op.isdir('expyfun')
                pytest.raises(IOError, download_version, want_version)
            finally:
                os.chdir(orig_dir)
    # make sure we can get latest version
    tempdir_2 = _TempDir()
    if _has_git:
        pytest.raises(IOError, download_version, dest_dir=tempdir)
        download_version(dest_dir=tempdir_2)
Example #6
0
def test_integrated_version_checking():
    """Test EC version checking during init."""
    tempdir = _TempDir()
    args = ['test']  # experiment name
    kwargs = dict(output_dir=tempdir, full_screen=False, window_size=(1, 1),
                  participant='foo', session='01', stim_db=0.0, noise_db=0.0,
                  verbose=True)
    pytest.raises(RuntimeError, ExperimentController, *args, version=None,
                  **kwargs)
    pytest.raises(AssertionError, ExperimentController, *args,
                  version='59f3f5b', **kwargs)  # the very first commit
Example #7
0
def test_integrated_version_checking():
    """Test EC version checking during init."""
    tempdir = _TempDir()
    args = ['test']  # experiment name
    kwargs = dict(output_dir=tempdir, full_screen=False, window_size=(1, 1),
                  participant='foo', session='01', stim_db=0.0, noise_db=0.0,
                  verbose=True)
    assert_raises(RuntimeError, ExperimentController, *args, version=None,
                  **kwargs)
    assert_raises(AssertionError, ExperimentController, *args,
                  version='59f3f5b', **kwargs)  # the very first commit
Example #8
0
def test_crm():
    """Test CRM Corpus functions."""
    fs = 40000  # native rate, to avoid large resampling delay in testing
    crm_info()
    tempdir = _TempDir()

    # corpus prep
    talkers = [dict(sex='f', talker_num=0)]

    crm_prepare_corpus(fs, path_out=tempdir, talker_list=talkers,
                       n_jobs=np.inf)
    crm_prepare_corpus(fs, path_out=tempdir, talker_list=talkers,
                       overwrite=True)
    # no overwrite
    assert_raises(RuntimeError, crm_prepare_corpus, fs, path_out=tempdir)

    # load sentence from hard drive
    crm_sentence(fs, 'f', 0, 0, 0, 0, 0, ramp_dur=0, path=tempdir)
    crm_sentence(fs, 1, '0', 'charlie', 'red', '5', stereo=True, path=tempdir)
    # bad value requested
    assert_raises(ValueError, crm_sentence, fs, 1, 0, 0, 'periwinkle', 0,
                  path=tempdir)
    # unprepared talker
    assert_raises(RuntimeError, crm_sentence, fs, 'm', 0, 0, 0, 0,
                  path=tempdir)
    # unprepared sampling rate
    assert_raises(RuntimeError, crm_sentence, fs + 1, 0, 0, 0, 0, 0,
                  path=tempdir)

    # CRMPreload class
    crm = CRMPreload(fs, path=tempdir)
    crm.sentence('f', 0, 0, 0, 0)
    # unprepared sampling rate
    assert_raises(RuntimeError, CRMPreload, fs + 1)
    # bad value requested
    assert_raises(ValueError, crm.sentence, 1, 0, 0, 'periwinkle', 0)
    # unprepared talker
    assert_raises(RuntimeError, crm.sentence, 'm', 0, 0, 0, 0)
    # try to specify parameters like fs, stereo, etc.
    assert_raises(TypeError, crm.sentence, fs, '1', '0', 'charlie', 'red', '5')

    # add_pad
    x1 = np.zeros(10)
    x2 = np.ones((2, 5))
    x = add_pad([x1, x2])
    assert_true(np.sum(x[..., -1] == 0))
    x = add_pad((x1, x2), 'center')
    assert_true(np.sum(x[..., -1] == 0) and np.sum(x[..., 0] == 0))
    x = add_pad((x1, x2), 'end')
    assert_true(np.sum(x[..., 0] == 0))
def test_data_line():
    """Test writing of data lines
    """
    entries = [['foo'],
               ['bar', 'bar\tbar'],
               ['bar2', r'bar\tbar'],
               ['fb', None, -0.5]]
    # this is what should be written to the file for each one
    goal_vals = ['None', 'bar\\tbar', 'bar\\\\tbar', 'None']
    assert_equal(len(entries), len(goal_vals))
    temp_dir = _TempDir()
    these_kwargs = deepcopy(std_kwargs)
    these_kwargs['output_dir'] = temp_dir
    with ExperimentController(*std_args, stim_fs=44100, **these_kwargs) as ec:
        for ent in entries:
            ec.write_data_line(*ent)
        fname = ec._data_file.name
    with open(fname) as fid:
        lines = fid.readlines()
    # check the header
    assert_equal(len(lines), len(entries) + 4)  # header, colnames, flip, stop
    assert_equal(lines[0][0], '#')  # first line is a comment
    for x in ['timestamp', 'event', 'value']:  # second line is col header
        assert_true(x in lines[1])
    assert_true('flip' in lines[2])  # ec.__init__ ends with a flip
    assert_true('stop' in lines[-1])  # last line is stop (from __exit__)
    outs = lines[1].strip().split('\t')
    assert_true(all(l1 == l2 for l1, l2 in zip(outs, ['timestamp',
                                                      'event', 'value'])))
    # check the entries
    ts = []
    for line, ent, gv in zip(lines[3:], entries, goal_vals):
        outs = line.strip().split('\t')
        assert_equal(len(outs), 3)
        # check timestamping
        if len(ent) == 3 and ent[2] is not None:
            assert_equal(outs[0], str(ent[2]))
        else:
            ts.append(float(outs[0]))
        # check events
        assert_equal(outs[1], ent[0])
        # check values
        assert_equal(outs[2], gv)
    # make sure we got monotonically increasing timestamps
    ts = np.array(ts)
    assert_true(np.all(ts[1:] >= ts[:-1]))
Example #10
0
def test_data_line():
    """Test writing of data lines
    """
    entries = [['foo'],
               ['bar', 'bar\tbar'],
               ['bar2', r'bar\tbar'],
               ['fb', None, -0.5]]
    # this is what should be written to the file for each one
    goal_vals = ['None', 'bar\\tbar', 'bar\\\\tbar', 'None']
    assert_equal(len(entries), len(goal_vals))
    temp_dir = _TempDir()
    these_kwargs = deepcopy(std_kwargs)
    these_kwargs['output_dir'] = temp_dir
    with ExperimentController(*std_args, stim_fs=44100, **these_kwargs) as ec:
        for ent in entries:
            ec.write_data_line(*ent)
        fname = ec._data_file.name
    with open(fname) as fid:
        lines = fid.readlines()
    # check the header
    assert_equal(len(lines), len(entries) + 4)  # header, colnames, flip, stop
    assert_equal(lines[0][0], '#')  # first line is a comment
    for x in ['timestamp', 'event', 'value']:  # second line is col header
        assert_true(x in lines[1])
    assert_true('flip' in lines[2])  # ec.__init__ ends with a flip
    assert_true('stop' in lines[-1])  # last line is stop (from __exit__)
    outs = lines[1].strip().split('\t')
    assert_true(all(l1 == l2 for l1, l2 in zip(outs, ['timestamp',
                                                      'event', 'value'])))
    # check the entries
    ts = []
    for line, ent, gv in zip(lines[3:], entries, goal_vals):
        outs = line.strip().split('\t')
        assert_equal(len(outs), 3)
        # check timestamping
        if len(ent) == 3 and ent[2] is not None:
            assert_equal(outs[0], str(ent[2]))
        else:
            ts.append(float(outs[0]))
        # check events
        assert_equal(outs[1], ent[0])
        # check values
        assert_equal(outs[2], gv)
    # make sure we got monotonically increasing timestamps
    ts = np.array(ts)
    assert_true(np.all(ts[1:] >= ts[:-1]))
Example #11
0
# -*- coding: utf-8 -*-
import os
from os import path as op
from nose.tools import assert_raises, assert_true, assert_equal

from expyfun import (ExperimentController, assert_version, download_version,
                     __version__)
from expyfun._utils import _TempDir
from expyfun._git import _has_git

tempdir = _TempDir()
tempdir_2 = _TempDir()


def test_version():
    """Test version assertions
    """
    assert_raises(TypeError, assert_version, 1)
    assert_raises(TypeError, assert_version, '1' * 8)
    assert_raises(AssertionError, assert_version, 'x' * 7)
    assert_version(__version__[-7:])

    v = '1088717'
    if not _has_git:
        assert_raises(ImportError, download_version, v, tempdir)
    else:
        assert_raises(IOError, download_version, v, op.join(tempdir, 'foo'))
        assert_raises(RuntimeError, download_version, 'x' * 7, tempdir)
        download_version(v, tempdir)
        ex_dir = op.join(tempdir, 'expyfun')
        assert_true(op.isdir(ex_dir))
Example #12
0
# -*- coding: utf-8 -*-
import os
from os import path as op
from nose.tools import assert_raises, assert_true, assert_equal

from expyfun import assert_version, download_version, __version__
from expyfun._utils import _TempDir
from expyfun._git import _has_git

tempdir = _TempDir()


def test_version():
    """Test version assertions
    """
    assert_raises(TypeError, assert_version, 1)
    assert_raises(TypeError, assert_version, '1' * 8)
    assert_raises(AssertionError, assert_version, 'x' * 7)
    assert_version(__version__[-7:])

    v = 'c18133c'
    if not _has_git:
        assert_raises(ImportError, download_version, v, tempdir)
    else:
        assert_raises(IOError, download_version, v, op.join(tempdir, 'foo'))
        assert_raises(RuntimeError, download_version, 'x' * 7, tempdir)
        download_version(v, tempdir)
        ex_dir = op.join(tempdir, 'expyfun')
        assert_true(op.isdir(ex_dir))
        assert_true(op.isfile(op.join(ex_dir, '__init__.py')))
        with open(op.join(ex_dir, '_version.py')) as fid:
Example #13
0
# -*- coding: utf-8 -*-

import numpy as np
import warnings
from nose.tools import assert_raises, assert_equal, assert_true
from numpy.testing import (assert_array_equal, assert_array_almost_equal,
                           assert_allclose)
from scipy.signal import butter, lfilter

from expyfun._utils import _TempDir, requires_lib, _hide_window
from expyfun.stimuli import (rms, play_sound, convolve_hrtf, window_edges,
                             vocode, texture_ERB)

warnings.simplefilter('always')

tempdir = _TempDir()


def test_textures():
    """Test stimulus textures."""
    texture_ERB()  # smoke test
    assert_raises(TypeError, texture_ERB, seq='foo')
    assert_raises(ValueError, texture_ERB, seq=('foo', ))
    with warnings.catch_warnings(record=True) as w:
        x = texture_ERB(freq_lims=(200, 500))
    assert_true(any('less than' in str(ww.message).lower() for ww in w))
    assert_allclose(len(x) / 24414., 4., rtol=1e-5)


@requires_lib('h5py')
def test_hrtf_convolution():
Example #14
0
# -*- coding: utf-8 -*-
import os
from os import path as op
from nose.tools import assert_raises, assert_true, assert_equal

from expyfun import (ExperimentController, assert_version, download_version,
                     __version__)
from expyfun._utils import _TempDir
from expyfun._git import _has_git

tempdir = _TempDir()
tempdir_2 = _TempDir()


def test_version():
    """Test version assertions
    """
    assert_raises(TypeError, assert_version, 1)
    assert_raises(TypeError, assert_version, '1' * 8)
    assert_raises(AssertionError, assert_version, 'x' * 7)
    assert_version(__version__[-7:])

    v = 'b798e65'
    f = 'drammock'
    if not _has_git:
        assert_raises(ImportError, download_version, v, tempdir, f)
    else:
        assert_raises(IOError, download_version, v, op.join(tempdir, 'foo'), f)
        assert_raises(RuntimeError, download_version, 'x' * 7, tempdir, f)
        download_version(v, tempdir, f)
        ex_dir = op.join(tempdir, 'expyfun')
Example #15
0
This shows how to use the CRM corpus functions.

@author: rkmaddox
"""

from expyfun._utils import _TempDir
from expyfun import ExperimentController, analyze, building_doc
from expyfun.stimuli import (crm_prepare_corpus, crm_sentence, crm_info,
                             crm_response_menu, add_pad, CRMPreload)

import numpy as np

print(__doc__)

crm_path = _TempDir()
fs = 40000

###############################################################################
# Prepare the corpus
# ------------------
#
# For simplicity, here we prepare just two talkers at the native 40000 Hz
# sampling rate.
#
# .. note:: For your experiment, you only need to prepare the corpus once per
#           sampling rate, you should probably use the default path, and you
#           should just do all the talkers at once. For the example, we are
#           using fs=40000 and only doing two talkers so that the stimulus
#           preparation is very fast, and a temp directory so that we don't
#           interfere with any other prepared corpuses. Your code will likely
Example #16
0
import numpy as np
from os import path as op
from nose.tools import assert_raises, assert_equal
import warnings

import expyfun.analyze as ea
from expyfun._utils import _TempDir, requires_pandas

warnings.simplefilter('always')
temp_dir = _TempDir()


@requires_pandas
def test_barplot_with_pandas():
    """Test bar plot function pandas support"""
    import pandas as pd
    tmp = pd.DataFrame(np.arange(20).reshape((4, 5)),
                       columns=['a', 'b', 'c', 'd', 'e'],
                       index=['one', 'two', 'three', 'four'])
    ea.barplot(tmp)
    ea.barplot(tmp, axis=0, lines=True)


def test_barplot():
    """Test bar plot function
    """
    import matplotlib.pyplot as plt
    ax = plt.subplot(1, 1, 1)
    tmp1 = np.arange(4)  # 1-Dim
    tmp2 = np.arange(20).reshape((4, 5))  # 2-Dim
    ea.barplot(tmp1, err_bars=tmp1, brackets=[(0, 1), (2, 3)],
Example #17
0
import numpy as np
import pytest
from numpy.testing import assert_equal

from expyfun import ExperimentController, __version__
from expyfun.io import read_tab, reconstruct_tracker, reconstruct_dealer
from expyfun._utils import _TempDir
from expyfun.stimuli import TrackerUD, TrackerBinom, TrackerDealer

temp_dir = _TempDir()
std_args = ['test']  # experiment name
std_kwargs = dict(output_dir=temp_dir,
                  full_screen=False,
                  window_size=(1, 1),
                  participant='foo',
                  session='01',
                  stim_db=0.0,
                  noise_db=0.0,
                  verbose=True,
                  version='dev')


def test_parse_basic(hide_window, tmpdir):
    """Test .tab parsing."""
    with ExperimentController(*std_args, **std_kwargs) as ec:
        ec.identify_trial(ec_id='one', ttl_id=[0])
        ec.start_stimulus()
        ec.write_data_line('misc', 'trial one')
        ec.stop()
        ec.trial_ok()
        ec.write_data_line('misc', 'between trials')
Example #18
0
This shows how to use the CRM corpus functions.

@author: rkmaddox
"""

from expyfun._utils import _TempDir
from expyfun import ExperimentController, analyze, building_doc
from expyfun.stimuli import (crm_prepare_corpus, crm_sentence, crm_info,
                             crm_response_menu, add_pad, CRMPreload)

import numpy as np

print(__doc__)

crm_path = _TempDir()
fs = 40000

###############################################################################
# Prepare the corpus
# ------------------
#
# For simplicity, here we prepare just two talkers at the native 40000 Hz
# sampling rate.
#
# .. note:: For your experiment, you only need to prepare the corpus once per
#           sampling rate, you should probably use the default path, and you
#           should just do all the talkers at once. For the example, we are
#           using fs=40000 and only doing two talkers so that the stimulus
#           preparation is very fast, and a temp directory so that we don't
#           interfere with any other prepared corpuses. Your code will likely