├── .gitignore ├── LICENSE ├── README.md ├── Seizure Detection Pipeline-Description.docx ├── evaluate ├── 2-unet-prediction.py ├── 3-lstm-fusion.py ├── 4-postprocessing.py ├── Preparing Predictions.ipynb ├── README.md ├── attention_unet_iclabel.h5 ├── attention_unet_raw.h5 ├── attention_unet_wiener.h5 └── model-dnn-dnnw-dnnicalbl-lstm-4.h5 ├── hyp_lstm.txt ├── library ├── filters.pickle ├── loading.py ├── nedc.py ├── preprocess.py ├── spir.py └── wiener.py ├── neureka_ieee_spmb.pdf ├── python_requirements.txt └── training ├── 1-wiener-training.py ├── 2-iclabel ├── README.md ├── findRecording.m ├── getContent.m ├── input.mat ├── neureka.locs ├── pop_clean_rawdata.m ├── pop_runica.m ├── run_ica.m └── run_icalabel.m ├── 3-DNN ├── 3-load-data.py ├── 3-train-unet.py ├── README.md └── utils.py ├── 4-train-lstm.py └── README.md /.gitignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mabhijithn/irregulars-neureka-codebase/a5d96ce0f8b972f3b98e848454196b84e6bbc4c0/.gitignore -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Seizure Detection Codebase used in Neureka Challenge 2020 2 | 3 | 4 | This repository contains the code of the *Biomed Irregulars* submission to the Neureka Challenge 2020. The *Biomed irregulars* team consists of PhD students from the the ESAT-STADIUS research group at KU Leuven: C. Chatzichristos, J. Dan, A.M. Narayanan, N. Seeuws, K. Vandecasteele. 5 | 6 | The seizure detection algorithm is based on the fusion of multiple attention U-nets, each operating on a distinct view of the EEG data. The outputs of the different U-nets are fused by an LSTM network. More information about the methods and results can be found in the preliminary version of the paper [neureka_ieee_spmb.pdf](neureka_ieee_spmb.pdf). 7 | 8 | 9 | ## Code 10 | 1. `library/` - This folder contains the general functions used accross modules: data loading, re-referencing, resampling and filtering. 11 | 2. `training/` - Contains the code to train the Wiener filters, U-nets and LSTM models. 12 | 3. `evaluate/` - Contains the code to run the seizure detection pipeline on unlabelled data. 13 | 14 | ## Requirements 15 | 16 | The codebase uses a mix of Python 3 and Matlab. 17 | 18 | The dataset used is the [TUH EEG Seizure dataset](https://www.isip.piconepress.com/projects/tuh_eeg/html/downloads.shtml). 19 | 20 | Matlab requires the [EEGlab](https://sccn.ucsd.edu/eeglab/index.php) toolbox. 21 | 22 | Python requires the libraries listed in [python_requirements.txt](python_requirements.txt). 23 | 24 | ---- 25 | 26 | While the intent of the code is to allow deceminatation and re-use of our pipeline and model architecture. We realize the code is not *click & run* and documentation is sometimes lacking. We do invite you to contact us through email or as a github issue to improve quality and understanding of the code. 27 | 28 | 29 | --- 30 | 31 | The code is release under the GNU GPLv3 license. 32 | 33 | 34 | -------------------------------------------------------------------------------- /Seizure Detection Pipeline-Description.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mabhijithn/irregulars-neureka-codebase/a5d96ce0f8b972f3b98e848454196b84e6bbc4c0/Seizure Detection Pipeline-Description.docx -------------------------------------------------------------------------------- /evaluate/2-unet-prediction.py: -------------------------------------------------------------------------------- 1 | """Generate U-net predictions 2 | 3 | Requires pre-processed EDF files similar to the training step 4 | Requires the trained U-net model 5 | 6 | Produces a results HDF5 file with predictions for every file 7 | """ 8 | 9 | 10 | # Libraries 11 | import h5py 12 | import numpy as np 13 | from sklearn import model_selection 14 | from sklearn import metrics 15 | import os 16 | import tensorflow as tf 17 | 18 | # Import some utilities from the training folder 19 | import sys 20 | sys.path.insert(0, 'training/3-DNN/') 21 | from utils import build_windowfree_unet, setup_tf 22 | 23 | # All relevant files 24 | val_path = 'PATH_TO_DATASET.h5' # Pre-processed data file 25 | saved_predictions = 'PATH_TO_PREDICTIONS.h5' # File to store the prediction 26 | network_path = 'PATH_TO_NETWORK_WEIGHTS.h5' # Path to trained weights 27 | 28 | # Data settings 29 | fs = 200 30 | n_channels = 18 31 | n_filters = 8 32 | 33 | # Tensorflow function to detect GPU properly 34 | setup_tf() 35 | 36 | # Loading the signals 37 | with h5py.File(val_path, 'r') as f: 38 | file_names_test = [] 39 | signals_test = [] 40 | 41 | file_names_ds = f['filenames'] 42 | signals_ds = f['signals'] 43 | 44 | for i in range(len(signals_ds)): 45 | file_names_test.append(file_names_ds[i]) 46 | data = np.asarray(np.vstack(signals_ds[i]).T, dtype=np.float32) 47 | mean = np.mean(data, axis=0) 48 | std = np.std(data, axis=0) 49 | signals_test.append((data-mean)/(std+1e-8)) 50 | 51 | # Building a windowfree U-net and load trained weights 52 | unet = build_windowfree_unet(n_channels=n_channels, n_filters=n_filters) 53 | unet.load_weights(network_path) 54 | 55 | # Predictions using the windowfree U-net on CPU, our GPU ran out of memory 56 | y_probas = [] 57 | reduction = 4096//4 58 | with tf.device('cpu:0'): 59 | for signal in signals_test: 60 | signal = signal[:len(signal)//reduction*reduction, :] 61 | prediction = unet.predict(signal[np.newaxis, :, :, np.newaxis])[0, :, 0, 0] 62 | y_probas.append(prediction) 63 | 64 | # Saving predictions 65 | dt_fl = h5py.vlen_dtype(np.dtype('float32')) 66 | dt_str = h5py.special_dtype(vlen=str) 67 | with h5py.File(saved_predictions, 'w') as f: 68 | dset_signals = f.create_dataset('signals', (len(file_names_test),), dtype=dt_fl) 69 | dset_file_names = f.create_dataset('filenames', (len(file_names_test),), dtype=dt_str) 70 | 71 | for i in range(len(file_names_test)): 72 | dset_signals[i] = y_probas[i] 73 | dset_file_names[i] = file_names_test[i] 74 | -------------------------------------------------------------------------------- /evaluate/3-lstm-fusion.py: -------------------------------------------------------------------------------- 1 | """Fuse U-net predictions with an LSTM network 2 | 3 | Requires predictions from the U-nets 4 | Requires the trained LSTM model 5 | 6 | Produces a results pickle file to be used by the postprocessing 7 | """ 8 | 9 | # + 10 | import sys 11 | # Root folder of main library 12 | sys.path.insert(0, 'library') 13 | # Root folder of EDF files 14 | EDF_ROOT = '/esat/biomeddata/Neureka_challenge/edf/dev/' 15 | # Root folder of predictions on edf files 16 | PREDICTION_ROOT = 'evaluation' 17 | 18 | # std lib 19 | import os 20 | import pickle 21 | 22 | # 3rd party lib 23 | import h5py 24 | from keras.models import load_model 25 | import numpy as np 26 | import resampy 27 | 28 | 29 | # + 30 | def load_filenames(): 31 | filenames = list() 32 | with h5py.File(os.joind(PREDICTION_ROOT, 'prediction_test_iclabel.h5'), 'r') as f: 33 | filenames = list(f['filenames']) 34 | return filenames 35 | 36 | 37 | def prepare_file(file_i, filename, classifiers, f_nick, model_type): 38 | # Load data 39 | x = list() 40 | for classifier in classifiers: 41 | if classifier['format'] == 'nick': 42 | z = list(f_nick[classifier['name']]['filenames']) 43 | file_i = z.index(filename) 44 | predictions = f_nick[classifier['name']]['signals'][file_i] 45 | predictions = downsample(predictions, 200, fs) 46 | x.append(np.array(predictions, dtype=float)) 47 | 48 | x = np.array(x) 49 | x = np.transpose(x) 50 | if model_type == 'lstm' or model_type == 'gru': 51 | x = x.reshape((len(x), 1, len(x[0]))) 52 | 53 | return x 54 | 55 | def downsample(x, oldFs, newFs): 56 | return resampy.resample(x, oldFs, newFs) 57 | 58 | 59 | 60 | def test(model, modeltype, classifiers, filenames): 61 | # Preload Nick data 62 | f_nick = dict() 63 | for classifier in classifiers: 64 | if classifier['format'] == 'nick': 65 | f_nick[classifier['name']] = h5py.File(classifier['file'], 'r') 66 | 67 | # Predict probabilities 68 | results = list() 69 | for i, filename in enumerate(filenames): 70 | x, y = prepare_file(i, filename, classifiers, f_nick, modeltype) 71 | u = model.predict(x, batch_size=1) 72 | model.reset_states() 73 | results.append(u) 74 | 75 | with open('lstm-results.pkl', 'wb') as filehandler: 76 | pickle.dump(results, filehandler) 77 | 78 | # Close Nick data 79 | for key in f_nick: 80 | f_nick[key].close() 81 | 82 | 83 | # + 84 | fs = 1 85 | 86 | classifiers = [{ 87 | 'name': 'ICA', 88 | 'file': os.join(PREDICTION_ROOT, 'prediction_test_iclabel.h5'), 89 | 'fs': 200, 90 | 'format': 'nick', 91 | }, 92 | { 93 | 'name': 'DNN', 94 | 'file': os.join(PREDICTION_ROOT, 'prediction_test_raw.h5'), 95 | 'fs': 200, 96 | 'format': 'nick', 97 | }, 98 | { 99 | 'name': 'DNN-wiener', 100 | 'file': os.join(PREDICTION_ROOT, 'prediction_test_wiener.h5'), 101 | 'fs': 200, 102 | 'format': 'nick', 103 | } 104 | ] 105 | 106 | modeltype = 'lstm' 107 | complexity = 4 108 | 109 | filenames = load_filenames() 110 | model = load_model('model-dnn-dnnw-dnnicalbl-lstm-4.h5') 111 | test(model, modeltype, classifiers, filenames) -------------------------------------------------------------------------------- /evaluate/4-postprocessing.py: -------------------------------------------------------------------------------- 1 | 2 | """Build hypothesis file by applying post-processing rules 3 | to LSTM output 4 | 5 | Requires LSTM output 6 | 7 | Produces a hypothesis txt file 8 | """ 9 | 10 | # + 11 | import sys 12 | # Root folder of main library 13 | sys.path.insert(0, 'library') 14 | # Root folder of EDF files 15 | EDF_ROOT = '/esat/biomeddata/Neureka_challenge/edf/dev/' 16 | # Root folder of predictions on edf files 17 | PREDICTION_ROOT = 'evaluation' 18 | 19 | # custom lib 20 | import spir 21 | 22 | # std lib 23 | import os 24 | import pickle 25 | 26 | # 3rd party lib 27 | import h5py 28 | import numpy as np 29 | 30 | 31 | # + 32 | def load_filenames(): 33 | filenames = list() 34 | with h5py.File(os.join(PREDICTION_ROOT, 'prediction_test_iclabel.h5'), 'r') as f: 35 | filenames = list(f['filenames']) 36 | return filenames 37 | 38 | 39 | filenames = load_filenames() 40 | with open('lstm-results.pkl', 'rb') as filehandler: 41 | results = pickle.load(filehandler) 42 | 43 | 44 | threshold = 0.55 45 | 46 | for i, filename in enumerate(filenames): 47 | # Apply threshold on baseline corrected prediction 48 | hyp = spir.mask2eventList((results[i].flatten() - np.median(results[i].flatten())) > threshold, fs) 49 | # Merge events closer than 30seconds 50 | hyp = spir.merge_events(hyp, 30) 51 | 52 | # Remove events with mean prediction < 82% of event with max prediction 53 | if len(hyp): 54 | amp = list() 55 | for event in hyp: 56 | amp.append(np.mean(results[i].flatten()[int(event[0]*fs):int(event[1]*fs)])) 57 | amp = np.array(amp) 58 | amp /= np.max(amp) 59 | 60 | hyp = list(np.array(hyp)[amp > 0.82]) 61 | 62 | with open('hyp_lstm.txt', 'a') as handle: 63 | for event in hyp: 64 | # Remove short events 65 | if event[1] - event[0] > 15: 66 | amp = np.mean(results[i][int(event[0]*fs):int(event[1]*fs)]) 67 | # Shorten events by 2 seconds 68 | handle.write('{} {} {} {} 16\n'.format(filename, event[0]+1, event[1]-1), amp) 69 | -------------------------------------------------------------------------------- /evaluate/Preparing Predictions.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "import h5py\n", 10 | "import numpy as np\n", 11 | "from sklearn import model_selection\n", 12 | "import matplotlib.pyplot as plt\n", 13 | "from sklearn import metrics\n", 14 | "import os\n", 15 | "import tensorflow as tf\n", 16 | "from tensorflow.keras import Model, Input\n", 17 | "from tensorflow.keras.layers import Conv2D, UpSampling2D, MaxPooling2D, AveragePooling2D, Attention\n", 18 | "from tensorflow.keras.layers import ELU, BatchNormalization, Reshape, Concatenate, Dropout, Add, Multiply\n", 19 | "\n", 20 | "from utils import SeizureState, setup_tf, AttentionPooling, BiasedConv" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "metadata": {}, 27 | "outputs": [], 28 | "source": [ 29 | "val_path = 'PATH_TO_DATASET.h5'\n", 30 | "saved_predictions = 'PATH_TO_PREDICTIONS.h5'\n", 31 | "network_path = 'PATH_TO_NETWORK_WEIGHTS.h5'\n", 32 | "\n", 33 | "fs = 200\n", 34 | "n_channels = 18\n", 35 | "seizure = 'seiz'\n", 36 | "background = 'bckg'" 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": null, 42 | "metadata": {}, 43 | "outputs": [], 44 | "source": [ 45 | "setup_tf()" 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "execution_count": null, 51 | "metadata": {}, 52 | "outputs": [], 53 | "source": [ 54 | "with h5py.File(val_path, 'r') as f:\n", 55 | " file_names_test = []\n", 56 | " signals_test = []\n", 57 | " \n", 58 | " file_names_ds = f['filenames']\n", 59 | " signals_ds = f['signals']\n", 60 | " \n", 61 | " for i in range(len(signals_ds)):\n", 62 | " file_names_test.append(file_names_ds[i])\n", 63 | " data = np.asarray(np.vstack(signals_ds[i]).T, dtype=np.float32)\n", 64 | " mean = np.mean(data, axis=0)\n", 65 | " std = np.std(data, axis=0)\n", 66 | " signals_test.append((data-mean)/(std+1e-8))" 67 | ] 68 | }, 69 | { 70 | "cell_type": "markdown", 71 | "metadata": {}, 72 | "source": [ 73 | "# Seizure detection" 74 | ] 75 | }, 76 | { 77 | "cell_type": "markdown", 78 | "metadata": {}, 79 | "source": [ 80 | "### Building U-Net" 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": null, 86 | "metadata": {}, 87 | "outputs": [], 88 | "source": [ 89 | "n_filters = 8" 90 | ] 91 | }, 92 | { 93 | "cell_type": "code", 94 | "execution_count": null, 95 | "metadata": {}, 96 | "outputs": [], 97 | "source": [ 98 | "input_seq = Input(shape=(None, n_channels, 1))\n", 99 | "\n", 100 | "x = Conv2D(filters=n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(input_seq)\n", 101 | "x = BatchNormalization()(x)\n", 102 | "lvl0 = ELU()(x)\n", 103 | "\n", 104 | "x = MaxPooling2D(pool_size=(4, 1), padding='same')(lvl0)\n", 105 | "x = Conv2D(filters=2*n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(x)\n", 106 | "x = BatchNormalization()(x)\n", 107 | "lvl1 = ELU()(x)\n", 108 | "\n", 109 | "x = MaxPooling2D(pool_size=(4, 1), padding='same')(lvl1)\n", 110 | "x = Conv2D(filters=4*n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(x)\n", 111 | "x = BatchNormalization()(x)\n", 112 | "lvl2 = ELU()(x)\n", 113 | "\n", 114 | "x = MaxPooling2D(pool_size=(4, 1), padding='same')(lvl2)\n", 115 | "x = Conv2D(filters=4*n_filters, kernel_size=(7, 1), strides=(1, 1), padding='same', activation=None)(x)\n", 116 | "x = BatchNormalization()(x)\n", 117 | "lvl3 = ELU()(x)\n", 118 | "\n", 119 | "x = MaxPooling2D(pool_size=(4, 1), padding='same')(lvl3)\n", 120 | "x = Conv2D(filters=8*n_filters, kernel_size=(3, 1), strides=(1, 1), padding='same', activation=None)(x)\n", 121 | "x = BatchNormalization()(x)\n", 122 | "lvl4 = ELU()(x)\n", 123 | "\n", 124 | "x = MaxPooling2D(pool_size=(4, 1), padding='same')(lvl4)\n", 125 | "x = Conv2D(filters=8*n_filters, kernel_size=(3, 1), strides=(1, 1), padding='same', activation=None)(x)\n", 126 | "x = BatchNormalization()(x)\n", 127 | "x = ELU()(x)\n", 128 | "lvl5 = x\n", 129 | "\n", 130 | "x = MaxPooling2D(pool_size=(1, 20), padding='same')(lvl5)\n", 131 | "x = Conv2D(filters=4*n_filters, kernel_size=(3, 1), strides=(1, 1), padding='same', activation=None)(x)\n", 132 | "x = BatchNormalization()(x)\n", 133 | "x = ELU()(x)\n", 134 | "x = Dropout(rate=0.5)(x)\n", 135 | "x = Conv2D(filters=4*n_filters, kernel_size=(3, 1), strides=(1, 1), padding='same', activation=None)(x)\n", 136 | "x = BatchNormalization()(x)\n", 137 | "x = ELU()(x)\n", 138 | "x = Dropout(rate=0.5)(x)\n", 139 | "\n", 140 | "up4 = UpSampling2D(size=(4, 1))(x)\n", 141 | "att4 = AttentionPooling(filters=4*n_filters, channels=n_channels)([up4, lvl4])\n", 142 | "\n", 143 | "x = Concatenate(axis=-1)([up4, att4])\n", 144 | "x = Conv2D(filters=4*n_filters, kernel_size=(3, 1), strides=(1, 1), padding='same', activation=None)(x)\n", 145 | "x = BatchNormalization()(x)\n", 146 | "x = ELU()(x)\n", 147 | "\n", 148 | "up3 = UpSampling2D(size=(4, 1))(x)\n", 149 | "att3 = AttentionPooling(filters=4*n_filters, channels=n_channels)([up3, lvl3])\n", 150 | "\n", 151 | "x = Concatenate(axis=-1)([up3, att3])\n", 152 | "x = Conv2D(filters=4*n_filters, kernel_size=(7, 1), strides=(1, 1), padding='same', activation=None)(x)\n", 153 | "x = BatchNormalization()(x)\n", 154 | "x = ELU()(x)\n", 155 | "\n", 156 | "up2 = UpSampling2D(size=(4, 1))(x)\n", 157 | "att2 = AttentionPooling(filters=4*n_filters, channels=n_channels)([up2, lvl2])\n", 158 | "\n", 159 | "x = Concatenate(axis=-1)([up2, att2])\n", 160 | "x = Conv2D(filters=4*n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(x)\n", 161 | "x = BatchNormalization()(x)\n", 162 | "x = ELU()(x)\n", 163 | "\n", 164 | "\n", 165 | "up1 = UpSampling2D(size=(4, 1))(x)\n", 166 | "att1 = AttentionPooling(filters=4*n_filters, channels=n_channels)([up1, lvl1])\n", 167 | "\n", 168 | "x = Concatenate(axis=-1)([up1, att1])\n", 169 | "x = Conv2D(filters=4*n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(x)\n", 170 | "x = BatchNormalization()(x)\n", 171 | "x = ELU()(x)\n", 172 | "\n", 173 | "up0 = UpSampling2D(size=(4, 1))(x)\n", 174 | "att0 = AttentionPooling(filters=4*n_filters, channels=n_channels)([up0, lvl0])\n", 175 | "x = Concatenate(axis=-1)([up0, att0])\n", 176 | "x = Conv2D(filters=4*n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(x)\n", 177 | "x = BatchNormalization()(x)\n", 178 | "x = ELU()(x)\n", 179 | "x = Conv2D(filters=4*n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(x)\n", 180 | "x = BatchNormalization()(x)\n", 181 | "x = ELU()(x)\n", 182 | "output = Conv2D(filters=1, kernel_size=(15, 1), strides=(1, 1), padding='same', activation='sigmoid')(x)\n", 183 | "\n", 184 | "unet = Model(input_seq, output)" 185 | ] 186 | }, 187 | { 188 | "cell_type": "code", 189 | "execution_count": null, 190 | "metadata": {}, 191 | "outputs": [], 192 | "source": [ 193 | "unet.load_weights(network_path)\n", 194 | "unet.summary()" 195 | ] 196 | }, 197 | { 198 | "cell_type": "markdown", 199 | "metadata": {}, 200 | "source": [ 201 | "### Prediction step" 202 | ] 203 | }, 204 | { 205 | "cell_type": "code", 206 | "execution_count": null, 207 | "metadata": {}, 208 | "outputs": [], 209 | "source": [ 210 | "y_probas = []\n", 211 | "reduction = 4096//4\n", 212 | "with tf.device('cpu:0'):\n", 213 | " for signal in signals_test:\n", 214 | " signal = signal[:len(signal)//reduction*reduction, :]\n", 215 | " prediction = unet.predict(signal[np.newaxis, :, :, np.newaxis])[0, :, 0, 0]\n", 216 | " y_probas.append(prediction)" 217 | ] 218 | }, 219 | { 220 | "cell_type": "markdown", 221 | "metadata": {}, 222 | "source": [ 223 | "# Saving predictions" 224 | ] 225 | }, 226 | { 227 | "cell_type": "code", 228 | "execution_count": null, 229 | "metadata": {}, 230 | "outputs": [], 231 | "source": [ 232 | "dt_fl = h5py.vlen_dtype(np.dtype('float32'))\n", 233 | "dt_str = h5py.special_dtype(vlen=str)\n", 234 | "\n", 235 | "with h5py.File(saved_predictions, 'w') as f:\n", 236 | " dset_signals = f.create_dataset('signals', (len(file_names_test),), dtype=dt_fl)\n", 237 | " dset_file_names = f.create_dataset('filenames', (len(file_names_test),), dtype=dt_str)\n", 238 | " \n", 239 | " for i in range(len(file_names_test)):\n", 240 | " dset_signals[i] = y_probas[i]\n", 241 | " dset_file_names[i] = file_names_test[i]" 242 | ] 243 | }, 244 | { 245 | "cell_type": "code", 246 | "execution_count": null, 247 | "metadata": {}, 248 | "outputs": [], 249 | "source": [] 250 | } 251 | ], 252 | "metadata": { 253 | "kernelspec": { 254 | "display_name": "Python 3", 255 | "language": "python", 256 | "name": "python3" 257 | }, 258 | "language_info": { 259 | "codemirror_mode": { 260 | "name": "ipython", 261 | "version": 3 262 | }, 263 | "file_extension": ".py", 264 | "mimetype": "text/x-python", 265 | "name": "python", 266 | "nbconvert_exporter": "python", 267 | "pygments_lexer": "ipython3", 268 | "version": "3.7.3" 269 | } 270 | }, 271 | "nbformat": 4, 272 | "nbformat_minor": 4 273 | } 274 | -------------------------------------------------------------------------------- /evaluate/README.md: -------------------------------------------------------------------------------- 1 | # Evaluate 2 | 3 | Code to produce seizure detection and a hypothesis file. 4 | 5 | When evaluation a new file: 6 | 7 | 1. Save a filtered version of the data using ICLabel filtering 8 | 2. Make prediction files using the U-Net model, utilizing the 3-load-data.py file from ../training/3-DNN 9 | 3. Fuse the U-Net predictions with the LSTM model 10 | 4. Use the predictions to produce a hypothesis file -------------------------------------------------------------------------------- /evaluate/attention_unet_iclabel.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mabhijithn/irregulars-neureka-codebase/a5d96ce0f8b972f3b98e848454196b84e6bbc4c0/evaluate/attention_unet_iclabel.h5 -------------------------------------------------------------------------------- /evaluate/attention_unet_raw.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mabhijithn/irregulars-neureka-codebase/a5d96ce0f8b972f3b98e848454196b84e6bbc4c0/evaluate/attention_unet_raw.h5 -------------------------------------------------------------------------------- /evaluate/attention_unet_wiener.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mabhijithn/irregulars-neureka-codebase/a5d96ce0f8b972f3b98e848454196b84e6bbc4c0/evaluate/attention_unet_wiener.h5 -------------------------------------------------------------------------------- /evaluate/model-dnn-dnnw-dnnicalbl-lstm-4.h5: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mabhijithn/irregulars-neureka-codebase/a5d96ce0f8b972f3b98e848454196b84e6bbc4c0/evaluate/model-dnn-dnnw-dnnicalbl-lstm-4.h5 -------------------------------------------------------------------------------- /hyp_lstm.txt: -------------------------------------------------------------------------------- 1 | 00011846_s004_t003 462.0 476.0 1.0 15 2 | 00011846_s004_t000 224.0 243.0 1.0 15 3 | 00011846_s003_t006 125.0 154.0 1.0 15 4 | 00011846_s003_t008 67.0 91.0 1.0 15 5 | 00011846_s004_t002 330.0 373.0 1.0 15 6 | 00011846_s002_t001 3087.0 3102.0 1.0 15 7 | 00011846_s003_t005 86.0 108.0 1.0 15 8 | 00011846_s003_t005 519.0 542.0 1.0 15 9 | 00011846_s004_t001 236.0 267.0 1.0 15 10 | 00011846_s003_t002 537.0 555.0 1.0 15 11 | 00011846_s003_t007 27.0 61.0 1.0 15 12 | 00011846_s003_t007 337.0 367.0 1.0 15 13 | 00011846_s004_t004 208.0 230.0 1.0 15 14 | 00011846_s003_t003 152.0 174.0 1.0 15 15 | 00011846_s004_t006 500.0 522.0 1.0 15 16 | 00005028_s006_t007 134.0 159.0 1.0 15 17 | 00005028_s006_t009 333.0 348.0 1.0 15 18 | 00005028_s006_t002 454.0 489.0 1.0 15 19 | 00005028_s004_t000 35.0 54.0 1.0 15 20 | 00012427_s001_t000 140.0 169.0 1.0 15 21 | 00012427_s001_t000 245.0 270.0 1.0 15 22 | 00012427_s001_t000 902.0 928.0 1.0 15 23 | 00012534_s004_t000 136.0 162.0 1.0 15 24 | 00012534_s001_t000 159.0 182.0 1.0 15 25 | 00012534_s001_t000 1229.0 1251.0 1.0 15 26 | 00012534_s001_t000 1428.0 1450.0 1.0 15 27 | 00012534_s001_t000 1626.0 1646.0 1.0 15 28 | 00012534_s001_t000 1806.0 1839.0 1.0 15 29 | 00012534_s004_t001 59.0 95.0 1.0 15 30 | 00012534_s004_t001 403.0 444.0 1.0 15 31 | 00011332_s002_t010 350.0 460.0 1.0 15 32 | 00011332_s002_t010 563.0 661.0 1.0 15 33 | 00011332_s002_t005 375.0 407.0 1.0 15 34 | 00011332_s001_t000 372.0 480.0 1.0 15 35 | 00011332_s001_t000 920.0 952.0 1.0 15 36 | 00011332_s001_t000 1302.0 1401.0 1.0 15 37 | 00011332_s002_t007 87.0 183.0 1.0 15 38 | 00011332_s002_t004 352.0 458.0 1.0 15 39 | 00011332_s002_t012 280.0 294.0 1.0 15 40 | 00011332_s002_t002 542.0 583.0 1.0 15 41 | 00011332_s002_t000 128.0 151.0 1.0 15 42 | 00011332_s002_t011 180.0 201.0 1.0 15 43 | 00011332_s002_t011 236.0 294.0 1.0 15 44 | 00011326_s006_t005 312.0 329.0 1.0 15 45 | 00011326_s003_t004 344.0 372.0 1.0 15 46 | 00011326_s003_t002 348.0 365.0 1.0 15 47 | 00012742_s002_t002 315.0 330.0 1.0 15 48 | 00012742_s002_t002 527.0 560.0 1.0 15 49 | 00012742_s001_t001 558.0 645.0 1.0 15 50 | 00012742_s001_t001 732.0 860.0 1.0 15 51 | 00012742_s001_t001 1016.0 1101.0 1.0 15 52 | 00012870_s002_t002 409.0 445.0 1.0 15 53 | 00013002_s002_t000 975.0 1023.0 1.0 15 54 | 00011497_s001_t000 446.0 505.0 1.0 15 55 | 00012941_s001_t001 497.0 524.0 1.0 15 56 | 00012941_s001_t001 558.0 592.0 1.0 15 57 | 00012941_s003_t003 349.0 405.0 1.0 15 58 | 00012941_s003_t003 679.0 695.0 1.0 15 59 | 00012941_s003_t007 361.0 442.0 1.0 15 60 | 00012941_s003_t007 580.0 745.0 1.0 15 61 | 00000458_s017_t020 1.0 24.0 1.0 15 62 | 00000458_s014_t009 796.0 815.0 1.0 15 63 | 00000458_s014_t003 53.0 69.0 1.0 15 64 | 00006546_s029_t001 111.0 141.0 1.0 15 65 | 00006546_s029_t001 599.0 629.0 1.0 15 66 | 00006546_s029_t001 944.0 970.0 1.0 15 67 | 00006546_s029_t003 521.0 555.0 1.0 15 68 | 00006546_s031_t000 229.0 252.0 1.0 15 69 | 00006546_s029_t002 522.0 552.0 1.0 15 70 | 00006546_s031_t005 97.0 132.0 1.0 15 71 | 00006546_s028_t000 183.0 218.0 1.0 15 72 | 00006546_s028_t000 678.0 711.0 1.0 15 73 | 00006546_s028_t000 1024.0 1055.0 1.0 15 74 | 00006546_s028_t000 1315.0 1341.0 1.0 15 75 | 00006546_s032_t003 202.0 234.0 1.0 15 76 | 00006546_s032_t003 565.0 585.0 1.0 15 77 | 00006546_s032_t003 733.0 770.0 1.0 15 78 | 00006546_s031_t002 131.0 152.0 1.0 15 79 | 00006546_s031_t006 19.0 61.0 1.0 15 80 | 00006546_s031_t006 446.0 485.0 1.0 15 81 | 00006546_s032_t004 91.0 105.0 1.0 15 82 | 00006546_s029_t006 322.0 356.0 1.0 15 83 | 00006546_s032_t000 336.0 377.0 1.0 15 84 | 00006546_s032_t000 588.0 627.0 1.0 15 85 | 00006546_s032_t000 744.0 785.0 1.0 15 86 | 00006546_s032_t000 961.0 996.0 1.0 15 87 | 00006546_s032_t002 118.0 153.0 1.0 15 88 | 00006546_s032_t002 308.0 346.0 1.0 15 89 | 00006546_s032_t002 513.0 535.0 1.0 15 90 | 00006546_s029_t004 141.0 182.0 1.0 15 91 | 00006546_s031_t003 78.0 113.0 1.0 15 92 | 00006546_s031_t003 234.0 261.0 1.0 15 93 | 00006546_s031_t003 386.0 402.0 1.0 15 94 | 00006546_s031_t003 534.0 558.0 1.0 15 95 | 00006546_s032_t001 3.0 47.0 1.0 15 96 | 00006546_s032_t001 245.0 294.0 1.0 15 97 | 00006546_s029_t000 151.0 179.0 1.0 15 98 | 00006546_s031_t001 136.0 155.0 1.0 15 99 | 00006546_s031_t001 480.0 495.0 1.0 15 100 | 00006546_s031_t004 10.0 46.0 1.0 15 101 | 00006546_s031_t004 226.0 269.0 1.0 15 102 | 00006546_s031_t004 391.0 426.0 1.0 15 103 | 00006546_s031_t004 576.0 597.0 1.0 15 104 | 00011575_s004_t001 331.0 363.0 1.0 15 105 | 00011575_s004_t005 307.0 396.0 1.0 15 106 | 00011575_s004_t004 253.0 339.0 1.0 15 107 | 00011575_s004_t006 307.0 381.0 1.0 15 108 | 00011575_s004_t006 562.0 636.0 1.0 15 109 | 00011575_s001_t001 823.0 899.0 1.0 15 110 | 00011575_s001_t001 1923.0 2008.0 1.0 15 111 | 00011575_s004_t016 663.0 691.0 1.0 15 112 | 00011575_s004_t007 305.0 329.0 1.0 15 113 | 00011575_s004_t002 317.0 350.0 1.0 15 114 | 00011575_s003_t000 543.0 599.0 1.0 15 115 | 00011575_s003_t000 2330.0 2372.0 1.0 15 116 | 00011575_s004_t000 542.0 595.0 1.0 15 117 | 00010930_s010_t003 651.0 711.0 1.0 15 118 | 00005208_s011_t000 110.0 137.0 1.0 15 119 | 00005208_s014_t000 101.0 126.0 1.0 15 120 | 00011276_s002_t000 531.0 552.0 1.0 15 121 | 00011276_s003_t001 337.0 351.0 1.0 15 122 | 00011276_s001_t000 176.0 209.0 1.0 15 123 | 00002849_s007_t001 566.0 584.0 1.0 15 124 | 00012320_s005_t011 302.0 359.0 1.0 15 125 | 00012320_s005_t007 326.0 378.0 1.0 15 126 | 00012391_s002_t007 367.0 407.0 1.0 15 127 | 00012391_s003_t004 326.0 376.0 1.0 15 128 | 00012391_s001_t000 814.0 910.0 1.0 15 129 | 00011975_s003_t026 305.0 335.0 1.0 15 130 | 00011975_s003_t022 346.0 362.0 1.0 15 131 | 00013002_s004_t011 49.0 110.0 1.0 15 132 | -------------------------------------------------------------------------------- /library/filters.pickle: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mabhijithn/irregulars-neureka-codebase/a5d96ce0f8b972f3b98e848454196b84e6bbc4c0/library/filters.pickle -------------------------------------------------------------------------------- /library/loading.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import resampy 3 | 4 | import nedc 5 | import preprocess 6 | 7 | def loadRecording(filename, wiener=False): 8 | """Loads and preprocess an EDF file. 9 | 10 | Loads an EDF file. Converts it to a bipolar montage, resamples it to 200Hz 11 | and applies a preprocessing pipeline to the data. 12 | 13 | Args: 14 | filename: EDF filename 15 | wiener: apply Wiener filter (Default=False) 16 | Return 17 | fs: sampling frequency of the signal in Hz (200 Hz) 18 | data: np.array containing the channels as rows and samples as columns 19 | labels_mount: list of the labels of the bipolar montage 20 | """ 21 | 22 | # Load Data 23 | (fsamp, sig, labels) = nedc.nedc_load_edf(filename) 24 | fs = fsamp[nedc._index(labels, 'FP1')] 25 | (sig_mont, labels_mont) = nedc.rereference(sig, labels) 26 | data = np.array(sig_mont, dtype=np.float32) 27 | 28 | # Resample data 29 | data = resampy.resample(data, fs, 200) 30 | fs = 200 31 | 32 | # Preprocess 33 | data = preprocess.preprocess(data, fs, wiener) 34 | 35 | return (fs, data, labels_mont) 36 | 37 | -------------------------------------------------------------------------------- /library/nedc.py: -------------------------------------------------------------------------------- 1 | import pyedflib 2 | import re 3 | import sys 4 | import numpy as np 5 | 6 | #------------------------------------------------------------------------------ 7 | # function: nedc_load_edf 8 | # 9 | # arguments: 10 | # fname: filename (input) 11 | # 12 | # return: 13 | # labels: store the EDF signal labels 14 | # fsamp: store the EDF signal sample frequency 15 | # sig: signals in the EDF file 16 | # 17 | # this function loads the EDF and return the signals 18 | # 19 | def nedc_load_edf(fname_a): 20 | 21 | # open an EDF file 22 | # 23 | fp = pyedflib.EdfReader(fname_a) 24 | 25 | # get the metadata that we need: 26 | # convert the labels to ascii and remove whitespace 27 | # to make matching easier 28 | # 29 | num_chans = fp.signals_in_file 30 | labels_tmp = fp.getSignalLabels() 31 | labels = [str(lbl.replace(' ', '')) for lbl in labels_tmp] 32 | 33 | # load each channel 34 | # 35 | sig = [] 36 | fsamp = [] 37 | for i in range(num_chans): 38 | sig.append(fp.readSignal(i)) 39 | fsamp.append(fp.getSampleFrequency(i)) 40 | 41 | # exit gracefully 42 | # 43 | return (fsamp, sig, labels) 44 | # 45 | # end of function 46 | 47 | 48 | # + endofcell="--" 49 | #------------------------------------------------------------------------------ 50 | # function: rereference 51 | # 52 | # arguments: 53 | # sig: the signal data 54 | # labels: the channel labels 55 | # 56 | # return: 57 | # sig_mont: output signal data 58 | # labels_mont: output channel labels 59 | # 60 | # This rereferences the signal to a bipolar montage. 61 | # 62 | def rereference(sig, labels): 63 | sig_mont = list() 64 | 65 | # Define target bipolar montage 66 | # 67 | labels_mont = ['FP1-F7', 68 | 'F7-T3', 69 | 'T3-T5', 70 | 'T5-O1', 71 | 'FP2-F8', 72 | 'F8-T4', 73 | 'T4-T6', 74 | 'T6-O2', 75 | 'T3-C3', 76 | 'C3-CZ', 77 | 'CZ-C4', 78 | 'C4-T4', 79 | 'FP1-F3', 80 | 'F3-C3', 81 | 'C3-P3', 82 | 'P3-O1', 83 | 'FP2-F4', 84 | 'F4-C4'] 85 | bipolarPairs = [('FP1', 'F7'), 86 | ('F7', 'T3'), 87 | ('T3', 'T5'), 88 | ('T5', 'O1'), 89 | ('FP2', 'F8'), 90 | ('F8', 'T4'), 91 | ('T4', 'T6'), 92 | ('T6', 'O2'), 93 | ('T3', 'C3'), 94 | ('C3', 'CZ'), 95 | ('CZ', 'C4'), 96 | ('C4', 'T4'), 97 | ('FP1', 'F3'), 98 | ('F3', 'C3'), 99 | ('C3', 'P3'), 100 | ('P3', 'O1'), 101 | ('FP2', 'F4'), 102 | ('F4', 'C4')] 103 | 104 | 105 | # Apply montage to signal 106 | # 107 | for i, pair in enumerate(bipolarPairs): 108 | try: 109 | sig_mont.append( 110 | sig[_index(labels, pair[0])] - sig[_index(labels, pair[1])]) 111 | except TypeError: 112 | sig_mont.append(np.zeros_like(sig[_index(labels, 'FP1')])) 113 | 114 | # exit gracefully 115 | # 116 | return (sig_mont, labels_mont) 117 | # 118 | # end of function 119 | 120 | 121 | def _index(labels, match): 122 | regex = re.compile('^EEG\ ?{}-(REF|LE)'.format(match)) 123 | for i, item in enumerate(labels): 124 | if re.search(regex, item): 125 | return i 126 | 127 | 128 | # - 129 | 130 | 131 | #------------------------------------------------------------------------------ 132 | # function: loadTSE 133 | # 134 | # arguments: 135 | # tfile_a: TSE event file 136 | # 137 | # return: 138 | # seizures: output list of seizures. Each event is tuple of 4 items: 139 | # (seizure_start [s], seizure_end [s], seizure_type, probability) 140 | # labels_mont: output channel labels 141 | # 142 | # Load seizure events from a TSE file. 143 | # 144 | def loadTSE(tfile_a): 145 | VERSION = 'version = tse_v1.0.0\n' 146 | SEIZURES = ('seiz', 'fnsz', 'gnsz', 'spsz', 'cpsz', 'absz', 'tnsz', 'cnsz', 147 | 'tcsz', 'atsz', 'mysz', 'nesz') 148 | seizures = list() 149 | 150 | # Parse TSE file 151 | # 152 | with open(tfile_a, 'r') as tse: 153 | firstLine = tse.readline() 154 | 155 | # Check valid TSE 156 | # 157 | if firstLine != VERSION: 158 | raise ValueError( 159 | 'Expected "{}" on first line but read \n {}'.format(VERSION, 160 | firstLine)) 161 | 162 | # Skip empty second line 163 | # 164 | tse.readline() 165 | 166 | # Read all events 167 | # 168 | for line in tse.readlines(): 169 | fields = line.split(' ') 170 | 171 | if fields[2] in SEIZURES: 172 | # Parse fields 173 | # 174 | start = float(fields[0]) 175 | end = float(fields[1]) 176 | seizure = fields[2] 177 | prob = float(fields[3][:-1]) 178 | 179 | seizures.append((start, end, seizure, prob)) 180 | 181 | # exit gracefully 182 | # 183 | return seizures 184 | # 185 | # end of function 186 | # -- 187 | -------------------------------------------------------------------------------- /library/preprocess.py: -------------------------------------------------------------------------------- 1 | from scipy.signal import butter, filtfilt 2 | 3 | 4 | def preprocess(data, fs, wienerFilt=False): 5 | """Apply EEG pre-processing pipeline. 6 | 7 | Currently preprocessing only consists of a high pass (0.5Hz) and notch 8 | filter. 9 | 10 | Args: 11 | data: np.array containing the channels as rows and samples as columns 12 | fs: sampling frequency of the signal in Hz (200 Hz) 13 | wiener: apply Wiener filter (Default=False) 14 | Return: 15 | data: in-place transformed data np.array 16 | """ 17 | 18 | # Low pass filter 19 | b, a = butter(4, 1/(fs/2), 'high') 20 | data = filtfilt(b, a, data) 21 | # 50 Hz notch 22 | b, a = butter(4, [47.5/(fs/2), 52.5/(fs/2)], 'bandstop') 23 | data = filtfilt(b, a, data) 24 | # 60 Hz notch 25 | b, a = butter(4, [57.5/(fs/2), 62.5/(fs/2)], 'bandstop') 26 | data = filtfilt(b, a, data) 27 | 28 | # Apply Wiener filter 29 | if wienerFilt: 30 | import wiener 31 | for filt in wiener.filters: 32 | filtered = wiener.wiener_filter(data, filt) 33 | data -= filtered 34 | 35 | return data 36 | 37 | 38 | -------------------------------------------------------------------------------- /library/spir.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from scipy.signal import convolve 3 | 4 | 5 | # ## COVARIANCE MATRIX ESTIMATION ### 6 | 7 | def build_lagged_copies(data, lag, ram=True, file=None): 8 | """ Build matrix containing lagged copies of data 9 | 10 | Create a matrix with lagged copies of the rows in data. 11 | Args: 12 | data: data contained in an array (row = channels, column = samples) 13 | lag: number of sample lags 14 | ram: if True store in RAM; else as a memmap 15 | file: location of memmap. If ram is True and file is None. memmap is 16 | stored in /tmp 17 | Return 18 | noise: list of noise events in seconds. Each row contains two 19 | columns: [start time, end time] 20 | noise_mask: bool mask containing True on samples marked as noise. 21 | """ 22 | if ram: 23 | # Build copies matrix in RAM 24 | lagged_data = np.empty((len(data)*(lag+1), len(data[0]))) 25 | else: 26 | # Build copies as a memmap 27 | if file is None: 28 | with tempfile.NamedTemporaryFile() as f: 29 | file = f.name 30 | lagged_data = np.memmap(f.name, dtype='float64', mode='w+', shape=(len(data)*(lag+1), len(data[0]))) 31 | else: 32 | lagged_data = np.memmap(file, dtype='float64', mode='w+', shape=(len(data)*(lag+1), len(data[0]))) 33 | logging.info('Created file ({}) containing lagged copies of data'.format(file)) 34 | for num in range(lag + 1): 35 | for ch in range(len(data)): 36 | if num > 0: 37 | lagged_data[ch*(lag+1)+num,:-num] = data[ch,num:] 38 | lagged_data[ch*(lag+1)+num,-num:] = 0 39 | else: 40 | lagged_data[ch*(lag+1)+num,:] = data[ch,:] 41 | return lagged_data 42 | 43 | 44 | def build_cov(data, events, lag, fs): 45 | """Build signal covariance matrix. 46 | 47 | Covariance matrix is calculated over all event epochs. 48 | 49 | Args: 50 | data: data contained in an array (row = channels, column = samples) 51 | events: list of events times in seconds. Each row contains two 52 | columns: [start time, end time] 53 | lag: positive lag in samples 54 | fs: sampling frequency of the data in Hertz 55 | 56 | Return: 57 | Rxx: covariance matrix of event epochs (accross channels and lags) 58 | """ 59 | t = 0 60 | Rxx = np.zeros((len(data)*(lag+1), len(data)*(lag+1))) 61 | for event in events: 62 | lagged = build_lagged_copies(data[:,np.arange(int(event[0]*fs), int(event[1]*fs))], lag) 63 | t += len(lagged) 64 | Rxx += np.dot(lagged, np.transpose(lagged)) 65 | Rxx = Rxx / t 66 | return Rxx 67 | 68 | 69 | def build_rnn(data, seizures, lag, fs): 70 | """Build noise covariance matrix. 71 | 72 | Covariance matrix is calculated over all non-seizure epochs. 73 | 74 | Args: 75 | data: data contained in an array (row = channels, column = samples) 76 | seizures: list of events times in seconds. Each row contains two 77 | columns: [start time, end time] 78 | lag: positive lag in samples 79 | fs: sampling frequency of the data in Hertz 80 | 81 | Return: 82 | Rnn: covariance matrix of noise epochs (accross channels and lags) 83 | """ 84 | # Get noise events from seizure events 85 | seizure_mask = eventList2Mask(seizures, len(data[0]), fs) 86 | noise_mask = np.logical_not(seizure_mask) 87 | noise_events = mask2eventList(noise_mask, fs) 88 | 89 | Rnn = build_cov(data, noise_events, lag, fs) 90 | 91 | return Rnn 92 | 93 | 94 | 95 | # ## MAX-SNR filtering ## 96 | 97 | def find_noise(data, fs): 98 | """Detect noise events on a channel by channel basis 99 | 100 | Noise is defined as samples above 600uV 101 | 102 | Args: 103 | data: data contained in an array (row = channels, column = samples) 104 | fs: sampling frequency of the data in Hertz 105 | Return 106 | noise_list: list of noise masks. Each element of the list is a 107 | a channel. 108 | """ 109 | noise_list = np.zeros((len(data), len(data[0])), dtype=bool) 110 | for i in range(len(data)): 111 | noise_mask = np.abs(data[i]) > 400 112 | noise = mask2eventList(noise_mask, fs) 113 | noise = extend_event(noise, 1.5, len(data[0])/fs) 114 | noise_list[i, :] = eventList2Mask(noise, len(data[0]), fs) 115 | return noise_list 116 | 117 | 118 | def maxspir_filter(data, v, noise): 119 | """Apply maxSPIR filter. 120 | 121 | Args: 122 | data: data contained in an array (row = channels, column = samples) 123 | v: maxSPIR filter as a flattened vector 124 | noise: noise binary mask contained in an array of the same size as data 125 | Return: 126 | out: filtered data 127 | """ 128 | lag = int(len(v)/len(data)) 129 | v_shaped = np.reshape(v, (len(data), lag)) 130 | out = np.convolve(v_shaped[0, :], data[0, :]*np.logical_not(noise[0, :]), 'same') 131 | for i in range(1, v_shaped.shape[0]): 132 | out += np.convolve(v_shaped[i, :], data[i, :]*np.logical_not(noise[i, :]), 'same') 133 | return out 134 | 135 | 136 | def calculate_filter(rss, rnn, regularization_strategy='none'): 137 | """Calculate max-SNR filter 138 | """ 139 | ws, vs = np.linalg.eig(rss) 140 | index_s = np.argmax(np.cumsum(ws)/np.sum(ws)> 0.95) 141 | wn, vn = np.linalg.eig(rnn) 142 | index_n = np.argmax(np.cumsum(wn)/np.sum(wn)> 0.9) 143 | vt = np.concatenate((vn[:,:index_n+1], vs[:,:index_s+1]), axis=1) 144 | u, s, v = np.linalg.svd(vt, full_matrices=False) 145 | index_t = np.argmax(np.cumsum(s)/np.sum(s)> 0.99) 146 | i = index_t 147 | t = u 148 | 149 | if regularization_strategy == 'none': 150 | w, v = np.linalg.eig(np.dot(np.linalg.inv(rnn), rss)) 151 | elif regularization_strategy == 'pca': 152 | w, v = np.linalg.eig(np.dot(np.dot( 153 | np.dot(t[:,0:i], np.linalg.inv(np.dot(np.dot(np.transpose(t[:,0:i]), rnn), t[:,0:i]))), 154 | np.transpose(t[:,0:i])), rss)) 155 | 156 | return np.real(v) 157 | 158 | 159 | def find_events(seizures, power, data, fs, duration=30, minTresh=70): 160 | """Find events in power of filtered data. 161 | 162 | Args: 163 | power: power of filtered data (single channel) 164 | data: raw data contained in an array (row = channels, column = samples) 165 | fs: sampling frequency in Hz 166 | duration: duration of each event in seconds [default:30] 167 | minTreshold: minimum detection threshold in mV [default:70] 168 | Return: 169 | events: indices of detected events (sorted with decreasing power) 170 | """ 171 | threshold = 9999 172 | power_derivative = np.diff(power) 173 | s_len = int(fs/2) 174 | smooth_derivative = np.convolve(power_derivative, np.ones((s_len,))/s_len, 'same') 175 | power_copy = np.copy(power) 176 | seizure_mask = eventList2Mask(seizures, len(power), fs) 177 | np.putmask(power_copy, seizure_mask, 0) 178 | events = list() 179 | while threshold > minTresh and len(events) < 150: 180 | i = np.argmax(power_copy) 181 | threshold = power_copy[i] 182 | 183 | # Start 184 | i0 = i - s_len 185 | while i0 > 0 and smooth_derivative[i0] > 0: 186 | i0 -= 1 187 | i0 += s_len 188 | #End 189 | i1 = i + s_len 190 | while i1 < len(smooth_derivative) and smooth_derivative[i1] < 0: 191 | i1 += 1 192 | i1 -= s_len 193 | 194 | np.put(power_copy, np.arange( 195 | max(0, i0-s_len), 196 | min(len(power_copy), i1+s_len)), 0) 197 | if threshold > minTresh and i1-i0 < 60*fs and i1-i0 > fs: 198 | events.append((i0, i1)) 199 | 200 | return events 201 | 202 | 203 | def find_interference(data, fs, seizures, maxThresh=500, minTresh=70): 204 | """Find interference in raw data. 205 | 206 | Args: 207 | data: raw data contained in an array (row = channels, column = samples) 208 | fs: sampling frequency in Hz 209 | duration: duration of each event in seconds [default:30] 210 | minTreshold: minimum detection threshold in mV [default:70] 211 | Return: 212 | interferences: indices of detected events (sorted with decreasing power) 213 | """ 214 | threshold = 9999 215 | power = rolling_rms(data, int(1*fs)) 216 | 217 | 218 | dpower = np.diff(power) 219 | s_len = int(fs/2) 220 | dpower = convolve(dpower, np.ones((dpower.shape[0],s_len))/s_len, 'same') 221 | seizure_mask = eventList2Mask(seizures, power.shape[1], fs) 222 | 223 | interference_mask = np.zeros((data.shape[1],)) 224 | 225 | for c, channel in enumerate(power): 226 | np.putmask(channel, seizure_mask, 0) 227 | events = list() 228 | while threshold > minTresh and len(events) < 50: 229 | i = np.argmax(channel) 230 | threshold = channel[i] 231 | 232 | # Start 233 | i0 = i - s_len 234 | while i0 > 0 and dpower[c, i0] > 0: 235 | i0 -= 1 236 | i0 += s_len 237 | #End 238 | i1 = i + s_len 239 | while i1 < dpower.shape[1] and dpower[c, i1] < 0: 240 | i1 += 1 241 | i1 -= s_len 242 | 243 | np.put(channel, np.arange( 244 | max(0, i0-s_len), 245 | min(len(channel), i1+s_len)), 0) 246 | if threshold > minTresh and threshold < maxThresh and i1-i0 < 60*fs and i1-i0 > fs: 247 | events.append((i0/fs, i1/fs)) 248 | eventmask = eventList2Mask(events, len(interference_mask), fs) 249 | interference_mask = np.logical_or(interference_mask, eventmask) 250 | 251 | return mask2eventList(interference_mask, fs) 252 | 253 | 254 | def rolling_rms(data, duration): 255 | """ Calculate rolling average RMS. 256 | 257 | Args: 258 | data: data contained in a vector 259 | duration: rolling average window duration in samples 260 | Return: 261 | power: rolling average RMS 262 | """ 263 | power = np.square(data) 264 | if data.ndim == 2: 265 | power = convolve(power, np.ones((data.shape[0], duration))/duration, mode='same') 266 | elif data.ndim == 1: 267 | power = convolve(power, np.ones((duration,))/duration, mode='same') 268 | else: 269 | TypeError('Dimmension of data should be 1 or 2 to convolve.') 270 | return np.sqrt(power) 271 | 272 | 273 | # ## EVENT & MASK MANIPULATION ### 274 | 275 | def eventList2Mask(events, totalLen, fs): 276 | """Convert list of events to mask. 277 | 278 | Returns a logical array of length totalLen. 279 | All event epochs are set to True 280 | 281 | Args: 282 | events: list of events times in seconds. Each row contains two 283 | columns: [start time, end time] 284 | totalLen: length of array to return in samples 285 | fs: sampling frequency of the data in Hertz 286 | Return: 287 | mask: logical array set to True during event epochs and False the rest 288 | if the time. 289 | """ 290 | mask = np.zeros((totalLen,), dtype=bool) 291 | for event in events: 292 | for i in range(min(int(event[0]*fs), totalLen-1), min(int(event[1]*fs), totalLen-1)): 293 | mask[i] = True 294 | return mask 295 | 296 | 297 | def mask2eventList(mask, fs): 298 | """Convert mask to list of events. 299 | 300 | Args: 301 | mask: logical array set to True during event epochs and False the rest 302 | if the time. 303 | fs: sampling frequency of the data in Hertz 304 | Return: 305 | events: list of events times in seconds. Each row contains two 306 | columns: [start time, end time] 307 | """ 308 | events = list() 309 | tmp = [] 310 | start_i = np.where(np.diff(np.array(mask, dtype=int)) == 1)[0] 311 | end_i = np.where(np.diff(np.array(mask, dtype=int)) == -1)[0] 312 | 313 | if len(start_i) == 0 and mask[0]: 314 | events.append([0, (len(mask)-1)/fs]) 315 | else: 316 | # Edge effect 317 | if mask[0]: 318 | events.append([0, end_i[0]/fs]) 319 | end_i = np.delete(end_i, 0) 320 | # Edge effect 321 | if mask[-1]: 322 | if len(start_i): 323 | tmp = [[start_i[-1]/fs, (len(mask)-1)/fs]] 324 | start_i = np.delete(start_i, len(start_i)-1) 325 | for i in range(len(start_i)): 326 | events.append([start_i[i]/fs, end_i[i]/fs]) 327 | events += tmp 328 | return events 329 | 330 | 331 | def extend_event(events, time, max_time): 332 | """Extends events in event list by time. 333 | 334 | The start time of each event is moved time seconds back and the end 335 | time is moved time seconds later 336 | 337 | Args: 338 | events: list of events. Each event is a tuple 339 | time: time to extend each event in seconds 340 | max_time: maximum end time allowed of an event. 341 | Return 342 | extended_events: list of events which each event extended. 343 | """ 344 | extended_events = events.copy() 345 | for i, event in enumerate(events): 346 | extended_events[i] = [max(0, event[0] - time), 347 | min(max_time, event[1] + time)] 348 | return extended_events 349 | 350 | 351 | def merge_events(events, distance): 352 | i = 1 353 | tot_len = len(events) 354 | while i < tot_len: 355 | if events[i][0] - events[i-1][1] < distance: 356 | events[i-1][1] = events[i][1] 357 | events.pop(i) 358 | tot_len -= 1 359 | else: 360 | i += 1 361 | return events 362 | -------------------------------------------------------------------------------- /library/wiener.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pickle 3 | 4 | filters = None 5 | with open('filters.pickle', 'rb') as handle: 6 | filters = pickle.load(handle) 7 | 8 | def wiener_filter(data, v): 9 | """Apply Wiener filter. 10 | 11 | Args: 12 | data: data contained in an array (row = channels, column = samples) 13 | v: Wiener filter 14 | Return: 15 | out: filtered data 16 | """ 17 | lag = int(v.shape[0]/data.shape[0]) 18 | filtered = list() 19 | for j in range(v.shape[1]): 20 | v_shaped = np.reshape(v[:,j], (data.shape[0], lag)) 21 | out = np.convolve(v_shaped[0, :], data[0, :], 'full') 22 | for i in range(1, v_shaped.shape[0]): 23 | out += np.convolve(v_shaped[i, :], data[i, :], 'full') 24 | filtered.append(out) 25 | t = np.arange(0, v.shape[0], step=lag, dtype=int) 26 | filtered = np.dot(v[t,:], filtered) 27 | return np.array(filtered[:,:data.shape[1]]) 28 | -------------------------------------------------------------------------------- /neureka_ieee_spmb.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mabhijithn/irregulars-neureka-codebase/a5d96ce0f8b972f3b98e848454196b84e6bbc4c0/neureka_ieee_spmb.pdf -------------------------------------------------------------------------------- /python_requirements.txt: -------------------------------------------------------------------------------- 1 | h5py==2.10.0 2 | keras==1.1.2 3 | matplotlib==3.3.4 4 | numpy==1.22.0 5 | pyedflib==0.1.20 6 | resampy==0.2.2 7 | scipy==1.6.1 8 | scikit-learn==0.24.1 9 | tensorflow==2.7.2 10 | -------------------------------------------------------------------------------- /training/1-wiener-training.py: -------------------------------------------------------------------------------- 1 | """ 2 | Train Wiener filters based on clusters of similar artefacts 3 | 4 | This script is heavy in computation and RAM (~50GB) as it computes and loads many large covariance matrices. 5 | This script was originally a jupyter notebook (converted with jupytext). Some plots are intended as interactive 6 | steps to optimize the algorithm parameters (such as number of clusters). 7 | 8 | The script produces a pickle object containing the filters 9 | """ 10 | 11 | import sys 12 | # Adapt these two path to the root of the EDF data and to the root of the codebase 13 | EDF_ROOT = '/esat/biomeddata/Neureka_challenge/edf/train' 14 | sys.path.insert(0, 'library') 15 | 16 | # custom library 17 | import nedc 18 | import loading 19 | import spir 20 | 21 | # std lib 22 | import glob 23 | from joblib import Parallel, delayed 24 | import multiprocessing 25 | import os 26 | from pathlib import Path 27 | import pickle 28 | 29 | # 3rd party lib 30 | import numpy as np 31 | import matplotlib.pyplot as plt 32 | from scipy.signal import convolve 33 | from sklearn.cluster import KMeans 34 | from sklearn.decomposition import PCA 35 | 36 | num_cores = multiprocessing.cpu_count() 37 | 38 | 39 | # - 40 | # ## Find interference 41 | # + 42 | def find_interference(data, fs, seizures, maxThresh=500, minTresh=70): 43 | """Find interference in raw data. 44 | 45 | Args: 46 | data: raw data contained in an array (row = channels, column = samples) 47 | fs: sampling frequency in Hz 48 | duration: duration of each event in seconds [default:30] 49 | minTreshold: minimum detection threshold in mV [default:70] 50 | Return: 51 | interferences: indices of detected events (sorted with decreasing power) 52 | """ 53 | threshold = 9999 54 | power = spir.rolling_rms(data, int(1*fs)) 55 | 56 | dpower = np.diff(power) 57 | s_len = int(fs/2) 58 | dpower = convolve(dpower, np.ones((dpower.shape[0],s_len))/s_len, 'same') 59 | seizure_mask = spir.eventList2Mask(seizures, power.shape[1], fs) 60 | 61 | interference_mask = np.zeros((data.shape[1],)) 62 | 63 | for c, channel in enumerate(power): 64 | np.putmask(channel, seizure_mask, 0) 65 | events = list() 66 | while threshold > minTresh and len(events) < 50: 67 | i = np.argmax(channel) 68 | threshold = channel[i] 69 | 70 | # Start 71 | i0 = i - s_len 72 | while i0 > 0 and dpower[c, i0] > 0: 73 | i0 -= 1 74 | i0 += s_len 75 | #End 76 | i1 = i + s_len 77 | while i1 < dpower.shape[1] and dpower[c, i1] < 0: 78 | i1 += 1 79 | i1 -= s_len 80 | 81 | np.put(channel, np.arange( 82 | max(0, i0-s_len), 83 | min(len(channel), i1+s_len)), 0) 84 | if threshold > minTresh and threshold < maxThresh and i1-i0 < 60*fs and i1-i0 > fs: 85 | events.append((i0/fs, i1/fs)) 86 | eventmask = spir.eventList2Mask(events, len(interference_mask), fs) 87 | interference_mask = np.logical_or(interference_mask, eventmask) 88 | 89 | return spir.mask2eventList(interference_mask, fs) 90 | 91 | 92 | # + 93 | # Find artefacts and compute covariance matrix 94 | lag = 50 95 | total_events = 0 96 | total_seizures = 0 97 | event_dict = dict() 98 | eventFiles = list() 99 | allEvents = list() 100 | 101 | rnns = list() 102 | 103 | for filename in glob.iglob(EDF_ROOT + '/**/*.edf', recursive=True): 104 | seizures = nedc.loadTSE(filename[:-3] + 'tse') 105 | (fs, data, labels) = loading.loadRecording(filename) 106 | 107 | events = find_interference(data, fs, seizures, maxThresh=500, minTresh=100) 108 | 109 | if len(events) > 0: 110 | event_dict[filename] = events 111 | allEvents += events 112 | total_events += len(events) 113 | total_seizures += len(seizures) 114 | 115 | for i in range(len(events)): 116 | eventFiles.append(filename) 117 | 118 | rnn = Parallel(n_jobs=num_cores)(delayed(spir.build_cov)(data, [event], lag, fs) for event in events) 119 | rnns += rnn 120 | 121 | # Limit to 2000 events 122 | if total_events > 2000: 123 | break 124 | 125 | 126 | # - 127 | # ## Compress Rnns 128 | # + 129 | tmp = list() 130 | for rnn in rnns: 131 | tmp.append(rnn.flatten()/np.sum(np.diag(rnn))) # Normalize 132 | pca = PCA(0.99) 133 | pca.fit(tmp) 134 | compressed = pca.fit_transform(tmp) 135 | print('Number of compressed components: {}'.format(compressed.shape[1])) 136 | 137 | 138 | # - 139 | # ## Perform K-means clustering 140 | # + 141 | ## Find n-clusters 142 | def calculate_WSS(points, kmax): 143 | sse = [] 144 | for k in range(1, kmax+1): 145 | kmeans = KMeans(n_clusters = k).fit(points) 146 | centroids = kmeans.cluster_centers_ 147 | pred_clusters = kmeans.predict(points) 148 | curr_sse = 0 149 | 150 | for i in range(len(points)): 151 | curr_center = centroids[pred_clusters[i]] 152 | curr_sse += (points[i, 0] - curr_center[0]) ** 2 + (points[i, 1] - curr_center[1]) ** 2 153 | 154 | sse.append(curr_sse) 155 | return sse 156 | 157 | 158 | sse = calculate_WSS(compressed, 12) 159 | 160 | plt.figure(figsize=(16, 6)) 161 | plt.plot(sse[:]) 162 | plt.ylabel('# SSE') 163 | plt.xlabel('# of clusters') 164 | plt.title('Choice of # of cluster') 165 | plt.show() 166 | # - 167 | n_clusters = 6 # Select 6 clusters (based on SSE plot) 168 | 169 | kmeans = KMeans(n_clusters=n_clusters).fit(compressed) 170 | 171 | import pickle 172 | with open('kmeans.pkl', 'wb') as filehandler: 173 | pickle.dump(kmeans, filehandler) 174 | 175 | plt.figure(figsize=(16, 6)) 176 | plt.hist(kmeans.labels_) 177 | plt.xlabel('Cluster labels') 178 | plt.title('histogram of cluster labels') 179 | plt.show() 180 | 181 | plt.figure(figsize=(9, 9)) 182 | for label in range(n_clusters): 183 | examples = np.where(kmeans.labels_ == label)[0] 184 | plt.scatter(compressed[examples, 0], compressed[examples, 1]) 185 | plt.xlabel('PC 1') 186 | plt.ylabel('PC 2') 187 | plt.title('Scatter of the first two principle components') 188 | plt.legend(range(6)) 189 | plt.show() 190 | 191 | 192 | # + 193 | ## Calculate filters 194 | 195 | # Average cluster 196 | avg = list() 197 | for label in range(n_clusters): 198 | avg.append(np.zeros_like(rnns[0])) 199 | examples = np.where(kmeans.labels_ == label)[0] 200 | for example in examples: 201 | avg[-1] += rnns[example] / np.sum(np.diag(rnns[example])) / len(examples) 202 | 203 | # Filter 204 | filters = list() 205 | for label in range(n_clusters): 206 | w, v = np.linalg.eig(avg[label]) 207 | index_i = np.argmax(np.cumsum(np.real(w))/np.sum(np.real(w)) > 0.99) 208 | filters.append(np.real(v[:,:index_i])) 209 | 210 | # Write filters 211 | with open('filters.pkl', 'wb') as filehandler: 212 | pickle.dump(filters, filehandler) -------------------------------------------------------------------------------- /training/2-iclabel/README.md: -------------------------------------------------------------------------------- 1 | ## README file for the use of iclabel preprocessing for the whole Neureka database 2 | 3 | The main script that must be run is "run_icalabel.m" (number of start and end subject must be defined as an input in order to be able to parallelize it) 4 | The architecture of the files must be the same as in the initial dataset 5 | 6 | The level for artifact removal has been set to correlation 0.6 (everything above this are rejected as artifact). 7 | 8 | In order to run the code you need eeglab2019_1, with plugins Biosig, Cleanrawdata and IClabel v 1.2.4 preinstalled 9 | You need to replace the following functions of eeglab: 10 | - pop_runica.m (line 385 adapted in order to have full rank) 11 | - pop_clean_rawdata.m (line 125 adapted in order to be able to load the same preselected settings for Cleanrawdata plugin). 12 | 13 | The file input.mat includes the preselected settings for Cleanrawdata plugin 14 | 15 | The file neureca.locs includes the positions and different namings of the electrodes in Neureka challenge 16 | 17 | The files findRecording.m and getContent.m are used in order to browse among different subjects 18 | -------------------------------------------------------------------------------- /training/2-iclabel/findRecording.m: -------------------------------------------------------------------------------- 1 | function [recs] = findRecording(root, subjectstrname, sessionname) 2 | ext = 'edf'; 3 | [f,d] = getContent(root, 0); 4 | N = size(d,1); 5 | recnames=[]; 6 | r=[]; 7 | for i = 1:N 8 | ss = strsplit(d{i},{'_','.'}); 9 | if(length(ss)~= 4) 10 | continue 11 | end 12 | if(strcmp(ss{1}, subjectstrname)) 13 | if(strcmp(ss{2}, sessionname)) 14 | if(strcmp(ss{4}, ext)) 15 | r.recstrname = ss(3); 16 | r.recnum = str2num(r.recstrname{1}(2:end)); 17 | r.edfname = d(i); 18 | r.lblname = {[subjectstrname,'_',sessionname,'_',r.recstrname{1},'.lbl']}; 19 | recnames=[recnames; r]; 20 | end 21 | end 22 | end 23 | end 24 | recs = struct2table(recnames); 25 | recs = sortrows(recs, 'recnum'); 26 | end -------------------------------------------------------------------------------- /training/2-iclabel/getContent.m: -------------------------------------------------------------------------------- 1 | function [dirs, fnames] = getContent(root, isdir) 2 | d = struct2table(dir(root)); 3 | d(strcmp(d.name, '.'),:)=[]; 4 | d(strcmp(d.name, '..'),:)=[]; 5 | if(~isdir) 6 | d(d.isdir,:) = []; 7 | end 8 | 9 | fnames = d.name; 10 | dirs= d.folder; 11 | end -------------------------------------------------------------------------------- /training/2-iclabel/input.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mabhijithn/irregulars-neureka-codebase/a5d96ce0f8b972f3b98e848454196b84e6bbc4c0/training/2-iclabel/input.mat -------------------------------------------------------------------------------- /training/2-iclabel/neureka.locs: -------------------------------------------------------------------------------- 1 | 1 -18 0.51111 FP1 2 | 1 -18 0.51111 Fp1 3 | 2 18 0.51111 FP2 4 | 2 18 0.51111 Fp2 5 | 3 0 0.51111 FPZ 6 | 3 0 0.51111 FPz 7 | 4 -54 0.51111 F7 8 | 5 -39 0.33333 F3 9 | 6 0 0.25556 FZ 10 | 6 0 0.25556 Fz 11 | 7 39 0.33333 F4 12 | 8 54 0.51111 F8 13 | 9 -90 0.51111 T3 14 | 10 -90 0.25556 C3 15 | 11 90 0 CZ 16 | 11 90 0 Cz 17 | 12 90 0.25556 C4 18 | 13 90 0.51111 T4 19 | 14 -126 0.51111 T5 20 | 15 -141 0.33333 P3 21 | 16 180 0.25556 Pz 22 | 17 141 0.33333 P4 23 | 18 126 0.51111 T6 24 | 19 -162 0.51111 O1 25 | 20 180 0.51111 OPZ 26 | 20 180 0.51111 OPz 27 | 21 162 0.51111 O2 28 | 29 | 30 | -------------------------------------------------------------------------------- /training/2-iclabel/pop_clean_rawdata.m: -------------------------------------------------------------------------------- 1 | % pop_clean_rawdata(): Launches GUI to collect user inputs for clean_artifacts(). 2 | % ASR stands for artifact subspace reconstruction. 3 | % To disable method(s), enter -1. 4 | % Usage: 5 | % >> EEG = pop_clean_rawdata(EEG); 6 | % 7 | % see also: clean_artifacts 8 | 9 | % Author: Makoto Miyakoshi and Christian Kothe, SCCN,INC,UCSD 10 | % History: 11 | % 07/31/2018 Makoto. Returns error if input data size is 3. 12 | % 04/26/2017 Makoto. Deletes existing EEG.etc.clean_channel/sample_mask. Try-catch to skip potential error in vis_artifact. 13 | % 07/18/2014 ver 1.4 by Makoto and Christian. New channel removal method supported. str2num -> str2num due to str2num([a b]) == NaN. 14 | % 11/08/2013 ver 1.3 by Makoto. Menu words changed. asr_process() line 168 bug fixed. 15 | % 10/07/2013 ver 1.2 by Makoto. Help implemented. History bug fixed. 16 | % 07/16/2013 ver 1.1 by Makoto and Christian. Minor update for help and default values. 17 | % 06/26/2013 ver 1.0 by Makoto. Created. 18 | 19 | % Copyright (C) 2013, Makoto Miyakoshi and Christian Kothe, SCCN,INC,UCSD 20 | % 21 | % This program is free software; you can redistribute it and/or modify 22 | % it under the terms of the GNU General Public License as published by 23 | % the Free Software Foundation; either version 2 of the License, or 24 | % (at your option) any later version. 25 | % 26 | % This program is distributed in the hope that it will be useful, 27 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 28 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 29 | % GNU General Public License for more details. 30 | % 31 | % You should have received a copy of the GNU General Public License 32 | % along with this program; if not, write to the Free Software 33 | % Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 34 | 35 | function [EEG,com] = pop_clean_rawdata(EEG, varargin) 36 | 37 | % Check input 38 | com = ''; 39 | if size(EEG(1).data) == 3 40 | error('Input data must be continuous. This data seems epoched.') 41 | end 42 | 43 | if nargin < 2 44 | % Obtain user inputs. 45 | cb_filter = 'if get(gcbo, ''value''), set(findobj(gcbf, ''userdata'', ''filter''), ''enable'', ''on''); else set(findobj(gcbf, ''userdata'', ''filter''), ''enable'', ''off''); end'; 46 | cb_chan = 'if get(gcbo, ''value''), set(findobj(gcbf, ''userdata'', ''chan'') , ''enable'', ''on''); else set(findobj(gcbf, ''userdata'', ''chan'') , ''enable'', ''off''); end'; 47 | cb_asr = 'if get(gcbo, ''value''), set(findobj(gcbf, ''userdata'', ''asr'') , ''enable'', ''on''); else set(findobj(gcbf, ''userdata'', ''asr'') , ''enable'', ''off''); end'; 48 | cb_rej = 'if get(gcbo, ''value''), set(findobj(gcbf, ''userdata'', ''rej'') , ''enable'', ''on''); else set(findobj(gcbf, ''userdata'', ''rej'') , ''enable'', ''off''); end'; 49 | winsize = max(0.5,1.5*EEG(1).nbchan/EEG(1).srate); 50 | uilist = {... 51 | {'style' 'checkbox' 'string' 'Remove channel drift (data not already high-pass filtered)' 'fontweight' 'bold' 'tag' 'filter' 'callback' cb_filter} ... 52 | {} {'style' 'text' 'string' 'Linear filter (FIR) transition band [lo hi] in Hz ' 'userdata' 'filter' 'enable' 'off' } ... 53 | {'style' 'edit' 'string' '0.25 0.75', 'enable' 'off' 'tag','filterfreqs', 'userdata' 'filter' 'tooltipstring', wordwrap('The first number is the frequency below which everything is removed, and the second number is the frequency above which everything is retained. There is a linear transition in between. For best performance of subsequent processing steps the upper frequency should be close to 1 or 2 Hz, but you can go lower if certain activities need to be retained.',80)} ... 54 | ... 55 | {} {'style' 'checkbox' 'string' 'Remove bad channels' 'fontweight' 'bold' 'tag' 'chanrm' 'callback' cb_chan 'value' 1 } ... 56 | {} {'style' 'checkbox' 'string' 'Remove channel if it is flat for more than (seconds)' 'tag' 'rmflat' 'userdata' 'chan' 'value' 1 } ... 57 | {'style' 'edit' 'string' '5', 'userdata' 'chan' 'tag' 'rmflatsec' 'tooltipstring', wordwrap('If a channel has a longer flatline than this, it will be removed. In seconds.',80)} ... 58 | ... 59 | {} {'style' 'checkbox' 'string' 'Max acceptable high-frequency noise std dev' 'value' 1 'tag' 'rmnoise' 'userdata' 'chan' } ... 60 | {'style' 'edit' 'string' '4', 'userdata' 'chan' 'tag' 'rmnoiseval' 'tooltipstring', wordwrap('If a channel has more line noise relative to its signal than this value, in standard deviations relative to the overall channel population, it will be removed.',80)} ... 61 | ... 62 | {} {'style' 'checkbox' 'string' 'Min acceptable correlation with nearby chans [0-1]' 'value' 1 'tag' 'rmcorr' 'userdata' 'chan' } ... 63 | {'style' 'edit' 'string' '0.8', 'userdata' 'chan' 'tag' 'rmcorrval' 'tooltipstring', wordwrap('If a channel has lower correlation than this to an estimate of its activity based on other channels, and this applies to more than half of the recording, the channel will be removed. This method requires that channel locations are available and roughly correct; otherwise a fallback criterion will tried used using a default setting; you can customize the fallback method by directly calling clean_channels_nolocs in the command line.',80)} ... 64 | ... 65 | {} {'style' 'checkbox' 'string' 'Perform Artifact Subspace Reconstruction bad burst correction' 'fontweight' 'bold' 'value' 1 'tag' 'asr' 'callback' cb_asr } ... 66 | {} {'style' 'text' 'string' sprintf('Max acceptable %1.1f second window std dev', winsize) 'value' 1 'userdata' 'asr' } ... 67 | {'style' 'edit' 'string' '20', 'tag' 'asrstdval' 'userdata' 'asr' 'tooltipstring', wordwrap('Standard deviation cutoff for removal of bursts. Data portions whose variance is larger than this threshold relative to the calibration data are considered missing data and will be removed. The most aggressive value that can be used without losing much EEG is 3. A reasonably conservative value is 5, but some extreme EEG bursts (e.g., sleep spindles) can cross even 5. For new users it is recommended to at first visually inspect the difference between the original and cleaned data to get a sense of the removed content at various levels.',80)} ... 68 | {} {'style' 'checkbox' 'string' 'Use Riemanian distance metric (not Euclidean) - beta' 'userdata' 'asr' 'value' 0 'tag' 'distance' } {} ... 69 | {} {'style' 'checkbox' 'tag' 'asrrej' 'string' 'Remove bad data periods (instead of correcting them)' 'value' 1 'userdata' 'asr'} {} ... 70 | ... 71 | {} {'style' 'checkbox' 'string' 'Additional removal of bad data periods' 'fontweight' 'bold' 'value' 1 'tag' 'rejwin' 'callback' cb_rej } ... 72 | {} {'style' 'text' 'tag' 'asrwintext' 'string' 'Acceptable [min max] channel power range (+/- std dev)' 'userdata' 'rej'} ... 73 | {'style' 'edit' 'string' '-Inf 7','tag', 'rejwinval1', 'userdata' 'rej' 'tooltipstring', wordwrap('If a time window has a larger fraction of simultaneously corrupted channels than this (after the other cleaning attempts), it will be cut out of the data. This can happen if a time window was corrupted beyond the point where it could be recovered.',80)} ... 74 | {} {'style' 'text' 'tag' 'asrwintext' 'string' 'Maximum out-of-bound channels (%)' 'userdata' 'rej'} ... 75 | {'style' 'edit' 'string' '25','tag', 'rejwinval2', 'userdata' 'rej' 'tooltipstring', wordwrap('If a time window has a larger fraction of simultaneously corrupted channels than this (after the other cleaning attempts), it will be cut out of the data. This can happen if a time window was corrupted beyond the point where it could be recovered.',80)} ... 76 | ... 77 | {} {'style' 'checkbox' 'string' 'Pop up scrolling data window with rejected data highlighted' 'tag' 'vis' 'value' fastif(length(EEG) > 1, 0, 1) 'enable' fastif(length(EEG) > 1, 'off', 'on') }}; 78 | 79 | row = [0.1 1 0.3]; 80 | row2 = [0.1 1.2 0.1]; 81 | geom = { 1 row 1 1 row row row 1 1 row row2 row2 1 1 row row 1 1 }; 82 | geomvert = [ 1 1 0.3 1 1 1 1 0.3 1 1 1 1 0.3 1 1 1 0.3 1 ]; 83 | [res,~,~,outs] = inputgui('title', 'pop_clean_rawdata()', 'geomvert', geomvert, 'geometry', geom, 'uilist',uilist, 'helpcom', 'pophelp(''clean_artifacts'');'); 84 | 85 | % Return error if no input. 86 | if isempty(res) return; end 87 | 88 | % process multiple datasets 89 | % ------------------------- 90 | options = {}; 91 | opt.FlatlineCriterion = 'off'; 92 | opt.ChannelCriterion = 'off'; 93 | opt.LineNoiseCriterion = 'off'; 94 | opt.Highpass = 'off'; 95 | opt.BurstCriterion = 'off'; 96 | opt.WindowCriterion = 'off'; 97 | opt.BurstRejection = 'off'; 98 | opt.Distance = 'Euclidian'; 99 | 100 | if outs.filter, opt.Highpass = str2num(outs.filterfreqs); end 101 | 102 | if outs.chanrm 103 | if outs.rmflat, opt.FlatlineCriterion = str2num(outs.rmflatsec); end 104 | if outs.rmcorr, opt.ChannelCriterion = str2num(outs.rmcorrval); end 105 | if outs.rmnoise, opt.LineNoiseCriterion = str2num(outs.rmnoiseval); end 106 | end 107 | 108 | if outs.asr 109 | opt.BurstCriterion = str2num(outs.asrstdval); 110 | if outs.distance, opt.Distance = 'Riemannian'; end 111 | end 112 | 113 | if outs.rejwin 114 | opt.WindowCriterionTolerances = str2num(outs.rejwinval1); 115 | opt.WindowCriterion = str2num(outs.rejwinval2)/100; 116 | end 117 | if outs.asrrej, opt.BurstRejection = 'on'; end 118 | 119 | % convert structure to cell 120 | options = fieldnames(opt); 121 | options(:,2) = struct2cell(opt); 122 | options = options'; 123 | options = options(:)'; 124 | else 125 | options = varargin{1,1}; 126 | end 127 | 128 | if length(EEG) > 1 129 | % process multiple datasets 130 | [ EEG, com ] = eeg_eval( 'clean_artifacts', EEG, 'warning', 'on', 'params', options ); 131 | return; 132 | end 133 | 134 | % Delete EEG.etc.clean_channel_mask and EEG.etc.clean_sample_mask if present. 135 | if isfield(EEG.etc, 'clean_channel_mask') 136 | EEG.etc = rmfield(EEG.etc, 'clean_channel_mask'); 137 | disp('EEG.etc.clean_channel_mask present: Deleted.') 138 | end 139 | if isfield(EEG.etc, 'clean_sample_mask') 140 | EEG.etc = rmfield(EEG.etc, 'clean_sample_mask'); 141 | disp('EEG.etc.clean_sample_mask present: Deleted.') 142 | end 143 | 144 | cleanEEG = clean_artifacts(EEG, options{:}); 145 | 146 | % Apply Christian's function before and after comparison visualization. 147 | if nargin < 2 && outs.vis == 1 148 | try 149 | vis_artifacts(cleanEEG,EEG); 150 | catch 151 | warning('vis_artifacts failed. Skipping visualization.') 152 | end 153 | end 154 | 155 | % Update EEG. 156 | EEG = cleanEEG; 157 | 158 | % Output eegh. 159 | com = sprintf('EEG = clean_artifacts(EEG, %s);', vararg2str(options)); 160 | 161 | % Display the ending message. 162 | disp('Done.') 163 | 164 | function outtext = wordwrap(intext,nChars) 165 | outtext = ''; 166 | while ~isempty(intext) 167 | if length(intext) > nChars 168 | cutoff = nChars+find([intext(nChars:end) ' ']==' ',1)-1; 169 | outtext = [outtext intext(1:cutoff-1) '\n']; %#ok<*AGROW> 170 | intext = intext(cutoff+1:end); 171 | else 172 | outtext = [outtext intext]; 173 | intext = ''; 174 | end 175 | end 176 | outtext = sprintf(outtext); 177 | -------------------------------------------------------------------------------- /training/2-iclabel/pop_runica.m: -------------------------------------------------------------------------------- 1 | % pop_runica() - Run an ICA decomposition of an EEG dataset using runica(), 2 | % binica(), or another ICA or other linear decomposition. 3 | % Usage: 4 | % >> OUT_EEG = pop_runica( EEG ); % pops-up a data entry window 5 | % >> OUT_EEG = pop_runica( EEG, 'key', 'val' ); % no pop_up 6 | % 7 | % Graphic interface: 8 | % "ICA algorithm to use" - [edit box] The ICA algorithm to use for 9 | % ICA decomposition. Command line equivalent: 'icatype' 10 | % "Commandline options" - [edit box] Command line options to forward 11 | % to the ICA algorithm. Command line equivalent: 'options' 12 | % Inputs: 13 | % EEG - input EEG dataset or array of datasets 14 | % 15 | % Optional inputs: 16 | % 'icatype' - ['runica'|'binica'|'jader'|'fastica'] ICA algorithm 17 | % to use for the ICA decomposition. The nature of any 18 | % differences in the results of these algorithms have 19 | % not been well characterized. {default: binica(), if 20 | % found, else runica()} 21 | % 'dataset' - [integer array] dataset index or indices. 22 | % 'chanind' - [integer array or cell array] subset of channel indices 23 | % for running the ICA decomposition. Alternatively, you may 24 | % also enter channel types here in a cell array. 25 | % 'concatenate' - ['on'|'off'] 'on' concatenate all input datasets 26 | % (assuming there are several). 'off' run ICA independently 27 | % on each dataset. Default is 'off'. 28 | % 'concatcond' - ['on'|'off'] 'on' concatenate conditions for input datasets 29 | % of the same sessions and the same subject. Default is 'off'. 30 | % 'reorder' - ['on'|'off'] re-order components by variance if that's not 31 | % already the case. Default is 'on'. 32 | % 'key','val' - ICA algorithm options (see ICA routine help messages). 33 | % 34 | % Adding a new algorithm: 35 | % Add the algorithm to the list of algorithms line 366 to 466, for example 36 | % 37 | % case 'myalgo', [EEG.icaweights] = myalgo( tmpdata, g.options{:} ); 38 | % 39 | % where "myalgo" is the name of your algorithm (and Matlab function). 40 | % tmpdata is the 2-D array containing the EEG data (channels x points) and 41 | % g.options{} contains custom options for your algorithm (there is no 42 | % predetermined format for these options). The output EEG.icaweights is the 43 | % mixing matrix (or inverse of the unmixing matrix). 44 | % 45 | % Note: 46 | % 1) Infomax (runica, binica) is the ICA algorithm we use most. It is based 47 | % on Tony Bell's infomax algorithm as implemented for automated use by 48 | % Scott Makeig et al. using the natural gradient of Amari et al. It can 49 | % also extract sub-Gaussian sources using the (recommended) 'extended' option 50 | % of Lee and Girolami. Function runica() is the all-Matlab version; function 51 | % binica() calls the (1.5x faster) binary version (a separate download) 52 | % translated into C from runica() by Sigurd Enghoff. 53 | % 2) jader() calls the JADE algorithm of Jean-Francois Cardoso. This is 54 | % included in the EEGLAB toolbox by his permission. See >> help jader 55 | % 3) To run fastica(), download the fastICA toolbox from its website, 56 | % http://www.cis.hut.fi/projects/ica/fastica/, and make it available 57 | % in your Matlab path. According to its authors, default parameters 58 | % are not optimal: Try args 'approach', 'sym' to estimate components 59 | % in parallel. 60 | % 61 | % Outputs: 62 | % OUT_EEG = The input EEGLAB dataset with new fields icaweights, icasphere 63 | % and icachansind (channel indices). 64 | % 65 | % Author: Arnaud Delorme, CNL / Salk Institute, 2001 66 | % 67 | % See also: runica(), binica(), jader(), fastica() 68 | 69 | % Copyright (C) 2001 Arnaud Delorme, Salk Institute, arno@salk.edu 70 | % 71 | % This file is part of EEGLAB, see http://www.eeglab.org 72 | % for the documentation and details. 73 | % 74 | % Redistribution and use in source and binary forms, with or without 75 | % modification, are permitted provided that the following conditions are met: 76 | % 77 | % 1. Redistributions of source code must retain the above copyright notice, 78 | % this list of conditions and the following disclaimer. 79 | % 80 | % 2. Redistributions in binary form must reproduce the above copyright notice, 81 | % this list of conditions and the following disclaimer in the documentation 82 | % and/or other materials provided with the distribution. 83 | % 84 | % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 85 | % AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 86 | % IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 87 | % ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 88 | % LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 89 | % CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 90 | % SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 91 | % INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 92 | % CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 93 | % ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 94 | % THE POSSIBILITY OF SUCH DAMAGE. 95 | 96 | % 01-25-02 reformated help & license -ad 97 | % 03-07-02 add the eeglab options -ad 98 | % 03-18-02 add other decomposition options -ad 99 | % 03-19-02 text edition -sm 100 | 101 | function [ALLEEG, com] = pop_runica( ALLEEG, varargin ) 102 | 103 | com = ''; 104 | if nargin < 1 105 | help pop_runica; 106 | return; 107 | end 108 | 109 | % find available algorithms 110 | % ------------------------- 111 | allalgs = { 'runica' 'binica' 'jader' 'jadeop' 'jade_td_p' 'MatlabshibbsR' 'fastica' ... 112 | 'tica' 'erica' 'simbec' 'unica' 'amuse' 'fobi' 'evd' 'evd24' 'sons' 'sobi' 'ng_ol' ... 113 | 'acsobiro' 'acrsobibpf' 'pearson_ica' 'egld_ica' 'eeA' 'tfbss' 'icaML' 'icaMS' 'picard' }; % do not use egld_ica => too slow 114 | selectalg = {}; 115 | linenb = 1; 116 | count = 1; 117 | for index = length(allalgs):-1:1 118 | if exist(allalgs{index}) ~= 2 && exist(allalgs{index}) ~= 6 119 | allalgs(index) = []; 120 | end 121 | end 122 | 123 | % special AMICA 124 | % ------------- 125 | selectamica = 0; 126 | defaultopts = [ '''extended'', 1' ] ; 127 | if nargin > 1 128 | if ischar(varargin{1}) 129 | if strcmpi(varargin{1}, 'selectamica') 130 | selectamica = 1; 131 | allalgs = { 'amica' allalgs{:} }; 132 | defaultopts = sprintf('''outdir'', ''%s''', fullfile(pwd, 'amicaout')); 133 | elseif strcmpi(varargin{1}, 'selectamicaloc') 134 | selectamica = 1; 135 | allalgs = { 'amica' allalgs{:} }; 136 | defaultopts = sprintf('''outdir'', ''%s'', ''qsub'', ''off''', fullfile(pwd, 'amicaout')); 137 | end 138 | end 139 | end 140 | 141 | % popup window parameters 142 | % ----------------------- 143 | fig = []; 144 | if nargin < 2 || selectamica 145 | commandchans = [ 'tmpchans = get(gcbf, ''userdata'');' ... 146 | 'tmpchans = tmpchans{1};' ... 147 | 'set(findobj(gcbf, ''tag'', ''chantype''), ''string'', ' ... 148 | ' int2str(pop_chansel( tmpchans )));' ... 149 | 'clear tmpchans;' ]; 150 | commandtype = ['tmptype = get(gcbf, ''userdata'');' ... 151 | 'tmptype = tmptype{2};' ... 152 | 'if ~isempty(tmptype),' ... 153 | ' [tmps,tmpv, tmpstr] = listdlg2(''PromptString'',''Select type(s)'', ''ListString'', tmptype);' ... 154 | ' if tmpv' ... 155 | ' set(findobj(''parent'', gcbf, ''tag'', ''chantype''), ''string'', tmpstr);' ... 156 | ' end;' ... 157 | 'else,' ... 158 | ' warndlg2(''No channel type'', ''No channel type'');' ... 159 | 'end;' ... 160 | 'clear tmps tmpv tmpstr tmptype tmpchans;' ]; 161 | cb_ica = [ 'if get(gcbo, ''value'') < 3, ' ... 162 | ' set(findobj(gcbf, ''tag'', ''params''), ''string'', ''''''extended'''', 1'');' ... 163 | 'else set(findobj(gcbf, ''tag'', ''params''), ''string'', '''');' ... 164 | 'end;' ]; 165 | 166 | promptstr = { { 'style' 'text' 'string' 'ICA algorithm to use (click to select)' } ... 167 | { 'style' 'listbox' 'string' strvcat(allalgs{:}) 'callback', cb_ica } ... 168 | { 'style' 'text' 'string' 'Commandline options (See help messages)' } ... 169 | { 'style' 'edit' 'string' defaultopts 'tag' 'params' } ... 170 | { 'style' 'checkbox' 'string' 'Reorder components by variance (if that''s not already the case)' 'value' 1 } ... 171 | { 'style' 'text' 'string' 'Channel type(s) or channel indices' } ... 172 | { 'style' 'edit' 'string' '' 'tag' 'chantype' } ... 173 | { 'style' 'pushbutton' 'string' '... types' 'callback' commandtype } ... 174 | { 'style' 'pushbutton' 'string' '... channels' 'callback' commandchans } }; 175 | geometry = { [2 1.5] [2 1.5] [1] [2 1 1 1] }; 176 | geomvert = [ 1.5 1 1 1]; 177 | if length(ALLEEG) > 1 178 | cb1 = 'set(findobj(''parent'', gcbf, ''tag'', ''concat2''), ''value'', 0);'; 179 | cb2 = 'set(findobj(''parent'', gcbf, ''tag'', ''concat1''), ''value'', 0);'; 180 | promptstr = { promptstr{:}, ... 181 | { 'style' 'text' 'string' 'Concatenate all datasets (check=yes; uncheck=run ICA on each dataset)?' }, ... 182 | { 'style' 'checkbox' 'string' '' 'value' 0 'tag' 'concat1' 'callback' cb1 }, ... 183 | { 'style' 'text' 'string' 'Concatenate datasets for the same subject and session (check=yes)?' }, ... 184 | { 'style' 'checkbox' 'string' '' 'value' 1 'tag' 'concat2' 'callback' cb2 } }; 185 | geometry = { geometry{:} [ 2 0.2 ] [ 2 0.2 ]}; 186 | geomvert = [ geomvert 1 1]; 187 | end 188 | 189 | % channel types 190 | % ------------- 191 | if isfield(ALLEEG(1).chanlocs, 'type') 192 | tmpchanlocs = ALLEEG(1).chanlocs; 193 | alltypes = { tmpchanlocs.type }; 194 | indempty = cellfun('isempty', alltypes); 195 | alltypes(indempty) = ''; 196 | try 197 | alltypes = unique_bc(alltypes); 198 | catch 199 | alltypes = ''; 200 | end 201 | else 202 | alltypes = ''; 203 | end 204 | 205 | % channel labels 206 | % -------------- 207 | if ~isempty(ALLEEG(1).chanlocs) 208 | tmpchanlocs = ALLEEG(1).chanlocs; 209 | alllabels = { tmpchanlocs.labels }; 210 | else 211 | for index = 1:ALLEEG(1).nbchan 212 | alllabels{index} = int2str(index); 213 | end 214 | end 215 | 216 | % gui 217 | % --- 218 | result = inputgui( 'geometry', geometry, 'geomvert', geomvert, 'uilist', promptstr, ... 219 | 'helpcom', 'pophelp(''pop_runica'')', ... 220 | 'title', 'Run ICA decomposition -- pop_runica()', 'userdata', { alllabels alltypes } ); 221 | if length(result) == 0 return; end 222 | options = { 'icatype' allalgs{result{1}} 'dataset' [1:length(ALLEEG)] 'options' eval( [ '{' result{2} '}' ]) 'reorder' fastif(result{3}, 'on', 'off') }; 223 | if ~isempty(result{4}) 224 | if ~isempty(str2num(result{4})), options = { options{:} 'chanind' str2num(result{4}) }; 225 | else options = { options{:} 'chanind' parsetxt(result{4}) }; 226 | end 227 | end 228 | if length(result) > 4 229 | options = { options{:} 'concatenate' fastif(result{5}, 'on', 'off') }; 230 | options = { options{:} 'concatcond' fastif(result{6}, 'on', 'off') }; 231 | end 232 | else 233 | if mod(length(varargin),2) == 1 234 | options = { 'icatype' varargin{1:end} }; 235 | else 236 | options = varargin; 237 | end 238 | end 239 | 240 | % decode input arguments 241 | % ---------------------- 242 | [ g, addoptions ] = finputcheck( options, { 'icatype' 'string' allalgs 'runica'; ... 243 | 'dataset' 'integer' [] [1:length(ALLEEG)]; 244 | 'options' 'cell' [] {}; 245 | 'concatenate' 'string' { 'on','off' } 'off'; 246 | 'concatcond' 'string' { 'on','off' } 'off'; 247 | 'reorder' 'string' { 'on','off' } 'on'; 248 | 'chanind' { 'cell','integer' } { [] [] } [];}, ... 249 | 'pop_runica', 'ignore'); 250 | if ischar(g), error(g); end 251 | if ~isempty(addoptions), g.options = { g.options{:} addoptions{:}}; end 252 | 253 | % select datasets, create new big dataset if necessary 254 | % ---------------------------------------------------- 255 | if length(g.dataset) == 1 256 | EEG = ALLEEG(g.dataset); 257 | EEG = eeg_checkset(EEG, 'loaddata'); 258 | elseif length(ALLEEG) > 1 && ~strcmpi(g.concatenate, 'on') && ~strcmpi(g.concatcond, 'on') 259 | [ ALLEEG, com ] = eeg_eval( 'pop_runica', ALLEEG, 'warning', 'off', 'params', ... 260 | { 'icatype' g.icatype 'options' g.options 'chanind' g.chanind } ); 261 | return; 262 | elseif length(ALLEEG) > 1 && strcmpi(g.concatcond, 'on') 263 | allsubjects = { ALLEEG.subject }; 264 | allsessions = { ALLEEG.session }; 265 | alltags = zeros(1,length(allsubjects)); 266 | if any(cellfun('isempty', allsubjects)) 267 | errordlg2( [ 'Aborting: Subject names missing from at least one dataset file.' 10 ... 268 | 'Subject names must be stored within the datasets. To do so,' 10 ... 269 | 'use the STUDY > Edit STUDY Info menu and check the box' 10 ... 270 | '"Dataset info (condition, group, ...) differs from study info..."' ]); 271 | end 272 | dats = {}; 273 | for index = 1:length(allsubjects) 274 | if ~alltags(index) 275 | allinds = strmatch(allsubjects{index}, allsubjects, 'exact'); 276 | rmind = []; 277 | % if we have different sessions they will not be concatenated 278 | for tmpi = setdiff_bc(allinds,index)' 279 | if ~isequal(allsessions(index), allsessions(tmpi)), rmind = [rmind tmpi]; 280 | end 281 | end 282 | allinds = setdiff_bc(allinds, rmind); 283 | fprintf('Found %d datasets for subject ''%s''\n', length(allinds), allsubjects{index}); 284 | dats = { dats{:} allinds }; 285 | alltags(allinds) = 1; 286 | end 287 | end 288 | fprintf('**************************\nNOW RUNNING ALL DECOMPOSITIONS\n****************************\n'); 289 | for index = 1:length(dats) 290 | ALLEEG(dats{index}) = pop_runica(ALLEEG(dats{index}), 'icatype', g.icatype, ... 291 | 'options', g.options, 'chanind', g.chanind, 'concatenate', 'on'); 292 | for idat = 1:length(dats{index}) 293 | ALLEEG(dats{index}(idat)).saved = 'no'; 294 | pop_saveset(ALLEEG(dats{index}(idat)), 'savemode', 'resave'); 295 | ALLEEG(dats{index}(idat)).saved = 'yes'; 296 | end 297 | end 298 | com = sprintf('EEG = pop_runica(EEG, %s);', ... 299 | vararg2str({ 'icatype' g.icatype 'concatcond' 'on' 'options' g.options }) ); 300 | return; 301 | else 302 | disp('Concatenating datasets...'); 303 | EEG = ALLEEG(g.dataset(1)); 304 | 305 | % compute total data size 306 | % ----------------------- 307 | totalpnts = 0; 308 | for i = g.dataset 309 | totalpnts = totalpnts+ALLEEG(g.dataset(i)).pnts*ALLEEG(g.dataset(i)).trials; 310 | end 311 | EEG.data = zeros(EEG.nbchan, totalpnts); 312 | 313 | % copy data 314 | % --------- 315 | cpnts = 1; 316 | for i = g.dataset 317 | tmplen = ALLEEG(g.dataset(i)).pnts*ALLEEG(g.dataset(i)).trials; 318 | TMP = eeg_checkset(ALLEEG(g.dataset(i)), 'loaddata'); 319 | EEG.data(:,cpnts:cpnts+tmplen-1) = reshape(TMP.data, size(TMP.data,1), size(TMP.data,2)*size(TMP.data,3)); 320 | cpnts = cpnts+tmplen; 321 | end 322 | EEG.icaweights = []; 323 | EEG.trials = 1; 324 | EEG.pnts = size(EEG.data,2); 325 | EEG.saved = 'no'; 326 | end 327 | 328 | % Store and then remove current EEG ICA weights and sphere 329 | % --------------------------------------------------- 330 | fprintf('\n'); 331 | if ~isempty(EEG.icaweights) 332 | fprintf('Saving current ICA decomposition in "EEG.etc.oldicaweights" (etc.).\n'); 333 | if ~isfield(EEG,'etc'), EEG.etc = []; end 334 | if ~isfield(EEG.etc,'oldicaweights') 335 | EEG.etc.oldicaweights = {}; 336 | EEG.etc.oldicasphere = {}; 337 | EEG.etc.oldicachansind = {}; 338 | end 339 | tmpoldicaweights = EEG.etc.oldicaweights; 340 | tmpoldicasphere = EEG.etc.oldicasphere; 341 | tmpoldicachansind = EEG.etc.oldicachansind; 342 | EEG.etc.oldicaweights = { EEG.icaweights tmpoldicaweights{:} }; 343 | EEG.etc.oldicasphere = { EEG.icasphere tmpoldicasphere{:} }; 344 | EEG.etc.oldicachansind = { EEG.icachansind tmpoldicachansind{:} }; 345 | fprintf(' Decomposition saved as entry %d.\n',length(EEG.etc.oldicaweights)); 346 | end 347 | EEG.icaweights = []; 348 | EEG.icasphere = []; 349 | EEG.icawinv = []; 350 | EEG.icaact = []; 351 | 352 | % select sub_channels 353 | % ------------------- 354 | if isempty(g.chanind) 355 | g.chanind = 1:EEG.nbchan; 356 | end 357 | if iscell(g.chanind) 358 | datatype = {EEG.chanlocs.type}; 359 | tmpChanInd = []; 360 | for iChan = 1:length(datatype) 361 | if ~isempty(datatype{iChan}) && ~isempty(strmatch(datatype{iChan}, g.chanind)) 362 | tmpChanInd = [ tmpChanInd iChan ]; 363 | end 364 | end 365 | g.chanind = tmpChanInd; 366 | end 367 | EEG.icachansind = g.chanind; 368 | 369 | % is pca already an option? 370 | % ------------------------- 371 | pca_opt = 0; 372 | for i = 1:length(g.options) 373 | if ischar(g.options{i}) 374 | if strcmpi(g.options{i}, 'pca') 375 | pca_opt = 1; 376 | pca_ind = i; 377 | end 378 | end 379 | end 380 | 381 | %------------------------------ 382 | % compute ICA on a definite set 383 | % ----------------------------- 384 | tmpdata = reshape( EEG.data(g.chanind,:,:), length(g.chanind), EEG.pnts*EEG.trials); 385 | tmprank = length(g.chanind); 386 | tmpdata = tmpdata - repmat(mean(tmpdata,2), [1 size(tmpdata,2)]); % zero mean 387 | if ~strcmpi(g.icatype, 'binica') 388 | try 389 | disp('Attempting to convert data matrix to double precision for more accurate ICA results.') 390 | tmpdata = double(tmpdata); 391 | tmpdata = tmpdata - repmat(mean(tmpdata,2), [1 size(tmpdata,2)]); % zero mean (more precise than single precision) 392 | catch 393 | disp('*************************************************************') 394 | disp('Not enough memory to convert data matrix to double precision.') 395 | disp('All computations will be done in single precision. Matlab 7.x') 396 | disp('under 64-bit Linux and others is imprecise in this mode.') 397 | disp('We advise use of "binica" instead of "runica."') 398 | disp('*************************************************************') 399 | end 400 | end 401 | switch lower(g.icatype) 402 | case 'runica' 403 | try if ismatlab, g.options = { g.options{:}, 'interrupt', 'on' }; end; catch, end 404 | if tmprank == size(tmpdata,1) || pca_opt 405 | [EEG.icaweights,EEG.icasphere] = runica( tmpdata, 'lrate', 0.001, g.options{:} ); 406 | else 407 | if nargin < 2 408 | uilist = { { 'style' 'text' 'string' [ 'EEGLAB has detected that the rank of your data matrix' 10 ... 409 | 'is lower the number of input data channels. This might' 10 ... 410 | 'be because you are including a reference channel or' 10 ... 411 | 'because you are running a second ICA decomposition.' 10 ... 412 | sprintf('The proposed dimension for ICA is %d (out of %d channels).', tmprank, size(tmpdata,1)) 10 ... 413 | 'Rank computation may be inacurate so you may edit this' 10 ... 414 | 'number below. If you do not understand, simply press OK.' ] } { } ... 415 | { 'style' 'text' 'string' 'Proposed rank:' } ... 416 | { 'style' 'edit' 'string' num2str(tmprank) } }; 417 | res = inputgui('uilist', uilist, 'geometry', { [1] [1] [1 1] }, 'geomvert', [6 1 1]); 418 | if isempty(res), return; end 419 | tmprank = str2num(res{1}); 420 | g.options = [g.options { 'pca' tmprank }]; 421 | else 422 | g.options = [g.options {'pca' tmprank }]; % automatic for STUDY (batch processing) 423 | end 424 | disp(['Data rank (' int2str(tmprank) ') is smaller than the number of channels (' int2str(size(tmpdata,1)) ').']); 425 | [EEG.icaweights,EEG.icasphere] = runica( tmpdata, 'lrate', 0.001, g.options{:} ); 426 | end 427 | case 'binica' 428 | icadefs; 429 | fprintf(['Warning: If the binary ICA function does not work, check that you have added the\n' ... 430 | 'binary file location (in the EEGLAB directory) to your Unix /bin directory (.cshrc file)\n']); 431 | if exist(ICABINARY) ~= 2 432 | error('Pop_runica(): binary ICA executable not found. Edit icadefs.m file to specify the ICABINARY location'); 433 | end 434 | tmprank = getrank(tmpdata(:,1:min(3000, size(tmpdata,2)))); 435 | if tmprank == size(tmpdata,1) || pca_opt 436 | [EEG.icaweights,EEG.icasphere] = binica( tmpdata, 'lrate', 0.001, g.options{:} ); 437 | else 438 | disp(['Data rank (' int2str(tmprank) ') is smaller than the number of channels (' int2str(size(tmpdata,1)) ').']); 439 | [EEG.icaweights,EEG.icasphere] = binica( tmpdata, 'lrate', 0.001, 'pca', tmprank, g.options{:} ); 440 | end 441 | case 'amica' 442 | tmprank = getrank(tmpdata(:,1:min(3000, size(tmpdata,2)))); 443 | fprintf('Now Running AMICA\n'); 444 | if length(g.options) > 1 445 | if ischar(g.options{2}) 446 | fprintf('See folder %s for outputs\n', g.options{2}); 447 | end 448 | end 449 | fprintf('To import results, use menu item "Tools > Run AMICA > Load AMICA components\n'); 450 | modres = runamica( tmpdata, [], size(tmpdata,1), size(tmpdata,2), g.options{:} ); 451 | if ~isempty(modres) 452 | EEG.icaweights = modres.W; 453 | EEG.icasphere = modres.S; 454 | else 455 | return; 456 | end 457 | case 'picard' 458 | options2 = g.options; 459 | if pca_opt 460 | if g.options{pca_ind+1} < 0 461 | [tmpdata,eigvec] = runpca(tmpdata, size(tmpdata,1)+g.options{pca_ind+1}); 462 | else 463 | [tmpdata,eigvec] = runpca(tmpdata, g.options{pca_ind+1}); 464 | end 465 | options2(pca_ind:pca_ind+1) = []; 466 | end 467 | [~, EEG.icaweights] = picard( tmpdata, 'verbose', true, options2{:}); 468 | if pca_opt 469 | EEG.icaweights = EEG.icaweights*pinv(eigvec); 470 | end 471 | case 'pearson_ica' 472 | if isempty(g.options) 473 | disp('Warning: EEGLAB default for pearson ICA is 1000 iterations and epsilon=0.0005'); 474 | [~, EEG.icaweights] = pearson_ica( tmpdata, 'maxNumIterations', 1000,'epsilon',0.0005); 475 | else 476 | [~, EEG.icaweights] = pearson_ica( tmpdata, g.options{:}); 477 | end 478 | case 'egld_ica', disp('Warning: This algorithm is very slow!!!'); 479 | [~, EEG.icaweights] = egld_ica( tmpdata, g.options{:} ); 480 | case 'tfbss' 481 | if isempty(g.options) 482 | [~, EEG.icaweights] = tfbss( tmpdata, size(tmpdata,1), 8, 512 ); 483 | else 484 | [~, EEG.icaweights] = tfbss( tmpdata, g.options{:} ); 485 | end 486 | case 'jader', [EEG.icaweights] = jader( tmpdata, g.options{:} ); 487 | case 'matlabshibbsr', [EEG.icaweights] = MatlabshibbsR( tmpdata, g.options{:} ); 488 | case 'eea', [EEG.icaweights] = eeA( tmpdata, g.options{:} ); 489 | case 'icaml', [~, EEG.icawinv] = icaML( tmpdata, g.options{:} ); 490 | case 'icams', [~, EEG.icawinv] = icaMS( tmpdata, g.options{:} ); 491 | case 'fastica', [~, EEG.icawinv, EEG.icaweights] = fastica( tmpdata, 'displayMode', 'off', g.options{:} ); 492 | case { 'tica' 'erica' 'simbec' 'unica' 'amuse' 'fobi' 'evd' 'sons' ... 493 | 'jadeop' 'jade_td_p' 'evd24' 'sobi' 'ng_ol' 'acsobiro' 'acrsobibpf' } 494 | fig = figure('tag', 'alg_is_run', 'visible', 'off'); 495 | 496 | if isempty(g.options), g.options = { size(tmpdata,1) }; end 497 | switch lower(g.icatype) 498 | case 'tica', EEG.icaweights = tica( tmpdata, g.options{:} ); 499 | case 'erica', EEG.icaweights = erica( tmpdata, g.options{:} ); 500 | case 'simbec', EEG.icaweights = simbec( tmpdata, g.options{:} ); 501 | case 'unica', EEG.icaweights = unica( tmpdata, g.options{:} ); 502 | case 'amuse', EEG.icaweights = amuse( tmpdata ); 503 | case 'fobi', [~, EEG.icaweights] = fobi( tmpdata, g.options{:} ); 504 | case 'evd', EEG.icaweights = evd( tmpdata, g.options{:} ); 505 | case 'sons', EEG.icaweights = sons( tmpdata, g.options{:} ); 506 | case 'jadeop', EEG.icaweights = jadeop( tmpdata, g.options{:} ); 507 | case 'jade_td_p',EEG.icaweights = jade_td_p( tmpdata, g.options{:} ); 508 | case 'evd24', EEG.icaweights = evd24( tmpdata, g.options{:} ); 509 | case 'sobi', EEG.icawinv = sobi( tmpdata, g.options{:} ); 510 | case 'ng_ol', [~, EEG.icaweights] = ng_ol( tmpdata, g.options{:} ); 511 | case 'acsobiro', EEG.icawinv = acsobiro( tmpdata, g.options{:} ); 512 | case 'acrsobibpf', EEG.icawinv = acrsobibpf( tmpdata, g.options{:} ); 513 | end 514 | clear tmp; 515 | close(fig); 516 | otherwise, error('Pop_runica: unrecognized algorithm'); 517 | end 518 | 519 | % update weight and inverse matrices etc... 520 | % ----------------------------------------- 521 | if ~isempty(fig), try close(fig); catch, end; end 522 | if isempty(EEG.icaweights) 523 | EEG.icaweights = pinv(EEG.icawinv); 524 | end 525 | if isempty(EEG.icasphere) 526 | EEG.icasphere = eye(size(EEG.icaweights,2)); 527 | end 528 | if isempty(EEG.icawinv) 529 | EEG.icawinv = pinv(EEG.icaweights*EEG.icasphere); % a priori same result as inv 530 | end 531 | 532 | % Reorder components by variance 533 | % ------------------------------ 534 | meanvar = sum(EEG.icawinv.^2).*sum(transpose((EEG.icaweights * EEG.icasphere)*EEG.data(EEG.icachansind,:)).^2)/((length(EEG.icachansind)*EEG.pnts)-1); 535 | [~, windex] = sort(meanvar); 536 | windex = windex(end:-1:1); % order large to small 537 | meanvar = meanvar(windex); 538 | EEG.icaweights = EEG.icaweights(windex,:); 539 | EEG.icawinv = pinv( EEG.icaweights * EEG.icasphere ); 540 | if ~isempty(EEG.icaact) 541 | EEG.icaact = EEG.icaact(windex,:,:); 542 | end 543 | 544 | % copy back data to datasets if necessary 545 | % --------------------------------------- 546 | if length(g.dataset) > 1 547 | for i = g.dataset 548 | ALLEEG(i).icaweights = EEG.icaweights; 549 | ALLEEG(i).icasphere = EEG.icasphere; 550 | ALLEEG(i).icawinv = EEG.icawinv; 551 | ALLEEG(i).icachansind = g.chanind; 552 | end 553 | ALLEEG = eeg_checkset(ALLEEG); 554 | else 555 | EEG = eeg_checkset(EEG); 556 | ALLEEG = eeg_store(ALLEEG, EEG, g.dataset); 557 | end 558 | 559 | if nargin < 2 || selectamica 560 | if ~isempty(g.options) 561 | com = sprintf('EEG = pop_runica(EEG, ''icatype'', ''%s'', %s);', g.icatype, vararg2str(g.options) ); %vararg2str({ 'icatype' g.icatype 'dataset' g.dataset 'options' g.options }) ); 562 | else 563 | com = sprintf('EEG = pop_runica(EEG, ''icatype'', ''%s'');',g.icatype ); 564 | end 565 | end 566 | 567 | return; 568 | 569 | function tmprank2 = getrank(tmpdata) 570 | 571 | tmprank = rank(tmpdata); 572 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 573 | %Here: alternate computation of the rank by Sven Hoffman 574 | %tmprank = rank(tmpdata(:,1:min(3000, size(tmpdata,2)))); old code 575 | covarianceMatrix = cov(tmpdata', 1); 576 | [~, D] = eig (covarianceMatrix); 577 | rankTolerance = 1e-7; 578 | tmprank2=sum (diag (D) > rankTolerance); 579 | if tmprank ~= tmprank2 580 | fprintf('Warning: fixing rank computation inconsistency (%d vs %d) most likely because running under Linux 64-bit Matlab\n', tmprank, tmprank2); 581 | tmprank2 = max(tmprank, tmprank2); 582 | end 583 | 584 | 585 | -------------------------------------------------------------------------------- /training/2-iclabel/run_ica.m: -------------------------------------------------------------------------------- 1 | function run_ica(startsub,stopsub) 2 | 3 | cd //user//leuven//336//vsc33613//eeglab2019_1 4 | eeglab 5 | cd //user//leuven//336//vsc33613//Extra 6 | %% params 7 | newroot = '//scratch//leuven//333//vsc33378//Datasets//Neureka_challenge//ICAlabel'; 8 | root0 = '//scratch//leuven//333//vsc33378//Datasets//Neureka_challenge'; 9 | root1 = '//edf//train'; 10 | root = [root0,root1]; 11 | montage = '02_tcp_le'; 12 | path = fullfile(root, montage); 13 | [f,d] = getContent(path, 1); 14 | N = size(d,1); 15 | 16 | 17 | recs0=[]; 18 | for ifolder = startsub:stopsub 19 | p = fullfile(f{ifolder}, d{ifolder}); 20 | [f2,d2] = getContent(p, 1); 21 | N2 = size(d2,1); 22 | subject = []; 23 | for isubject = 1:N2 24 | p = fullfile(f2{isubject}, d2{isubject}); 25 | subjectstrname = d2{isubject}; 26 | subjectname = num2str(str2num(subjectstrname)); 27 | [f3,d3] = getContent(p, 1); 28 | N3 = size(d3,1); %number of sessions 29 | 30 | %newsubjectfolder = fullfile(newroot,subjectname); 31 | %if(~exist(newsubjectfolder , 'dir')) 32 | % mkdir(newsubjectfolder ) 33 | %end 34 | 35 | for isession = 1:N3 36 | pf = fullfile(f3{isession }, d3{isession }); 37 | foldername = d3{isession}; 38 | sessionname = strsplit(foldername,'_'); 39 | sessionname = sessionname{1}; 40 | recnames = findRecording(pf, subjectstrname, sessionname); 41 | newrecCounter = 0; 42 | for irec = 1:size(recnames,1) 43 | fprintf('processing ifolder: %d, isubject: %d, isession: %d, irec: %d \n', ifolder, isubject, isession, irec); 44 | display([pf, ' -> ', recnames.recstrname{irec}]); 45 | %newedfname = [subjectname, char('a' + newrecCounter)]; 46 | %newedfpath = fullfile(newsubjectfolder, [newedfname,'.edf']); 47 | %newannpath = fullfile(newsubjectfolder, [newedfname,'.tsv']); 48 | oldedfpath = fullfile(pf, recnames.edfname{irec}); 49 | newrecCounter = newrecCounter + 1; 50 | newrecfolder = fullfile(newroot, subjectname); 51 | newedfname = [subjectname,'_r', num2str(newrecCounter)]; 52 | newedfpath = fullfile(newrecfolder, [newedfname,'.mat']); 53 | EEG=pop_biosig(oldedfpath,'importevent','off','rmeventchan','off'); 54 | EEG=pop_runica(EEG,'chanind',[1:21]); 55 | if(~exist(newrecfolder , 'dir')) 56 | mkdir(newrecfolder); 57 | end 58 | save(newedfpath,'EEG') 59 | end 60 | end 61 | end 62 | 63 | clc 64 | end 65 | end 66 | 67 | 68 | -------------------------------------------------------------------------------- /training/2-iclabel/run_icalabel.m: -------------------------------------------------------------------------------- 1 | function run_icalabel(startsub,stopsub,root,montage,saveroot) 2 | %Function for run the complete icalabel to all subjects (you need to include in the path eeglab and folder with "Extra" functions 3 | %Inputs 4 | %startsub,stopsub - the number of subjects for which you want to run the algorithm. 5 | %montage - the montage for which you want to run the algorithm (with the appropriate selection of montage startsub,stopsub you can parallelize the algorithm) 6 | %root- The root where the data are saved - the format must follow the one given by Temple Un. 7 | %saveroot- The folder where the results will be saved 8 | 9 | %Example of the function paths which shall be included, root saveroot and montage formats 10 | %cd //user//leuven//336//vsc33613//eeglab2019_1 11 | %cd //user//leuven//336//vsc33613//Extra 12 | %root0 = '//scratch//leuven//333//vsc33378//Datasets//Neureka_challenge'; 13 | %root1 = '//edf//dev'; 14 | %root = [root0,root1]; 15 | %montage='02_tcp_le'; 16 | 17 | eeglab 18 | path = fullfile(root, montage); 19 | [f,d] = getContent(path, 1); 20 | for ifolder = startsub:stopsub 21 | p = fullfile(f{ifolder}, d{ifolder}); 22 | [f2,d2] = getContent(p, 1); 23 | N2 = size(d2,1); 24 | for isubject = 1:N2 25 | p = fullfile(f2{isubject}, d2{isubject}); 26 | subjectstrname = d2{isubject}; 27 | [f3,d3] = getContent(p, 1); 28 | N3 = size(d3,1); %number of sessions 29 | for isession = 1:N3 30 | pf = fullfile(f3{isession }, d3{isession }); 31 | foldername = d3{isession}; 32 | sessionname = strsplit(foldername,'_'); 33 | sessionname = sessionname{1}; 34 | recnames = findRecording(pf, subjectstrname, sessionname); 35 | for irec = 1:size(recnames,1) 36 | fprintf('processing ifolder: %d, isubject: %d, isession: %d, irec: %d \n', ifolder, isubject, isession, irec); 37 | display([pf, ' -> ', recnames.recstrname{irec}]); 38 | oldedfpath = fullfile(pf, recnames.edfname{irec}); 39 | newedfname = [pf,'/',erase(recnames.edfname{irec},'.edf'),'_icalbl.edf']; 40 | EEG=pop_biosig(oldedfpath,'importevent','off','rmeventchan','off'); 41 | temp=load('input.mat'); 42 | EEG=pop_clean_rawdata(EEG,temp.options); 43 | neureka_locs=squeeze(struct2cell(readlocs('neureka.locs'))); 44 | eeg1=struct2cell(EEG.chanlocs); 45 | for i=1:size(eeg1,2) 46 | for j=1:size(neureka_locs,2) 47 | if contains(eeg1{1,i},neureka_locs{3,j}) 48 | eeg1{3,i}=neureka_locs{1,j}; 49 | eeg1{4,i}=neureka_locs{2,j}; 50 | eeg1{5,i}=neureka_locs{8,j}; 51 | eeg1{6,i}=neureka_locs{9,j}; 52 | eeg1{7,i}=neureka_locs{10,j}; 53 | eeg1{8,i}=neureka_locs{4,j}; 54 | eeg1{9,i}=neureka_locs{5,j}; 55 | end 56 | end 57 | end 58 | channels_ic=find(cellfun(@isempty,(eeg1(3,:)))==0); 59 | EEG.chanlocs=cell2struct(eeg1,fieldnames(EEG.chanlocs)',1); 60 | EEG=pop_runica(EEG,'chanind',channels_ic); 61 | EEG=iclabel(EEG); 62 | [indx,indy]=find(EEG.etc.ic_classification.ICLabel.classifications(:,2:6)>0.8); 63 | if (size(channels_ic,2)-size(indx,1))==0 64 | [indx,indy]=find(EEG.etc.ic_classification.ICLabel.classifications(:,2:6)>0.9); 65 | end 66 | if (size(channels_ic,2)-size(indx,1))==0 67 | OUTEEG=EEG; 68 | else 69 | OUTEEG = pop_subcomp( EEG,indx ); 70 | end 71 | %pfz=erase(f3{isession},'/ddn1/vol1/site_scratch/leuven/333/vsc33378/Datasets/Neureka_challenge'); 72 | %pfz=['/data/leuven/336/vsc33613/Neureka', pfz]; 73 | pfz=erase(f3{isession},root); 74 | pfz=[saveroot,pfz]; 75 | if(~exist(pfz , 'dir')) 76 | mkdir(pfz); 77 | end 78 | newedfname = [pfz,'/',erase(recnames.edfname{irec},'.edf'),'_icalbl.edf']; 79 | pop_writeeeg(OUTEEG, newedfname, 'TYPE','EDF'); 80 | end 81 | end 82 | end 83 | 84 | clc 85 | end 86 | end 87 | 88 | 89 | -------------------------------------------------------------------------------- /training/3-DNN/3-load-data.py: -------------------------------------------------------------------------------- 1 | """ Load all edf files. 2 | 3 | This file reads all edf files in a given directory and combines them in a data structure 4 | to be used during training of the U-net. 5 | Has to be run for every U-net that is going to be trained. 6 | """ 7 | 8 | 9 | # Importing of necessary libraries 10 | 11 | import sys 12 | # Root folder of main library 13 | sys.path.insert(0, 'library') 14 | import loading 15 | import nedc 16 | 17 | # Libraries 18 | import os 19 | import pandas as pd 20 | import numpy as np 21 | import matplotlib.pyplot as plt 22 | from multiprocessing import Pool 23 | import h5py 24 | 25 | 26 | # Variables that have to be set accordingly 27 | base_directory = 'PATH_OF_ORIGINAL_DATASET' # Path to directory with EDF files 28 | save_path = 'PATH_OF_LOADED_FILE.h5' # Path to file containing the loaded data structure 29 | 30 | includes_tse = False # Boolean flag, whether .tse files with ground-truth labels can also be loaded 31 | wiener = False # Boolean flag, whether Wiener filtering is applied 32 | 33 | def wrangle_tse(tse_path, length, fs=200): 34 | """ 35 | Function to process a given .tse file into a time series of labels. 36 | tse_path: Path to .tse file 37 | length: Number of time samples in the corresponding EEG time series 38 | fs: Sampling rate of the time series 39 | """ 40 | label_dct = { 41 | 'bckg': 0, 42 | 'seiz': 1 43 | } 44 | 45 | label = np.zeros(shape=(length,)) 46 | 47 | df_label = pd.read_csv( 48 | filepath_or_buffer=tse_path, 49 | header=None, 50 | sep=' ', 51 | names=['start', 'stop', 'label', 'confidence'], 52 | skiprows=2, 53 | na_filter=False 54 | ) 55 | 56 | for i, time_s in enumerate(df_label.start): 57 | label_str = df_label.label[i] 58 | label[int(time_s*fs):] = label_dct[label_str] 59 | 60 | return label 61 | 62 | 63 | """ 64 | Function that loads a given recording, resamples and re-references. 65 | Applies Wiener filtering, and loads the .tse file; both when appropriate. 66 | """ 67 | if includes_tse: 68 | def process_file(file_path): 69 | file_name = file_path[-22-7:-4-7] 70 | 71 | try: 72 | (fs, data, mount) = loading.loadRecording(file_path, wiener=wiener) 73 | signal = np.asarray(data, dtype=np.float32) 74 | 75 | label = wrangle_tse(file_path[:-4]+'.tse_bi', length=signal.shape[1]) 76 | label = np.asarray(label, dtype=np.uint8) 77 | except TypeError: 78 | signal = 0 79 | 80 | return file_name, signal, label 81 | else: 82 | def process_file(file_path): 83 | file_name = file_path[-22-7:-4-7] 84 | 85 | try: 86 | (fs, data, mount) = loading.loadRecording(file_path, wiener=wiener) 87 | signal = np.asarray(data, dtype=np.float32) 88 | 89 | except TypeError: 90 | signal = 0 91 | 92 | return file_name, signal 93 | 94 | 95 | # Walks through the given directory and creates list of all .edf files 96 | edf_files = [] 97 | for root, dirs, files in os.walk(base_directory): 98 | for file in files: 99 | if file.endswith(".edf"): 100 | edf_files.append(os.path.join(root, file)) 101 | 102 | # Processes all files in parallel 103 | pool = Pool() 104 | 105 | if includes_tse: 106 | file_names, signals, labels = zip(*pool.map(process_file, edf_files)) 107 | else: 108 | file_names, signals = zip(*pool.map(process_file, edf_files)) 109 | 110 | # Necessary manipulation, the ICLabel procedure rejects some training files due to noise. 111 | file_names, signals = zip(*[[file_name, signal] for file_name, signal in zip(file_names, signals) 112 | if len(np.asarray(signal).shape)!=0]) 113 | 114 | # Saves new data structure to disk 115 | if includes_tse: 116 | dt_fl = h5py.vlen_dtype(np.dtype('float32')) 117 | dt_int = h5py.vlen_dtype(np.dtype('uint8')) 118 | dt_str = h5py.special_dtype(vlen=str) 119 | 120 | with h5py.File(save_path, 'w') as f: 121 | dset_signals = f.create_dataset('signals', (len(signals), 18), dtype=dt_fl) 122 | dset_labels = f.create_dataset('labels', (len(labels),), dtype=dt_int) 123 | dset_file_names = f.create_dataset('filenames', (len(file_names),), dtype=dt_str) 124 | 125 | for i in range(len(signals)): 126 | dset_signals[i] = signals[i] 127 | dset_labels[i] = labels[i] 128 | dset_file_names[i] = file_names[i] 129 | else: 130 | dt_fl = h5py.vlen_dtype(np.dtype('float32')) 131 | dt_str = h5py.special_dtype(vlen=str) 132 | 133 | with h5py.File(save_path, 'w') as f: 134 | dset_signals = f.create_dataset('signals', (len(signals), 18), dtype=dt_fl) 135 | dset_file_names = f.create_dataset('filenames', (len(file_names),), dtype=dt_str) 136 | 137 | for i in range(len(signals)): 138 | dset_signals[i] = signals[i] 139 | dset_file_names[i] = file_names[i] -------------------------------------------------------------------------------- /training/3-DNN/3-train-unet.py: -------------------------------------------------------------------------------- 1 | """Train a U-net for a specific data view. 2 | 3 | This file loads a pre-processed data object, creates a new U-net and starts the training loop on the data. 4 | During training, the network weights with the best validation performance are saved to disk. 5 | """ 6 | # Importing of necessary libraries 7 | import h5py 8 | import numpy as np 9 | from sklearn import model_selection 10 | import matplotlib.pyplot as plt 11 | from sklearn import metrics 12 | 13 | import tensorflow as tf 14 | from tensorflow.keras.optimizers import Adam 15 | 16 | from utils import SegmentGenerator, setup_tf, build_unet 17 | 18 | 19 | # Variables locating the pre-processed data and the to-be-saved network weights 20 | save_path = 'PATH_TO_LOADED_DATA.h5' 21 | network_path = 'PATH_TO_NETWORK_WEIGHTS.h5' 22 | 23 | # Some random variables 24 | fs = 200 25 | n_secs = 30 26 | n_channels = 18 27 | 28 | # Tensorflow function to detect GPU properly 29 | setup_tf() 30 | 31 | # Loading data + normalizing 32 | with h5py.File(save_path, 'r') as f: 33 | file_names = [] 34 | labels = [] 35 | signals = [] 36 | 37 | file_names_ds = f['filenames'] 38 | signals_ds = f['signals'] 39 | labels_ds = f['labels'] 40 | 41 | for i in range(len(signals_ds)): 42 | file_names.append(file_names_ds[i]) 43 | data = np.asarray(np.vstack(signals_ds[i]), dtype=np.float32).T 44 | mean = np.mean(data, axis=0) 45 | std = np.std(data, axis=0) 46 | signals.append((data-mean)/std) 47 | labels.append(labels_ds[i]) 48 | 49 | # Building a list for stratified train-val split, balance the amount of files containing seizures 50 | seizure_label = [] 51 | for label in labels: 52 | seizure_label.append(np.sum(label)>0) 53 | seizure_label = np.asarray(seizure_label, dtype=np.uint8) 54 | 55 | # Train-val split 56 | signal_train, signal_val, label_train, label_val = model_selection.train_test_split(signals, labels, 57 | test_size=0.2, random_state=1337, stratify=seizure_label) 58 | 59 | # Network settings 60 | n_filters = 8 61 | window_size = 4096 62 | n_channels = 18 63 | 64 | # Build the unet, and unet_train objects (use same underlying layers, unet_train is used for deep supervision) 65 | unet, unet_train = build_unet(window_size=window_size, n_channels=n_channels, n_filters=n_filters) 66 | 67 | # Build a Keras data generator object 68 | generator = SegmentGenerator(signals=signal_train, labels=label_train, batch_size=32, 69 | window_size=window_size, stride=1000, n_channels=n_channels) 70 | 71 | # Training settings + bookkeeping variables 72 | n_batches = len(generator) 73 | n_epochs = 100 74 | optimizer = Adam(lr=1e-4) 75 | 76 | loss_train = np.zeros(shape=(n_epochs,)) 77 | xentr_train = np.zeros(shape=(n_epochs,)) 78 | xentr_val_mean = np.zeros(shape=(n_epochs,)) 79 | xentr_val_std = np.zeros(shape=(n_epochs,)) 80 | one = np.float32(1.) 81 | bin_xent = tf.keras.losses.BinaryCrossentropy(label_smoothing=0.2) 82 | 83 | best_loss = 1e20 84 | 85 | # Loss weights 86 | all_labels = np.copy(np.concatenate(label_train)) 87 | n_bckg = np.sum(all_labels==0) 88 | n_seiz = np.sum(all_labels==1) 89 | del all_labels 90 | 91 | 92 | # Actual training loop 93 | for epoch in range(n_epochs): 94 | 95 | epoch_loss_avg = tf.keras.metrics.Mean() 96 | epoch_xentr_avg = tf.keras.metrics.Mean() 97 | print('====== Epoch #{0:3d} ======'.format(epoch)) 98 | # Training loop over all batches 99 | for batch in range(n_batches): 100 | x, y = generator.__getitem__(batch) 101 | 102 | with tf.GradientTape() as t: 103 | y_0, y_1, y_2, y_3, y_4, y_5 = unet_train(x, training=True) 104 | xentr0 = bin_xent(y_true=tf.expand_dims(y, axis=-1), y_pred=tf.expand_dims(y_0, axis=-1), 105 | sample_weight=n_bckg/n_seiz*y+(one-y)) 106 | y = y[:, ::4] 107 | xentr1 = bin_xent(y_true=tf.expand_dims(y, axis=-1), y_pred=tf.expand_dims(y_1, axis=-1), 108 | sample_weight=n_bckg/n_seiz*y+(one-y)) 109 | y = y[:, ::4] 110 | xentr2 = bin_xent(y_true=tf.expand_dims(y, axis=-1), y_pred=tf.expand_dims(y_2, axis=-1), 111 | sample_weight=n_bckg/n_seiz*y+(one-y)) 112 | y = y[:, ::4] 113 | xentr3 = bin_xent(y_true=tf.expand_dims(y, axis=-1), y_pred=tf.expand_dims(y_3, axis=-1), 114 | sample_weight=n_bckg/n_seiz*y+(one-y)) 115 | y = y[:, ::4] 116 | xentr4 = bin_xent(y_true=tf.expand_dims(y, axis=-1), y_pred=tf.expand_dims(y_4, axis=-1), 117 | sample_weight=n_bckg/n_seiz*y+(one-y)) 118 | y = y[:, ::4] 119 | xentr5 = bin_xent(y_true=tf.expand_dims(y, axis=-1), y_pred=tf.expand_dims(y_5, axis=-1), 120 | sample_weight=n_bckg/n_seiz*y+(one-y)) 121 | 122 | loss0 = tf.reduce_mean(xentr0) 123 | loss1 = tf.reduce_mean(xentr1) 124 | loss2 = tf.reduce_mean(xentr2) 125 | loss3 = tf.reduce_mean(xentr3) 126 | loss4 = tf.reduce_mean(xentr4) 127 | loss5 = tf.reduce_mean(xentr5) 128 | loss = loss0 + 0.2*(loss1 + loss2 + loss3 + loss4 + loss5) 129 | 130 | grad = t.gradient(loss, unet_train.trainable_variables) 131 | optimizer.apply_gradients(zip(grad, unet_train.trainable_variables)) 132 | epoch_loss_avg(loss) 133 | epoch_xentr_avg(loss0) 134 | 135 | generator.on_epoch_end() 136 | 137 | xentr_train[epoch] = epoch_xentr_avg.result() 138 | loss_train[epoch] = epoch_loss_avg.result() 139 | print('Loss Train - {0:.4f}'.format(loss_train[epoch])) 140 | print('Xentropy Train - {0:.4f}'.format(xentr_train[epoch])) 141 | 142 | # Calculating validation loss for "early stopping" 143 | xentr = [] 144 | for j in range(len(signal_val)): 145 | signal = signal_val[j] 146 | label = label_val[j] 147 | if len(signal) < window_size: 148 | break 149 | x = [] 150 | y = [] 151 | for i in range(len(signal)//window_size): 152 | x.append(signal[window_size*i:(i+1)*window_size, :]) 153 | y.append(label[window_size*i:(i+1)*window_size]) 154 | x = np.asarray(x, dtype=np.float32) 155 | y = np.asarray(y, dtype=np.float32) 156 | y_ = unet.predict(x) 157 | xentr.append(bin_xent(y_true=tf.expand_dims(y, axis=-1), y_pred=tf.expand_dims(y_, axis=-1), 158 | sample_weight=n_bckg/n_seiz*y+(one-y)).numpy()) 159 | 160 | xentr_val_mean[epoch] = np.mean(xentr) 161 | xentr_val_std[epoch] = np.std(xentr) 162 | 163 | if xentr_val_mean[epoch] < best_loss: 164 | best_loss = xentr_val_mean[epoch] 165 | unet.save_weights(network_path) 166 | 167 | print('Xentropy Val - {0:.4f} ± {1:.4f}'.format(xentr_val_mean[epoch], xentr_val_std[epoch])) -------------------------------------------------------------------------------- /training/3-DNN/README.md: -------------------------------------------------------------------------------- 1 | ## README file for the base detection neural network code for the Neureka data 2 | 3 | 4 | * 3-load-data.py 5 | 6 | This file processes a directory structure of EEG recordings, preprocessed with ICLabel or not, and prepares a data structure 7 | fit for training the neural network. 8 | 9 | * 3-train-unet.py 10 | 11 | Script providing code for training a model on either raw EEG, Wiener filtered EEG, or ICLabel processed EEG. The notebook 12 | saves the model parameters during training for later use. 13 | 14 | * utils.py 15 | 16 | File with utility code for the data generator and building the U-net 17 | -------------------------------------------------------------------------------- /training/3-DNN/utils.py: -------------------------------------------------------------------------------- 1 | import h5py 2 | import numpy as np 3 | 4 | import tensorflow as tf 5 | from tensorflow import keras 6 | from tensorflow.keras import Model, Input 7 | from tensorflow.keras.layers import Conv2D, UpSampling2D, MaxPooling2D, AveragePooling2D, Attention 8 | from tensorflow.keras.layers import ELU, BatchNormalization, Reshape, Concatenate, Dropout, Add, Multiply 9 | from tensorflow.keras.optimizers import Adam 10 | from tensorflow.python.keras import activations 11 | from tensorflow.python.keras import constraints 12 | from tensorflow.python.keras import initializers 13 | from tensorflow.python.keras import regularizers 14 | from tensorflow.python.framework import tensor_shape 15 | from tensorflow.python.ops import nn 16 | 17 | 18 | def setup_tf(): 19 | """ 20 | Detects GPUs and (currently) sets automatic memory growth 21 | """ 22 | gpus = tf.config.experimental.list_physical_devices('GPU') 23 | 24 | if gpus: 25 | try: 26 | for gpu in gpus: 27 | tf.config.experimental.set_memory_growth(gpu,True) 28 | logical_gpus = tf.config.experimental.list_logical_devices('GPU') 29 | 30 | print(len(gpus), 'Physical GPUs, ', len(logical_gpus), 'Logical GPUs') 31 | except RuntimeError as e: 32 | print(e) 33 | 34 | 35 | class SegmentGenerator(keras.utils.Sequence): 36 | def __init__(self, signals, labels, batch_size=128, shuffle=True, stride=200, window_size=1024, n_channels=20): 37 | super().__init__() 38 | self.signals = signals 39 | self.labels = labels 40 | self.batch_size = batch_size 41 | self.shuffle = shuffle 42 | self.stride = stride 43 | self.window_size = window_size 44 | self.n_channels = n_channels 45 | 46 | key_array = [] 47 | 48 | for i, array in enumerate(self.signals): 49 | n = (array.shape[0] - self.window_size)//self.stride 50 | for j in range(n): 51 | key_array.append([i, self.stride*j]) 52 | 53 | self.key_array = np.asarray(key_array, dtype=np.uint32) 54 | 55 | self.on_epoch_end() 56 | 57 | def __len__(self): 58 | return len(self.key_array)//self.batch_size 59 | 60 | def __getitem__(self, index): 61 | keys = np.arange(start=index*self.batch_size, stop=(index+1)*self.batch_size) 62 | 63 | x, y = self.__data_generation__(keys) 64 | 65 | return x, y 66 | 67 | def on_epoch_end(self): 68 | if self.shuffle: 69 | self.key_array = np.random.permutation(self.key_array) 70 | 71 | def __data_generation__(self, keys): 72 | x = np.empty(shape=(self.batch_size, self.window_size, self.n_channels), dtype=np.float32) 73 | y = np.empty(shape=(self.batch_size, self.window_size)) 74 | 75 | for i in range(self.batch_size): 76 | key = self.key_array[keys[i]] 77 | x[i, :, :] = self.signals[key[0]][key[1]:key[1]+self.window_size, :] 78 | y[i, :] = self.labels[key[0]][key[1]:key[1]+self.window_size] 79 | 80 | return x, y 81 | 82 | 83 | class BiasedConv(Conv2D): 84 | def __init__(self, 85 | filters, 86 | kernel_size, 87 | strides=(1, 1), 88 | padding='valid', 89 | data_format=None, 90 | dilation_rate=(1, 1), 91 | activation=None, 92 | use_bias=True, 93 | kernel_initializer='glorot_uniform', 94 | bias_initializer='zeros', 95 | kernel_regularizer=None, 96 | bias_regularizer=None, 97 | activity_regularizer=None, 98 | kernel_constraint=None, 99 | bias_constraint=None, 100 | **kwargs): 101 | super(Conv2D, self).__init__( 102 | rank=2, 103 | filters=filters, 104 | kernel_size=kernel_size, 105 | strides=strides, 106 | padding=padding, 107 | data_format=data_format, 108 | dilation_rate=dilation_rate, 109 | activation=activations.get(activation), 110 | use_bias=True, 111 | kernel_initializer=initializers.get(kernel_initializer), 112 | bias_initializer=initializers.get(bias_initializer), 113 | kernel_regularizer=regularizers.get(kernel_regularizer), 114 | bias_regularizer=regularizers.get(bias_regularizer), 115 | activity_regularizer=regularizers.get(activity_regularizer), 116 | kernel_constraint=constraints.get(kernel_constraint), 117 | bias_constraint=constraints.get(bias_constraint), 118 | **kwargs) 119 | 120 | def build(self, input_shape): 121 | input_shape = tensor_shape.TensorShape(input_shape) 122 | 123 | self.bias = self.add_weight( 124 | name='bias', 125 | shape=(self.filters,), 126 | initializer=self.bias_initializer, 127 | regularizer=self.bias_regularizer, 128 | constraint=self.bias_constraint, 129 | trainable=True, 130 | dtype=self.dtype) 131 | 132 | self.built = True 133 | 134 | def compute_output_shape(self, input_shape): 135 | return input_shape 136 | 137 | def call(self, inputs): 138 | # Check if the input_shape in call() is different from that in build(). 139 | # If they are different, recreate the _convolution_op to avoid the stateful 140 | # behavior. 141 | call_input_shape = inputs.get_shape() 142 | outputs = inputs 143 | 144 | if self.data_format == 'channels_first': 145 | if self.rank == 1: 146 | # nn.bias_add does not accept a 1D input tensor. 147 | bias = array_ops.reshape(self.bias, (1, self.filters, 1)) 148 | outputs += bias 149 | else: 150 | outputs = nn.bias_add(outputs, self.bias, data_format='NCHW') 151 | else: 152 | outputs = nn.bias_add(outputs, self.bias, data_format='NHWC') 153 | 154 | if self.activation is not None: 155 | return self.activation(outputs) 156 | return outputs 157 | 158 | class AttentionPooling(object): 159 | def __init__(self,filters, channels=18): 160 | self.filters = filters 161 | self.channels = channels 162 | 163 | def __call__(self, inputs): 164 | query, value = inputs 165 | 166 | att_q = Conv2D(filters=self.filters, kernel_size=(1, 1), strides=(1, 1), 167 | padding='same', activation=None, use_bias=False)(query) 168 | att_k = Conv2D(filters=self.filters, kernel_size=(1, 1), strides=(1, 1), 169 | padding='same', activation=None, use_bias=False)(value) 170 | gate = BiasedConv(filters=self.filters, kernel_size=(1, 1), strides=(1, 1), 171 | padding='same', activation='sigmoid', 172 | kernel_initializer='zeros', bias_initializer='ones')(Add()([att_q, att_k])) 173 | att = Conv2D(filters=1, kernel_size=(1, 1), strides=(1, 1), 174 | padding='same', activation='sigmoid', 175 | kernel_initializer='ones', bias_initializer='zeros')(gate) 176 | 177 | return AveragePooling2D(pool_size=(1, self.channels), padding='same')(Multiply()([att, value])) 178 | 179 | def build_unet(window_size=4096, n_channels=18, n_filters=8): 180 | input_seq = Input(shape=(window_size, n_channels)) 181 | 182 | x = Reshape(target_shape=(window_size, n_channels, 1))(input_seq) 183 | 184 | x = Conv2D(filters=n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(x) 185 | x = BatchNormalization()(x) 186 | lvl0 = ELU()(x) 187 | 188 | x = MaxPooling2D(pool_size=(4, 1), padding='same')(lvl0) 189 | x = Conv2D(filters=2*n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(x) 190 | x = BatchNormalization()(x) 191 | lvl1 = ELU()(x) 192 | 193 | x = MaxPooling2D(pool_size=(4, 1), padding='same')(lvl1) 194 | x = Conv2D(filters=4*n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(x) 195 | x = BatchNormalization()(x) 196 | lvl2 = ELU()(x) 197 | 198 | x = MaxPooling2D(pool_size=(4, 1), padding='same')(lvl2) 199 | x = Conv2D(filters=4*n_filters, kernel_size=(7, 1), strides=(1, 1), padding='same', activation=None)(x) 200 | x = BatchNormalization()(x) 201 | lvl3 = ELU()(x) 202 | 203 | x = MaxPooling2D(pool_size=(4, 1), padding='same')(lvl3) 204 | x = Conv2D(filters=8*n_filters, kernel_size=(3, 1), strides=(1, 1), padding='same', activation=None)(x) 205 | x = BatchNormalization()(x) 206 | lvl4 = ELU()(x) 207 | 208 | x = MaxPooling2D(pool_size=(4, 1), padding='same')(lvl4) 209 | x = Conv2D(filters=8*n_filters, kernel_size=(3, 1), strides=(1, 1), padding='same', activation=None)(x) 210 | x = BatchNormalization()(x) 211 | x = ELU()(x) 212 | lvl5 = x 213 | 214 | x = MaxPooling2D(pool_size=(1, 20), padding='same')(lvl5) 215 | x = Conv2D(filters=4*n_filters, kernel_size=(3, 1), strides=(1, 1), padding='same', activation=None)(x) 216 | x = BatchNormalization()(x) 217 | x = ELU()(x) 218 | x = Dropout(rate=0.5)(x) 219 | x = Conv2D(filters=4*n_filters, kernel_size=(3, 1), strides=(1, 1), padding='same', activation=None)(x) 220 | x = BatchNormalization()(x) 221 | x = ELU()(x) 222 | x = Dropout(rate=0.5)(x) 223 | 224 | out5 = Conv2D(filters=1, kernel_size=(3, 1), strides=(1, 1), padding='same', activation='sigmoid')(x) 225 | out5 = Reshape(target_shape=(window_size//1024,))(out5) 226 | 227 | up4 = UpSampling2D(size=(4, 1))(x) 228 | att4 = AttentionPooling(filters=4*n_filters, channels=n_channels)([up4, lvl4]) 229 | 230 | out4 = Conv2D(filters=1, kernel_size=(3, 1), strides=(1, 1), padding='same', activation='sigmoid')(att4) 231 | out4 = Reshape(target_shape=(window_size//256,))(out4) 232 | 233 | x = Concatenate(axis=-1)([up4, att4]) 234 | x = Conv2D(filters=4*n_filters, kernel_size=(3, 1), strides=(1, 1), padding='same', activation=None)(x) 235 | x = BatchNormalization()(x) 236 | x = ELU()(x) 237 | 238 | up3 = UpSampling2D(size=(4, 1))(x) 239 | att3 = AttentionPooling(filters=4*n_filters, channels=n_channels)([up3, lvl3]) 240 | 241 | out3 = Conv2D(filters=1, kernel_size=(7, 1), strides=(1, 1), padding='same', activation='sigmoid')(att3) 242 | out3 = Reshape(target_shape=(window_size//64,))(out3) 243 | 244 | x = Concatenate(axis=-1)([up3, att3]) 245 | x = Conv2D(filters=4*n_filters, kernel_size=(7, 1), strides=(1, 1), padding='same', activation=None)(x) 246 | x = BatchNormalization()(x) 247 | x = ELU()(x) 248 | 249 | up2 = UpSampling2D(size=(4, 1))(x) 250 | att2 = AttentionPooling(filters=4*n_filters, channels=n_channels)([up2, lvl2]) 251 | 252 | out2 = Conv2D(filters=1, kernel_size=(15, 1), strides=(1, 1), padding='same', activation='sigmoid')(att2) 253 | out2 = Reshape(target_shape=(window_size//16,))(out2) 254 | 255 | x = Concatenate(axis=-1)([up2, att2]) 256 | x = Conv2D(filters=4*n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(x) 257 | x = BatchNormalization()(x) 258 | x = ELU()(x) 259 | 260 | 261 | up1 = UpSampling2D(size=(4, 1))(x) 262 | att1 = AttentionPooling(filters=4*n_filters, channels=n_channels)([up1, lvl1]) 263 | 264 | out1 = Conv2D(filters=1, kernel_size=(15, 1), strides=(1, 1), padding='same', activation='sigmoid')(att1) 265 | out1 = Reshape(target_shape=(window_size//4,))(out1) 266 | 267 | x = Concatenate(axis=-1)([up1, att1]) 268 | x = Conv2D(filters=4*n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(x) 269 | x = BatchNormalization()(x) 270 | x = ELU()(x) 271 | 272 | up0 = UpSampling2D(size=(4, 1))(x) 273 | att0 = AttentionPooling(filters=4*n_filters, channels=n_channels)([up0, lvl0]) 274 | x = Concatenate(axis=-1)([up0, att0]) 275 | x = Conv2D(filters=4*n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(x) 276 | x = BatchNormalization()(x) 277 | x = ELU()(x) 278 | x = Conv2D(filters=4*n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(x) 279 | x = BatchNormalization()(x) 280 | x = ELU()(x) 281 | x = Conv2D(filters=1, kernel_size=(15, 1), strides=(1, 1), padding='same', activation='sigmoid')(x) 282 | 283 | output = Reshape(target_shape=(window_size,))(x) 284 | 285 | unet = Model(input_seq, output) 286 | unet_train = Model(input_seq, [output, out1, out2, out3, out4, out5]) 287 | 288 | return unet, unet_train 289 | 290 | 291 | def build_windowfree_unet(n_channels=18, n_filters=8): 292 | input_seq = Input(shape=(None, n_channels, 1)) 293 | 294 | x = Conv2D(filters=n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(input_seq) 295 | x = BatchNormalization()(x) 296 | lvl0 = ELU()(x) 297 | 298 | x = MaxPooling2D(pool_size=(4, 1), padding='same')(lvl0) 299 | x = Conv2D(filters=2*n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(x) 300 | x = BatchNormalization()(x) 301 | lvl1 = ELU()(x) 302 | 303 | x = MaxPooling2D(pool_size=(4, 1), padding='same')(lvl1) 304 | x = Conv2D(filters=4*n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(x) 305 | x = BatchNormalization()(x) 306 | lvl2 = ELU()(x) 307 | 308 | x = MaxPooling2D(pool_size=(4, 1), padding='same')(lvl2) 309 | x = Conv2D(filters=4*n_filters, kernel_size=(7, 1), strides=(1, 1), padding='same', activation=None)(x) 310 | x = BatchNormalization()(x) 311 | lvl3 = ELU()(x) 312 | 313 | x = MaxPooling2D(pool_size=(4, 1), padding='same')(lvl3) 314 | x = Conv2D(filters=8*n_filters, kernel_size=(3, 1), strides=(1, 1), padding='same', activation=None)(x) 315 | x = BatchNormalization()(x) 316 | lvl4 = ELU()(x) 317 | 318 | x = MaxPooling2D(pool_size=(4, 1), padding='same')(lvl4) 319 | x = Conv2D(filters=8*n_filters, kernel_size=(3, 1), strides=(1, 1), padding='same', activation=None)(x) 320 | x = BatchNormalization()(x) 321 | x = ELU()(x) 322 | lvl5 = x 323 | 324 | x = MaxPooling2D(pool_size=(1, 20), padding='same')(lvl5) 325 | x = Conv2D(filters=4*n_filters, kernel_size=(3, 1), strides=(1, 1), padding='same', activation=None)(x) 326 | x = BatchNormalization()(x) 327 | x = ELU()(x) 328 | x = Dropout(rate=0.5)(x) 329 | x = Conv2D(filters=4*n_filters, kernel_size=(3, 1), strides=(1, 1), padding='same', activation=None)(x) 330 | x = BatchNormalization()(x) 331 | x = ELU()(x) 332 | x = Dropout(rate=0.5)(x) 333 | 334 | up4 = UpSampling2D(size=(4, 1))(x) 335 | att4 = AttentionPooling(filters=4*n_filters, channels=n_channels)([up4, lvl4]) 336 | 337 | x = Concatenate(axis=-1)([up4, att4]) 338 | x = Conv2D(filters=4*n_filters, kernel_size=(3, 1), strides=(1, 1), padding='same', activation=None)(x) 339 | x = BatchNormalization()(x) 340 | x = ELU()(x) 341 | 342 | up3 = UpSampling2D(size=(4, 1))(x) 343 | att3 = AttentionPooling(filters=4*n_filters, channels=n_channels)([up3, lvl3]) 344 | 345 | x = Concatenate(axis=-1)([up3, att3]) 346 | x = Conv2D(filters=4*n_filters, kernel_size=(7, 1), strides=(1, 1), padding='same', activation=None)(x) 347 | x = BatchNormalization()(x) 348 | x = ELU()(x) 349 | 350 | up2 = UpSampling2D(size=(4, 1))(x) 351 | att2 = AttentionPooling(filters=4*n_filters, channels=n_channels)([up2, lvl2]) 352 | 353 | x = Concatenate(axis=-1)([up2, att2]) 354 | x = Conv2D(filters=4*n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(x) 355 | x = BatchNormalization()(x) 356 | x = ELU()(x) 357 | 358 | 359 | up1 = UpSampling2D(size=(4, 1))(x) 360 | att1 = AttentionPooling(filters=4*n_filters, channels=n_channels)([up1, lvl1]) 361 | 362 | x = Concatenate(axis=-1)([up1, att1]) 363 | x = Conv2D(filters=4*n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(x) 364 | x = BatchNormalization()(x) 365 | x = ELU()(x) 366 | 367 | up0 = UpSampling2D(size=(4, 1))(x) 368 | att0 = AttentionPooling(filters=4*n_filters, channels=n_channels)([up0, lvl0]) 369 | x = Concatenate(axis=-1)([up0, att0]) 370 | x = Conv2D(filters=4*n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(x) 371 | x = BatchNormalization()(x) 372 | x = ELU()(x) 373 | x = Conv2D(filters=4*n_filters, kernel_size=(15, 1), strides=(1, 1), padding='same', activation=None)(x) 374 | x = BatchNormalization()(x) 375 | x = ELU()(x) 376 | output = Conv2D(filters=1, kernel_size=(15, 1), strides=(1, 1), padding='same', activation='sigmoid')(x) 377 | 378 | unet = Model(input_seq, output) 379 | 380 | return unet 381 | 382 | class SeizureState: 383 | def __init__(self, state): 384 | if state == 'seiz': 385 | self.state = 1 386 | elif state == 'bckg': 387 | self.state = 0 388 | else: 389 | raise ValueError('Invalid initial seizure state given') 390 | 391 | def print_state(self): 392 | if self.state: 393 | return 'seiz' 394 | else: 395 | return 'bckg' 396 | 397 | def change_state(self): 398 | self.state = (self.state+1)%2 -------------------------------------------------------------------------------- /training/4-train-lstm.py: -------------------------------------------------------------------------------- 1 | """ Train LSTM network 2 | LSTM network fuses output of U-nets 3 | 4 | This file relies on pre-computed predictions and uses them to train the LSTM. 5 | The model is saved in model-dnn-dnnw-dnnicalbl-lstm-4.h5 6 | """ 7 | 8 | import sys 9 | # Root folder of main library 10 | sys.path.insert(0, 'library') 11 | # Root folder of EDF files 12 | EDF_ROOT = '/esat/biomeddata/Neureka_challenge/edf/dev/' 13 | # Root folder of predictions on edf files 14 | PREDICTION_ROOT = 'evaluation' 15 | 16 | # custom library 17 | import nedc 18 | import spir 19 | 20 | # std lib 21 | import glob 22 | import os 23 | 24 | # 3rd party lib 25 | import h5py 26 | from keras.models import Sequential 27 | from keras.layers import Bidirectional, Dense, GRU, LSTM 28 | import numpy as np 29 | import resampy 30 | 31 | 32 | # + 33 | def load_filenames(): 34 | ''' 35 | 36 | 37 | Returns 38 | ------- 39 | filenames : list 40 | List of names of EEG recordings whose predictions are present in all views. ICLabel view excludes 41 | some files due to bad channels, hence has the lowest number 42 | of common files 43 | 44 | ''' 45 | filenames = list() 46 | with h5py.File(os.path.join(PREDICTION_ROOT, 'prediction_test_iclabel.h5'), 'r') as f: 47 | filenames = list(f['filenames']) 48 | return filenames 49 | 50 | 51 | def prepare_file(file_i, filename, classifiers, f_unet, model_type, fs): 52 | ''' 53 | 54 | 55 | Parameters 56 | ---------- 57 | file_i : TYPE 58 | Index of predictions belonging to a file. 59 | filename : TYPE 60 | Unique name of the EEG recording. 61 | classifiers : TYPE 62 | The set of multi-view U-Net classifiers. 63 | f_unet : TYPE 64 | File pointer to h5 dataset containing the U-Net predictions. 65 | model_type : TYPE 66 | The ype of RNN to be trained. 'lstm' or 'gru' currently supported 67 | fs : TYPE 68 | Frequency of predictions of the output model. 69 | 70 | Returns 71 | ------- 72 | x : numpy array 73 | Array of U-Net predictions; training data for RNN 74 | y : numpy array 75 | Array of labels; training labels for the RNN. 76 | 77 | ''' 78 | # Load data 79 | x = list() 80 | for classifier in classifiers: 81 | if classifier['format'] == 'unet': 82 | z = list(f_unet[classifier['name']]['filenames']) 83 | file_i = z.index(filename) 84 | predictions = f_unet[classifier['name']]['signals'][file_i] 85 | predictions = downsample(predictions, 200, fs) 86 | x.append(np.array(predictions, dtype=float)) 87 | 88 | x = np.array(x) 89 | x = np.transpose(x) 90 | if model_type == 'lstm' or model_type == 'gru': 91 | x = x.reshape((len(x), 1, len(x[0]))) 92 | # Collect the true lables 93 | seizures = nedc.loadTSE(os.path.join(EDF_ROOT,filename[:-4]+'.tse')) 94 | 95 | # Create labels at fs sampling rate 96 | y = spir.eventList2Mask(seizures, len(x), fs) 97 | 98 | return x,y 99 | 100 | 101 | class AvgModel: 102 | def fit(*argv, **kwargs): 103 | return 0 104 | 105 | def reset_states(*argv, **kwargs): 106 | return 0 107 | 108 | def predict(x, *argv, **kwargs): 109 | if np.ndim(x) > 1: 110 | return np.mean(x, axis=1) 111 | else: 112 | return x 113 | 114 | 115 | def downsample(x, oldFs, newFs): 116 | ''' 117 | 118 | 119 | Parameters 120 | ---------- 121 | x : numpy array 122 | Data to be downsampled. 123 | oldFs : int 124 | Sampling rate (Hz) of data. 125 | newFs : TYPE 126 | Target sampling rate (Hz). 127 | 128 | Returns 129 | ------- 130 | numpy array 131 | Downsampled data to newFs. 132 | 133 | ''' 134 | return resampy.resample(x, oldFs, newFs) 135 | 136 | 137 | def findTse(filename): 138 | ''' 139 | 140 | 141 | Parameters 142 | ---------- 143 | filename : string 144 | Unique name of the EEG recording. 145 | 146 | Returns 147 | ------- 148 | string 149 | Unique name/path of the seizure annotation of the EEG recording. 150 | 151 | ''' 152 | result = glob.glob(os.path.join(EDF_ROOT, '*', filename[3:6], filename.split('_')[0], filename.split('_')[1] + '_' + '[0-9_]*', filename + '.tse')) 153 | return result[0] 154 | 155 | 156 | def build_model(n_input, model_type, complexity=None): 157 | ''' 158 | 159 | 160 | Parameters 161 | ---------- 162 | n_input : TYPE 163 | DESCRIPTION. 164 | model_type : str 165 | Type of final output layer. Currently supported: 166 | 'lstm' - An LSTM RNN 167 | 'gru' - GRU based RNN 168 | 'dense' - A dense neural-network layer 169 | 'avg' - A simple average of multi-view U-Net predictions 170 | complexity : int, optional 171 | Complexity of RNNs. Required for model_type 'lstm' and 'gru' 172 | The default is None. 173 | 174 | Returns 175 | ------- 176 | model : TYPE 177 | DESCRIPTION. 178 | 179 | ''' 180 | if model_type == 'lstm': 181 | model = Sequential() 182 | model.add(Bidirectional(LSTM(complexity, stateful=True, return_sequences=False), 183 | input_shape=(1, n_input), batch_size=1)) 184 | model.add(Dense(1, activation='sigmoid')) 185 | model.compile(loss='mse', optimizer='adam') 186 | elif model_type == 'gru': 187 | model = Sequential() 188 | model.add(Bidirectional(GRU(complexity, stateful=True, return_sequences=False), 189 | input_shape=(1, n_input), batch_size=1)) 190 | model.add(Dense(1, activation='sigmoid')) 191 | model.compile(loss='mse', optimizer='adam') 192 | elif model_type == 'dense': 193 | model = Sequential() 194 | model.add(Dense(1, activation='sigmoid', input_shape=(n_input, ), batch_size=1)) 195 | model.compile(loss='mse', optimizer='adam') 196 | elif model_type == 'avg': 197 | model = AvgModel 198 | return model 199 | 200 | 201 | def train(model, model_type, classifiers, filenames, fs=1): 202 | ''' 203 | 204 | 205 | Parameters 206 | ---------- 207 | model : TYPE 208 | DESCRIPTION. 209 | model_type : str 210 | Type of final output layer. Currently supported: 211 | 'lstm' - An LSTM RNN 212 | 'gru' - GRU based RNN 213 | 'dense' - A dense neural-network layer 214 | 'avg' - A simple average of multi-view U-Net predictions 215 | classifiers : list (of dicts) 216 | Defined in main. 217 | filenames : list 218 | List of names of EEG recordings whose predictions are present in all views.. 219 | fs : int, optional 220 | Frequency of predictions. The default is 1 Hz. 221 | 222 | Returns 223 | ------- 224 | int 225 | DESCRIPTION. 226 | 227 | ''' 228 | if model_type == 'avg': 229 | return 0 230 | 231 | # Preload U-Net data 232 | f_unet = dict() 233 | for classifier in classifiers: 234 | if classifier['format'] == 'unet': 235 | f_unet[classifier['name']] = h5py.File(classifier['file'], 'r') 236 | 237 | # Train 238 | for i, filename in enumerate(filenames): 239 | x, y = prepare_file(i, filename, classifiers, f_unet, model_type, fs) 240 | if np.any(y): 241 | model.fit(x, y, batch_size=1, epochs=15, verbose=1) 242 | else: 243 | model.fit(x, y, batch_size=1, epochs=1, verbose=1) 244 | model.reset_states() 245 | 246 | # Close U-Net data 247 | for key in f_unet: 248 | f_unet[key].close() 249 | 250 | 251 | # + 252 | fs = 1 # LSTM prediction sampling frequency 253 | 254 | classifiers = [{ 255 | 'name': 'ICA', 256 | 'file': os.join(PREDICTION_ROOT, 'prediction_test_iclabel.h5'), 257 | 'fs': 200, 258 | 'format': 'unet', 259 | }, 260 | { 261 | 'name': 'DNN', 262 | 'file': os.join(PREDICTION_ROOT, 'prediction_test_raw.h5'), 263 | 'fs': 200, 264 | 'format': 'unet', 265 | }, 266 | { 267 | 'name': 'DNN-wiener', 268 | 'file': os.join(PREDICTION_ROOT, 'prediction_test_wiener.h5'), 269 | 'fs': 200, 270 | 'format': 'unet', 271 | } 272 | ] 273 | 274 | modeltype = 'lstm' 275 | complexity = 4 276 | 277 | filenames = load_filenames() 278 | model = build_model(len(classifiers), modeltype, complexity) 279 | train(model, modeltype, classifiers, filenames, fs) 280 | model.save('model-dnn-dnnw-dnnicalbl-lstm-4.h5') 281 | -------------------------------------------------------------------------------- /training/README.md: -------------------------------------------------------------------------------- 1 | # Training pipeline 2 | 3 | The seizure detection pipeline is trained in several independent steps: 4 | 5 | 1. Train and build the Wiener filters. 6 | 2. Remove artifcats with ICLabel 7 | 3. Train U-nets 8 | 4. Train LSTM 9 | 10 | 11 | ## 1. Wiener pre-processing 12 | 13 | Wiener pre-processing builds a filter bank of spatio-temporal filters based on artifacts identified in the training set. 14 | 15 | 1. A set of high power non-seizure epochs are identified 16 | 2. PCA compressed spatio-temporal covariance matrices are used to represent the artifacts 17 | 3. K-means clustering is used to group the artifacts 18 | 4. The average representation of the groups is used to pre-compute a spatio-temporal wiener filter 19 | 20 | ## 2. ICLabel pre-processing 21 | 22 | ICLabel pre-processing rejects any ``bad-channels'' and then removes any components of the signal which are clustered as artifacts. 23 | 24 | 1. High pass filtering of the data 25 | 2. Rejection of any bad channels (flat channels for above 20 seconds, channels with high SNR and channels with very low correlation to their estimation based on the rest of the channels) 26 | 3. Computation of the Independent Components using SOBI ICA. 27 | 4. Classification of the components using the ICLabel package of EEGlab 28 | 5. Rejection of all the components with a correlation higher than 0.6 to the following clusters: Muscle, Eye, Heart, Line Noise, Channel Noise 29 | 30 | ## 3. Train U-net 31 | 32 | A separate U-net is trained and stored for each available "view" on the data. 33 | 34 | ## 4. Train LSTM 35 | Fusion of the different U-Net DNN results is done using a shallow recurrent neural network. 36 | 37 | The recurrent NN is built using two layers: 38 | 39 | 1. A bidirectional LSTM layer with a state vector of length 4 40 | 2. A dense layer combining the the outputs of the LSTM layer 41 | --------------------------------------------------------------------------------