Esempio n. 1
0
def test_predict():
    speech_response = loadmat(str(root / "data" / "speech_data.mat"))
    fs = speech_response["fs"][0][0]
    response = speech_response["resp"]
    stimulus = speech_response["stim"]
    tmin = np.random.uniform(-0.1, 0.05)
    tmax = np.random.uniform(0.1, 0.4)
    regularization = np.random.uniform(0, 10)
    trf = TRF()
    trf.train(stimulus, response, fs, tmin, tmax, regularization)
    reps = np.random.randint(2, 10)
    stimuli = np.stack([stimulus for _ in range(reps)])
    responses = np.stack([response for _ in range(reps)])
    predictions = trf.predict(stimuli)
    assert predictions.shape == responses.shape
    for p in range(predictions.shape[0] - 1):
        np.testing.assert_equal(predictions[p], predictions[p + 1])
    predictions, correlations, error = trf.predict(stimuli, responses)
    assert np.isscalar(correlations) and np.isscalar(error)
    predictions, correlations, error = trf.predict(stimuli,
                                                   responses,
                                                   average_trials=False)
    assert correlations.shape[0] == error.shape[0] == reps
    predictions, correlations, error = trf.predict(stimuli,
                                                   responses,
                                                   average_features=False)
    assert correlations.shape[-1] == trf.weights.shape[-1]
    features = [randint(trf.weights.shape[0]) for _ in range(randint(2, 10))]
    lags = [randint(len(trf.times)) for _ in range(randint(2, 10))]
    predictions, correlations, error = trf.predict(stimuli, responses, lags,
                                                   features)
    assert predictions.shape == responses.shape
Esempio n. 2
0
def test_train(direction=None):
    speech_response = loadmat(str(root / "data" / "speech_data.mat"))
    fs = speech_response["fs"][0][0]
    response = speech_response["resp"][0:100]
    stimulus = speech_response["stim"][0:100]
    reps = np.random.randint(2, 10)
    stimuli = np.stack([stimulus for _ in range(reps)])
    responses = np.stack([response for _ in range(reps)])
    tmin = np.random.uniform(-0.1, 0.05)
    tmax = np.random.uniform(0.1, 0.4)
    if direction is None:
        direction = np.random.choice([1, -1])
    else:
        pass
    regularization = np.random.uniform(0, 10)
    trf1 = TRF(direction=direction)
    trf1.train(stimuli, responses, fs, tmin, tmax, regularization)
    trf2 = TRF(direction=direction)
    trf2.train(stimuli[0], responses[0], fs, tmin, tmax, regularization)
    if direction == 1:
        assert trf1.weights.shape[0] == stimuli.shape[-1]
        assert trf1.weights.shape[-1] == response.shape[-1]
    if direction == -1:
        assert trf1.weights.shape[-1] == stimuli.shape[-1]
        assert trf1.weights.shape[0] == response.shape[-1]

    try:
        np.testing.assert_almost_equal(trf1.weights, trf2.weights, 10)
    except:
        print(
            f"direction:{direction},regularization:{regularization},tmin:{tmin}, tmax:{tmax}, reps:{reps}"
        )
        raise
Esempio n. 3
0
def test_save_load():
    tmpdir = Path(tempfile.gettempdir())
    speech_response = loadmat(str(root / "data" / "speech_data.mat"))
    fs = speech_response["fs"][0][0]
    response = np.stack([speech_response["resp"][0:100] for _ in range(20)])
    stimulus = np.stack([speech_response["stim"][0:100] for _ in range(20)])
    tmin = np.random.uniform(-0.1, 0.05)
    tmax = np.random.uniform(0.1, 0.4)
    direction = np.random.choice([1, -1])
    reg = np.random.uniform(0, 10)
    trf1 = TRF(direction=direction)
    trf1.fit(stimulus, response, fs, tmin, tmax, reg)
    trf1.save(tmpdir / "test.trf")
    trf2 = TRF()
    trf2.load(tmpdir / "test.trf")
    np.testing.assert_equal(trf1.weights, trf2.weights)
