class_docstr: Implement the General Linear Model for single run :term:`fMRI` data.
  
  Parameters
  ----------
  t_r : float
      This parameter indicates :term:`repetition times<TR>`
      of the experimental runs.
      In seconds. It is necessary to correctly consider times in the design
      matrix. This parameter is also passed to :func:`nilearn.signal.clean`.
      Please see the related documentation for details.
  
  slice_time_ref : float, default=0
      This parameter indicates the time of the reference slice used in the
      slice timing preprocessing step of the experimental runs.
      It is expressed as a fraction of the ``t_r`` (repetition time),
      so it can have values between 0. and 1.
  %(hrf_model)s
      Default='glover'.
  drift_model : string, default='cosine'
      This parameter specifies the desired drift model for the design
      matrices. It can be 'polynomial', 'cosine' or None.
  
  high_pass : float, default=0.01
      This parameter specifies the cut frequency of the high-pass filter in
      Hz for the design matrices. Used only if drift_model is 'cosine'.
  
  drift_order : int, default=1
      This parameter specifies the order of the drift model (in case it is
      polynomial) for the design matrices.
  
  fir_delays : array of shape(n_onsets) or list, default=[0]
      In case of :term:`FIR` design,
      yields the array of delays used in the :term:`FIR` model,
      in scans.
  
  min_onset : float, default=-24
      This parameter specifies the minimal onset relative to the design
      (in seconds). Events that start before (slice_time_ref * t_r +
      min_onset) are not considered.
  
  mask_img : Niimg-like, NiftiMasker object or False, optional
      Mask to be used on data. If an instance of masker is passed,
      then its mask will be used. If no mask is given,
      it will be computed automatically by a NiftiMasker with default
      parameters. If False is given then the data will not be masked.
  
  target_affine : 3x3 or 4x4 matrix, optional
      This parameter is passed to nilearn.image.resample_img.
      Please see the related documentation for details.
  
  target_shape : 3-tuple of integers, optional
      This parameter is passed to nilearn.image.resample_img.
      Please see the related documentation for details.
  %(smoothing_fwhm)s
  memory : string or pathlib.Path, optional
      Path to the directory used to cache the masking process and the glm
      fit. By default, no caching is done.
      Creates instance of joblib.Memory.
  
  memory_level : integer, optional
      Rough estimator of the amount of memory used by caching. Higher value
      means more memory for caching.
  
  standardize : boolean, default=False
      If standardize is True, the time-series are centered and normed:
      their variance is put to 1 in the time dimension.
  
  signal_scaling : False, int or (int, int), default=0
      If not False, fMRI signals are
      scaled to the mean value of scaling_axis given,
      which can be 0, 1 or (0, 1).
      0 refers to mean scaling each voxel with respect to time,
      1 refers to mean scaling each time point with respect to all voxels &
      (0, 1) refers to scaling with respect to voxels and time,
      which is known as grand mean scaling.
      Incompatible with standardize (standardize=False is enforced when
      signal_scaling is not False).
  
  noise_model : {'ar1', 'ols'}, default='ar1'
      The temporal variance model.
  
  verbose : integer, default=0
      Indicate the level of verbosity. By default, nothing is printed.
      If 0 prints nothing. If 1 prints progress by computation of
      each run. If 2 prints timing details of masker and GLM. If 3
      prints masker computation details.
  
  n_jobs : integer, default=1
      The number of CPUs to use to do the computation. -1 means
      'all CPUs', -2 'all CPUs but one', and so on.
  
  minimize_memory : boolean, default=True
      Gets rid of some variables on the model fit results that are not
      necessary for contrast computation and would only be useful for
      further inspection of model details. This has an important impact
      on memory consumption.
  
  subject_label : string, optional
      This id will be used to identify a `FirstLevelModel` when passed to
      a `SecondLevelModel` object.
  
  random_state : int or numpy.random.RandomState, default=None.
      Random state seed to sklearn.cluster.KMeans
      for autoregressive models
      of order at least 2 ('ar(N)' with n >= 2).
  
      .. versionadded:: 0.9.1
  
  Attributes
  ----------
  labels_ : array of shape (n_voxels,),
      a map of values on voxels used to identify the corresponding model
  
  results_ : dict,
      with keys corresponding to the different labels values.
      Values are SimpleRegressionResults corresponding to the voxels,
      if minimize_memory is True,
      RegressionResults if minimize_memory is False
