code: def test_brain_init(
      renderer_pyvistaqt, tmp_path, pixel_ratio, brain_gc
  ):
      """Test initialization of the Brain instance."""
  
      class FakeSTC(_BaseSourceEstimate):
          def __init__(self):
              pass
  
      hemi = "lh"
      surf = "inflated"
      cortex = "low_contrast"
      title = "test"
      size = (300, 300)
  
      kwargs = dict(subject=subject, subjects_dir=subjects_dir)
      with pytest.raises(ValueError, match='"size" parameter must be'):
          Brain(hemi=hemi, surf=surf, size=[1, 2, 3], **kwargs)
      with pytest.raises(ValueError, match=".*hemi.*Allowed values.*"):
          Brain(hemi="foo", surf=surf, **kwargs)
      with pytest.raises(ValueError, match=".*view.*Allowed values.*"):
          Brain(hemi="lh", surf=surf, views="foo", **kwargs)
      with pytest.raises(TypeError, match="figure"):
          Brain(hemi=hemi, surf=surf, figure="foo", **kwargs)
      with pytest.raises(TypeError, match="interaction"):
          Brain(hemi=hemi, surf=surf, interaction=0, **kwargs)
      with pytest.raises(ValueError, match="interaction"):
          Brain(hemi=hemi, surf=surf, interaction="foo", **kwargs)
      with pytest.raises(FileNotFoundError, match=r"lh\.whatever"):
          Brain(hemi="lh", surf="whatever", **kwargs)
      with pytest.raises(ValueError, match="`surf` cannot be seghead"):
          Brain(hemi="lh", surf="seghead", **kwargs)
      with pytest.raises(ValueError, match="RGB argument"):
          Brain("sample", cortex="badcolor")
      # test no surfaces
      with pytest.raises(
          TypeError, match="missing 1 required positional"
      ):
          Brain()
      renderer_pyvistaqt.backend._close_all()
  
      brain = Brain(
          hemi=hemi,
          surf=surf,
          size=size,
          title=title,
          cortex=cortex,
          units="m",
          silhouette=dict(decimate=0.95),
          **kwargs,
      )
      assert "data" not in brain._actors
      with pytest.raises(TypeError, match="not supported"):
          brain._check_stc(hemi="lh", array=FakeSTC(), vertices=None)
      with pytest.raises(ValueError, match="add_data"):
          brain.setup_time_viewer(time_viewer=True)
      brain._hemi = "foo"  # for testing: hemis
      with pytest.raises(ValueError, match="not be None"):
          brain._check_hemi(hemi=None)
      with pytest.raises(ValueError, match="Invalid.*hemi.*Allowed"):
          brain._check_hemi(hemi="foo")
      brain._hemi = hemi  # end testing: hemis
      with pytest.raises(ValueError, match="bool or positive"):
          brain._to_borders(None, None, "foo")
      assert brain.interaction == "trackball"
      # add_data
      stc = read_source_estimate(fname_stc)
      fmin = stc.data.min()
      fmax = stc.data.max()
      for h in brain._hemis:
          if h == "lh":
              hi = 0
          else:
              hi = 1
          hemi_data = stc.data[: len(stc.vertices[hi]), 10]
          hemi_vertices = stc.vertices[hi]
  
          with pytest.raises(TypeError, match="scale_factor"):
              brain.add_data(hemi_data, hemi=h, scale_factor="foo")
          with pytest.raises(TypeError, match="vector_alpha"):
              brain.add_data(hemi_data, hemi=h, vector_alpha="foo")
          with pytest.raises(ValueError, match="thresh"):
              brain.add_data(hemi_data, hemi=h, thresh=-1)
          with pytest.raises(ValueError, match="remove_existing"):
              brain.add_data(hemi_data, hemi=h, remove_existing=-1)
          with pytest.raises(ValueError, match="time_label_size"):
              brain.add_data(
                  hemi_data,
                  hemi=h,
                  time_label_size=-1,
                  vertices=hemi_vertices,
              )
          with pytest.raises(ValueError, match="is positive"):
              brain.add_data(
                  hemi_data,
                  hemi=h,
                  smoothing_steps=-1,
                  vertices=hemi_vertices,
              )
          with pytest.raises(TypeError, match="int or NoneType"):
              brain.add_data(hemi_data, hemi=h, smoothing_steps="foo")
          with pytest.raises(ValueError, match="dimension mismatch"):
              brain.add_data(
                  array=np.array([0, 1, 2]),
                  hemi=h,
                  vertices=hemi_vertices,
              )
          with pytest.raises(
              ValueError, match="vertices parameter must not be"
          ):
              brain.add_data(
                  hemi_data,
                  fmin=fmin,
                  hemi=hemi,
                  fmax=fmax,
                  vertices=None,
              )
          with pytest.raises(ValueError, match="has shape"):
              brain.add_data(
                  hemi_data[:, np.newaxis],
                  fmin=fmin,
                  hemi=hemi,
                  fmax=fmax,
                  vertices=None,
                  time=[0, 1],
              )
  
          brain.add_data(
              hemi_data,
              fmin=fmin,
              hemi=h,
              fmax=fmax,
              colormap="hot",
              vertices=hemi_vertices,
              smoothing_steps="nearest",
              colorbar=(0, 0),
              time=None,
          )
          with pytest.raises(
              ValueError, match="brain has no defined times"
          ):
              brain.set_time(0.0)
          assert brain.data["lh"]["array"] is hemi_data
          assert brain.views == ["lateral"]
          assert brain.hemis == ("lh",)
          brain.add_data(
              hemi_data[:, np.newaxis],
              fmin=fmin,
              hemi=h,
              fmax=fmax,
              colormap="hot",
              vertices=hemi_vertices,
              smoothing_steps=1,
              initial_time=0.0,
              colorbar=False,
              time=[0],
          )
          with pytest.raises(
              ValueError, match="the range of available times"
          ):
              brain.set_time(7.0)
          brain.set_time(0.0)
          brain.set_time_point(0)  # should hit _safe_interp1d
  
          with pytest.raises(ValueError, match="consistent with"):
              brain.add_data(
                  hemi_data[:, np.newaxis],
                  fmin=fmin,
                  hemi=h,
                  fmax=fmax,
                  colormap="hot",
                  vertices=hemi_vertices,
                  smoothing_steps="nearest",
                  colorbar=False,
                  time=[1],
              )
          with pytest.raises(ValueError, match="different from"):
              brain.add_data(
                  hemi_data[:, np.newaxis][:, [0, 0]],
                  fmin=fmin,
                  hemi=h,
                  fmax=fmax,
                  colormap="hot",
                  vertices=hemi_vertices,
              )
          with pytest.raises(ValueError, match="need shape"):
              brain.add_data(
                  hemi_data[:, np.newaxis],
                  time=[0, 1],
                  fmin=fmin,
                  hemi=h,
                  fmax=fmax,
                  colormap="hot",
                  vertices=hemi_vertices,
              )
          with pytest.raises(ValueError, match="If array has 3"):
              brain.add_data(
                  hemi_data[:, np.newaxis, np.newaxis],
                  fmin=fmin,
                  hemi=h,
                  fmax=fmax,
                  colormap="hot",
                  vertices=hemi_vertices,
              )
      assert len(brain._actors["data"]) == 4
      brain.remove_data()
      assert "data" not in brain._actors
      assert "time_change" not in ui_events._get_event_channel(brain)
  
      # add label
      label = read_label(fname_label)
      with pytest.raises(ValueError, match="not a filename"):
          brain.add_label(0)
      with pytest.raises(ValueError, match="does not exist"):
          brain.add_label("foo", subdir="bar")
      label.name = None  # test unnamed label
      brain.add_label(label, scalar_thresh=0.0, color="green")
      assert isinstance(brain.labels[label.hemi], list)
      overlays = brain._layered_meshes[label.hemi]._overlays
      assert "unnamed0" in overlays
      assert np.allclose(
          overlays["unnamed0"]._colormap[0], [0, 0, 0, 0]
      )  # first component is transparent
      assert np.allclose(
          overlays["unnamed0"]._colormap[1], [0, 128, 0, 255]
      )  # second is green
      brain.remove_labels()
      assert "unnamed0" not in overlays
      brain.add_label(str(fname_label))
      brain.add_label("V1", borders=True)
      brain.remove_labels()
      brain.remove_labels()
  
      # add foci
      brain.add_foci([0], coords_as_verts=True, hemi=hemi, color="blue")
  
      # add head and skull
      brain.add_head(color="red", alpha=0.1)
      brain.remove_head()
      brain.add_skull(outer=True, color="green", alpha=0.1)
      brain.remove_skull()
  
      # add volume labels
      plotargs = {
          "bcolor": (0.5, 0.5, 0.5),
          "border": False,
          "size": (0.2, 0.6),
          "loc": "upper left",
      }
      brain.add_volume_labels(
          aseg="aseg",
          labels=("Brain-Stem", "Left-Hippocampus", "Left-Amygdala"),
          legend=plotargs,
      )
      brain.remove_volume_labels()
  
      # add sensors
      info = read_info(fname_raw_testing)
      brain.add_sensors(info, trans=fname_trans)
      for kind in (
          "meg",
          "eeg",
          "fnirs",
          "ecog",
          "seeg",
          "dbs",
          "helmet",
      ):
          brain.remove_sensors(kind)
      brain.add_sensors(info, trans=fname_trans)
      brain.remove_sensors()
  
      info["chs"][0]["coord_frame"] = 99
      with pytest.raises(
          RuntimeError, match='must be "meg", "head" or "mri"'
      ):
          brain.add_sensors(info, trans=fname_trans)
      brain.close()
  
      # test sEEG projection onto inflated
      # make temp path to fake pial surface
      os.makedirs(tmp_path / subject / "surf", exist_ok=True)
      for hemi in ("lh", "rh"):
          # fake white surface for pial, and no .curv file
          copyfile(
              subjects_dir / subject / "surf" / f"{hemi}.white",
              tmp_path / subject / "surf" / f"{hemi}.pial",
          )
          copyfile(
              subjects_dir / subject / "surf" / f"{hemi}.inflated",
              tmp_path / subject / "surf" / f"{hemi}.inflated",
          )
      brain = Brain(
          hemi=hemi,
          surf=surf,
          size=size,
          title=title,
          cortex=cortex,
          units="m",
          subject=subject,
          subjects_dir=tmp_path,
      )
      proj_info = create_info(
          [f"Ch{i}" for i in range(1, 7)], 1000, "seeg"
      )
      pos = (
          np.array(
              [
                  [25.85, 9.04, -5.38],
                  [33.56, 9.04, -5.63],
                  [40.44, 9.04, -5.06],
                  [46.75, 9.04, -6.78],
                  [-30.08, 9.04, 28.23],
                  [-32.95, 9.04, 37.99],
                  [-36.39, 9.04, 46.03],
              ]
          )
          / 1000
      )
      proj_info.set_montage(
          make_dig_montage(
              ch_pos=dict(zip(proj_info.ch_names, pos)),
              coord_frame="head",
          )
      )
      brain.add_sensors(proj_info, trans=fname_trans)
      brain._subjects_dir = subjects_dir  # put back
  
      # add dipole
      dip = Dipole(
          times=[0],
          pos=[[-0.06439933, 0.00733009, 0.06280205]],
          amplitude=[3e-8],
          ori=[[0, 1, 0]],
          gof=50,
      )
      brain.add_dipole(
          dip, fname_trans, colors="blue", scales=5, alpha=0.5
      )
      brain.remove_dipole()
  
      with pytest.raises(ValueError, match="The number of colors"):
          brain.add_dipole(dip, fname_trans, colors=["red", "blue"])
  
      with pytest.raises(ValueError, match="The number of scales"):
          brain.add_dipole(dip, fname_trans, scales=[1, 2])
  
      fwd = read_forward_solution(fname_fwd)
      brain.add_forward(fwd, fname_trans, alpha=0.5, scale=10)
      brain.remove_forward()
  
      # fake incorrect coordinate frame
      fwd["coord_frame"] = 99
      with pytest.raises(RuntimeError, match='must be "head" or "mri"'):
          brain.add_forward(fwd, fname_trans)
      fwd["coord_frame"] = 2003
      with pytest.raises(RuntimeError, match='must be "head" or "mri"'):
          brain.add_forward(fwd, fname_trans)
  
      # add text
      brain.add_text(x=0, y=0, text="foo")
      with pytest.raises(ValueError, match="already exists"):
          brain.add_text(x=0, y=0, text="foo")
      brain.remove_text("foo")
      brain.add_text(x=0, y=0, text="foo")
      brain.remove_text()
  
      brain.close()
  
      # add annotation
      annots = [
          "aparc",
          subjects_dir
          / "fsaverage"
          / "label"
          / "lh.PALS_B12_Lobes.annot",
      ]
      borders = [True, 2]
      alphas = [1, 0.5]
      colors = [None, "r"]
      brain = Brain(
          subject="fsaverage",
          hemi="both",
          size=size,
          surf="inflated",
          subjects_dir=subjects_dir,
      )
      with pytest.raises(ValueError, match="does not exist"):
          brain.add_annotation("foo")
      brain.add_annotation(annots[1])
      brain.close()
      brain = Brain(
          subject="fsaverage",
          hemi=hemi,
          size=size,
          surf="inflated",
          subjects_dir=subjects_dir,
      )
      for a, b, p, color in zip(annots, borders, alphas, colors):
          brain.add_annotation(str(a), b, p, color=color)
      brain.close()
  
imports: import os
  import platform
  from pathlib import Path
  from shutil import copyfile
  import numpy
  import pytest
  from matplotlib import image
  from matplotlib.lines import Line2D
  from numpy.testing import assert_allclose, assert_array_equal
  from mne import Dipole, MixedSourceEstimate, SourceEstimate, VolSourceEstimate, create_info, pick_types_forward, read_cov, read_evokeds, read_forward_solution, read_source_estimate, vertex_to_mni, write_surface
  from mne.channels import make_dig_montage
  from mne.datasets import testing
  from mne.io import read_info
  from mne.label import read_label
  from mne.minimum_norm import apply_inverse, make_inverse_operator
  from mne.source_estimate import _BaseSourceEstimate
  from mne.source_space import read_source_spaces, setup_volume_source_space
  from mne.utils import check_version
  from mne.viz import ui_events
  from mne.viz._brain import Brain, _BrainScraper, _LayeredMesh, _LinkViewer
  from mne.viz._brain.colormap import calculate_lut
  from mne.viz.utils import _get_cmap
label_desc: Use image node_id 5 for calling a global function with example usage: test_brain_init(renderer_pyvistaqt, tmp_path, pixel_ratio, brain_gc) without return types