code: def linear_regression(inst, design_matrix, names=None):
      """Fit Ordinary Least Squares (OLS) regression.
  
      Parameters
      ----------
      inst : instance of Epochs | iterable of SourceEstimate
          The data to be regressed. Contains all the trials, sensors, and time
          points for the regression. For Source Estimates, accepts either a list
          or a generator object.
      design_matrix : ndarray, shape (n_observations, n_regressors)
          The regressors to be used. Must be a 2d array with as many rows as
          the first dimension of the data. The first column of this matrix will
          typically consist of ones (intercept column).
      names : array-like | None
          Optional parameter to name the regressors (i.e., the columns in the
          design matrix). If provided, the length must correspond to the number
          of columns present in design matrix (including the intercept, if
          present). Otherwise, the default names are ``'x0'``, ``'x1'``,
          ``'x2', …, 'x(n-1)'`` for ``n`` regressors.
  
      Returns
      -------
      results : dict of namedtuple
          For each regressor (key), a namedtuple is provided with the
          following attributes:
  
              - ``beta`` : regression coefficients
              - ``stderr`` : standard error of regression coefficients
              - ``t_val`` : t statistics (``beta`` / ``stderr``)
              - ``p_val`` : two-sided p-value of t statistic under the t
                distribution
              - ``mlog10_p_val`` : -log₁₀-transformed p-value.
  
          The tuple members are numpy arrays. The shape of each numpy array is
          the shape of the data minus the first dimension; e.g., if the shape of
          the original data was ``(n_observations, n_channels, n_timepoints)``,
          then the shape of each of the arrays will be
          ``(n_channels, n_timepoints)``.
      """
      if names is None:
          names = ["x%i" % i for i in range(design_matrix.shape[1])]
  
      if isinstance(inst, BaseEpochs):
          picks = pick_types(
              inst.info,
              meg=True,
              eeg=True,
              ref_meg=True,
              stim=False,
              eog=False,
              ecg=False,
              emg=False,
              exclude=["bads"],
          )
          if [inst.ch_names[p] for p in picks] != inst.ch_names:
              warn(
                  "Fitting linear model to non-data or bad channels. "
                  "Check picking"
              )
          msg = "Fitting linear model to epochs"
          data = inst.get_data(copy=False)
          out = EvokedArray(
              np.zeros(data.shape[1:]), inst.info, inst.tmin
          )
      elif isgenerator(inst):
          msg = "Fitting linear model to source estimates (generator input)"
          out = next(inst)
          data = np.array([out.data] + [i.data for i in inst])
      elif isinstance(inst, list) and isinstance(
          inst[0], SourceEstimate
      ):
          msg = "Fitting linear model to source estimates (list input)"
          out = inst[0]
          data = np.array([i.data for i in inst])
      else:
          raise ValueError(
              "Input must be epochs or iterable of source " "estimates"
          )
      logger.info(
          msg
          + ", (%s targets, %s regressors)"
          % (np.prod(data.shape[1:]), len(names))
      )
      lm_params = _fit_lm(data, design_matrix, names)
      lm = namedtuple("lm", "beta stderr t_val p_val mlog10_p_val")
      lm_fits = {}
      for name in names:
          parameters = [p[name] for p in lm_params]
          for ii, value in enumerate(parameters):
              out_ = out.copy()
              if not isinstance(out_, (SourceEstimate, Evoked)):
                  raise RuntimeError("Invalid container.")
              out_._data[:] = value
              parameters[ii] = out_
          lm_fits[name] = lm(*parameters)
      logger.info("Done")
      return lm_fits
  
file_path: mne-python/mne/stats/regression.py
imports: from collections import namedtuple
  from inspect import isgenerator
  import numpy
  from scipy import linalg, sparse, stats
  from .._fiff.pick import _picks_to_idx, pick_info, pick_types
  from ..epochs import BaseEpochs
  from ..evoked import Evoked, EvokedArray
  from ..source_estimate import SourceEstimate
  from ..utils import _reject_data_segments, fill_doc, logger, warn
label_desc: Use image node_id 1 for calling a global function with example usage: linear_regression(inst, design_matrix, names) and returns: lm_fits