├── requirements.txt
├── README.md
├── example.ipynb
├── EEGExtract.py
└── LICENSE
/requirements.txt:
--------------------------------------------------------------------------------
1 | dit==1.5
2 | numpy==1.24.3
3 | pandas==2.0.1
4 | PyWavelets==1.8.0
5 | scikit-learn==1.7.2
6 | scipy==1.15.3
7 | statsmodels==0.14.5
8 | pyod==2.0.5
9 | librosa==0.11.0
10 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # EEGExtract 1.2.0
2 | [Sari Saba-Sadiya](https://cse.msu.edu/~sadiyasa/)1,2,
3 | [Eric Chantland]()2,
4 | [Taosheng Liu](https://npal.psy.msu.edu/)2,
5 | [Tuka Alhanai](https://talhanai.xyz/)3,
6 | [Mohammad Ghassemi](https://ghassemi.xyz/)1
7 |
8 | 1 Human Augmentation and Artificial Intelligence lab, Michigan State University, Department of Computer Science
9 | 2 Neuroimaging of Perception and Attention Lab, Michigan State University, Department of Psychology
10 | 3 Computer Human Intelligence Lab, New York University Abu Dhabi, Department of Electrical and Computer Engineering
11 |
12 |
13 | **2025 Update:** Thanks to [Alperen Kantarcı](https://github.com/Alpkant) for new update
14 |
15 |
16 | A python package for extracting EEG features. First developed for the paper ["Unsupervised EEG Artifact Detection and Correction"](https://www.frontiersin.org/articles/10.3389/fdgth.2020.608920/abstract), published in Frontiers in Digital Health, Special issue on Machine Learning in Clinical Decision-Making. [Press here](https://www.frontiersin.org/articles/10.3389/fdgth.2020.608920/bibTex) for a BibTex citation (or scroll to the bottom of this page).
17 |
18 | To the best of our knowledge EEGExtract is the most comprehensive library for EEG feature extraction currently available. This library is actively maintained, __please open an issue if you believe adding a specific feature will be of benefit for the community!__
19 |
20 |
21 | ## Setup
22 | 1. Make sure that you have the required packages listed in `requirements.txt`. Use `pip install -r requirements.txt` if unsure.
23 | 2. Simply download and place the `EEGExtract.py` file in the same folder as your repo. You can then use `import EEGExtract as eeg`.
24 |
25 | ## License
26 |
27 |
28 |
GPL-3.0 License
29 |
30 | Free to use and modify, but must cite the original publication below.
31 |
32 | ## The Features
33 |
34 | | _Signal Descriptor_ | _Brief Description_ | _Function_ |
35 | | --------------- | --------------- | --------------- |
36 | | __Complexity Features__ | _degree of randomness or irregularity_ |
37 | | Shannon Entropy | additive measure of signal stochasticity | shannonEntropy |
38 | | Tsalis Entropy (n=10) | non-additive measure of signal stochasticity | tsalisEntropy |
39 | | Information Quantity (δ,α,θ,β,γ) | entropy of a wavelet decomposed signal | filt_data + shannonEntropy |
40 | | Cepstrum Coefficients (n=2) | rate of change in signal spectral band power | mfcc |
41 | | Lyapunov Exponent | separation between signals with similar trajectories | lyapunov|
42 | | Fractal Embedding Dimension | how signal properties change with scale | hFD |
43 | | Hjorth Mobility | mean signal frequency | hjorthParameters |
44 | | Hjorth Complexity | rate of change in mean signal frequency | hjorthParameters |
45 | | False Nearest Neighbor | signal continuity and smoothness | falseNearestNeighbor |
46 | | ARMA Coefficients (n=2) | autoregressive coefficient of signal at (t-1) and (t-2) | arma |
47 | | __Continuity Features__ | _clinically grounded signal characteristics_ |
48 | | Median Frequency | the median spectral power | medianFreq |
49 | | δ band Power | spectral power in the 0-3Hz range | bandPower |
50 | | α band Power | spectral power in the 4-7Hz range | bandPower |
51 | | θ band Power | spectral power in the 8-15Hz range | bandPower |
52 | | β band Power | spectral power in the 16-31Hz range | bandPower |
53 | | γ band Power | spectral power above 32Hz | bandPower |
54 | | Median Frequency | median spectral power | medianFreq |
55 | | Standard Deviation | average difference between signal value and it's mean | eegStd |
56 | | α/δ Ratio | ratio of the power spectral density in α and δ bands | eegRatio |
57 | | Regularity (burst-suppression) | measure of signal stationarity / spectral consistency | eegRegularity |
58 | | Voltage < (5μ, 10μ, 20μ) | low signal amplitude | eegVoltage |
59 | | Normal EEG | Peak spectral power textgreater= 8Hz | |
60 | | Diffuse Slowing | indicator of peak power spectral density less than 8Hz | diffuseSlowing |
61 | | Spikes | signal amplitude exceeds μ by 3σ for 70 ms or less | spikeNum |
62 | | Delta Burst after spike | Increased δ after spike, relative to δ before spike | burstAfterSpike |
63 | | Sharp spike | spikes lasting less than 70 ms | shortSpikeNum |
64 | | Number of Bursts | number of amplitude bursts | numBursts |
65 | | Burst length μ and σ | statistical properties of bursts | burstLengthStats |
66 | | Burst band powers (δ,α,θ,β,γ) | spectral power of bursts | burstBandPowers |
67 | | Number of Suppressions | segments with contiguous amplitude suppression | numSuppressions |
68 | | Suppression length μ and σ | statistical properties of suppressions | suppressionLengthStats |
69 | | __Connectivity Features__ | _interactions between EEG electrode pairs_ |
70 | | Coherence - δ | correlation in in 0-4 Hz power between signals | filt_data + coherence |
71 | | Coherence - All | correlation in overall power between signals | coherence |
72 | | Mutual Information | measure of dependence | calculate2Chan_MI |
73 | | Granger causality - All | measure of causality | calcGrangerCausality |
74 | | Phase Lag Index | association between the instantaneous phase of signals | phaseLagIndex |
75 | | Cross-correlation Magnitude | maximum correlation between two signals | crossCorrMag |
76 | | Crosscorrelation - Lag | time-delay that maximizes correlation between signals | corrCorrLagAux |
77 |
78 | Additionally, `EEGExtract` also contains implementations for a number of auxiliary functions
79 |
80 | | _Function_ | params | _Brief Description_ |
81 | | --------------- | --------------- | --------------- |
82 | | filt_data | eegData, lowcut, highcut, fs, order=7 | midpass filter between lowcut and highcut |
83 | | fcnRemoveShortEvents | z,n| z=[chan x samples ], n is threshold |
84 | | get_intervals | A,B,endIdx | Find interval of consistent values in binary 1D numpy array |
85 |
86 | ## Important Note
87 | The feature extractor is an independent section that can be used with any artifact correction method (recently there have been quite a few including some notable example [1,2]). If you are interested in the specific setup that was used in the paper, as well as a link to the data, please visit [the following repository](https://github.com/sari-saba-sadiya/EEG-Artifact-Correction-Via-Completion).
88 |
89 | [1] S. Phadikar, N. Sinha, and R. Ghosh, “Automatic eeg eyeblink artifact identification and removal technique using independent component analysis in combination with support vector machines and denoising autoencoder”
90 |
91 | [2] B. Somers, T. Francart, and A. Bertrand, “A generic eeg artifact removal algorithm based on the multi-channel wiener filter.”
92 |
93 |
94 |
95 | ## Cite
96 | ```
97 | @article{saba2020unsupervised,
98 | title={Unsupervised EEG Artifact Detection and Correction},
99 | author={Saba-Sadiya, Sari and Chantland, Eric and Alhanai, Tuka and Liu, Taosheng and Ghassemi, Mohammad Mahdi},
100 | journal={Frontiers in Digital Health},
101 | volume={2},
102 | pages={57},
103 | year={2020},
104 | publisher={Frontiers}
105 | }
106 | ```
107 |
108 |
--------------------------------------------------------------------------------
/example.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 1,
6 | "metadata": {},
7 | "outputs": [],
8 | "source": [
9 | "%load_ext autoreload\n",
10 | "%autoreload 2\n",
11 | "import EEGExtract as eeg\n",
12 | "import glob\n",
13 | "import numpy as np"
14 | ]
15 | },
16 | {
17 | "cell_type": "code",
18 | "execution_count": 2,
19 | "metadata": {},
20 | "outputs": [],
21 | "source": [
22 | "# Export data from the BCI Competition Dataset IV 2a dataset\n",
23 | "# Code used from https://github.com/bregydoc/bcidatasetIV2a\n",
24 | "class MotorImageryDataset:\n",
25 | " def __init__(self, dataset='A01T.npz'):\n",
26 | " if not dataset.endswith('.npz'):\n",
27 | " dataset += '.npz'\n",
28 | "\n",
29 | " self.data = np.load(dataset)\n",
30 | "\n",
31 | " self.Fs = 250 # 250Hz from original paper\n",
32 | "\n",
33 | " # keys of data ['s', 'etyp', 'epos', 'edur', 'artifacts']\n",
34 | " self.raw = self.data['s'].T\n",
35 | " self.events_type = self.data['etyp'].T\n",
36 | " self.events_position = self.data['epos'].T\n",
37 | " self.events_duration = self.data['edur'].T\n",
38 | " self.artifacts = self.data['artifacts'].T\n",
39 | "\n",
40 | " # Types of motor imagery\n",
41 | " self.mi_types = {769: 'left', 770: 'right', 771: 'foot',\n",
42 | " 772: 'tongue', 783: 'unknown', 1023:'rejected'}\n",
43 | "\n",
44 | " def get_trials_from_channel(self):\n",
45 | "\n",
46 | " # Channel default is C3\n",
47 | " startrial_code = 768\n",
48 | " starttrial_events = self.events_type == startrial_code\n",
49 | " idxs = [i for i, x in enumerate(starttrial_events[0]) if x]\n",
50 | "\n",
51 | " trials = []\n",
52 | " classes = []\n",
53 | " artifacts = []\n",
54 | " for ii, index in enumerate(idxs):\n",
55 | " type_e = self.events_type[0, index+1]\n",
56 | " if type_e not in self.mi_types.keys():\n",
57 | " continue\n",
58 | " class_e = self.mi_types[type_e]\n",
59 | " if class_e == 'unknown':\n",
60 | " continue\n",
61 | " classes.append(type_e-769)\n",
62 | "\n",
63 | " start = self.events_position[0, index] + 0.5 * self.Fs\n",
64 | " stop = start + self.events_duration[0, index]\n",
65 | " if stop < start + 2* self.Fs:\n",
66 | " print(stop,start + 2* self.Fs)\n",
67 | " raise '(MotorImageryDataset error): EEG is shorter than 2 sec'\n",
68 | " trial = self.raw[0:22, int(start):int(start + 2* self.Fs)]\n",
69 | " trials.append(trial)\n",
70 | " artifacts.append(self.artifacts[0,ii])\n",
71 | " return trials, classes, artifacts"
72 | ]
73 | },
74 | {
75 | "cell_type": "code",
76 | "execution_count": 3,
77 | "metadata": {},
78 | "outputs": [],
79 | "source": [
80 | "trials = []\n",
81 | "classes = []\n",
82 | "artifacts = []\n",
83 | "for file in glob.glob('../EEGExtract/bcidatasetIV2a/*.npz'):\n",
84 | " datasetA1 = MotorImageryDataset(file)\n",
85 | " # trials contains the N valid trials, and clases its related class.\n",
86 | " tmp_trials, tmp_classes, tmp_artifacts = datasetA1.get_trials_from_channel()\n",
87 | " trials.extend(tmp_trials)\n",
88 | " classes.extend(tmp_classes)\n",
89 | " artifacts.extend(tmp_artifacts)"
90 | ]
91 | },
92 | {
93 | "cell_type": "code",
94 | "execution_count": 4,
95 | "metadata": {},
96 | "outputs": [],
97 | "source": [
98 | "eegData = np.dstack(trials)"
99 | ]
100 | },
101 | {
102 | "cell_type": "code",
103 | "execution_count": 5,
104 | "metadata": {},
105 | "outputs": [],
106 | "source": [
107 | "fs = 250"
108 | ]
109 | },
110 | {
111 | "cell_type": "code",
112 | "execution_count": 6,
113 | "metadata": {},
114 | "outputs": [
115 | {
116 | "data": {
117 | "text/plain": [
118 | "(22, 500, 2816)"
119 | ]
120 | },
121 | "execution_count": 6,
122 | "metadata": {},
123 | "output_type": "execute_result"
124 | }
125 | ],
126 | "source": [
127 | "# eegData: 3D np array [chans x ms x epochs] \n",
128 | "eegData.shape"
129 | ]
130 | },
131 | {
132 | "cell_type": "code",
133 | "execution_count": 7,
134 | "metadata": {},
135 | "outputs": [],
136 | "source": [
137 | "feature_list = []"
138 | ]
139 | },
140 | {
141 | "cell_type": "markdown",
142 | "metadata": {},
143 | "source": [
144 | "## Complexity Features"
145 | ]
146 | },
147 | {
148 | "cell_type": "code",
149 | "execution_count": 34,
150 | "metadata": {},
151 | "outputs": [],
152 | "source": [
153 | "#Shannon Entropy\n",
154 | "ShannonRes = eeg.shannonEntropy(eegData, bin_min=-200, bin_max=200, binWidth=2)"
155 | ]
156 | },
157 | {
158 | "cell_type": "code",
159 | "execution_count": 35,
160 | "metadata": {},
161 | "outputs": [],
162 | "source": [
163 | "#Tsalis Entropy (n=10)\n",
164 | "tsalisRes = eeg.tsalisEntropy(eegData, bin_min=-200, bin_max=200, binWidth=2,orders=list(range(1,10+1)))"
165 | ]
166 | },
167 | {
168 | "cell_type": "code",
169 | "execution_count": 36,
170 | "metadata": {},
171 | "outputs": [],
172 | "source": [
173 | "# Subband Information Quantity\n",
174 | "# delta (0.5–4 Hz)\n",
175 | "eegData_delta = eeg.filt_data(eegData, 0.5, 4, fs)\n",
176 | "ShannonRes_delta = eeg.shannonEntropy(eegData_delta, bin_min=-200, bin_max=200, binWidth=2)\n",
177 | "# theta (4–8 Hz)\n",
178 | "eegData_theta = eeg.filt_data(eegData, 4, 8, fs)\n",
179 | "ShannonRes_theta = eeg.shannonEntropy(eegData_theta, bin_min=-200, bin_max=200, binWidth=2)\n",
180 | "# alpha (8–12 Hz)\n",
181 | "eegData_alpha = eeg.filt_data(eegData, 8, 12, fs)\n",
182 | "ShannonRes_alpha = eeg.shannonEntropy(eegData_alpha, bin_min=-200, bin_max=200, binWidth=2)\n",
183 | "# beta (12–30 Hz)\n",
184 | "eegData_beta = eeg.filt_data(eegData, 12, 30, fs)\n",
185 | "ShannonRes_beta = eeg.shannonEntropy(eegData_beta, bin_min=-200, bin_max=200, binWidth=2)\n",
186 | "# gamma (30–100 Hz)\n",
187 | "eegData_gamma = eeg.filt_data(eegData, 30, 100, fs)\n",
188 | "ShannonRes_gamma = eeg.shannonEntropy(eegData_gamma, bin_min=-200, bin_max=200, binWidth=2)"
189 | ]
190 | },
191 | {
192 | "cell_type": "code",
193 | "execution_count": 9,
194 | "metadata": {},
195 | "outputs": [
196 | {
197 | "name": "stderr",
198 | "output_type": "stream",
199 | "text": [
200 | "/Users/alperen/miniconda3/envs/eegextract/lib/python3.11/site-packages/librosa/core/spectrum.py:266: UserWarning: n_fft=2048 is too large for input signal of length=500\n",
201 | " warnings.warn(\n"
202 | ]
203 | }
204 | ],
205 | "source": [
206 | "# Cepstrum Coefficients (n=2)\n",
207 | "CepstrumRes = eeg.mfcc(eegData, fs,order=2)"
208 | ]
209 | },
210 | {
211 | "cell_type": "code",
212 | "execution_count": 10,
213 | "metadata": {},
214 | "outputs": [],
215 | "source": [
216 | "# Lyapunov Exponent\n",
217 | "LyapunovRes = eeg.lyapunov(eegData)"
218 | ]
219 | },
220 | {
221 | "cell_type": "code",
222 | "execution_count": 11,
223 | "metadata": {},
224 | "outputs": [
225 | {
226 | "name": "stderr",
227 | "output_type": "stream",
228 | "text": [
229 | "/Users/alperen/Documents/Goethe/PhD/HONDA/eegextract_trial/EEGExtract.py:243: FutureWarning: `rcond` parameter will change to the default of machine precision times ``max(M, N)`` where M and N are the input matrix dimensions.\n",
230 | "To use the future default and silence this warning we advise to pass `rcond=None`, to keep using the old, explicitly pass `rcond=-1`.\n",
231 | " (p, r1, r2, s)=np.linalg.lstsq(x, L)\n"
232 | ]
233 | }
234 | ],
235 | "source": [
236 | "# Fractal Embedding Dimension\n",
237 | "HiguchiFD_Res = eeg.hFD(eegData[0,:,0],3)"
238 | ]
239 | },
240 | {
241 | "cell_type": "code",
242 | "execution_count": 12,
243 | "metadata": {},
244 | "outputs": [],
245 | "source": [
246 | "# Hjorth Mobility\n",
247 | "# Hjorth Complexity\n",
248 | "HjorthMob, HjorthComp = eeg.hjorthParameters(eegData)"
249 | ]
250 | },
251 | {
252 | "cell_type": "code",
253 | "execution_count": 13,
254 | "metadata": {},
255 | "outputs": [],
256 | "source": [
257 | "# False Nearest Neighbor\n",
258 | "FalseNnRes = eeg.falseNearestNeighbor(eegData)"
259 | ]
260 | },
261 | {
262 | "cell_type": "code",
263 | "execution_count": null,
264 | "metadata": {},
265 | "outputs": [],
266 | "source": [
267 | "# ARMA Coefficients (n=2)\n",
268 | "armaRes = eeg.arma(eegData,order=2)"
269 | ]
270 | },
271 | {
272 | "cell_type": "markdown",
273 | "metadata": {},
274 | "source": [
275 | "## Category Features"
276 | ]
277 | },
278 | {
279 | "cell_type": "code",
280 | "execution_count": 16,
281 | "metadata": {},
282 | "outputs": [],
283 | "source": [
284 | "# Median Frequency\n",
285 | "medianFreqRes = eeg.medianFreq(eegData,fs)"
286 | ]
287 | },
288 | {
289 | "cell_type": "code",
290 | "execution_count": 17,
291 | "metadata": {},
292 | "outputs": [],
293 | "source": [
294 | "# δ band Power\n",
295 | "bandPwr_delta = eeg.bandPower(eegData, 0.5, 4, fs)\n",
296 | "# θ band Power\n",
297 | "bandPwr_theta = eeg.bandPower(eegData, 4, 8, fs)\n",
298 | "# α band Power\n",
299 | "bandPwr_alpha = eeg.bandPower(eegData, 8, 12, fs)\n",
300 | "# β band Power\n",
301 | "bandPwr_beta = eeg.bandPower(eegData, 12, 30, fs)\n",
302 | "# γ band Power\n",
303 | "bandPwr_gamma = eeg.bandPower(eegData, 30, 100, fs)"
304 | ]
305 | },
306 | {
307 | "cell_type": "code",
308 | "execution_count": 18,
309 | "metadata": {},
310 | "outputs": [],
311 | "source": [
312 | "# Standard Deviation\n",
313 | "std_res = eeg.eegStd(eegData)"
314 | ]
315 | },
316 | {
317 | "cell_type": "code",
318 | "execution_count": 19,
319 | "metadata": {},
320 | "outputs": [],
321 | "source": [
322 | "# α/δ Ratio\n",
323 | "ratio_res = eeg.eegRatio(eegData,fs)"
324 | ]
325 | },
326 | {
327 | "cell_type": "code",
328 | "execution_count": 20,
329 | "metadata": {},
330 | "outputs": [],
331 | "source": [
332 | "# Regularity (burst-suppression)\n",
333 | "regularity_res = eeg.eegRegularity(eegData,fs)"
334 | ]
335 | },
336 | {
337 | "cell_type": "code",
338 | "execution_count": 21,
339 | "metadata": {},
340 | "outputs": [],
341 | "source": [
342 | "# Voltage < 5μ\n",
343 | "volt05_res = eeg.eegVoltage(eegData,voltage=5)\n",
344 | "# Voltage < 10μ\n",
345 | "volt10_res = eeg.eegVoltage(eegData,voltage=10)\n",
346 | "# Voltage < 20μ\n",
347 | "volt20_res = eeg.eegVoltage(eegData,voltage=20)"
348 | ]
349 | },
350 | {
351 | "cell_type": "code",
352 | "execution_count": 22,
353 | "metadata": {},
354 | "outputs": [],
355 | "source": [
356 | "# Diffuse Slowing\n",
357 | "df_res = eeg.diffuseSlowing(eegData)"
358 | ]
359 | },
360 | {
361 | "cell_type": "code",
362 | "execution_count": 23,
363 | "metadata": {},
364 | "outputs": [],
365 | "source": [
366 | "# Spikes\n",
367 | "minNumSamples = int(70*fs/1000)\n",
368 | "spikeNum_res = eeg.spikeNum(eegData,minNumSamples)"
369 | ]
370 | },
371 | {
372 | "cell_type": "code",
373 | "execution_count": 24,
374 | "metadata": {},
375 | "outputs": [],
376 | "source": [
377 | "# Delta burst after Spike\n",
378 | "deltaBurst_res = eeg.burstAfterSpike(eegData,eegData_delta,minNumSamples=7,stdAway = 3)"
379 | ]
380 | },
381 | {
382 | "cell_type": "code",
383 | "execution_count": 25,
384 | "metadata": {},
385 | "outputs": [],
386 | "source": [
387 | "# Sharp spike\n",
388 | "sharpSpike_res = eeg.shortSpikeNum(eegData,minNumSamples)"
389 | ]
390 | },
391 | {
392 | "cell_type": "code",
393 | "execution_count": 26,
394 | "metadata": {},
395 | "outputs": [],
396 | "source": [
397 | "# Number of Bursts\n",
398 | "numBursts_res = eeg.numBursts(eegData,fs)"
399 | ]
400 | },
401 | {
402 | "cell_type": "code",
403 | "execution_count": 27,
404 | "metadata": {},
405 | "outputs": [
406 | {
407 | "name": "stderr",
408 | "output_type": "stream",
409 | "text": [
410 | "/Users/alperen/miniconda3/envs/eegextract/lib/python3.11/site-packages/numpy/core/fromnumeric.py:3464: RuntimeWarning: Mean of empty slice.\n",
411 | " return _methods._mean(a, axis=axis, dtype=dtype,\n",
412 | "/Users/alperen/miniconda3/envs/eegextract/lib/python3.11/site-packages/numpy/core/_methods.py:269: RuntimeWarning: Degrees of freedom <= 0 for slice\n",
413 | " ret = _var(a, axis=axis, dtype=dtype, out=out, ddof=ddof,\n"
414 | ]
415 | }
416 | ],
417 | "source": [
418 | "# Burst length μ and σ\n",
419 | "burstLenMean_res,burstLenStd_res = eeg.burstLengthStats(eegData,fs)"
420 | ]
421 | },
422 | {
423 | "cell_type": "code",
424 | "execution_count": 28,
425 | "metadata": {},
426 | "outputs": [],
427 | "source": [
428 | "# Burst Band Power for δ\n",
429 | "burstBandPwrAlpha = eeg.burstBandPowers(eegData, 0.5, 4, fs)"
430 | ]
431 | },
432 | {
433 | "cell_type": "code",
434 | "execution_count": 29,
435 | "metadata": {},
436 | "outputs": [],
437 | "source": [
438 | "# Number of Suppressions\n",
439 | "numSupps_res = eeg.numSuppressions(eegData,fs)"
440 | ]
441 | },
442 | {
443 | "cell_type": "code",
444 | "execution_count": 30,
445 | "metadata": {},
446 | "outputs": [],
447 | "source": [
448 | "# Suppression length μ and σ\n",
449 | "suppLenMean_res,suppLenStd_res = eeg.suppressionLengthStats(eegData,fs)"
450 | ]
451 | },
452 | {
453 | "cell_type": "markdown",
454 | "metadata": {},
455 | "source": [
456 | "## Connectivity features"
457 | ]
458 | },
459 | {
460 | "cell_type": "code",
461 | "execution_count": 31,
462 | "metadata": {},
463 | "outputs": [],
464 | "source": [
465 | "# Coherence - δ\n",
466 | "coherence_res = eeg.coherence(eegData,fs)"
467 | ]
468 | },
469 | {
470 | "cell_type": "code",
471 | "execution_count": 32,
472 | "metadata": {},
473 | "outputs": [],
474 | "source": [
475 | "#import importlib\n",
476 | "#importlib.reload(eeg)"
477 | ]
478 | },
479 | {
480 | "cell_type": "code",
481 | "execution_count": 37,
482 | "metadata": {},
483 | "outputs": [],
484 | "source": [
485 | "feature_list = []\n",
486 | "feature_list.append(ShannonRes)\n",
487 | "feature_list.append(ShannonRes_delta)\n",
488 | "feature_list.append(ShannonRes_theta)\n",
489 | "#feature_list.append(ShannonRes_alpha)\n",
490 | "#feature_list.append(ShannonRes_beta)\n",
491 | "feature_list.append(ShannonRes_gamma)\n",
492 | "feature_list.append(bandPwr_delta)\n",
493 | "feature_list.append(bandPwr_theta)\n",
494 | "#feature_list.append(bandPwr_alpha)\n",
495 | "#feature_list.append(bandPwr_beta)\n",
496 | "feature_list.append(bandPwr_gamma)\n",
497 | "feature_list.append(std_res)\n",
498 | "#feature_list.append(ratio_res)\n",
499 | "feature_list.append(regularity_res)\n",
500 | "feature_list.append(volt05_res)\n",
501 | "feature_list.append(volt10_res)\n",
502 | "feature_list.append(volt20_res)\n",
503 | "feature_list.append(df_res)\n",
504 | "feature_list.append(spikeNum_res)\n",
505 | "feature_list.append(deltaBurst_res)\n",
506 | "feature_list.append(sharpSpike_res)\n",
507 | "feature_list.append(numBursts_res)\n",
508 | "#feature_list.append(burstLenMean_res)\n",
509 | "#feature_list.append(burstLenStd_res)\n",
510 | "feature_list.append(numSupps_res)\n",
511 | "#feature_list.append(coherence_res)"
512 | ]
513 | },
514 | {
515 | "cell_type": "code",
516 | "execution_count": 38,
517 | "metadata": {},
518 | "outputs": [],
519 | "source": [
520 | "feature_arr = np.vstack(feature_list).transpose()"
521 | ]
522 | },
523 | {
524 | "cell_type": "code",
525 | "execution_count": 39,
526 | "metadata": {},
527 | "outputs": [
528 | {
529 | "data": {
530 | "text/plain": [
531 | "(2816, 396)"
532 | ]
533 | },
534 | "execution_count": 39,
535 | "metadata": {},
536 | "output_type": "execute_result"
537 | }
538 | ],
539 | "source": [
540 | "feature_arr.shape"
541 | ]
542 | },
543 | {
544 | "cell_type": "code",
545 | "execution_count": 40,
546 | "metadata": {},
547 | "outputs": [
548 | {
549 | "data": {
550 | "text/plain": [
551 | "18"
552 | ]
553 | },
554 | "execution_count": 40,
555 | "metadata": {},
556 | "output_type": "execute_result"
557 | }
558 | ],
559 | "source": [
560 | "len(feature_list)"
561 | ]
562 | },
563 | {
564 | "cell_type": "code",
565 | "execution_count": 41,
566 | "metadata": {},
567 | "outputs": [
568 | {
569 | "data": {
570 | "text/plain": [
571 | "0.17329545454545456"
572 | ]
573 | },
574 | "execution_count": 41,
575 | "metadata": {},
576 | "output_type": "execute_result"
577 | }
578 | ],
579 | "source": [
580 | "sum(artifacts) / len(artifacts)"
581 | ]
582 | },
583 | {
584 | "cell_type": "code",
585 | "execution_count": 45,
586 | "metadata": {},
587 | "outputs": [],
588 | "source": [
589 | "# https://pyod.readthedocs.io/en/latest/pyod.models.html\n",
590 | "from pyod import models\n",
591 | "from pyod.models import hbos,auto_encoder,lof,so_gaal,lscp,vae,abod,ocsvm,xgbod,pca"
592 | ]
593 | },
594 | {
595 | "cell_type": "code",
596 | "execution_count": 46,
597 | "metadata": {},
598 | "outputs": [
599 | {
600 | "data": {
601 | "text/plain": [
602 | "HBOS(alpha=0.07, contamination=0.15, n_bins=17, tol=0.5)"
603 | ]
604 | },
605 | "execution_count": 46,
606 | "metadata": {},
607 | "output_type": "execute_result"
608 | }
609 | ],
610 | "source": [
611 | "clf = hbos.HBOS(n_bins=17, alpha=0.07, tol=0.5,contamination=.15)\n",
612 | "clf.fit(feature_arr)"
613 | ]
614 | },
615 | {
616 | "cell_type": "code",
617 | "execution_count": 47,
618 | "metadata": {},
619 | "outputs": [],
620 | "source": [
621 | "from sklearn.metrics import confusion_matrix,cohen_kappa_score,f1_score"
622 | ]
623 | },
624 | {
625 | "cell_type": "code",
626 | "execution_count": 48,
627 | "metadata": {},
628 | "outputs": [
629 | {
630 | "data": {
631 | "text/plain": [
632 | "array([[2025, 303],\n",
633 | " [ 368, 120]])"
634 | ]
635 | },
636 | "execution_count": 48,
637 | "metadata": {},
638 | "output_type": "execute_result"
639 | }
640 | ],
641 | "source": [
642 | "confusion_matrix(artifacts, clf.labels_)"
643 | ]
644 | },
645 | {
646 | "cell_type": "code",
647 | "execution_count": 49,
648 | "metadata": {},
649 | "outputs": [
650 | {
651 | "data": {
652 | "text/plain": [
653 | "0.12217820163082671"
654 | ]
655 | },
656 | "execution_count": 49,
657 | "metadata": {},
658 | "output_type": "execute_result"
659 | }
660 | ],
661 | "source": [
662 | "cohen_kappa_score(artifacts, clf.labels_)"
663 | ]
664 | },
665 | {
666 | "cell_type": "code",
667 | "execution_count": 50,
668 | "metadata": {},
669 | "outputs": [
670 | {
671 | "data": {
672 | "text/plain": [
673 | "0.26344676180021953"
674 | ]
675 | },
676 | "execution_count": 50,
677 | "metadata": {},
678 | "output_type": "execute_result"
679 | }
680 | ],
681 | "source": [
682 | "f1_score(artifacts, clf.labels_)"
683 | ]
684 | },
685 | {
686 | "cell_type": "code",
687 | "execution_count": null,
688 | "metadata": {},
689 | "outputs": [],
690 | "source": []
691 | },
692 | {
693 | "cell_type": "code",
694 | "execution_count": null,
695 | "metadata": {},
696 | "outputs": [],
697 | "source": []
698 | }
699 | ],
700 | "metadata": {
701 | "kernelspec": {
702 | "display_name": "eegextract",
703 | "language": "python",
704 | "name": "python3"
705 | },
706 | "language_info": {
707 | "codemirror_mode": {
708 | "name": "ipython",
709 | "version": 3
710 | },
711 | "file_extension": ".py",
712 | "mimetype": "text/x-python",
713 | "name": "python",
714 | "nbconvert_exporter": "python",
715 | "pygments_lexer": "ipython3",
716 | "version": "3.11.14"
717 | }
718 | },
719 | "nbformat": 4,
720 | "nbformat_minor": 2
721 | }
722 |
--------------------------------------------------------------------------------
/EEGExtract.py:
--------------------------------------------------------------------------------
1 | import bisect
2 | import numpy as np
3 | import pandas as pd
4 | import pywt
5 | from scipy import stats, signal, integrate
6 | from dit.other import tsallis_entropy
7 | import dit
8 | import librosa
9 | import statsmodels.api as sm
10 | import itertools
11 | from statsmodels import tsa
12 | from sklearn.metrics import mutual_info_score
13 | import numpy as np
14 | from scipy import signal,integrate
15 | from sklearn.metrics.cluster import normalized_mutual_info_score as normed_mutual_info
16 |
17 | ################################################
18 | # Auxiliary Functions
19 | ################################################
20 |
21 | ##########
22 | # Filter the eegData, midpass filter
23 | # eegData: 3D np array [chans x ms x epochs]
24 | def filt_data(eegData, lowcut, highcut, fs, order=7):
25 | nyq = 0.5 * fs
26 | low = lowcut / nyq
27 | high = highcut / nyq
28 | b, a = signal.butter(order, [low, high], btype='band')
29 | filt_eegData = signal.lfilter(b, a, eegData, axis = 1)
30 | return filt_eegData
31 |
32 | #########
33 | # remove short bursts / spikes
34 | def fcnRemoveShortEvents(z,n):
35 | for chan in range(z.shape[0]):
36 | # check for too-short suppressions
37 | ct=0
38 | i0=1
39 | i1=1
40 | for i in range(2,len(z[chan,:])):
41 | if z[chan,i]==z[chan,i-1]:
42 | ct=ct+1
43 | i1=i
44 | else:
45 | if ct np.array(chD[1:]))[0].tolist() for chD in z.tolist()]
100 |
101 | bursts = get_intervals(went_high,went_low)
102 | supressions = get_intervals(went_low,went_high)
103 |
104 | return bursts,supressions
105 |
106 | ##########
107 | # Coherence in the Delta Band
108 | def CoherenceDelta(eegData, i, j, fs=100):
109 | nfft=eegData.shape[1]
110 | f, Cxy = signal.coherence(eegData[i,:,:], eegData[j,:,:], fs=fs, nfft=nfft, axis=0)#, window=np.hanning(nfft))
111 | out = np.mean(Cxy[np.all([f >= 0.5, f<=4], axis=0)], axis=0)
112 | return out
113 |
114 | ##########
115 | # correlation across channels
116 | def PhaseLagIndex(eegData, i, j):
117 | hxi = ss.hilbert(eegData[i,:,:])
118 | hxj = ss.hilbert(eegData[j,:,:])
119 | # calculating the INSTANTANEOUS PHASE
120 | inst_phasei = np.arctan(np.angle(hxi))
121 | inst_phasej = np.arctan(np.angle(hxj))
122 |
123 | out = np.abs(np.mean(np.sign(inst_phasej - inst_phasei), axis=0))
124 | return out
125 |
126 | ##########
127 | # Cross Correlation
128 | def crossCorrelation(eegData, i, j):
129 | out = np.zeros(eegData.shape[2])
130 | for epoch in range(eegData.shape[2]):
131 | ccor = np.correlate(eegData[i,:,epoch], eegData[j,:,epoch], mode="full")
132 | absccor = np.abs(ccor)
133 | out[epoch] = (np.max(absccor) - np.mean(absccor)) / np.std(absccor)
134 | return out
135 |
136 | ##########
137 | # Auxilary Cross-correlation Lag
138 | def corrCorrLagAux(eegData,ii,jj,Fs=100):
139 | out = np.zeros(eegData.shape[2])
140 | lagCorr = []
141 | for lag in range(0,eegData.shape[1],int(0.2*Fs)):
142 | tmp = eegData.copy()
143 | tmp[jj,:,:] = np.roll(tmp[jj,:,:], lag, axis=0)
144 | lagCorr.append(CrossCorrelation(tmp, ii, jj, Fs))
145 | return np.argmax(lagCorr,axis=0)
146 |
147 | ################################################
148 | # bandpower Functions
149 | ################################################
150 |
151 | ##########
152 | # compute the bandpower (area under segment (from fband[0] to fband[1] in Hz)
153 | # of curve in freqency domain) of data, at sampling frequency of Fs (100 ussually)
154 | def bandpower(data, fs, fband):
155 | freqs, powers = periodogram(data, fs)
156 | idx_min = np.argmax(freqs > fband[0]) - 1
157 | idx_max = np.argmax(freqs > fband[1]) - 1
158 | idx_delta = np.zeros(dtype=bool, shape=freqs.shape)
159 | idx_delta[idx_min:idx_max] = True
160 | bpower = simps(powers[idx_delta], freqs[idx_delta])
161 | return bpower
162 |
163 | ##########
164 | # computes the same thing as vecbandpower but with a loop
165 | def pfvecbandpower(data, fs, fband):
166 | bpowers = np.zeros((data.shape[0], data.shape[2]))
167 | for i in range(data.shape[0]):
168 | freqs, powers = periodogram(data[i, :, :], fs, axis=0)
169 | idx_min = np.argmax(freqs > fband[0]) - 1
170 | idx_max = np.argmax(freqs > fband[1]) - 1
171 | idx_delta = np.zeros(dtype=bool, shape=freqs.shape)
172 | idx_delta[idx_min:idx_max] = True
173 |
174 | bpower = simps(powers[idx_delta, :], freqs[idx_delta], axis=0)
175 | bpowers[i, :] = bpower
176 |
177 | return bpowers
178 |
179 | ################################################
180 | # Complexity features
181 | ################################################
182 |
183 | ##########
184 | # Extract the Shannon Entropy
185 | # threshold the signal and make it discrete, normalize it and then compute entropy
186 | def shannonEntropy(eegData, bin_min, bin_max, binWidth):
187 | H = np.zeros((eegData.shape[0], eegData.shape[2]))
188 | for chan in range(H.shape[0]):
189 | for epoch in range(H.shape[1]):
190 | counts, binCenters = np.histogram(eegData[chan,:,epoch], bins=np.arange(bin_min+1, bin_max, binWidth))
191 | nz = counts > 0
192 | prob = counts[nz] / np.sum(counts[nz])
193 | H[chan, epoch] = -np.dot(prob, np.log2(prob/binWidth))
194 | return H
195 |
196 | ##########
197 | # Extract the tsalis Entropy
198 | def tsalisEntropy(eegData, bin_min, bin_max, binWidth, orders = [1]):
199 | H = [np.zeros((eegData.shape[0], eegData.shape[2]))]*len(orders)
200 | for chan in range(H[0].shape[0]):
201 | for epoch in range(H[0].shape[1]):
202 | counts, bins = np.histogram(eegData[chan,:,epoch], bins=np.arange(-200+1, 200, 2))
203 | dist = dit.Distribution([str(bc).zfill(5) for bc in bins[:-1]],counts/sum(counts))
204 | for ii,order in enumerate(orders):
205 | H[ii][chan,epoch] = tsallis_entropy(dist,order)
206 | return H
207 |
208 | ##########
209 | # Cepstrum Coefficients (n=2)
210 | def mfcc(eegData,fs,order=2):
211 | H = np.zeros((eegData.shape[0], eegData.shape[2],order))
212 | for chan in range(H.shape[0]):
213 | for epoch in range(H.shape[1]):
214 | H[chan, epoch, : ] = librosa.feature.mfcc(y=np.asfortranarray(eegData[chan,:,epoch]), sr=fs)[0:order].T
215 | return H
216 |
217 | ##########
218 | # Lyapunov exponent
219 | def lyapunov(eegData):
220 | return np.mean(np.log(np.abs(np.gradient(eegData,axis=1))),axis=1)
221 |
222 | ##########
223 | # Fractal Embedding Dimension
224 | # From pyrem: packadge for sleep scoring from EEG data
225 | # https://github.com/gilestrolab/pyrem/blob/master/src/pyrem/univariate.py
226 | def hFD(a, k_max): #Higuchi FD
227 | L = []
228 | x = []
229 | N = len(a)
230 |
231 | for k in range(1,k_max):
232 | Lk = 0
233 | for m in range(0,k):
234 | #we pregenerate all idxs
235 | idxs = np.arange(1,int(np.floor((N-m)/k)),dtype=np.int32)
236 | Lmk = np.sum(np.abs(a[m+idxs*k] - a[m+k*(idxs-1)]))
237 | Lmk = (Lmk*(N - 1)/(((N - m)/ k)* k)) / k
238 | Lk += Lmk
239 |
240 | L.append(np.log(Lk/(m+1)))
241 | x.append([np.log(1.0/ k), 1])
242 |
243 | (p, r1, r2, s)=np.linalg.lstsq(x, L)
244 | return p[0]
245 |
246 | ##########
247 | # Hjorth Mobility
248 | # Hjorth Complexity
249 | # variance = mean(signal^2) iff mean(signal)=0
250 | # which it is be because I normalized the signal
251 | # Assuming signals have mean 0
252 | # Mobility = sqrt( mean(dx^2) / mean(x^2) )
253 | def hjorthParameters(xV):
254 | dxV = np.diff(xV, axis=1)
255 | ddxV = np.diff(dxV, axis=1)
256 |
257 | mx2 = np.mean(np.square(xV), axis=1)
258 | mdx2 = np.mean(np.square(dxV), axis=1)
259 | mddx2 = np.mean(np.square(ddxV), axis=1)
260 |
261 | mob = mdx2 / mx2
262 | complexity = np.sqrt((mddx2 / mdx2) / mob)
263 | mobility = np.sqrt(mob)
264 |
265 | # PLEASE NOTE that Mohammad did NOT ACTUALLY use hjorth complexity,
266 | # in the matlab code for hjorth complexity subtraction by mob not division was used
267 | return mobility, complexity
268 |
269 | ##########
270 | # false nearest neighbor descriptor
271 | def falseNearestNeighbor(eegData, fast=True):
272 | # Average Mutual Information
273 | # There exist good arguments that if the time delayed mutual
274 | # information exhibits a marked minimum at a certain value of tex2html_wrap_inline6553,
275 | # then this is a good candidate for a reasonable time delay.
276 | npts = 1000 # not sure about this?
277 | maxdims = 50
278 | max_delay = 2 # max_delay = 200 # TODO: need to use 200, but also need to speed this up
279 | distance_thresh = 0.5
280 |
281 | out = np.zeros((eegData.shape[0], eegData.shape[2]))
282 | for chan in range(eegData.shape[0]):
283 | for epoch in range(eegData.shape[2]):
284 | if fast:
285 | out[chan, epoch] = 0
286 | else:
287 | cur_eegData = eegData[chan, :, epoch]
288 | lagidx = 0 # we are looking for the index of the lag that makes the signal maximally uncorrelated to the original
289 | # # minNMI = 1 # normed_mutual_info is from 1 (perfectly correlated) to 0 (not at all correlated)
290 | # # for lag in range(1, max_delay):
291 | # # x = cur_eegData[:-lag]
292 | # # xlag = cur_eegData[lag:]
293 | # # # convert float data into histogram bins
294 | # # nbins = int(np.floor(1 + np.log2(len(x)) + 0.5))
295 | # # x_discrete = np.histogram(x, bins=nbins)[0]
296 | # # xlag_discrete = np.histogram(xlag, bins=nbins)[0]
297 | # # cNMI = normed_mutual_info(x_discrete, xlag_discrete)
298 | # # if cNMI < minNMI:
299 | # # minNMI = cNMI
300 | # # lagidx = lag
301 | # nearest neighbors part
302 | knn = int(max(2, 6*lagidx)) # heuristic (number of nearest neighbors to look up)
303 | m = 1 # lagidx + 1
304 |
305 | # y is the embedded version of the signal
306 | y = np.zeros((maxdims+1, npts))
307 | for d in range(maxdims+1):
308 | tmp = cur_eegData[d*m:d*m + npts]
309 | y[d, :tmp.shape[0]] = tmp
310 |
311 | nnd = np.ones((npts, maxdims))
312 | nnz = np.zeros((npts, maxdims))
313 |
314 | # see where it tends to settle
315 | for d in range(1, maxdims):
316 | for k in range(0, npts):
317 | # get the distances to all points in the window (distance given embedding dimension)
318 | dists = []
319 | for nextpt in range(1, knn+1):
320 | if k+nextpt < npts:
321 | dists.append(np.linalg.norm(y[:d, k] - y[:d, k+nextpt]))
322 | if len(dists) > 0:
323 | minIdx = np.argmin(dists)
324 | if dists[minIdx] == 0:
325 | dists[minIdx] = 0.0000001 # essentially 0 just silence the error
326 | nnd[k, d-1] = dists[minIdx]
327 | nnz[k, d-1] = np.abs( y[d+1, k] - y[d+1, minIdx+1+k] )
328 | # aggregate results
329 | mindim = np.mean(nnz/nnd > distance_thresh, axis=0) < 0.1
330 | # get the index of the first occurence of the value true
331 | # (a 1 in the binary representation of true and false)
332 | out[chan, epoch] = np.argmax(mindim)
333 |
334 | return out
335 |
336 | ##########
337 | # ARMA coefficients
338 | def arma(eegData,order=2):
339 | H = np.zeros((eegData.shape[0], eegData.shape[2],order))
340 | for chan in range(H.shape[0]):
341 | for epoch in range(H.shape[1]):
342 | # ARMA is deprecated, use ARIMA with d=0 instead
343 | arma_mod = sm.tsa.ARIMA(eegData[chan,:,epoch], order=(order, 0, order), trend='n')
344 | arma_res = arma_mod.fit(method_kwargs={'disp': False})
345 | H[chan, epoch, : ] = arma_res.arparams
346 | return H
347 |
348 | ################################################
349 | # Continuity features
350 | ################################################
351 |
352 | ##########
353 | # median frequency
354 | def medianFreq(eegData,fs):
355 | H = np.zeros((eegData.shape[0], eegData.shape[2]))
356 | for chan in range(H.shape[0]):
357 | freqs, powers = signal.periodogram(eegData[chan, :, :], fs, axis=0)
358 | H[chan,:] = freqs[np.argsort(powers,axis=0)[len(powers)//2]]
359 | return H
360 |
361 | ##########
362 | # calculate band power
363 | def bandPower(eegData, lowcut, highcut, fs):
364 | eegData_band = filt_data(eegData, lowcut, highcut, fs, order=7)
365 | freqs, powers = signal.periodogram(eegData_band, fs, axis=1)
366 | bandPwr = np.mean(powers,axis=1)
367 | return bandPwr
368 |
369 | ##########
370 | # numberOfSpikes
371 | def spikeNum(eegData,minNumSamples=7,stdAway = 3):
372 | H = np.zeros((eegData.shape[0], eegData.shape[2]))
373 | for chan in range(H.shape[0]):
374 | for epoch in range(H.shape[1]):
375 | mean = np.mean(eegData[chan, :, epoch])
376 | std = np.std(eegData[chan,:,epoch],axis=1)
377 | H[chan,epoch] = len(signal.find_peaks(abs(eegData[chan,:,epoch]-mean), 3*std,epoch,width=7)[0])
378 | return H
379 |
380 | ##########
381 | # Standard Deviation
382 | def eegStd(eegData):
383 | std_res = np.std(eegData,axis=1)
384 | return std_res
385 |
386 | ##########
387 | # α/δ Ratio
388 | def eegRatio(eegData,fs):
389 | # alpha (8–12 Hz)
390 | eegData_alpha = filt_data(eegData, 8, 12, fs)
391 | # delta (0.5–4 Hz)
392 | eegData_delta = filt_data(eegData, 0.5, 4, fs)
393 | # calculate the power
394 | powers_alpha = bandPower(eegData, 8, 12, fs)
395 | powers_delta = bandPower(eegData, 0.5, 4, fs)
396 | ratio_res = np.sum(powers_alpha,axis=0) / np.sum(powers_delta,axis=0)
397 | return np.expand_dims(ratio_res, axis=0)
398 |
399 | ###########
400 | # Regularity (burst-suppression)
401 | # Regularity of eeg
402 | # filter with a window of 0.5 seconds to create a nonnegative smooth signal.
403 | # In this technique, we first squared the signal and applied a moving-average
404 | # The window length of the moving average was set at 0.5 seconds.
405 | def eegRegularity(eegData, Fs=100):
406 | in_x = np.square(eegData) # square signal
407 | num_wts = Fs//2 # find the filter length in samples - we want 0.5 seconds.
408 | q = signal.lfilter(np.ones(num_wts) / num_wts, 1, in_x, axis=1)
409 | q = -np.sort(-q, axis=1) # descending sort on smooth signal
410 | N = q.shape[1]
411 | u2 = np.square(np.arange(1, N+1))
412 | # COMPUTE THE Regularity
413 | # dot each 5min epoch with the quadratic data points and then normalize by the size of the dotted things
414 | reg = np.sqrt( np.einsum('ijk,j->ik', q, u2) / (np.sum(q, axis=1)*(N**2)/3) )
415 | return reg
416 |
417 | ###########
418 | # Voltage < (5μ, 10μ, 20μ)
419 | def eegVoltage(eegData,voltage=20):
420 | eegFilt = eegData.copy()
421 | eegFilt[abs(eegFilt) > voltage] = np.nan
422 | volt_res = np.nanmean(eegFilt,axis=1)
423 | return volt_res
424 |
425 | ##########
426 | # Diffuse Slowing
427 | # look for diffuse slowing (bandpower max from frequency domain integral)
428 | # repeated integration of a huge tensor is really expensive
429 | def diffuseSlowing(eegData, Fs=100, fast=True):
430 | maxBP = np.zeros((eegData.shape[0], eegData.shape[2]))
431 | idx = np.zeros((eegData.shape[0], eegData.shape[2]))
432 | if fast:
433 | return idx
434 | for j in range(1, Fs//2):
435 | print("BP", j)
436 | cbp = bandpower(eegData, Fs, [j-1, j])
437 | biggerCIdx = cbp > maxBP
438 | idx[biggerCIdx] = j
439 | maxBP[biggerCIdx] = cbp[biggerCIdx]
440 | return (idx < 8)
441 |
442 | ##########
443 | # Spikes
444 | def spikeNum(eegData,minNumSamples=7,stdAway = 3):
445 | H = np.zeros((eegData.shape[0], eegData.shape[2]))
446 | for chan in range(H.shape[0]):
447 | for epoch in range(H.shape[1]):
448 | mean = np.mean(eegData[chan, :, epoch])
449 | std = np.std(eegData[chan,:,epoch])
450 | H[chan,epoch] = len(signal.find_peaks(abs(eegData[chan,:,epoch]-mean), 3*std,epoch,width=7)[0])
451 | return H
452 |
453 | ##########
454 | # Delta Burst after spike
455 | def burstAfterSpike(eegData,eegData_subband,minNumSamples=7,stdAway = 3):
456 | H = np.zeros((eegData.shape[0], eegData.shape[2]))
457 | for chan in range(H.shape[0]):
458 | for epoch in range(H.shape[1]):
459 | preBurst = 0
460 | postBurst = 0
461 | mean = np.mean(eegData[chan, :, epoch])
462 | std = np.std(eegData[chan,:,epoch])
463 | idxList = signal.find_peaks(abs(eegData[chan,:,epoch]-mean), stdAway*std,epoch,width=minNumSamples)[0]
464 | for idx in idxList:
465 | preBurst += np.mean(eegData_subband[chan,idx-7:idx-1,epoch])
466 | postBurst += np.mean(eegData_subband[chan,idx+1:idx+7,epoch])
467 | H[chan,epoch] = postBurst - preBurst
468 | return H
469 |
470 | ##########
471 | # Sharp spike
472 | def shortSpikeNum(eegData,minNumSamples=7,stdAway = 3):
473 | H = np.zeros((eegData.shape[0], eegData.shape[2]))
474 | for chan in range(H.shape[0]):
475 | for epoch in range(H.shape[1]):
476 | mean = np.mean(eegData[chan, :, epoch])
477 | std = np.std(eegData[chan,:,epoch])
478 | longSpikes = set(signal.find_peaks(abs(eegData[chan,:,epoch]-mean), 3*std,epoch,width=7)[0])
479 | shortSpikes = set(signal.find_peaks(abs(eegData[chan,:,epoch]-mean), 3*std,epoch,width=1)[0])
480 | H[chan,epoch] = len(shortSpikes.difference(longSpikes))
481 | return H
482 |
483 | ##########
484 | # Number of Bursts
485 | def numBursts(eegData,fs):
486 | bursts = []
487 | supressions = []
488 | for epoch in range(eegData.shape[2]):
489 | epochBurst,epochSupressions = burst_supression_detection(eegData[:,:,epoch],fs,suppression_threshold=10)#,low=30,high=49)
490 | bursts.append(epochBurst)
491 | supressions.append(epochSupressions)
492 | # Number of Bursts
493 | numBursts_res = np.zeros((eegData.shape[0], eegData.shape[2]))
494 | for chan in range(numBursts_res.shape[0]):
495 | for epoch in range(numBursts_res.shape[1]):
496 | numBursts_res[chan,epoch] = len(bursts[epoch][chan])
497 | return numBursts_res
498 |
499 | ##########
500 | # Burst length μ and σ
501 | def burstLengthStats(eegData,fs):
502 | bursts = []
503 | supressions = []
504 | for epoch in range(eegData.shape[2]):
505 | epochBurst,epochSupressions = burst_supression_detection(eegData[:,:,epoch],fs,suppression_threshold=10)#,low=30,high=49)
506 | bursts.append(epochBurst)
507 | supressions.append(epochSupressions)
508 | # Number of Bursts
509 | burstMean_res = np.zeros((eegData.shape[0], eegData.shape[2]))
510 | burstStd_res = np.zeros((eegData.shape[0], eegData.shape[2]))
511 | for chan in range(burstMean_res.shape[0]):
512 | for epoch in range(burstMean_res.shape[1]):
513 | burstMean_res[chan,epoch] = np.mean([burst[1]-burst[0] for burst in bursts[epoch][chan]])
514 | burstStd_res[chan,epoch] = np.std([burst[1]-burst[0] for burst in bursts[epoch][chan]])
515 | burstMean_res = np.nan_to_num(burstMean_res)
516 | burstStd_res = np.nan_to_num(burstStd_res)
517 | return burstMean_res,burstStd_res
518 |
519 | ##########
520 | # Burst band powers (δ, α, θ, β, γ)
521 | def burstBandPowers(eegData, lowcut, highcut, fs, order=7):
522 | band_burst_powers = np.zeros((eegData.shape[0], eegData.shape[2]))
523 | bursts = []
524 | supressions = []
525 | for epoch in range(eegData.shape[2]):
526 | epochBurst,epochSupressions = burst_supression_detection(eegData[:,:,epoch],fs,suppression_threshold=10)#,low=30,high=49)
527 | bursts.append(epochBurst)
528 | supressions.append(epochSupressions)
529 | eegData_band = filt_data(eegData, lowcut, highcut, fs, order=7)
530 | for epoch,epochBursts in enumerate(bursts):
531 | for chan,chanBursts in enumerate(epochBursts):
532 | epochPowers = []
533 | for burst in chanBursts:
534 | if burst[1] == eegData.shape[1]:
535 | burstData = eegData_band[:,burst[0]:,epoch]
536 | else:
537 | burstData = eegData_band[:,burst[0]:burst[1],epoch]
538 | freqs, powers = signal.periodogram(burstData, fs, axis=1)
539 | epochPowers.append(np.mean(powers,axis=1))
540 | band_burst_powers[chan,epoch] = np.mean(epochPowers)
541 | return band_burst_powers
542 |
543 | ##########
544 | # Number of Suppressions
545 | def numSuppressions(eegData,fs,suppression_threshold=10):
546 | bursts = []
547 | supressions = []
548 | for epoch in range(eegData.shape[2]):
549 | epochBurst,epochSupressions = burst_supression_detection(eegData[:,:,epoch],fs,suppression_threshold=suppression_threshold)#,low=30,high=49)
550 | bursts.append(epochBurst)
551 | supressions.append(epochSupressions)
552 | numSupprs_res = np.zeros((eegData.shape[0], eegData.shape[2]))
553 | for chan in range(numSupprs_res.shape[0]):
554 | for epoch in range(numSupprs_res.shape[1]):
555 | numSupprs_res[chan,epoch] = len(supressions[epoch][chan])
556 | return numSupprs_res
557 |
558 | ##########
559 | # Suppression length μ and σ
560 | def suppressionLengthStats(eegData,fs,suppression_threshold=10):
561 | bursts = []
562 | supressions = []
563 | for epoch in range(eegData.shape[2]):
564 | epochBurst,epochSupressions = burst_supression_detection(eegData[:,:,epoch],fs,suppression_threshold=suppression_threshold)#,low=30,high=49)
565 | bursts.append(epochBurst)
566 | supressions.append(epochSupressions)
567 | supressionMean_res = np.zeros((eegData.shape[0], eegData.shape[2]))
568 | supressionStd_res = np.zeros((eegData.shape[0], eegData.shape[2]))
569 | for chan in range(supressionMean_res.shape[0]):
570 | for epoch in range(supressionMean_res.shape[1]):
571 | supressionMean_res[chan,epoch] = np.mean([suppr[1]-suppr[0] for suppr in supressions[epoch][chan]])
572 | supressionStd_res[chan,epoch] = np.std([suppr[1]-suppr[0] for suppr in supressions[epoch][chan]])
573 | supressionMean_res = np.nan_to_num(supressionMean_res)
574 | supressionStd_res = np.nan_to_num(supressionStd_res)
575 | return supressionMean_res, supressionStd_res
576 |
577 | ################################################
578 | # Connectivity features
579 | ################################################
580 |
581 | ##########
582 | # Coherence - δ
583 | def coherence(eegData,fs):
584 | coh_res = []
585 | for ii, jj in itertools.combinations(range(eegData.shape[0]), 2):
586 | coh_res.append(CoherenceDelta(eegData, ii, jj, fs=fs))
587 | coh_res = np.array(coh_res)
588 | return coh_res
589 |
590 | ##########
591 | # Mutual information
592 | def calculate2Chan_MI(eegData,ii,jj,bin_min=-200, bin_max=200, binWidth=2):
593 | H = np.zeros(eegData.shape[2])
594 | bins = np.arange(bin_min+1, bin_max, binWidth)
595 | for epoch in range(eegData.shape[2]):
596 | c_xy = np.histogram2d(eegData[ii,:,epoch],eegData[jj,:,epoch],bins)[0]
597 | H[epoch] = mutual_info_score(None, None, contingency=c_xy)
598 | return H
599 |
600 | ##########
601 | # Granger causality
602 | def calcGrangerCausality(eegData,ii,jj):
603 | H = np.zeros(eegData.shape[2])
604 | for epoch in range(eegData.shape[2]):
605 | X = np.vstack([eegData[ii,:,epoch],eegData[jj,:,epoch]]).T
606 | H[epoch] = tsa.stattools.grangercausalitytests(X, 1, addconst=True, verbose=False)[1][0]['ssr_ftest'][0]
607 | return H
608 |
609 | ##########
610 | # phase Lag Index
611 | def phaseLagIndex(eegData, i, j):
612 | hxi = ss.hilbert(eegData[i,:,:])
613 | hxj = ss.hilbert(eegData[j,:,:])
614 | # calculating the INSTANTANEOUS PHASE
615 | inst_phasei = np.arctan(np.angle(hxi))
616 | inst_phasej = np.arctan(np.angle(hxj))
617 |
618 | out = np.abs(np.mean(np.sign(inst_phasej - inst_phasei), axis=0))
619 | return out
620 |
621 | ##########
622 | # Cross-correlation Magnitude
623 | def crossCorrMag(eegData,ii,jj):
624 | crossCorr_res = []
625 | for ii, jj in itertools.combinations(range(eegData.shape[0]), 2):
626 | crossCorr_res.append(crossCorrelation(eegData, ii, jj))
627 | crossCorr_res = np.array(crossCorr_res)
628 | return crossCorr_res
629 |
630 | ##########
631 | # Cross-correlation Lag
632 | def corrCorrLag(eegData,ii,jj,fs=100):
633 | crossCorrLag_res = []
634 | for ii, jj in itertools.combinations(range(eegData.shape[0]), 2):
635 | crossCorrLag_res.append(corrCorrLag(eegData, ii, jj, fs))
636 | crossCorrLag_res = np.array(crossCorrLag_res)
637 | return crossCorrLag_res
638 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------