Esempio n. 4
0
def test_plotting():
    # load the data
    speech_response = loadmat(str(root / "data" / "speech_data.mat"))
    fs = speech_response["fs"][0][0]
    response = speech_response["resp"]
    stimuli = speech_response["stim"]
    trf_encoder = TRF()
    tmin, tmax = -0.1, 0.4
    trf_encoder.train(stimuli, response * speech_response["factor"][0][0], fs,
                      tmin, tmax, 0.5)
    trf_encoder.plot_forward_weights(channels=85, kind="image", show=False)
    trf_encoder.plot_forward_weights(channels=[4, 7, 10],
                                     tmin=0.1,
                                     tmax=0.2,
                                     kind="line",
                                     show=False)
    trf_encoder.plot_forward_weights(kind="image", mode="gfp", show=False)
def test_encoding():
    # load the data
    speech_response = loadmat(str(root / "data" / "speech_data.mat"))
    fs = speech_response["fs"][0][0]
    response = speech_response["resp"]
    stimuli = speech_response["stim"]

    # and the expected result
    encoder_results = loadmat(str(root / "results" / "encoder_results.mat"))
    # w = input features (stimuli) x times x output features (=channels)
    w, b, times, _, direction, kind = encoder_results["modelEncoder"][0][0]
    prediction1 = encoder_results["predResp"]
    correlation1 = encoder_results["predRespStats"]["r"][0][0][0]
    error1 = encoder_results["predRespStats"]["err"][0][0][0]
    # train the TRF model on the data
    trf_encoder = TRF()
    tmin, tmax = -0.1, 0.2
    trf_encoder.train(stimuli, response, fs, tmin, tmax, 100)
    # use the trained TRF to predict data
    prediction2, correlation2, error2 = trf_encoder.predict(
        stimuli, response, average_features=False)

    # check that the results are the same as in matlab
    np.testing.assert_almost_equal(trf_encoder.weights, w, decimal=12)
    np.testing.assert_almost_equal(trf_encoder.bias, b, decimal=12)
    np.testing.assert_equal(trf_encoder.times, times[0] / 1e3)
    np.testing.assert_almost_equal(prediction1, prediction2, decimal=12)
    np.testing.assert_almost_equal(correlation1, correlation2, decimal=12)
    np.testing.assert_almost_equal(error1, error2, decimal=12)

    # we should get the same results if we duplicate the data and use the
    # fit function
    stimuli = np.stack([stimuli for _ in range(10)], axis=0)
    response = np.stack([response for _ in range(10)], axis=0)
    trf_encoder = TRF()
    tmin, tmax = -0.1, 0.2
    trf_encoder.fit(stimuli, response, fs, tmin, tmax, 100)
    prediction2, correlation2, error2 = trf_encoder.predict(
        stimuli, response, average_features=False)

    # check that the results are the same as in matlab
    np.testing.assert_almost_equal(trf_encoder.weights, w, decimal=12)
    np.testing.assert_almost_equal(trf_encoder.bias, b, decimal=12)
    np.testing.assert_equal(trf_encoder.times, times[0] / 1e3)
    np.testing.assert_almost_equal(correlation1, correlation2, decimal=12)
    np.testing.assert_almost_equal(error1, error2, decimal=12)
