events should be a NumPy array of integers, got numpy.ndarray

Hello,
So I’ve been working on ERP extraction, specifically the N200 ERP. I’m getting an error events should be a numpy array of integers, got numpy.ndarray. I’m not able to figure out where this error is coming from and how to resolve it.
Could someone please help me understand this?

Welcome to the Forum Pari.

Can you provide a code snippet, that shows where you encounter this error?

Thank you.

Carina

1 Like

Thank you for responding! Sure, its either in the mne_find.events( marked by a breakpoint) or in the epochs line (second SS, again marked by breakpoint)

Hello, please always share code and trackbacks as text (marked as “preformatted text” using the respective toolbar button in the editor). Screenshots are extremely difficult to work with and are not searchable. Thanks.

Also it seems important bits of the traceback are missing, I’m failing to find the line that actually yields that error in MNE?

Please share what events and cleaned_events look like. Thanks!

Richard

I’m sorry, this is the first time I’ve shared something on a support forum so I’m not familiar with the decorum. However, the traceback is as its seen in the screenshot. Even I’m having trouble in finding the line that’s causing the error.
here’s my cleaned_events function:

def clean_events(self, events):
      event_ids_reversed = self.exp_info["event_ids_reversed"]
      stimuli = self.exp_info["stimuli"]
      event_ids = self.exp_info["event_ids"]
      samp_freq = self.exp_info["sfreq"]

      df_events = pd.DataFrame(events, columns=["sample_nb", "stim_ch_val", "event_id"])

      # * convert sample nb into event onset time in seconds *
      event_time = df_events["sample_nb"] / samp_freq

      # df_events.insert(0, 'session', [sess_name] * len(events))
      df_events.insert(3, "event_time", event_time)

      # * replace event ID number by event name *
      df_events["event_id"].replace(to_replace=event_ids_reversed, inplace=True)

      df_trials = self.identify_trials(df_events)
      df_trials["RT"] = self.get_RTs(df_trials)

      # * Remove unwanted events and keep trial level data only *
      """ 1 trial = stim -> resp -> feedback  
          Unwanted events = Prepare, Rest, etc. """

      # * Select stimulus onset for each trial *
      cleaned_events = df_trials.query(f"event_id in {stimuli}").copy()

      # * Rename event IDs to their original number-coded format *
      cleaned_events["event_id"].replace(to_replace=event_ids, inplace=True)

      # * Convert to MNE events format *
      cleaned_events = cleaned_events[["sample_nb", "stim_ch_val", "event_id"]].to_numpy()

      return cleaned_events, df_trials

There’s no specific events function, however here;s the code wherein the events, epochs and extraction is defined:

