code: def first_level_from_bids(
      dataset_path,
      task_label,
      space_label=None,
      sub_labels=None,
      img_filters=None,
      t_r=None,
      slice_time_ref=0.0,
      hrf_model="glover",
      drift_model="cosine",
      high_pass=0.01,
      drift_order=1,
      fir_delays=[0],
      min_onset=-24,
      mask_img=None,
      target_affine=None,
      target_shape=None,
      smoothing_fwhm=None,
      memory=Memory(None),
      memory_level=1,
      standardize=False,
      signal_scaling=0,
      noise_model="ar1",
      verbose=0,
      n_jobs=1,
      minimize_memory=True,
      derivatives_folder="derivatives",
      **kwargs,
  ):
      """Create FirstLevelModel objects and fit arguments \
         from a :term:`BIDS` dataset.
  
      If ``t_r`` is ``None`` this function will attempt
      to load it from a bold.json.
      If ``slice_time_ref`` is  `None` this function will attempt
      to infer it from a bold.json.
      Otherwise ``t_r`` and ``slice_time_ref`` are taken as given,
      but a warning may be raised if they are not consistent with the bold.json.
  
      Parameters
      ----------
      dataset_path : :obj:`str` or :obj:`pathlib.Path`
          Directory of the highest level folder of the :term:`BIDS` dataset.
          Should contain subject folders and a derivatives folder.
  
      task_label : :obj:`str`
          Task_label as specified in the file names like _task-<task_label>_.
  
      space_label : :obj:`str`, optional
          Specifies the space label of the preprocessed bold.nii images.
          As they are specified in the file names like _space-<space_label>_.
  
      sub_labels : :obj:`list` of :obj:`str`, optional
          Specifies the subset of subject labels to model.
          If 'None', will model all subjects in the dataset.
  
          .. versionadded:: 0.10.1
  
      img_filters : :obj:`list` of :obj:`tuple` (str, str), optional
          Filters are of the form (field, label). Only one filter per field
          allowed.
          A file that does not match a filter will be discarded.
          Possible filters are 'acq', 'ce', 'dir', 'rec', 'run', 'echo', 'res',
          'den', and 'desc'.
          Filter examples would be ('desc', 'preproc'), ('dir', 'pa')
          and ('run', '10').
  
      slice_time_ref : :obj:`float` between 0.0 and 1.0, default=0.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 (time repetition), so it can have
          values between 0. and 1.
  
          .. deprecated:: 0.10.1
  
              The default=0 for ``slice_time_ref`` will be deprecated.
              The default value will change to 'None' in 0.12.
  
      derivatives_folder : :obj:`str`, default="derivatives".
          derivatives and app folder path containing preprocessed files.
          Like "derivatives/FMRIPREP".
  
      All other parameters correspond to a `FirstLevelModel` object, which
      contains their documentation.
      The subject label of the model will be determined directly
      from the :term:`BIDS` dataset.
  
      kwargs: :obj:`dict`
  
          .. versionadded:: 0.11.0
  
      Keyword arguments to be passed to functions called within this function.
  
      Kwargs prefixed with ``confound_``
      will be passed to :func:`~nilearn.interfaces.fmriprep.load_confounds`.
      This allows ``first_level_from_bids`` to return
      a specific set of confounds by relying on confound loading strategies
      defined in :func:`~nilearn.interfaces.fmriprep.load_confounds`.
      If no kwargs are passed, ``first_level_from_bids`` will return
      all the confounds available in the confounds TSV files.
  
      Examples
      --------
      If you want to only load
      the rotation and translation motion parameters confounds:
  
      .. code-block:: python
  
          models, imgs, events, confounds = first_level_from_bids(
              dataset_path=path_to_a_bids_dataset,
              task_label="TaskName",
              space_label="MNI",
              img_filters=[("desc", "preproc")],
              confounds_strategy=("motion"),
              confounds_motion="basic",
          )
  
      If you want to load the motion parameters confounds
      with their derivatives:
  
      .. code-block:: python
  
          models, imgs, events, confounds = first_level_from_bids(
              dataset_path=path_to_a_bids_dataset,
              task_label="TaskName",
              space_label="MNI",
              img_filters=[("desc", "preproc")],
              confounds_strategy=("motion"),
              confounds_motion="derivatives",
          )
  
      If you additionally want to load
      the confounds with CSF and white matter signal:
  
      .. code-block:: python
  
          models, imgs, events, confounds = first_level_from_bids(
              dataset_path=path_to_a_bids_dataset,
              task_label="TaskName",
              space_label="MNI",
              img_filters=[("desc", "preproc")],
              confounds_strategy=("motion", "wm_csf"),
              confounds_motion="derivatives",
              confounds_wm_csf="basic",
          )
  
      If you also want to scrub high-motion timepoints:
  
      .. code-block:: python
  
          models, imgs, events, confounds = first_level_from_bids(
              dataset_path=path_to_a_bids_dataset,
              task_label="TaskName",
              space_label="MNI",
              img_filters=[("desc", "preproc")],
              confounds_strategy=("motion", "wm_csf", "scrub"),
              confounds_motion="derivatives",
              confounds_wm_csf="basic",
              confounds_scrub=1,
              confounds_fd_threshold=0.2,
              confounds_std_dvars_threshold=0,
          )
  
      Please refer to the documentation
      of :func:`~nilearn.interfaces.fmriprep.load_confounds`
      for more details on the confounds loading strategies.
  
      Returns
      -------
      models : list of `FirstLevelModel` objects
          Each FirstLevelModel object corresponds to a subject.
          All runs from different sessions are considered together
          for the same subject to run a fixed effects analysis on them.
  
      models_run_imgs : list of list of Niimg-like objects,
          Items for the FirstLevelModel fit function of their respective model.
  
      models_events : list of list of pandas DataFrames,
          Items for the FirstLevelModel fit function of their respective model.
  
      models_confounds : list of list of pandas DataFrames or None,
          Items for the FirstLevelModel fit function of their respective model.
  
      """
      if slice_time_ref == 0:
          warn(
              "Starting in version 0.12, slice_time_ref will default to None.",
              DeprecationWarning,
          )
  
      sub_labels = sub_labels or []
      img_filters = img_filters or []
  
      _check_args_first_level_from_bids(
          dataset_path=dataset_path,
          task_label=task_label,
          space_label=space_label,
          sub_labels=sub_labels,
          img_filters=img_filters,
          derivatives_folder=derivatives_folder,
      )
  
      kwargs_load_confounds = _check_kwargs_load_confounds(**kwargs)
  
      if drift_model is not None and kwargs_load_confounds is not None:
          if "high_pass" in kwargs_load_confounds.get("strategy"):
              if drift_model == "cosine":
                  verb = "duplicate"
              if drift_model == "polynomial":
                  verb = "conflict with"
  
              warn(
                  f"""Confounds will contain a high pass filter,
   that may {verb} the {drift_model} one used in the model.
   Remember to visualize your design matrix before fitting your model
   to check that your model is not overspecified.""",
                  UserWarning,
              )
  
      derivatives_path = Path(dataset_path) / derivatives_folder
  
      # Get metadata for models.
      #
      # We do it once and assume all subjects and runs
      # have the same value.
  
      # Repetition time
      #
      # Try to find a t_r value in the bids datasets
      # If the parameter information is not found in the derivatives folder,
      # a search is done in the raw data folder.
      filters = _make_bids_files_filter(
          task_label=task_label,
          space_label=space_label,
          supported_filters=[
              *bids_entities()["raw"],
              *bids_entities()["derivatives"],
          ],
          extra_filter=img_filters,
          verbose=verbose,
      )
      inferred_t_r = infer_repetition_time_from_dataset(
          bids_path=derivatives_path, filters=filters, verbose=verbose
      )
      if inferred_t_r is None:
          filters = _make_bids_files_filter(
              task_label=task_label,
              supported_filters=[*bids_entities()["raw"]],
              extra_filter=img_filters,
              verbose=verbose,
          )
          inferred_t_r = infer_repetition_time_from_dataset(
              bids_path=dataset_path, filters=filters, verbose=verbose
          )
  
      if t_r is None and inferred_t_r is not None:
          t_r = inferred_t_r
      if t_r is not None and t_r != inferred_t_r:
          warn(
              f"'t_r' provided ({t_r}) is different "
              f"from the value found in the BIDS dataset ({inferred_t_r}).\n"
              "Note this may lead to the wrong model specification."
          )
      if t_r is not None:
          _check_repetition_time(t_r)
      else:
          warn(
              "'t_r' not provided and cannot be inferred from BIDS metadata.\n"
              "It will need to be set manually in the list of models, "
              "otherwise their fit will throw an exception."
          )
  
      # Slice time correction reference time
      #
      # Try to infer a slice_time_ref value in the bids derivatives dataset.
      #
      # If no value can be inferred, the default value of 0.0 is used.
      filters = _make_bids_files_filter(
          task_label=task_label,
          space_label=space_label,
          supported_filters=[
              *bids_entities()["raw"],
              *bids_entities()["derivatives"],
          ],
          extra_filter=img_filters,
          verbose=verbose,
      )
      StartTime = infer_slice_timing_start_time_from_dataset(
          bids_path=derivatives_path, filters=filters, verbose=verbose
      )
      if StartTime is not None and t_r is not None:
          assert StartTime < t_r
          inferred_slice_time_ref = StartTime / t_r
      else:
          if slice_time_ref is None:
              warn(
                  "'slice_time_ref' not provided "
                  "and cannot be inferred from metadata.\n"
                  "It will be assumed that the slice timing reference "
                  "is 0.0 percent of the repetition time.\n"
                  "If it is not the case it will need to "
                  "be set manually in the generated list of models."
              )
          inferred_slice_time_ref = 0.0
  
      if slice_time_ref is None and inferred_slice_time_ref is not None:
          slice_time_ref = inferred_slice_time_ref
      if (
          slice_time_ref is not None
          and slice_time_ref != inferred_slice_time_ref
      ):
          warn(
              f"'slice_time_ref' provided ({slice_time_ref}) is different "
              f"from the value found in the BIDS dataset "
              f"({inferred_slice_time_ref}).\n"
              "Note this may lead to the wrong model specification."
          )
      if slice_time_ref is not None:
          _check_slice_time_ref(slice_time_ref)
  
      # Build fit_kwargs dictionaries to pass to their respective models fit
      # Events and confounds files must match number of imgs (runs)
      models = []
      models_run_imgs = []
      models_events = []
      models_confounds = []
  
      sub_labels = _list_valid_subjects(derivatives_path, sub_labels)
      for sub_label_ in sub_labels:
          # Create model
          model = FirstLevelModel(
              t_r=t_r,
              slice_time_ref=slice_time_ref,
              hrf_model=hrf_model,
              drift_model=drift_model,
              high_pass=high_pass,
              drift_order=drift_order,
              fir_delays=fir_delays,
              min_onset=min_onset,
              mask_img=mask_img,
              target_affine=target_affine,
              target_shape=target_shape,
              smoothing_fwhm=smoothing_fwhm,
              memory=memory,
              memory_level=memory_level,
              standardize=standardize,
              signal_scaling=signal_scaling,
              noise_model=noise_model,
              verbose=verbose,
              n_jobs=n_jobs,
              minimize_memory=minimize_memory,
              subject_label=sub_label_,
          )
          models.append(model)
  
          imgs = _get_processed_imgs(
              derivatives_path=derivatives_path,
              sub_label=sub_label_,
              task_label=task_label,
              space_label=space_label,
              img_filters=img_filters,
              verbose=verbose,
          )
          models_run_imgs.append(imgs)
  
          events = _get_events_files(
              dataset_path=dataset_path,
              sub_label=sub_label_,
              task_label=task_label,
              img_filters=img_filters,
              imgs=imgs,
              verbose=verbose,
          )
          events = [
              pd.read_csv(event, sep="\t", index_col=None)
              for event in events
          ]
          models_events.append(events)
  
          confounds = _get_confounds(
              derivatives_path=derivatives_path,
              sub_label=sub_label_,
              task_label=task_label,
              img_filters=img_filters,
              imgs=imgs,
              verbose=verbose,
              kwargs_load_confounds=kwargs_load_confounds,
          )
          models_confounds.append(confounds)
  
      return models, models_run_imgs, models_events, models_confounds
  
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 13 for calling a global function with example usage: first_level_from_bids(dataset_path, task_label, space_label, sub_labels, img_filters, t_r, slice_time_ref, hrf_model, drift_model, high_pass, drift_order, fir_delays, min_onset, mask_img, target_affine, target_shape, smoothing_fwhm, memory, memory_level, standardize, signal_scaling, noise_model, verbose, n_jobs, minimize_memory, derivatives_folder) and returns: models,  models_run_imgs,  models_events,  models_confounds