Esempio n. 6
0
def test_crossval():
    speech_response = loadmat(str(root / "data" / "speech_data.mat"))
    fs = speech_response["fs"][0][0]
    response = np.stack([speech_response["resp"][0:100] for _ in range(20)])
    stimulus = np.stack([speech_response["stim"][0:100] for _ in range(20)])
    tmin = np.random.uniform(-0.1, 0.05)
    tmax = np.random.uniform(0.1, 0.4)
    direction = np.random.choice([1, -1])
    reg = np.random.uniform(0, 10)
    trf = TRF(direction=direction)
    splits = np.random.randint(2, 10)
    test_size = np.random.uniform(0.05, 0.3)
    models, correlations, errors = cross_validate(trf, stimulus, response, fs,
                                                  tmin, tmax, reg, splits)
    assert isinstance(models, TRF)
    assert np.isscalar(correlations) and np.isscalar(errors)
    models, correlations, errors = cross_validate(
        trf,
        stimulus,
        response,
        fs,
        tmin,
        tmax,
        reg,
        splits,
        average_splits=False,
    )
    assert correlations.ndim == 1 and len(correlations) == splits
    assert len(models) == splits
    models, correlations, errors = cross_validate(
        trf,
        stimulus,
        response,
        fs,
        tmin,
        tmax,
        reg,
        splits,
        average_splits=False,
    )
    assert correlations.ndim == 1 and len(correlations) == splits
    assert len(models) == splits
    models, correlations, errors = cross_validate(
        trf,
        stimulus,
        response,
        fs,
        tmin,
        tmax,
        reg,
        splits,
        average_features=False,
    )
    assert correlations.ndim == 1
    assert len(correlations) == models.weights.shape[-1]
Esempio n. 7
0
def test_fit():
    speech_response = loadmat(str(root / "data" / "speech_data.mat"))
    fs = speech_response["fs"][0][0]
    response = np.stack([speech_response["resp"][0:100] for _ in range(20)])
    stimulus = np.stack([speech_response["stim"][0:100] for _ in range(20)])
    tmin = np.random.uniform(-0.1, 0.05)
    tmax = np.random.uniform(0.1, 0.4)
    direction = np.random.choice([1, -1])
    reg = np.random.uniform(0, 10)
    trf = TRF(direction=direction)
    trf.fit(stimulus, response, fs, tmin, tmax, reg)
    reg = [np.random.uniform(0, 10) for _ in range(randint(2, 10))]
    trf = TRF(direction=direction)
    trf.fit(stimulus, response, fs, tmin, tmax, reg)
Esempio n. 8
0
def test_arithmatic():
    trf1 = TRF()
    trf2 = TRF()
    trf1.weights = np.ones((10, 10))
    trf2.weights = np.ones((10, 10))
    trf1.bias = np.ones(10)
    trf2.bias = np.ones(10)
    trf3 = trf1 + trf2
    np.testing.assert_equal(trf3.bias, trf1.bias + trf2.bias)
    np.testing.assert_equal(trf3.weights, trf1.weights + trf2.weights)
    trf4 = sum([trf1, trf2, trf3])
    np.testing.assert_equal(trf4.bias, trf1.bias + trf2.bias + trf3.bias)
    np.testing.assert_equal(trf4.weights,
                            trf1.weights + trf2.weights + trf3.weights)
    trf4 /= 4
    np.testing.assert_equal(trf4.weights, trf1.weights)
def test_decoding():
    # load data and expected results
    speech_response = loadmat(str(root / "data" / "speech_data.mat"))
    fs = speech_response["fs"][0][0]
    response = speech_response["resp"]
    stimuli = speech_response["stim"]
    decoder_results = loadmat(str(root / "results" / "decoder_results.mat"))
    w, b, times, _, direction, kind = decoder_results["modelDecoder"][0][0]
    prediction1 = decoder_results["predStim"]
    correlation1 = decoder_results["predStimStats"]["r"][0][0][0]
    error1 = decoder_results["predStimStats"]["err"][0][0][0]
    # train the model and predict stimulus
    trf_decoder = TRF(direction=-1)
    tmin, tmax = -0.1, 0.2
    trf_decoder.train(stimuli, response, fs, tmin, tmax, 100)
    prediction2, correlation2, error2 = trf_decoder.predict(
        stimuli, response, average_features=False)
    # check that the results are the same as in matlab
    np.testing.assert_almost_equal(trf_decoder.weights, w, decimal=11)
    np.testing.assert_almost_equal(trf_decoder.bias, b, decimal=11)
    np.testing.assert_equal(trf_decoder.times, times[0] / 1e3)
    np.testing.assert_almost_equal(prediction1, prediction2, decimal=11)
    np.testing.assert_almost_equal(correlation1, correlation2, decimal=11)
    np.testing.assert_almost_equal(error1, error2, decimal=11)