def individual_analysis(subj_fpath):
            subj_nb = subj_fpath.parent.name
            sess_name = f"subj{subj_nb}-" + re.findall(r"\d", subj_fpath.name)[0]

            # ! =========================== PREPROCESSING =============================
            print(steps["Analyzing"] % sess_name) if verbose else None
            # * .bdf file containig EEG data and events *
            # bdf_f = bdf_files[sess_name] # ! OLD
            # eeg_file = bdf_files[sess_name]

            # * .elp file containing head montage information *
            # elp_f = elp_files[sess_name[:-2]] # ! OLD

            ch_pos_file = {f.parent.name: f for f in self.channel_pos_files}[subj_nb]

            # raw = mne.io.read_raw_bdf(bdf_f, preload=True, verbose=False)
            raw = mne.io.read_raw_bdf(subj_fpath, preload=True, verbose=False)

            # subj_info = subj_info_dict[int(sess_name[5:7])] # ! OLD
            subj_info = self.subj_info[subj_nb]

            if subj_info["bad_ch"]:
                raw.info["bads"].extend(subj_info["bad_ch"])

            print(steps.get("Montage")) if verbose else None

            # * Set up head montage and save the figures
            montage = self.get_montage(subj_fpath)
            raw.set_montage(montage)

            # * Detect events in raw EEG data
            events = mne.find_events(
                raw, stim_channel="Status", shortest_event=1, initial_event=True, verbose=False
            )
            # * Average Reference *
            print(steps.get("Averaging")) if verbose else None
            raw.set_eeg_reference(ref_channels="average")

            # * Bipolar Reference for EOG detection*
            print(steps.get("Bipolar Ref", "")) if verbose else None

            anode, cathode = self.exp_info["bipolar_ref"]

            # * Plot electrodes used for bipolar_ref in 3D *
            raw.plot_sensors(
                kind="3d",
                ch_type=None,
                title=sess_name[:-2],
                show_names=[anode, cathode],
                ch_groups="position",
                block=False,
                show=False,
            )

            f_name = sess_name + "_Sim-EOG.png"
            plt.savefig(self.paths.montage / f_name, dpi=self.plotting_params["dpi"])
            plt.close()

            # * Set up a simulated EOG channel *
            mne.set_bipolar_reference(
                raw,
                anode,
                cathode,
                ch_name="sim_EOG",
                ch_info=None,
                drop_refs=True,
                copy=False,
                verbose=False,
            )

            raw.set_channel_types({"sim_EOG": "eog"}, verbose=False)

            # * Bandpass Filter: 0.1 - 100 Hz *
            print(steps.get("Bandpass1")) if verbose else None
            raw.filter(l_freq=0.1, h_freq=100, verbose=verbose)

            # * EOG artifact rejection using ICA *

            print(steps.get("ICA1_1")) if verbose else None
            # if ica_f:
            #     ica = mne.preprocessing.read_ica(ica_f)

            if (ica_f := self.paths.ica / f"{sess_name}_fitted-ica.fif").is_file():
                ica = mne.preprocessing.read_ica(ica_f)

            else:
                print(steps.get("ICA1_2")) if verbose else None
                ica = mne.preprocessing.ICA(
                    n_components=0.999999,
                    noise_cov=None,
                    random_state=self.seed,
                    method="fastica",
                    max_iter="auto",
                )
                ica.fit(raw)

                f_name = sess_name + "_fitted-ica.fif"
                ica.save(self.paths.ica / f_name)

            eog_inds, eog_scores = ica.find_bads_eog(raw, ch_name="sim_EOG")

            print(steps.get("EOG_ids") % eog_inds) if verbose else None

            ica.exclude = eog_inds

            print(steps.get("ICA2")) if verbose else None
            raw = ica.apply(raw)

            #! COMMENTED OUT 21/08/2022

            # data[sess_name]['rejections']['ICA_excluded'] = eog_inds

            # data[sess_name]['ICA_applied'] = raw.copy()

            # * barplot of ICA component "EOG match" scores
            # plt.figure()
            # ica.plot_scores(eog_scores, show=False)
            # ica.plot_sources(raw, show_scrollbars=False)
            # ica.plot_components(picks=[i for i in range(10)])
            # plt.show(block=False)
            # plt.close('all')

            # * plot diagnostics
            # ica.plot_properties(raw, picks=eog_inds)

            # * plot ICs applied to raw data, with EOG matches highlighted
            # ica.plot_sources(raw, show_scrollbars=False)

            # * plot ICs applied to the averaged EOG epochs, with EOG matches highlighted
            # ica.plot_sources(eog_evoked)

            #! COMMENTED OUT 21/08/2022

            # * Bandpass Filter: 1 - 10 Hz *
            print(steps.get("Bandpass2")) if verbose else None

            raw.filter(l_freq=1, h_freq=10, verbose=verbose)

            # ! =========================== EVENT CLEANING ============================

            print(steps.get("cleaning_events")) if verbose else None

            cleaned_events, df_trials = self.clean_events(events)

            # # * Convert to MNE events format *
            # cleaned_events = cleaned_events[["sample_nb", "stim_ch_val", "event_id"]].to_numpy()
            # ! ============================= EPOCHING ================================

            print(steps.get("epoching")) if verbose else None

            # # * Remove "EX"s chans, simulated EOG & stim chan from analysis*
            removed = raw.info["bads"].copy() + [
                "1EX1",
                "1EX2",
                "1EX3",
                "1EX6",
                "1EX7",
                "1EX8",
                "sim_EOG",
                "Status",
            ]

            picked_chs = [ch for ch in raw.ch_names if ch not in removed]

            epochs = mne.Epochs(
                raw,
                cleaned_events,
                event_id=self.exp_info["event_ids"],
                tmin=-0.2,
                tmax=0.5,
                baseline=(-0.2, 0),
                detrend=1,
                on_missing="warn",
                preload=True,
                picks=picked_chs,
            )

            # * Selecting epochs to reject *
            df_epochs = epochs.to_data_frame()

            epoch_inds = [idx for idx in df_epochs["epoch"].unique()]
            epochs_info = {}

            for idx in epoch_inds:
                # * Create a DF per epoch *
                df_ep = df_epochs[df_epochs["epoch"] == idx]

                # * Select only columns with channel info *
                df_ep = df_ep.iloc[:, 3:]

                # * Total nb of channels *
                nb_of_channels = df_ep.shape[1]

                # * nb of times each channel has values higher than +-100 µV *
                ch_counts = df_ep[(df_ep <= -100) | (df_ep >= 100)].count()

                # * Select only those that display such values at least once *
                ch_counts = ch_counts[ch_counts > 0].to_dict()

                bad_ch_ratio = len(ch_counts) / nb_of_channels

                epochs_info[idx] = []
                epochs_info[idx].append(ch_counts)
                epochs_info[idx].append(bad_ch_ratio)

            # * Reject trial if ~30% electrodes have some amplitudes over +- 100 ÎĽV *
            # * Reject channel if, for over 20 trials, amplitudes +- 100 ÎĽV *
            reject_crit = [20, 0.3]

            # * list of bad channels per epoch
            rej_ch_list = [list(info[0].keys()) for info in epochs_info.values()]

            # * Flatten the list
            rej_ch_list = list(itertools.chain(*rej_ch_list))

            # * Nb of trials where channels display values more than +-100 µV
            rej_ch_list = pd.Series(rej_ch_list).value_counts()
            rej_ch_list = rej_ch_list[rej_ch_list > reject_crit[0]].index.to_list()

            # * Reject entire trial if ~30% electrodes have some amplitudes over +- 100 microV
            rej_epoch_list = [idx for idx, info in epochs_info.items() if info[1] > reject_crit[1]]

            raw.info["bads"].extend(rej_ch_list)

            print(f'{len(raw.info["bads"])} channel(s) rejected') if verbose else None
            print(f"{len(rej_epoch_list)} epoch(s) rejected") if verbose else None

            # * Dropping bad epochs and channels from the MNE epochs instance *
            epochs.drop_channels(rej_ch_list)
            epochs.drop(rej_epoch_list)

            # ! ============================= GETTING ERP ================================

            # * Getting the Event-Related Potential (ERP)
            evoked = epochs.average()

            # * Dropping bad epochs from df_trial *
            inds_to_drop = df_trials.query(f"trial.isin({[e + 1 for e in rej_epoch_list]})").index

            df_trials.drop(index=inds_to_drop, inplace=True)

            # ! ============================= ACCURACY & RT ================================
            # * Accuracy list -> Correct resp. = 1; Incorrect resp. = 0 *
            accuracy = (
                df_trials.query(f"event_id.isin({feedbacks_combined})")["event_id"]
                .replace(incorrect_feedback, 0)
                .replace(correct_feedback, 1)
                .to_numpy()
            )

            # * Ratio of correct responses *
            accuracy_ratio = np.count_nonzero(accuracy == 1) / len(accuracy)
            accuracy_ratio = round(accuracy_ratio, 2)

            # * Reaction Times (RT)
            RT = df_trials["RT"].dropna().to_numpy()

            subj_data = dict(
                events = events,
                gender=self.subj_info["gender"],
                age=self.subj_info["age"],
                hand=self.subj_info["hand"],
                accuracy=accuracy,
                accuracy_ratio=accuracy_ratio,
                RT=RT,
                chan_pos=montage.get_positions(),
                evoked=evoked,
                # events = df_events["event_id"].value_counts().to_dict(),
                rejections=dict(channels=rej_ch_list, epochs=rej_epoch_list, EOG_comps=eog_inds),
                bad_ch=raw.info["bads"],
                bipolar_ref=dict(anode=anode, cathode=cathode),
                # trials = dict(total = len(df_events.query(f'event_id.isin([feedbacks_combined])')))
                #  raw_events = events
            )

            pickle_export(data=subj_data, path=self.paths.piclkle, f_name=f"{sess_name}-DataDict")

            # * N200_detection
            N200_detection(
                sess=sess_name,
                evoked=evoked,
                dir_figs=self.paths.figures,
                dir_pickle=self.paths.pickle,
                n200_window=self.erp_window,
                nb_chans=self.svd["nb_chans"],
                nb_comps=self.svd["nb_comps"],
                wave_template=self.wave_template,
                df_topo_tpl=pd.DataFrame(self.img_template_arr),
                figsize=self.plotting_params["figsize"],
                condition=None,
                show_topo_target=None,
            )

            plt.close("all")
            print("\n\n")
            # return data

        if subj_fpath:
            individual_analysis(subj_fpath)

        else:
            print("Running analysis for all valid participant files (5 to 25)")
            choice = input("Continue? (y/n): ")
            if choice.lower() == "y":
                for subj_fpath in self.raw_eeg_files[8:]:
                    # ! Removing the first 5 participants from analysis
                    # ! (sess 01-1 to 04-2) -> Indices 0 to 8
                    individual_analysis(subj_fpath)
            else:
                print("Analysis Aborted")

