def add_original(self, P): """ P : array Parameter map of the statistic of interest. """ self.clusters = [] # find clusters clusters, n = self._find_clusters(P) clusters_v = scipy.ndimage.measurements.sum(P, clusters, xrange(1, n + 1)) for i in xrange(n): v = clusters_v[i] p = 1 - percentileofscore(self.dist, np.abs(v), 'mean') / 100 if p <= self.pmax: im = P * (clusters == i + 1) name = 'p=%.3f' % p threshold = self.t_upper if (v > 0) else self.t_lower properties = {'p': p, 'unit': self.unit, 'threshold': threshold} ndv = ndvar(im, dims=self.dims, name=name, properties=properties) self.clusters.append(ndv) props = {'unit': self.unit, 'cs': self.cs, 'threshold_lower': self.t_lower, 'threshold_upper': self.t_upper} self.P = ndvar(P, dims=self.dims, name=self.name, properties=props)
def __init__(self, Y='MEG', X='condition', sub=None, ds=None, p=.05, contours={.01: '.5', .001: '0'}): """ uses scipy.stats.f_oneway """ Y = asndvar(Y, sub=sub, ds=ds) X = ascategorial(X, sub=sub, ds=ds) Ys = [Y[X == c] for c in X.cells] Ys = [y.x.reshape((y.x.shape[0], -1)) for y in Ys] N = Ys[0].shape[1] Ps = [] for i in xrange(N): groups = (y[:, i] for y in Ys) F, p = scipy.stats.f_oneway(*groups) Ps.append(p) test_name = 'One-way ANOVA' dims = Y.dims[1:] Ps = np.reshape(Ps, tuple(len(dim) for dim in dims)) properties = Y.properties.copy() properties['colorspace'] = _cs.get_sig(p=p, contours=contours) properties['test'] = test_name p = ndvar(Ps, dims, properties=properties, name=X.name) # store results self.name = "anova" self.p = p self.all = p
def fiff_mne(ds, fwd='{fif}*fwd.fif', cov='{fif}*cov.fif', label=None, name=None, tstart= -0.1, tstop=0.6, baseline=(None, 0)): """ adds data from one label as """ if name is None: if label: _, lbl = os.path.split(label) lbl, _ = os.path.splitext(lbl) name = lbl.replace('-', '_') else: name = 'stc' info = ds.info['info'] raw = ds.info['raw'] fif_name = raw.info['filename'] fif_name, _ = os.path.splitext(fif_name) if fif_name.endswith('raw'): fif_name = fif_name[:-3] fwd = fwd.format(fif=fif_name) if '*' in fwd: d, n = os.path.split(fwd) names = fnmatch.filter(os.listdir(d), n) if len(names) == 1: fwd = os.path.join(d, names[0]) else: raise IOError("No unique fwd file matching %r" % fwd) cov = cov.format(fif=fif_name) if '*' in cov: d, n = os.path.split(cov) names = fnmatch.filter(os.listdir(d), n) if len(names) == 1: cov = os.path.join(d, names[0]) else: raise IOError("No unique cov file matching %r" % cov) fwd = mne.read_forward_solution(fwd, force_fixed=False, surf_ori=True) cov = mne.Covariance(cov) inv = _mn.make_inverse_operator(info, fwd, cov, loose=0.2, depth=0.8) epochs = mne_Epochs(ds, tstart=tstart, tstop=tstop, baseline=baseline) # mne example: snr = 3.0 lambda2 = 1.0 / snr ** 2 if label is not None: label = mne.read_label(label) stcs = _mn.apply_inverse_epochs(epochs, inv, lambda2, dSPM=False, label=label) x = np.vstack(s.data.mean(0) for s in stcs) s = stcs[0] dims = ('case', var(s.times, 'time'),) ds[name] = ndvar(x, dims, properties=None, info='') return stcs
def _get_vessel_for_Y(self, Ydata): Ydata = np.array([self._cfunc(data, axis=0) for data in Ydata]) T = np.arange(self._tw.tstart, self._tw.tend, 1 / self._samplingrate) time = _vsl.var(T, name='time') dims = ('case', time) properties = {'samplingrate': self._samplingrate} Y = _vsl.ndvar(Ydata, dims, properties=properties, name=self._name) return Y
def evoked_ndvar(evoked, name='MEG'): "Convert an mne Evoked object of a list thereof to an ndvar" if isinstance(evoked, mne.fiff.Evoked): x = evoked.data dims = () else: x = np.array([e.data for e in evoked]) dims = ('case',) evoked = evoked[0] sensor = sensor_net(evoked) time = var(evoked.times, name='time') properties = {'colorspace': _cs.get_MEG(2e-13)} return ndvar(x, dims + (sensor, time), properties=properties, name=name)
def __init__(self, Y='MEG', X='condition', sub=None, ds=None, p=.05, contours={.01: '.5', .001: '0'}): self.name = "anova" Y = self.Y = asndvar(Y, sub=sub, ds=ds) X = self.X = asmodel(X, sub=sub, ds=ds) fitter = _glm.lm_fitter(X) properties = Y.properties.copy() properties['colorspace'] = _cs.get_sig(p=p, contours=contours) kwargs = dict(dims=Y.dims[1:], properties=properties) self.all = [] self.p_maps = {} for e, _, Ps in fitter.map(Y.x): name = e.name P = ndvar(Ps, name=name, **kwargs) self.all.append(P) self.p_maps[e] = P
def stc_ndvar(stc, subject='fsaverage', name=None, check=True): """ create an ndvar object from an mne SourceEstimate object stc : SourceEstimate | list of SourceEstimates The source estimate object(s). subject : str MRI subject (used for loading MRI in PySurfer plotting) name : str | None Ndvar name. check : bool If multiple stcs are provided, check if all stcs have the same times and vertices. """ if isinstance(stc, mne.SourceEstimate): case = False x = stc.data else: case = True stcs = stc stc = stcs[0] if check: vert_lh, vert_rh = stc.vertno times = stc.times for stc_ in stcs[1:]: assert np.all(times == stc_.times) lh, rh = stc_.vertno assert np.all(vert_lh == lh) assert np.all(vert_rh == rh) x = np.array([s.data for s in stcs]) time = var(stc.times, name='time') ss = source_space(stc.vertno, subject=subject) if case: dims = ('case', ss, time) else: dims = (ss, time) return ndvar(x, dims, name=name)
def epochs_ndvar(epochs, name='MEG', meg=True, eeg=False, exclude='bads', mult=1, unit='T', properties=None, sensors=None): """ Convert an mne.Epochs object to an ndvar. Parameters ---------- epoch : mne.Epochs The epochs object name : None | str Name for the ndvar. meg : bool or string MEG channels to include (:func:`mne.fiff.pick_types` kwarg). If True include all MEG channels. If False include None If string it can be 'mag' or 'grad' to select only gradiometers or magnetometers. It can also be 'ref_meg' to get CTF reference channels. eeg : bool If True include EEG channels (:func:`mne.fiff.pick_types` kwarg). exclude : list of string | str Channels to exclude (:func:`mne.fiff.pick_types` kwarg). If 'bads' (default), exclude channels in info['bads']. If empty do not exclude any. mult : scalar multiply all data by a constant. If used, the ``unit`` kwarg should specify the target unit, not the source unit. unit : str Unit of the data (default is 'T'). target : str name for the new ndvar containing the epoch data reject : None | scalar Threshold for rejecting epochs (peak to peak). Requires a for of mne-python which implements the Epochs.model['index'] variable. raw : None | mne.fiff.Raw Raw file providing the data; if ``None``, ``ds.info['raw']`` is used. sensors : None | eelbrain.vessels.sensors.sensor_net The default (``None``) reads the sensor locations from the fiff file. If the fiff file contains incorrect sensor locations, a different sensor_net can be supplied through this kwarg. """ props = {'proj': 'z root', 'unit': unit, 'ylim': 2e-12 * mult, 'summary_ylim': 3.5e-13 * mult, 'colorspace': _cs.get_MEG(2e-12 * mult), 'summary_colorspace': _cs.get_MEG(2e-13 * mult), 'samplingrate': epochs.info['sfreq'], } if properties: props.update(properties) picks = mne.fiff.pick_types(epochs.info, meg=meg, eeg=eeg, stim=False, eog=False, include=[], exclude=exclude) x = epochs.get_data()[:, picks] if mult != 1: x *= mult if sensors is None: sensor = sensor_net(epochs, picks=picks) else: sensor = sensors time = var(epochs.times, name='time') return ndvar(x, ('case', sensor, time), properties=props, name=name)
def __init__(self, Y, X, norm=None, sub=None, ds=None, contours={.05: (.8, .2, .0), .01: (1., .6, .0), .001: (1., 1., .0)}): """ Y : ndvar Dependent variable. X : continuous | None The continuous predictor variable. norm : None | categorial Categories in which to normalize (z-score) X. """ Y = asndvar(Y, sub=sub, ds=ds) X = asvar(X, sub=sub, ds=ds) if not Y.has_case: msg = ("Dependent variable needs case dimension") raise ValueError(msg) y = Y.x.reshape((len(Y), -1)) if norm is not None: y = y.copy() for cell in norm.cells: idx = (norm == cell) y[idx] = scipy.stats.mstats.zscore(y[idx]) n = len(X) x = X.x.reshape((n, -1)) # covariance m_x = np.mean(x) if np.isnan(m_x): raise ValueError("np.mean(x) is nan") x -= m_x y -= np.mean(y, axis=0) cov = np.sum(x * y, axis=0) / (n - 1) # correlation r = cov / (np.std(x, axis=0) * np.std(y, axis=0)) # p-value calculation # http://en.wikipedia.org/wiki/Pearson_product-moment_correlation_coefficient#Inference pcont = {} r_ps = {} df = n - 2 for p, color in contours.iteritems(): t = scipy.stats.distributions.t.isf(p, df) r_p = t / np.sqrt(n - 2 + t ** 2) pcont[r_p] = color r_ps[r_p] = p pcont[-r_p] = color r_ps[-r_p] = p dims = Y.dims[1:] shape = Y.x.shape[1:] properties = Y.properties.copy() cs = _cs.Colorspace(cmap=_cs.cm_xpolar, vmax=1, vmin= -1, contours=pcont, ps=r_ps) properties['colorspace'] = cs r = ndvar(r.reshape(shape), dims=dims, properties=properties) # store results self.name = "%s corr %s" % (Y.name, X.name) self.r = r self.all = r