{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from matplotlib import pyplot as plt\n",
    "\n",
    "import mne\n",
    "from mne import find_events, Epochs, compute_covariance, make_ad_hoc_cov\n",
    "from mne.datasets import sample\n",
    "from mne.simulation import simulate_sparse_stc, simulate_raw, add_noise, add_ecg, add_eog"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Opening raw data file /home/yeison/mne_data/MNE-sample-data/MEG/sample/sample_audvis_raw.fif...\n",
      "    Read a total of 3 projection items:\n",
      "        PCA-v1 (1 x 102)  idle\n",
      "        PCA-v2 (1 x 102)  idle\n",
      "        PCA-v3 (1 x 102)  idle\n",
      "    Range : 25800 ... 192599 =     42.956 ...   320.670 secs\n",
      "Ready.\n",
      "Adding average EEG reference projection.\n",
      "1 projection items deactivated\n",
      "Removing projector <Projection | PCA-v1, active : False, n_channels : 102>\n",
      "Removing projector <Projection | PCA-v2, active : False, n_channels : 102>\n",
      "Removing projector <Projection | PCA-v3, active : False, n_channels : 102>\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "\n",
       "<table class=\"table table-hover\">\n",
       "    <tr>\n",
       "        <th>Measurement date</th>\n",
       "        <td>December 03, 2002  19:01:10 GMT</td>\n",
       "        \n",
       "    </tr>\n",
       "    <tr>\n",
       "        <th>Experimenter</th>\n",
       "        <td>MEG</td>\n",
       "        \n",
       "    </tr>\n",
       "        <th>Participant</th>\n",
       "<td>Unknown</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "        <th>Digitized points</th>\n",
       "        <td>146 points</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "        <th>Good channels</th>\n",
       "        <td>0 magnetometer, 0 gradiometer,\n",
       "            and 16 EEG channels</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "        <th>Bad channels</th>\n",
       "        <td></td>\n",
       "        \n",
       "    </tr>\n",
       "    <tr>\n",
       "        <th>EOG channels</th>\n",
       "        <td>Not available</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "        <th>ECG channels</th>\n",
       "        <td>Not available</td>\n",
       "    <tr>\n",
       "        <th>Sampling frequency</th>\n",
       "        <td>600.61 Hz</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "        <th>Highpass</th>\n",
       "        <td>0.10 Hz</td>\n",
       "    </tr>\n",
       "     <tr>\n",
       "        <th>Lowpass</th>\n",
       "        <td>172.18 Hz</td>\n",
       "    </tr>\n",
       "\n",
       "    <tr>\n",
       "        <th>Filenames</th>\n",
       "        <td>sample_audvis_raw.fif</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "        <th>Duration</th>\n",
       "        <td>00:04:37 (HH:MM:SS)</td>\n",
       "    </tr>\n",
       "</table>\n"
      ],
      "text/plain": [
       "<Raw | sample_audvis_raw.fif, 16 x 166800 (277.7 s), ~2.9 MB, data not loaded>"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data_path = sample.data_path()\n",
    "raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'\n",
    "fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'\n",
    "\n",
    "# Load real data as the template\n",
    "raw = mne.io.read_raw_fif(raw_fname)\n",
    "raw.set_eeg_reference(projection=True)\n",
    "raw.pick_types(eeg=True)\n",
    "raw.pick_channels(raw.info.ch_names[:16])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Reading forward solution from /home/yeison/mne_data/MNE-sample-data/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif...\n",
      "    Reading a source space...\n",
      "    Computing patch statistics...\n",
      "    Patch information added...\n",
      "    Distance information added...\n",
      "    [done]\n",
      "    Reading a source space...\n",
      "    Computing patch statistics...\n",
      "    Patch information added...\n",
      "    Distance information added...\n",
      "    [done]\n",
      "    2 source spaces read\n",
      "    Desired named matrix (kind = 3523) not available\n",
      "    Read MEG forward solution (7498 sources, 306 channels, free orientations)\n",
      "    Desired named matrix (kind = 3523) not available\n",
      "    Read EEG forward solution (7498 sources, 60 channels, free orientations)\n",
      "    MEG and EEG forward solutions combined\n",
      "    Source spaces transformed to the forward solution coordinate frame\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 36552 characters]\n",
      "text/plain": [
       "<Figure size 432x288 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "n_dipoles = 4  # number of dipoles to create\n",
    "epoch_duration = 2.  # duration of each epoch/event\n",
    "n = 0  # harmonic number\n",
    "rng = np.random.RandomState(0)  # random state (make reproducible)\n",
    "\n",
    "\n",
    "def data_fun(times):\n",
    "    \"\"\"Generate time-staggered sinusoids at harmonics of 10Hz\"\"\"\n",
    "    global n\n",
    "    n_samp = len(times)\n",
    "    window = np.zeros(n_samp)\n",
    "    start, stop = [int(ii * float(n_samp) / (2 * n_dipoles))\n",
    "                   for ii in (2 * n, 2 * n + 1)]\n",
    "    window[start:stop] = 1.\n",
    "    n += 1\n",
    "    data = 25e-9 * np.sin(2. * np.pi * 10. * n * times)\n",
    "    data *= window\n",
    "    return data\n",
    "\n",
    "\n",
    "times = raw.times[:int(raw.info['sfreq'] * epoch_duration)]\n",
    "fwd = mne.read_forward_solution(fwd_fname)\n",
    "src = fwd['src']\n",
    "stc = simulate_sparse_stc(src, n_dipoles=n_dipoles, times=times,\n",
    "                          data_fun=data_fun, random_state=rng)\n",
    "# look at our source data\n",
    "fig, ax = plt.subplots(1)\n",
    "ax.plot(times, 1e9 * stc.data.T)\n",
    "ax.set(ylabel='Amplitude (nAm)', xlabel='Time (sec)')\n",
    "mne.viz.utils.plt_show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Adding noise to 16/16 channels (16 channels in cov)\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 66524 characters]\n",
      "text/plain": [
       "<MNEBrowseFigure size 432x288 with 5 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "raw_sim = simulate_raw(raw.info, [stc] * 10, forward=fwd, verbose=False)\n",
    "cov = make_ad_hoc_cov(raw_sim.info)\n",
    "add_noise(raw_sim, cov, iir_filter=[0.2, -0.2, 0.04], random_state=rng)\n",
    "# add_ecg(raw_sim, random_state=rng)\n",
    "# add_eog(raw_sim, random_state=rng)\n",
    "raw_sim.plot();"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(16, 20000)"
      ]
     },
     "execution_count": 72,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = np.linspace(0, 20, raw_sim._data.shape[1])\n",
    "xx = np.linspace(0, 20, 20*1000) \n",
    "y = []\n",
    "\n",
    "for channel in raw_sim._data:\n",
    "    y.append(np.interp(xx, x, channel))\n",
    "    \n",
    "y = np.array(y)\n",
    "y.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 73,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('fake_eeg-20s.npy', 'wb') as f:\n",
    "    np.save(f, y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 77,
   "metadata": {},
   "outputs": [],
   "source": [
    "import rawutil\n",
    "\n",
    "def eeg_(values): return [rawutil.pack('>u', v // 24) for v in values.tolist()]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'list' object has no attribute 'reshape'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-99-b3380eea58a2>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0meeg_data\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0marray\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mrawutil\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0munpack\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'>u'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mbytes\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mch\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mch\u001b[0m \u001b[0;32min\u001b[0m \u001b[0meeg\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mreshape\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mreshape\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m8\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m*\u001b[0m \u001b[0;36m24\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mAttributeError\u001b[0m: 'list' object has no attribute 'reshape'"
     ]
    }
   ],
   "source": [
    "eeg_data = np.array([rawutil.unpack('>u', bytes(ch))[0] for ch in eeg.reshape(-1, 3)]).reshape(-1, 8) * 24"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[0, 0, 16, 0, 0, 0, 0, 0, 0]"
      ]
     },
     "execution_count": 98,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "eeg = list(b''.join(eeg_(np.array([400, 5, 6]))))\n",
    "eeg"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
