def test_sigmoid(): """Test sigmoidal fitting and generation """ n_pts = 1000 x = np.random.randn(n_pts) p0 = (0., 1., 0., 1.) y = ea.sigmoid(x, *p0) assert_true(np.all(np.logical_and(y <= 1, y >= 0))) p = ea.fit_sigmoid(x, y) assert_allclose(p, p0, atol=1e-4, rtol=1e-4) y += np.random.rand(n_pts) * 0.01 p = ea.fit_sigmoid(x, y) assert_allclose(p, p0, atol=0.1, rtol=0.1)
def test_sigmoid(): """Test sigmoidal fitting and generation.""" n_pts = 1000 x = np.random.randn(n_pts) p0 = (0., 1., 0., 1.) y = ea.sigmoid(x, *p0) assert_true(np.all(np.logical_and(y <= 1, y >= 0))) p = ea.fit_sigmoid(x, y) assert_allclose(p, p0, atol=1e-4, rtol=1e-4) p = ea.fit_sigmoid(x, y, (0, 1, None, None), ('upper', 'lower')) assert_allclose(p, p0, atol=1e-4, rtol=1e-4) y += np.random.rand(n_pts) * 0.01 p = ea.fit_sigmoid(x, y) assert_allclose(p, p0, atol=0.1, rtol=0.1)
def test_sigmoid(): """Test sigmoidal fitting and generation.""" n_pts = 1000 x = np.random.RandomState(0).randn(n_pts) p0 = (0., 1., 0., 1.) y = ea.sigmoid(x, *p0) assert np.all(np.logical_and(y <= 1, y >= 0)) p = ea.fit_sigmoid(x, y) assert_allclose(p, p0, atol=1e-4, rtol=1e-4) with pytest.warns(None): # scipy convergence p = ea.fit_sigmoid(x, y, (0, 1, None, None), ('upper', 'lower')) assert_allclose(p, p0, atol=1e-4, rtol=1e-4) y += np.random.rand(n_pts) * 0.01 p = ea.fit_sigmoid(x, y) assert_allclose(p, p0, atol=0.1, rtol=0.1)
from expyfun.analyze import sigmoid # Make a callback function that prints to the console, rather than log file def callback(event_type, value=None, timestamp=None): print((str(event_type) + ':').ljust(40) + str(value)) # Define parameters for modeled human subject (sigmoid probability) true_thresh = 115 slope = 0.8 chance = 0.08 # if you don't hear it, you don't respond # Make a tracker that uses the weighted up-down procedure to find 75% tr = TrackerMHW(callback, 0, 120, base_step=5, start_value=80) # Initialize human state rng = np.random.RandomState(1) # Do the task until the tracker stops while not tr.stopped: tr.respond(rng.rand() < sigmoid( tr.x_current - true_thresh, lower=chance, slope=slope)) # Plot the results fig, ax, lines = tr.plot() lines += tr.plot_thresh() ax.set_title( 'Adaptive track of model human (true threshold is {})'.format(true_thresh))
# acquired. # initialize two tracker objects--one for each start value tr_ud = [TrackerUD(callback, up, down, step_size_up, step_size_down, stop_reversals, stop_trials, sv, change_indices, change_rule, x_min, x_max) for sv in start_value] # initialize TrackerDealer object td = TrackerDealer(callback, tr_ud, max_lag, pace_rule, rng_dealer) # Initialize human state rng_human = np.random.RandomState(1) # random seed for modeled subject for _, level in td: # Get information of which trial type is next and what the level is at # that time from TrackerDealer td.respond(rng_human.rand() < sigmoid(level - true_thresh, lower=chance, slope=slope)) ############################################################################## # Plotting the Results # --------------------------- axes = plt.subplots(2, 1)[1] for i in [0, 1]: fig, ax, lines = td.trackers.ravel()[i].plot(ax=axes[i], n_skip=4) ax.legend(loc='best') ax.set_title('Adaptive track with start value {} (true threshold ' 'is {})'.format(start_value[i], true_thresh)) fig.tight_layout()
def likelihood_3(params, x, y, upper, slope, lower): return np.sum((y - sigmoid(x, lower=lower, upper=upper, midpt=params[0], slope=slope))**2)
def likelihood(params, x, y, lower): return np.sum((y - sigmoid(x, lower=lower, upper=params[2], midpt=params[0], slope=params[1]))**2)
if w: print(':(') # do individual condition fits for (p, c, i) in zip(data, ['C0', 'C1'], range(2)): mid = [ok[0]] [temp, _, _, _, w] = fmin(likelihood_3, mid, (conditions, p, ok[2], ok[1], lower), full_output=True, disp=False) params.append(temp) if w: print(':\'(') thresholds = np.array([np.power(10, m / 20) for m in [params[0][0], params[1][0]]]) thresholds = np.array([-1. / ok[1] * np.log((ok[2] - .5) / (.75 - .5) - 1) + p[0] for p in params]) thresholds = np.power(10, thresholds / 20) perform_imp = (sigmoid(20 * np.log10(thresholds[0]), lower=.5, upper=ok[2], midpt=params[1][0], slope=ok[1]) - .75) * 100 # %% save the data data = dict(responses=responses[-1], thresholds=thresholds, ok = ok, params=params, percent=percent, perform_imp = perform_imp) write_hdf5((path + 'percent_' + subject), data, overwrite=True) # %% plot an example if subject=='016': from collections import OrderedDict from matplotlib.transforms import blended_transform_factory
perform_imp = np.empty((len(subjects), 1)) data_resamp = np.empty((len(subjects), 1000, 2, 5)) responses = [] biases = [] d_prime = np.empty((len(subjects), 5)) stem_perimp = np.empty((len(subjects), 1000, 2)) stem_thimp = np.empty((len(subjects), 1000, 2)) for i, s in enumerate(subjects): data = read_hdf5(path + 'percent_' + s) responses.append(data['responses']) thresholds[i] = data['thresholds'] per_cor[i] = data['percent'] ok = data['ok'] params = data['params'] curves[i] = [sigmoid(20 * np.log10(x_plot_fit), lower=0.5, upper=ok[2], midpt=p[0], slope=ok[1]) for p in params] perform_imp[i] = data['perform_imp'] lapse[i] = [ok[2]] slope[i] = [ok[1]] thresh[i] = [params[0], params[1]] percent = np.mean(per_cor, 0) inds = np.argsort(thresholds[:, 0]) # %% Plot improvement in threshold at central threshold dpi_fig = 200 dpi = 600 ms = 7