class_docstr_tok: ["Implement","the","General","Linear","Model","for","single","run",":","term",":","`","fMRI","`","data",".","Parameters","--","--","--","--","--","t_r",":","float","This","parameter","indicates",":","term",":","`","repetition","times","<","TR",">","`","of","the","experimental","runs",".","In","seconds",".","It","is","necessary","to","correctly","consider","times","in","the","design","matrix",".","This","parameter","is","also","passed","to",":","func",":","`","nilearn.signal.clean","`",".","Please","see","the","related","documentation","for","details",".","slice_time_ref",":","float",",","default=0","This","parameter","indicates","the","time","of","the","reference","slice","used","in","the","slice","timing","preprocessing","step","of","the","experimental","runs",".","It","is","expressed","as","a","fraction","of","the","``","t_r","``","(","repetition","time",")",",","so","it","can","have","values","between","0.","and","1",".","%","(","hrf_model",")","s","Default='glover","'",".","drift_model",":","string",",","default='cosine'","This","parameter","specifies","the","desired","drift","model","for","the","design","matrices",".","It","can","be","'polynomial","'",",","'cosine","'","or","None",".","high_pass",":","float",",","default=0.01","This","parameter","specifies","the","cut","frequency","of","the","high-pass","filter","in","Hz","for","the","design","matrices",".","Used","only","if","drift_model","is","'cosine","'",".","drift_order",":","int",",","default=1","This","parameter","specifies","the","order","of","the","drift","model","(","in","case","it","is","polynomial",")","for","the","design","matrices",".","fir_delays",":","array","of","shape","(","n_onsets",")","or","list",",","default=","[","0","]","In","case","of",":","term",":","`","FIR","`","design",",","yields","the","array","of","delays","used","in","the",":","term",":","`","FIR","`","model",",","in","scans",".","min_onset",":","float",",","default=-24","This","parameter","specifies","the","minimal","onset","relative","to","the","design","(","in","seconds",")",".","Events","that","start","before","(","slice_time_ref","*","t_r","+","min_onset",")","are","not","considered",".","mask_img",":","Niimg-like",",","NiftiMasker","object","or","False",",","optional","Mask","to","be","used","on","data",".","If","an","instance","of","masker","is","passed",",","then","its","mask","will","be","used",".","If","no","mask","is","given",",","it","will","be","computed","automatically","by","a","NiftiMasker","with","default","parameters",".","If","False","is","given","then","the","data","will","not","be","masked",".","target_affine",":","3x3","or","4x4","matrix",",","optional","This","parameter","is","passed","to","nilearn.image.resample_img",".","Please","see","the","related","documentation","for","details",".","target_shape",":","3-tuple","of","integers",",","optional","This","parameter","is","passed","to","nilearn.image.resample_img",".","Please","see","the","related","documentation","for","details",".","%","(","smoothing_fwhm",")","s","memory",":","string","or","pathlib.Path",",","optional","Path","to","the","directory","used","to","cache","the","masking","process","and","the","glm","fit",".","By","default",",","no","caching","is","done",".","Creates","instance","of","joblib.Memory",".","memory_level",":","integer",",","optional","Rough","estimator","of","the","amount","of","memory","used","by","caching",".","Higher","value","means","more","memory","for","caching",".","standardize",":","boolean",",","default=False","If","standardize","is","True",",","the","time-series","are","centered","and","normed",":","their","variance","is","put","to","1","in","the","time","dimension",".","signal_scaling",":","False",",","int","or","(","int",",","int",")",",","default=0","If","not","False",",","fMRI","signals","are","scaled","to","the","mean","value","of","scaling_axis","given",",","which","can","be","0",",","1","or","(","0",",","1",")",".","0","refers","to","mean","scaling","each","voxel","with","respect","to","time",",","1","refers","to","mean","scaling","each","time","point","with","respect","to","all","voxels","&","(","0",",","1",")","refers","to","scaling","with","respect","to","voxels","and","time",",","which","is","known","as","grand","mean","scaling",".","Incompatible","with","standardize","(","standardize=False","is","enforced","when","signal_scaling","is","not","False",")",".","noise_model",":","{","'ar1","'",",","'ols","'","}",",","default='ar1'","The","temporal","variance","model",".","verbose",":","integer",",","default=0","Indicate","the","level","of","verbosity",".","By","default",",","nothing","is","printed",".","If","0","prints","nothing",".","If","1","prints","progress","by","computation","of","each","run",".","If","2","prints","timing","details","of","masker","and","GLM",".","If","3","prints","masker","computation","details",".","n_jobs",":","integer",",","default=1","The","number","of","CPUs","to","use","to","do","the","computation",".","-1","means","'all","CPUs","'",",","-2","'all","CPUs","but","one","'",",","and","so","on",".","minimize_memory",":","boolean",",","default=True","Gets","rid","of","some","variables","on","the","model","fit","results","that","are","not","necessary","for","contrast","computation","and","would","only","be","useful","for","further","inspection","of","model","details",".","This","has","an","important","impact","on","memory","consumption",".","subject_label",":","string",",","optional","This","id","will","be","used","to","identify","a","`","FirstLevelModel","`","when","passed","to","a","`","SecondLevelModel","`","object",".","random_state",":","int","or","numpy.random.RandomState",",","default=None",".","Random","state","seed","to","sklearn.cluster.KMeans","for","autoregressive","models","of","order","at","least","2","(","'ar","(","N",")","'","with","n",">","=","2",")",".","..","versionadded",":",":","0.9.1","Attributes","--","--","--","--","--","labels_",":","array","of","shape","(","n_voxels",",",")",",","a","map","of","values","on","voxels","used","to","identify","the","corresponding","model","results_",":","dict",",","with","keys","corresponding","to","the","different","labels","values",".","Values","are","SimpleRegressionResults","corresponding","to","the","voxels",",","if","minimize_memory","is","True",",","RegressionResults","if","minimize_memory","is","False"]
docstr: Fit the :term:`GLM`.
  
  For each run:
  1. create design matrix X
  2. do a masker job: fMRI_data -> Y
  3. fit regression to (Y, X)
  
  Parameters
  ----------
  run_imgs : Niimg-like object or list of Niimg-like objects,
      Data on which the :term:`GLM` will be fitted. If this is a list,
      the affine is considered the same for all.
  
  events : pandas Dataframe or string or list of pandas DataFrames                  or strings, default=None
      :term:`fMRI` events used to build design matrices.
      One events object expected per run_img.
      Ignored in case designs is not None.
      If string, then a path to a csv file is expected.
  
  confounds : pandas Dataframe, numpy array or string or                     list of pandas DataFrames, numpy arrays or strings,                     default=None
      Each column in a DataFrame corresponds to a confound variable
      to be included in the regression model of the respective run_img.
      The number of rows must match the number of volumes in the
      respective run_img. Ignored in case designs is not None.
      If string, then a path to a csv file is expected.
  
  sample_masks : array_like, or list of array_like, default=None
      shape of array: (number of scans - number of volumes remove)
      Indices of retained volumes. Masks the niimgs along time/fourth
      dimension to perform scrubbing (remove volumes with high motion)
      and/or remove non-steady-state volumes.
  
      .. versionadded:: 0.9.2
  
  design_matrices : pandas DataFrame or                           list of pandas DataFrames, default=None
      Design matrices that will be used to fit the GLM. If given it
      takes precedence over events and confounds.
  
  bins : int, default=100
      Maximum number of discrete bins for the AR coef histogram.
      If an autoregressive model with order greater than one is specified
      then adaptive quantification is performed and the coefficients
      will be clustered via K-means with `bins` number of clusters.
