def test_fixed_effect_contrast_nonzero_effect(): X, y = make_regression(n_features=5, n_samples=20, random_state=0) y = y[:, None] labels, results = run_glm(y, X, 'ols') coef = LinearRegression(fit_intercept=False).fit(X, y).coef_ for i in range(X.shape[1]): contrast = np.zeros(X.shape[1]) contrast[i] = 1. fixed_effect = _compute_fixed_effect_contrast( [labels], [results], [contrast], ) assert_almost_equal(fixed_effect.effect_size(), coef.ravel()[i]) fixed_effect = _compute_fixed_effect_contrast([labels] * 3, [results] * 3, [contrast] * 3) assert_almost_equal(fixed_effect.effect_size(), coef.ravel()[i])
def test_fixed_effect_contrast(): n, p, q = 100, 80, 10 X, Y = np.random.randn(p, q), np.random.randn(p, n) lab, res = run_glm(Y, X, 'ols') c1, c2 = np.eye(q)[0], np.eye(q)[1] con = _compute_fixed_effect_contrast([lab, lab], [res, res], [c1, c2]) z_vals = con.z_score() assert_almost_equal(z_vals.mean(), 0, 0) assert_almost_equal(z_vals.std(), 1, 0)
def test_fixed_effect_contrast(): rng = np.random.RandomState(42) n, p, q = 100, 80, 10 X, Y = rng.standard_normal(size=(p, q)), rng.standard_normal(size=(p, n)) lab, res = run_glm(Y, X, 'ols') c1, c2 = np.eye(q)[0], np.eye(q)[1] con = _compute_fixed_effect_contrast([lab, lab], [res, res], [c1, c2]) z_vals = con.z_score() assert_almost_equal(z_vals.mean(), 0, 0) assert_almost_equal(z_vals.std(), 1, 0)
def compute_contrast(self, contrast_def, stat_type=None, output_type='z_score'): """Generate different outputs corresponding to the contrasts provided e.g. z_map, t_map, effects and variance. In multi-session case, outputs the fixed effects map. Parameters ---------- contrast_def : str or array of shape (n_col) or list of (string or array of shape (n_col)) where ``n_col`` is the number of columns of the design matrix, (one array per run). If only one array is provided when there are several runs, it will be assumed that the same contrast is desired for all runs. The string can be a formula compatible with `pandas.DataFrame.eval`. Basically one can use the name of the conditions as they appear in the design matrix of the fitted model combined with operators +- and combined with numbers with operators +-`*`/. stat_type : {'t', 'F'}, optional type of the contrast output_type : str, optional Type of the output map. Can be 'z_score', 'stat', 'p_value', 'effect_size', 'effect_variance' or 'all' Returns ------- output : Nifti1Image or dict The desired output image(s). If ``output_type == 'all'``, then the output is a dictionary of images, keyed by the type of image. """ if self.labels_ is None or self.results_ is None: raise ValueError('The model has not been fit yet') if isinstance(contrast_def, (np.ndarray, str)): con_vals = [contrast_def] elif isinstance(contrast_def, (list, tuple)): con_vals = contrast_def else: raise ValueError('contrast_def must be an array or str or list of' ' (array or str)') # Translate formulas to vectors for cidx, (con, design_mat) in enumerate(zip(con_vals, self.design_matrices_) ): design_columns = design_mat.columns.tolist() if isinstance(con, str): con_vals[cidx] = expression_to_contrast_vector( con, design_columns) n_runs = len(self.labels_) if len(con_vals) != n_runs: warn('One contrast given, assuming it for all %d runs' % n_runs) con_vals = con_vals * n_runs valid_types = ['z_score', 'stat', 'p_value', 'effect_size', 'effect_variance'] valid_types.append('all') # ensuring 'all' is the final entry. if output_type not in valid_types: raise ValueError( 'output_type must be one of {}'.format(valid_types)) contrast = _compute_fixed_effect_contrast(self.labels_, self.results_, con_vals, stat_type) output_types = (valid_types[:-1] if output_type == 'all' else [output_type]) outputs = {} for output_type_ in output_types: estimate_ = getattr(contrast, output_type_)() # Prepare the returned images output = self.masker_.inverse_transform(estimate_) contrast_name = str(con_vals) output.header['descrip'] = ( '%s of contrast %s' % (output_type_, contrast_name)) outputs[output_type_] = output return outputs if output_type == 'all' else output