In the screenshot, at the bottom, it says “Output is truncated… open in a text editor”. Please do that and then paste in the whole traceback here.

Here’s the entire traceback

{
	"name": "TypeError",
	"message": "events should be a NumPy array of integers, got <class 'numpy.ndarray'>",
	"stack": "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)\n\u001b[1;32md:\\N200_VET\\n200_vet\\run\\main.py\u001b[0m in \u001b[0;36mline 23\n\u001b[0;32m     <a href='file:///d%3A/N200_VET/n200_vet/run/main.py?line=19'>20</a>\u001b[0m raw_eeg_files \u001b[39m=\u001b[39m proj1\u001b[39m.\u001b[39mraw_eeg_files[\u001b[39m8\u001b[39m:]\n\u001b[0;32m     <a href='file:///d%3A/N200_VET/n200_vet/run/main.py?line=21'>22</a>\u001b[0m \u001b[39m# * Run analysis on one subject's data\u001b[39;00m\n\u001b[1;32m---> <a href='file:///d%3A/N200_VET/n200_vet/run/main.py?line=22'>23</a>\u001b[0m proj1\u001b[39m.\u001b[39;49mrun_analysis(subj_fpath\u001b[39m=\u001b[39;49mproj1\u001b[39m.\u001b[39;49mraw_eeg_files[\u001b[39m0\u001b[39;49m])\n\u001b[0;32m     <a href='file:///d%3A/N200_VET/n200_vet/run/main.py?line=24'>25</a>\u001b[0m \u001b[39m# * Run analysis on all subjects' data\u001b[39;00m\n\u001b[0;32m     <a href='file:///d%3A/N200_VET/n200_vet/run/main.py?line=25'>26</a>\u001b[0m \u001b[39m# proj1.run_analysis(subj_fpath=None)\u001b[39;00m\n\u001b[0;32m     <a href='file:///d%3A/N200_VET/n200_vet/run/main.py?line=26'>27</a>\u001b[0m \n\u001b[1;32m   (...)\u001b[0m\n\u001b[0;32m     <a href='file:///d%3A/N200_VET/n200_vet/run/main.py?line=43'>44</a>\u001b[0m \u001b[39m# if __name__ == '__main__':\u001b[39;00m\n\u001b[0;32m     <a href='file:///d%3A/N200_VET/n200_vet/run/main.py?line=44'>45</a>\u001b[0m \u001b[39m# \tmultiprocessing_analysis(r\"E:\\N200_Internship\\Datasets\\dataset1\", 0.5)\u001b[39;00m\n\nFile \u001b[1;32md:\\N200_VET\\n200_vet\\project_scripts\\project_structure\\project1.py:585\u001b[0m, in \u001b[0;36mProject1.run_analysis\u001b[1;34m(self, subj_fpath, verbose)\u001b[0m\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=581'>582</a>\u001b[0m     \u001b[39m# return data\u001b[39;00m\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=583'>584</a>\u001b[0m \u001b[39mif\u001b[39;00m subj_fpath:\n\u001b[1;32m--> <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=584'>585</a>\u001b[0m     individual_analysis(subj_fpath)\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=586'>587</a>\u001b[0m \u001b[39melse\u001b[39;00m:\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=587'>588</a>\u001b[0m     \u001b[39mprint\u001b[39m(\u001b[39m\"\u001b[39m\u001b[39mRunning analysis for all valid participant files (5 to 25)\u001b[39m\u001b[39m\"\u001b[39m)\n\nFile \u001b[1;32md:\\N200_VET\\n200_vet\\project_scripts\\project_structure\\project1.py:451\u001b[0m, in \u001b[0;36mProject1.run_analysis.<locals>.individual_analysis\u001b[1;34m(subj_fpath)\u001b[0m\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=437'>438</a>\u001b[0m removed \u001b[39m=\u001b[39m raw\u001b[39m.\u001b[39minfo[\u001b[39m\"\u001b[39m\u001b[39mbads\u001b[39m\u001b[39m\"\u001b[39m]\u001b[39m.\u001b[39mcopy() \u001b[39m+\u001b[39m [\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=438'>439</a>\u001b[0m     \u001b[39m\"\u001b[39m\u001b[39m1EX1\u001b[39m\u001b[39m\"\u001b[39m,\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=439'>440</a>\u001b[0m     \u001b[39m\"\u001b[39m\u001b[39m1EX2\u001b[39m\u001b[39m\"\u001b[39m,\n\u001b[1;32m   (...)\u001b[0m\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=445'>446</a>\u001b[0m     \u001b[39m\"\u001b[39m\u001b[39mStatus\u001b[39m\u001b[39m\"\u001b[39m,\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=446'>447</a>\u001b[0m ]\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=448'>449</a>\u001b[0m picked_chs \u001b[39m=\u001b[39m [ch \u001b[39mfor\u001b[39;00m ch \u001b[39min\u001b[39;00m raw\u001b[39m.\u001b[39mch_names \u001b[39mif\u001b[39;00m ch \u001b[39mnot\u001b[39;00m \u001b[39min\u001b[39;00m removed]\n\u001b[1;32m--> <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=450'>451</a>\u001b[0m epochs \u001b[39m=\u001b[39m mne\u001b[39m.\u001b[39;49mEpochs(\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=451'>452</a>\u001b[0m     raw,\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=452'>453</a>\u001b[0m     cleaned_events,\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=453'>454</a>\u001b[0m     event_id\u001b[39m=\u001b[39;49m\u001b[39mself\u001b[39;49m\u001b[39m.\u001b[39;49mexp_info[\u001b[39m\"\u001b[39;49m\u001b[39mevent_ids\u001b[39;49m\u001b[39m\"\u001b[39;49m],\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=454'>455</a>\u001b[0m     tmin\u001b[39m=\u001b[39;49m\u001b[39m-\u001b[39;49m\u001b[39m0.2\u001b[39;49m,\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=455'>456</a>\u001b[0m     tmax\u001b[39m=\u001b[39;49m\u001b[39m0.5\u001b[39;49m,\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=456'>457</a>\u001b[0m     baseline\u001b[39m=\u001b[39;49m(\u001b[39m-\u001b[39;49m\u001b[39m0.2\u001b[39;49m, \u001b[39m0\u001b[39;49m),\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=457'>458</a>\u001b[0m     detrend\u001b[39m=\u001b[39;49m\u001b[39m1\u001b[39;49m,\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=458'>459</a>\u001b[0m     on_missing\u001b[39m=\u001b[39;49m\u001b[39m\"\u001b[39;49m\u001b[39mwarn\u001b[39;49m\u001b[39m\"\u001b[39;49m,\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=459'>460</a>\u001b[0m     preload\u001b[39m=\u001b[39;49m\u001b[39mTrue\u001b[39;49;00m,\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=460'>461</a>\u001b[0m     picks\u001b[39m=\u001b[39;49mpicked_chs,\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=461'>462</a>\u001b[0m )\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=463'>464</a>\u001b[0m \u001b[39m# * Selecting epochs to reject *\u001b[39;00m\n\u001b[0;32m    <a href='file:///d%3A/N200_VET/n200_vet/project_scripts/project_structure/project1.py?line=464'>465</a>\u001b[0m df_epochs \u001b[39m=\u001b[39m epochs\u001b[39m.\u001b[39mto_data_frame()\n\nFile \u001b[1;32m<decorator-gen-288>:12\u001b[0m, in \u001b[0;36m__init__\u001b[1;34m(self, raw, events, event_id, tmin, tmax, baseline, picks, preload, reject, flat, proj, decim, reject_tmin, reject_tmax, detrend, on_missing, reject_by_annotation, metadata, event_repeated, verbose)\u001b[0m\n\nFile \u001b[1;32mc:\\Users\\parih\\AppData\\Roaming\\pypoetry\\venv\\lib\\site-packages\\mne\\epochs.py:3084\u001b[0m, in \u001b[0;36mEpochs.__init__\u001b[1;34m(self, raw, events, event_id, tmin, tmax, baseline, picks, preload, reject, flat, proj, decim, reject_tmin, reject_tmax, detrend, on_missing, reject_by_annotation, metadata, event_repeated, verbose)\u001b[0m\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3080'>3081</a>\u001b[0m raw_sfreq \u001b[39m=\u001b[39m raw\u001b[39m.\u001b[39minfo[\u001b[39m\"\u001b[39m\u001b[39msfreq\u001b[39m\u001b[39m\"\u001b[39m]\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3082'>3083</a>\u001b[0m \u001b[39m# call BaseEpochs constructor\u001b[39;00m\n\u001b[1;32m-> <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3083'>3084</a>\u001b[0m \u001b[39msuper\u001b[39;49m(Epochs, \u001b[39mself\u001b[39;49m)\u001b[39m.\u001b[39;49m\u001b[39m__init__\u001b[39;49m(\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3084'>3085</a>\u001b[0m     info,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3085'>3086</a>\u001b[0m     \u001b[39mNone\u001b[39;49;00m,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3086'>3087</a>\u001b[0m     events,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3087'>3088</a>\u001b[0m     event_id,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3088'>3089</a>\u001b[0m     tmin,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3089'>3090</a>\u001b[0m     tmax,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3090'>3091</a>\u001b[0m     metadata\u001b[39m=\u001b[39;49mmetadata,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3091'>3092</a>\u001b[0m     baseline\u001b[39m=\u001b[39;49mbaseline,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3092'>3093</a>\u001b[0m     raw\u001b[39m=\u001b[39;49mraw,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3093'>3094</a>\u001b[0m     picks\u001b[39m=\u001b[39;49mpicks,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3094'>3095</a>\u001b[0m     reject\u001b[39m=\u001b[39;49mreject,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3095'>3096</a>\u001b[0m     flat\u001b[39m=\u001b[39;49mflat,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3096'>3097</a>\u001b[0m     decim\u001b[39m=\u001b[39;49mdecim,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3097'>3098</a>\u001b[0m     reject_tmin\u001b[39m=\u001b[39;49mreject_tmin,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3098'>3099</a>\u001b[0m     reject_tmax\u001b[39m=\u001b[39;49mreject_tmax,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3099'>3100</a>\u001b[0m     detrend\u001b[39m=\u001b[39;49mdetrend,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3100'>3101</a>\u001b[0m     proj\u001b[39m=\u001b[39;49mproj,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3101'>3102</a>\u001b[0m     on_missing\u001b[39m=\u001b[39;49mon_missing,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3102'>3103</a>\u001b[0m     preload_at_end\u001b[39m=\u001b[39;49mpreload,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3103'>3104</a>\u001b[0m     event_repeated\u001b[39m=\u001b[39;49mevent_repeated,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3104'>3105</a>\u001b[0m     verbose\u001b[39m=\u001b[39;49mverbose,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3105'>3106</a>\u001b[0m     raw_sfreq\u001b[39m=\u001b[39;49mraw_sfreq,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3106'>3107</a>\u001b[0m     annotations\u001b[39m=\u001b[39;49mraw\u001b[39m.\u001b[39;49mannotations,\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=3107'>3108</a>\u001b[0m )\n\nFile \u001b[1;32m<decorator-gen-274>:12\u001b[0m, in \u001b[0;36m__init__\u001b[1;34m(self, info, data, events, event_id, tmin, tmax, baseline, raw, picks, reject, flat, decim, reject_tmin, reject_tmax, detrend, proj, on_missing, preload_at_end, selection, drop_log, filename, metadata, event_repeated, raw_sfreq, annotations, verbose)\u001b[0m\n\nFile \u001b[1;32mc:\\Users\\parih\\AppData\\Roaming\\pypoetry\\venv\\lib\\site-packages\\mne\\epochs.py:481\u001b[0m, in \u001b[0;36mBaseEpochs.__init__\u001b[1;34m(self, info, data, events, event_id, tmin, tmax, baseline, raw, picks, reject, flat, decim, reject_tmin, reject_tmax, detrend, proj, on_missing, preload_at_end, selection, drop_log, filename, metadata, event_repeated, raw_sfreq, annotations, verbose)\u001b[0m\n\u001b[0;32m    <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=448'>449</a>\u001b[0m \u001b[39m@verbose\u001b[39m\n\u001b[0;32m    <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=449'>450</a>\u001b[0m \u001b[39mdef\u001b[39;00m \u001b[39m__init__\u001b[39m(\n\u001b[0;32m    <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=450'>451</a>\u001b[0m     \u001b[39mself\u001b[39m,\n\u001b[1;32m   (...)\u001b[0m\n\u001b[0;32m    <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=477'>478</a>\u001b[0m     verbose\u001b[39m=\u001b[39m\u001b[39mNone\u001b[39;00m,\n\u001b[0;32m    <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=478'>479</a>\u001b[0m ):  \u001b[39m# noqa: D102\u001b[39;00m\n\u001b[0;32m    <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=479'>480</a>\u001b[0m     \u001b[39mif\u001b[39;00m events \u001b[39mis\u001b[39;00m \u001b[39mnot\u001b[39;00m \u001b[39mNone\u001b[39;00m:  \u001b[39m# RtEpochs can have events=None\u001b[39;00m\n\u001b[1;32m--> <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=480'>481</a>\u001b[0m         events \u001b[39m=\u001b[39m _ensure_events(events)\n\u001b[0;32m    <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=481'>482</a>\u001b[0m         events_max \u001b[39m=\u001b[39m events\u001b[39m.\u001b[39mmax()\n\u001b[0;32m    <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/epochs.py?line=482'>483</a>\u001b[0m         \u001b[39mif\u001b[39;00m events_max \u001b[39m>\u001b[39m INT32_MAX:\n\nFile \u001b[1;32mc:\\Users\\parih\\AppData\\Roaming\\pypoetry\\venv\\lib\\site-packages\\mne\\utils\\check.py:1175\u001b[0m, in \u001b[0;36m_ensure_events\u001b[1;34m(events)\u001b[0m\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/utils/check.py?line=1172'>1173</a>\u001b[0m             \u001b[39mraise\u001b[39;00m\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/utils/check.py?line=1173'>1174</a>\u001b[0m \u001b[39mif\u001b[39;00m \u001b[39mnot\u001b[39;00m np\u001b[39m.\u001b[39missubdtype(events\u001b[39m.\u001b[39mdtype, np\u001b[39m.\u001b[39minteger):\n\u001b[1;32m-> <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/utils/check.py?line=1174'>1175</a>\u001b[0m     \u001b[39mraise\u001b[39;00m \u001b[39mTypeError\u001b[39;00m(err_msg)\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/utils/check.py?line=1175'>1176</a>\u001b[0m \u001b[39mif\u001b[39;00m events\u001b[39m.\u001b[39mndim \u001b[39m!=\u001b[39m \u001b[39m2\u001b[39m \u001b[39mor\u001b[39;00m events\u001b[39m.\u001b[39mshape[\u001b[39m1\u001b[39m] \u001b[39m!=\u001b[39m \u001b[39m3\u001b[39m:\n\u001b[0;32m   <a href='file:///c%3A/Users/parih/AppData/Roaming/pypoetry/venv/lib/site-packages/mne/utils/check.py?line=1176'>1177</a>\u001b[0m     \u001b[39mraise\u001b[39;00m \u001b[39mValueError\u001b[39;00m(\u001b[39mf\u001b[39m\u001b[39m\"\u001b[39m\u001b[39mevents must be of shape (N, 3), got \u001b[39m\u001b[39m{\u001b[39;00mevents\u001b[39m.\u001b[39mshape\u001b[39m}\u001b[39;00m\u001b[39m\"\u001b[39m)\n\n\u001b[1;31mTypeError\u001b[0m: events should be a NumPy array of integers, got <class 'numpy.ndarray'>"
}