docstr_tok: ["Fit","the",":","term",":","`","GLM","`",".","For","each","run",":","1.","create","design","matrix","X","2.","do","a","masker","job",":","fMRI_data","-",">","Y","3.","fit","regression","to","(","Y",",","X",")","Parameters","--","--","--","--","--","run_imgs",":","Niimg-like","object","or","list","of","Niimg-like","objects",",","Data","on","which","the",":","term",":","`","GLM","`","will","be","fitted",".","If","this","is","a","list",",","the","affine","is","considered","the","same","for","all",".","events",":","pandas","Dataframe","or","string","or","list","of","pandas","DataFrames","or","strings",",","default=None",":","term",":","`","fMRI","`","events","used","to","build","design","matrices",".","One","events","object","expected","per","run_img",".","Ignored","in","case","designs","is","not","None",".","If","string",",","then","a","path","to","a","csv","file","is","expected",".","confounds",":","pandas","Dataframe",",","numpy","array","or","string","or","list","of","pandas","DataFrames",",","numpy","arrays","or","strings",",","default=None","Each","column","in","a","DataFrame","corresponds","to","a","confound","variable","to","be","included","in","the","regression","model","of","the","respective","run_img",".","The","number","of","rows","must","match","the","number","of","volumes","in","the","respective","run_img",".","Ignored","in","case","designs","is","not","None",".","If","string",",","then","a","path","to","a","csv","file","is","expected",".","sample_masks",":","array_like",",","or","list","of","array_like",",","default=None","shape","of","array",":","(","number","of","scans","-","number","of","volumes","remove",")","Indices","of","retained","volumes",".","Masks","the","niimgs","along","time\/fourth","dimension","to","perform","scrubbing","(","remove","volumes","with","high","motion",")","and\/or","remove","non-steady-state","volumes",".","..","versionadded",":",":","0.9.2","design_matrices",":","pandas","DataFrame","or","list","of","pandas","DataFrames",",","default=None","Design","matrices","that","will","be","used","to","fit","the","GLM",".","If","given","it","takes","precedence","over","events","and","confounds",".","bins",":","int",",","default=100","Maximum","number","of","discrete","bins","for","the","AR","coef","histogram",".","If","an","autoregressive","model","with","order","greater","than","one","is","specified","then","adaptive","quantification","is","performed","and","the","coefficients","will","be","clustered","via","K-means","with","`","bins","`","number","of","clusters","."]
code: def fit(
      self,
      run_imgs,
      events=None,
      confounds=None,
      sample_masks=None,
      design_matrices=None,
      bins=100,
  ):
      """Fit the :term:`GLM`.
  
          For each run:
          1. create design matrix X
          2. do a masker job: fMRI_data -> Y
          3. fit regression to (Y, X)
  
          Parameters
          ----------
          run_imgs : Niimg-like object or list of Niimg-like objects,
              Data on which the :term:`GLM` will be fitted. If this is a list,
              the affine is considered the same for all.
  
          events : pandas Dataframe or string or list of pandas DataFrames \
                   or strings, default=None
              :term:`fMRI` events used to build design matrices.
              One events object expected per run_img.
              Ignored in case designs is not None.
              If string, then a path to a csv file is expected.
  
          confounds : pandas Dataframe, numpy array or string or \
                      list of pandas DataFrames, numpy arrays or strings, \
                      default=None
              Each column in a DataFrame corresponds to a confound variable
              to be included in the regression model of the respective run_img.
              The number of rows must match the number of volumes in the
              respective run_img. Ignored in case designs is not None.
              If string, then a path to a csv file is expected.
  
          sample_masks : array_like, or list of array_like, default=None
              shape of array: (number of scans - number of volumes remove)
              Indices of retained volumes. Masks the niimgs along time/fourth
              dimension to perform scrubbing (remove volumes with high motion)
              and/or remove non-steady-state volumes.
  
              .. versionadded:: 0.9.2
  
          design_matrices : pandas DataFrame or \
                            list of pandas DataFrames, default=None
              Design matrices that will be used to fit the GLM. If given it
              takes precedence over events and confounds.
  
          bins : int, default=100
              Maximum number of discrete bins for the AR coef histogram.
              If an autoregressive model with order greater than one is specified
              then adaptive quantification is performed and the coefficients
              will be clustered via K-means with `bins` number of clusters.
  
          """
      # Initialize masker_ to None such that attribute exists
      self.masker_ = None
  
      # Raise a warning if both design_matrices and confounds are provided
      if design_matrices is not None and (
          confounds is not None or events is not None
      ):
          warn(
              "If design matrices are supplied, "
              "confounds and events will be ignored."
          )
      # Local import to prevent circular imports
      from nilearn.maskers import NiftiMasker
  
      # Check arguments
      # Check imgs type
      if events is not None:
          _check_events_file_uses_tab_separators(events_files=events)
      if not isinstance(run_imgs, (list, tuple)):
          run_imgs = [run_imgs]
      if design_matrices is None:
          if events is None:
              raise ValueError(
                  "events or design matrices must be provided"
              )
          if self.t_r is None:
              raise ValueError(
                  "t_r not given to FirstLevelModel object"
                  " to compute design from events"
              )
      else:
          design_matrices = _check_run_tables(
              run_imgs, design_matrices, "design_matrices"
          )
      # Check that number of events and confound files match number of runs
      # Also check that events and confound files can be loaded as DataFrame
      if events is not None:
          events = _check_run_tables(run_imgs, events, "events")
      if confounds is not None:
          confounds = _check_run_tables(
              run_imgs, confounds, "confounds"
          )
  
      if sample_masks is not None:
          sample_masks = check_run_sample_masks(
              len(run_imgs), sample_masks
          )
  
      # Learn the mask
      if self.mask_img is False:
          # We create a dummy mask to preserve functionality of api
          ref_img = check_niimg(run_imgs[0])
          self.mask_img = Nifti1Image(
              np.ones(ref_img.shape[:3]), ref_img.affine
          )
      if not isinstance(self.mask_img, NiftiMasker):
          self.masker_ = NiftiMasker(
              mask_img=self.mask_img,
              smoothing_fwhm=self.smoothing_fwhm,
              target_affine=self.target_affine,
              standardize=self.standardize,
              mask_strategy="epi",
              t_r=self.t_r,
              memory=self.memory,
              verbose=max(0, self.verbose - 2),
              target_shape=self.target_shape,
              memory_level=self.memory_level,
          )
          self.masker_.fit(run_imgs[0])
      else:
          # Make sure masker has been fitted otherwise no attribute mask_img_
          self.mask_img._check_fitted()
          if self.mask_img.mask_img_ is None and self.masker_ is None:
              self.masker_ = clone(self.mask_img)
              for param_name in [
                  "target_affine",
                  "target_shape",
                  "smoothing_fwhm",
                  "t_r",
                  "memory",
                  "memory_level",
              ]:
                  our_param = getattr(self, param_name)
                  if our_param is None:
                      continue
                  if getattr(self.masker_, param_name) is not None:
                      warn(
                          f"Parameter {param_name} of the masker overridden"
                      )
                  setattr(self.masker_, param_name, our_param)
              self.masker_.fit(run_imgs[0])
          else:
              self.masker_ = self.mask_img
  
      # For each run fit the model and keep only the regression results.
      self.labels_, self.results_, self.design_matrices_ = [], [], []
      n_runs = len(run_imgs)
      t0 = time.time()
      for run_idx, run_img in enumerate(run_imgs):
          # Report progress
          if self.verbose > 0:
              percent = float(run_idx) / n_runs
              percent = round(percent * 100, 2)
              dt = time.time() - t0
              # We use a max to avoid a division by zero
              if run_idx == 0:
                  remaining = "go take a coffee, a big one"
              else:
                  remaining = (
                      (100.0 - percent) / max(0.01, percent) * dt
                  )
                  remaining = f"{int(remaining)} seconds remaining"
  
              sys.stderr.write(
                  f"Computing run {run_idx + 1} "
                  f"out of {n_runs} runs ({remaining})\n"
              )
  
          # Build the experimental design for the glm
          run_img = check_niimg(run_img, ensure_ndim=4)
          if design_matrices is None:
              n_scans = get_data(run_img).shape[3]
              if confounds is not None:
                  confounds_matrix = confounds[run_idx].values
                  if confounds_matrix.shape[0] != n_scans:
                      raise ValueError(
                          "Rows in confounds does not match "
                          "n_scans in run_img "
                          f"at index {run_idx}."
                      )
                  confounds_names = confounds[run_idx].columns.tolist()
              else:
                  confounds_matrix = None
                  confounds_names = None
              start_time = self.slice_time_ref * self.t_r
              end_time = (n_scans - 1 + self.slice_time_ref) * self.t_r
              frame_times = np.linspace(start_time, end_time, n_scans)
              design = make_first_level_design_matrix(
                  frame_times,
                  events[run_idx],
                  self.hrf_model,
                  self.drift_model,
                  self.high_pass,
                  self.drift_order,
                  self.fir_delays,
                  confounds_matrix,
                  confounds_names,
                  self.min_onset,
              )
          else:
              design = design_matrices[run_idx]
  
          if sample_masks is not None:
              sample_mask = sample_masks[run_idx]
              design = design.iloc[sample_mask, :]
          else:
              sample_mask = None
  
          self.design_matrices_.append(design)
  
          # Mask and prepare data for GLM
          if self.verbose > 1:
              t_masking = time.time()
              sys.stderr.write("Starting masker computation \r")
  
          Y = self.masker_.transform(run_img, sample_mask=sample_mask)
          del run_img  # Delete unmasked image to save memory
  
          if self.verbose > 1:
              t_masking = time.time() - t_masking
              sys.stderr.write(
                  f"Masker took {int(t_masking)} seconds       \n"
              )
  
          if self.signal_scaling is not False:
              Y, _ = mean_scaling(Y, self.signal_scaling)
          if self.memory:
              mem_glm = self.memory.cache(run_glm, ignore=["n_jobs"])
          else:
              mem_glm = run_glm
  
          # compute GLM
          if self.verbose > 1:
              t_glm = time.time()
              sys.stderr.write("Performing GLM computation\r")
          labels, results = mem_glm(
              Y,
              design.values,
              noise_model=self.noise_model,
              bins=bins,
              n_jobs=self.n_jobs,
              random_state=self.random_state,
          )
          if self.verbose > 1:
              t_glm = time.time() - t_glm
              sys.stderr.write(
                  f"GLM took {int(t_glm)} seconds         \n"
              )
  
          self.labels_.append(labels)
          # We save memory if inspecting model details is not necessary
          if self.minimize_memory:
              for key in results:
                  results[key] = SimpleRegressionResults(results[key])
          self.results_.append(results)
          del Y
  
      # Report progress
      if self.verbose > 0:
          sys.stderr.write(
              f"\nComputation of {n_runs} runs done "
              f"in {time.time() - t0} seconds.\n\n"
          )
      return self
  
imports: from __future__ import annotations
  import csv
  import glob
  import os
  import sys
  import time
  from pathlib import Path
  from warnings import warn
  import numpy
  import pandas
  from joblib import Memory, Parallel, delayed
  from nibabel import Nifti1Image
  from sklearn.base import clone
  from sklearn.cluster import KMeans
  from nilearn._utils import fill_doc, stringify_path
  from nilearn._utils.niimg_conversions import check_niimg
  from nilearn._utils.param_validation import check_run_sample_masks
  from nilearn.glm._base import BaseGLM
  from nilearn.glm.contrasts import compute_fixed_effect_contrast, expression_to_contrast_vector
  from nilearn.glm.first_level.design_matrix import make_first_level_design_matrix
  from nilearn.glm.regression import ARModel, OLSModel, RegressionResults, SimpleRegressionResults
  from nilearn.image import get_data
  from nilearn.interfaces.bids import get_bids_files, parse_bids_filename
  from nilearn.interfaces.bids.query import infer_repetition_time_from_dataset, infer_slice_timing_start_time_from_dataset
  from nilearn.interfaces.bids.utils import bids_entities, check_bids_label
  from nilearn.interfaces.fmriprep.load_confounds import load_confounds
label_desc: Use image node_id 3 for calling the FirstLevelModel obj's underlying member method code with example usage: obj.fit(run_imgs, events, confounds, sample_masks, design_matrices, bins) and returns: self