can you look at the dtype of the events array? can you try doing events = events.astype(int) ?

Alex

i’m not able to get the print output of that statement as my code snippets are within a class object that I’m calling in a main.py file. Or at least I’m unsure how to get that output without taking the functions out of my current architecture.

Hello,

This is still not the traceback. The traceback tells you exactly which line, in which function, raised the error.
For instance:

import numpy as np
from mne import Epochs, create_info
from mne.io import RawArray

def my_function_to_create_epochs(raw):
    epochs = Epochs(raw, "whatever wrong input")
    return epochs

raw = RawArray(np.random.randn(2, 10000), create_info(2, 1000, "eeg"))
epochs = my_function_to_create_epochs(raw)

Yields the traceback:

Traceback (most recent call last):
  File "C:\Users\scheltie\Downloads\untitled0.py", line 10, in <module>
    epochs = my_function_to_create_epochs(raw)
  File "C:\Users\scheltie\Downloads\untitled0.py", line 6, in my_function_to_create_epochs
    epochs = Epochs(raw, "whatever wrong input")
  File "<decorator-gen-285>", line 12, in __init__
  File "C:\Users\scheltie\git\mscheltienne\mne-python\mne\epochs.py", line 3084, in __init__
    super(Epochs, self).__init__(
  File "<decorator-gen-271>", line 12, in __init__
  File "C:\Users\scheltie\git\mscheltienne\mne-python\mne\epochs.py", line 481, in __init__
    events = _ensure_events(events)
  File "C:\Users\scheltie\git\mscheltienne\mne-python\mne\utils\check.py", line 1186, in _ensure_events
    raise TypeError(err_msg)
TypeError: events should be a NumPy array of integers, got <class 'str'>

Note that it starts with Traceback and ends with the error, and includes all the lines that lead to the error. Could you provide this please?

Mathieu

1 Like

Hello Mathieu,
Do you mean this?

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
d:\N200_VET\n200_vet\run\main.py in line 23
     20 raw_eeg_files = proj1.raw_eeg_files[8:]
     22 # * Run analysis on one subject's data
---> 23 proj1.run_analysis(subj_fpath=proj1.raw_eeg_files[0])
     25 # * Run analysis on all subjects' data
     26 # proj1.run_analysis(subj_fpath=None)
     27 
   (...)
     44 # if __name__ == '__main__':
     45 # 	multiprocessing_analysis(r"E:\N200_Internship\Datasets\dataset1", 0.5)

File d:\N200_VET\n200_vet\project_scripts\project_structure\project1.py:584, in Project1.run_analysis(self, subj_fpath, verbose)
    581     # return data
    583 if subj_fpath:
--> 584     individual_analysis(subj_fpath)
    586 else:
    587     print("Running analysis for all valid participant files (5 to 25)")

File d:\N200_VET\n200_vet\project_scripts\project_structure\project1.py:450, in Project1.run_analysis..individual_analysis(subj_fpath)
    437 removed = raw.info["bads"].copy() + [
    438     "1EX1",
    439     "1EX2",
   (...)
    445     "Status",
    446 ]
    448 picked_chs = [ch for ch in raw.ch_names if ch not in removed]
--> 450 epochs = mne.Epochs(
    451     raw,
    452     cleaned_events,
    453     event_id=self.exp_info["event_ids"],
    454     tmin=-0.2,
    455     tmax=0.5,
    456     baseline=(-0.2, 0),
    457     detrend=1,
    458     on_missing="warn",
    459     preload=True,
    460     picks=picked_chs,
    461 )
    463 # * Selecting epochs to reject *
    464 df_epochs = epochs.to_data_frame()

File :12, in __init__(self, raw, events, event_id, tmin, tmax, baseline, picks, preload, reject, flat, proj, decim, reject_tmin, reject_tmax, detrend, on_missing, reject_by_annotation, metadata, event_repeated, verbose)

File c:\Users\parih\AppData\Roaming\pypoetry\venv\lib\site-packages\mne\epochs.py:3084, in Epochs.__init__(self, raw, events, event_id, tmin, tmax, baseline, picks, preload, reject, flat, proj, decim, reject_tmin, reject_tmax, detrend, on_missing, reject_by_annotation, metadata, event_repeated, verbose)
   3081 raw_sfreq = raw.info["sfreq"]
   3083 # call BaseEpochs constructor
-> 3084 super(Epochs, self).__init__(
   3085     info,
   3086     None,
   3087     events,
   3088     event_id,
   3089     tmin,
   3090     tmax,
   3091     metadata=metadata,
   3092     baseline=baseline,
   3093     raw=raw,
   3094     picks=picks,
   3095     reject=reject,
   3096     flat=flat,
   3097     decim=decim,
   3098     reject_tmin=reject_tmin,
   3099     reject_tmax=reject_tmax,
   3100     detrend=detrend,
   3101     proj=proj,
   3102     on_missing=on_missing,
   3103     preload_at_end=preload,
   3104     event_repeated=event_repeated,
   3105     verbose=verbose,
   3106     raw_sfreq=raw_sfreq,
   3107     annotations=raw.annotations,
   3108 )

File :12, in __init__(self, info, data, events, event_id, tmin, tmax, baseline, raw, picks, reject, flat, decim, reject_tmin, reject_tmax, detrend, proj, on_missing, preload_at_end, selection, drop_log, filename, metadata, event_repeated, raw_sfreq, annotations, verbose)

File c:\Users\parih\AppData\Roaming\pypoetry\venv\lib\site-packages\mne\epochs.py:481, in BaseEpochs.__init__(self, info, data, events, event_id, tmin, tmax, baseline, raw, picks, reject, flat, decim, reject_tmin, reject_tmax, detrend, proj, on_missing, preload_at_end, selection, drop_log, filename, metadata, event_repeated, raw_sfreq, annotations, verbose)
    449 @verbose
    450 def __init__(
    451     self,
   (...)
    478     verbose=None,
    479 ):  # noqa: D102
    480     if events is not None:  # RtEpochs can have events=None
--> 481         events = _ensure_events(events)
    482         events_max = events.max()
    483         if events_max > INT32_MAX:

File c:\Users\parih\AppData\Roaming\pypoetry\venv\lib\site-packages\mne\utils\check.py:1175, in _ensure_events(events)
   1173             raise
   1174 if not np.issubdtype(events.dtype, np.integer):
-> 1175     raise TypeError(err_msg)
   1176 if events.ndim != 2 or events.shape[1] != 3:
   1177     raise ValueError(f"events must be of shape (N, 3), got {events.shape}")

TypeError: events should be a NumPy array of integers, got 
1 Like

Yes, now can you try:

  • In File d:\N200_VET\n200_vet\project_scripts\project_structure\project1.py, line 452, change cleaned_events to cleaned_events.astype(int) to get the epochs creation like so:
epochs = mne.Epochs(
    raw,
    cleaned_events.astype(int),
    ...
)
  • If it still fails, in the same file, line 449 right before calling mne.Epochs, add a print of the type and dtype, like so:
print (type(cleaned_events))
print (cleaned_events.dtype)
epochs = mne.Epochs(
    ...
)

And let us know what it prints.

Mathieu

2 Likes

Hello Mathieu,
Thank you for your suggestion, cleaned_events is type numpy.ndarray 9sorry for forwarding a SS for this, I wasn’t sure how to forward this output as preformatted text)
image

The data type of your cleaned_events array is not what MNE-Python expects. And the first dimension is 0, meaning there are actually no events. You need to fix your custom code that creates that array.

Richard

Hello Richard,
I checked and my events array is not empty. however, in the cleaned_events function I saw that df_trials is an empty dataframe. I’m not sure why or if it is supposed to be empty right now.

image

Yes, this is what I meant: your event cleaning function is broken and needs to be fixed. Right now it doesn’t return a valid events array.

I’d maybe start with explicitly specifying the dtype for each DataFrame column.

Richard