├── .gitignore ├── LICENSE ├── PTB3_examples └── photocells.m ├── README.md ├── extra ├── small_cidlab_logo.png └── small_hnl_logo.png └── nunez_etal2017_mathpsych ├── EEG_R └── svderp.R ├── ewmav2.m ├── jagsins.mat ├── model1.jags ├── model2.jags ├── model3.jags ├── paper_figures └── pdm3b_trialsortplot.m ├── pdm3b_demo.m ├── pdm3b_model1.m ├── pdm3b_model2.m ├── pdm3b_model3.m └── visual_stimuli ├── makebardirec.m └── pdmexp3_public.m /.gitignore: -------------------------------------------------------------------------------- 1 | #Ignore Temporary files 2 | *~ 3 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /PTB3_examples/photocells.m: -------------------------------------------------------------------------------- 1 | function photocells 2 | %% README 3 | 4 | %THIS PROGRAM WILL NOT WORK WITHOUT SPECIFIC CHANGES FOR YOUR SOFTWARE AND HARDWARE 5 | 6 | %This program serves as examples of steady-state visual evoked 7 | %potential (SSVEP) stimuli. See the two papers for a description of example 8 | %experimental paradigms 9 | % 10 | %In order to replicate this experimental stimulus, you will need to run 11 | %Psychtoolbox 3 on Linux with a good video card, and then test 12 | %the frequency of the "photocell" squares in each corner of the screen to 13 | %ensure the intended frequencies of the flickering stimuli and thus possible SSVEP 14 | %responses (SSVEPs could also depend upon subject behavior, brain state, 15 | %contrast, luminance, etc. and must be tested with preliminary studies) 16 | 17 | %% Possible Citations 18 | % Nunez, M. D., Srinivasan, R., & Vandekerckhove, J. (2015). Individual differences in attention influence perceptual decision making. Frontiers in psychology, 8. 19 | % Nunez, M. D., Vandekerckhove, J., & Srinivasan, R. (2017) How attention influences perceptual decision making: Single-trial EEG correlates of drift-diffusion model parameters. Journal of Mathematical Psychology, 76, 117-130. 20 | 21 | %% Copyright 2016 Michael D. Nunez 22 | 23 | %This program is free software: you can redistribute it and/or modify 24 | % it under the terms of the GNU General Public License as published by 25 | % the Free Software Foundation, either version 3 of the License, or 26 | % (at your option) any later version. 27 | % 28 | % This program is distributed in the hope that it will be useful, 29 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 30 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 31 | % GNU General Public License for more details. 32 | % 33 | % You should have received a copy of the GNU General Public License 34 | % along with this program. If not, see . 35 | % 36 | %% Record of revisions: 37 | % Date Programmers Description of change 38 | % ==== ================= ===================== 39 | % 03/09/2016 Michael Nunez Original code 40 | 41 | %% Initial Code 42 | 43 | PsychJavaTrouble; 44 | 45 | AssertOpenGL; %Issue warning if PTB3 with non-openGL used 46 | 47 | if ~IsLinux 48 | error('This program was written to run on Ubuntu Linux.'); 49 | end 50 | 51 | %% Experimenter Prompt 52 | 53 | %Inputs Prompt and Output Setup 54 | %Experimenter Prompt 55 | Screenres = get(0,'Screensize'); 56 | 57 | prompt1={'Window Pointer:',... 58 | 'Screen Length (x-axis):','Screen Width (y-axis):','Refresh Rate (fps):',... 59 | 'Flicker1 Freq (Hz):','Flicker2 Freq (Hz):','Number of Trials:'}; 60 | def1={'0',num2str(Screenres(3)),num2str(Screenres(4)),'120','40','30','10'}; 61 | studytitle='Photocell Test'; 62 | 63 | 64 | lineNo=1; 65 | answer=inputdlg(prompt1,studytitle,lineNo,def1); 66 | 67 | %Window Pointer / 'Home Screen'. 0 - the primary monitor; 1 - the secondary monitor. 68 | whichScreen = str2num(answer{1}); 69 | %Screen resolution on the x-axis 70 | xres = str2num(answer{2}); 71 | 72 | %Screen resolution on the y-axis 73 | yres = str2num(answer{3}); 74 | 75 | %This should be the same as the Refresh Rate shown in the Display 76 | %Properties on the computer. Always check before running the experiment to 77 | %match flicker frequency. 78 | %This code is currently set up to only handle multiples of 60 fps. 79 | refrate = str2num(answer{4}); 80 | realrefrate = Screen(0,'FrameRate'); 81 | if refrate ~= Screen(0,'FrameRate') 82 | error(['The real screen refresh rate is set to ',num2str(realrefrate),... 83 | 'Hz while the proposed screen refresh rate is ',num2str(refrate),'Hz.']); 84 | end 85 | 86 | %Flicker1 frequency (Hz) 87 | noisehz = str2num(answer{5}); 88 | 89 | 90 | %Flicker2 frequency (Hz) 91 | flickerhz = str2num(answer{6}); 92 | 93 | %Number of Trials 94 | trialnum = str2num(answer{7}); 95 | 96 | %% Code 97 | 98 | 99 | %Colors 100 | txtcolor = round([0 .6 .6]*255); %Teal 101 | black = [0 0 0]; 102 | white = [255 255 255]; 103 | gray = 255*sqrt([.5 .5 .5]); 104 | blackwhite{1} = black; 105 | blackwhite{2} = white; 106 | 107 | % Load fonts 108 | myfont = '-bitstream-courier 14 pitch-bold-i-normal--0-0-0-0-m-0-ascii-0'; 109 | fontsize = 26; 110 | 111 | %Define photocell placement 112 | k = 0; 113 | photorect = [0 0 100 90]; 114 | for m = 1:6 115 | pRect(m,:) = CenterRectOnPoint(photorect,50,50+k); 116 | k = k + 160; 117 | end 118 | 119 | 120 | %The following TRY, CATCH, END statement ends psychtoolbox if an error occurs 121 | try 122 | %Open a fullscreen window on the first screen with black background 123 | PsychImaging('PrepareConfiguration'); 124 | PsychImaging('AddTask', 'General', 'UseVirtualFramebuffer'); 125 | [wptr,windowRect] = PsychImaging('OpenWindow', whichScreen,gray); 126 | PsychGPUControl('FullScreenWindowDisablesCompositor', 1); 127 | 128 | %This vector defines the Flicker 1 frequency for our image 129 | noiseflic = []; 130 | for i=1:ceil(4*noisehz) 131 | noiseflic = [noiseflic 1 zeros(1,(round(refrate/noisehz)- 1))]; 132 | end 133 | 134 | %This vector defines the Flicker 2 frequency for our image 135 | gaborflic = []; 136 | for i=1:ceil(4*flickerhz) 137 | gaborflic = [gaborflic 2*ones(1,round(refrate/2/flickerhz)) ones(1,round(refrate/2/flickerhz))]; 138 | end 139 | 140 | %Inter-trial interval, 1500ms to 2000ms 141 | intertrial = 1.5 + rand(1,trialnum)*.5; 142 | 143 | %Calculate the number of frames in a cycle of an image flicker 144 | numCycleFrames = ceil(refrate*1.2) + ceil(refrate*rand(1,trialnum)*.8); 145 | 146 | Screen('TextFont',wptr,'Arial'); 147 | Screen('TextSize',wptr,18); 148 | ShowCursor(0); % arrow cursor 149 | sessiontext = 'Spacebar to continue'; 150 | 151 | HideCursor; 152 | Screen('TextSize', wptr, fontsize); 153 | Screen('TextFont', wptr, myfont); 154 | Screen('DrawText',wptr, sessiontext,(xres - length(sessiontext)*9)/2,yres*(5/12),txtcolor); 155 | Screen(wptr,'FillRect',black,pRect'); 156 | Screen('Flip',wptr); 157 | 158 | 159 | %Wait for spacebar 160 | FlushEvents('keyDown'); 161 | [char,when] = GetChar; %Wait for keypress to continue 162 | notspace=1; 163 | while notspace 164 | switch char 165 | case ' ' 166 | notspace =0; 167 | otherwise 168 | [char,when] = GetChar; %Wait for keypress to continue 169 | notspace =1; 170 | end 171 | end 172 | 173 | %Initialize timer 174 | tic; 175 | for trials = 1:trialnum 176 | 177 | %Display rush loops (Rush is apparently obsolete in PTB3, test this) 178 | Priority(MaxPriority(wptr)); %New to PTB3 179 | 180 | %Loop: Flicker 1 in photocells 1 and 5 from top 181 | %Flicker 2 in photocells 2 and 6 from top 182 | %Photocells 3 and 4 give one impulse for the beginning of a trial 183 | noisenum = 0; 184 | bwswitch = 1; 185 | for i = 1:numCycleFrames(trials) 186 | if noiseflic(i) 187 | noisenum = noisenum + 1; 188 | bwswitch = mod(bwswitch,2) + 1; %Changes 1 to 2 and vica versa 189 | end 190 | if i == 1 191 | Screen(wptr,'FillRect',white,pRect([3 4],:)'); 192 | else 193 | Screen(wptr,'FillRect',black,pRect([3 4],:)'); 194 | end 195 | Screen(wptr,'FillRect',blackwhite{bwswitch},pRect([1 5],:)'); 196 | Screen(wptr,'FillRect',blackwhite{gaborflic(i)},pRect([2 6],:)'); 197 | Screen('Flip',wptr); 198 | end 199 | 200 | %Change all photocells to black after the trial has ended 201 | Screen(wptr,'FillRect',black,pRect'); 202 | Screen('Flip',wptr); 203 | 204 | pause(intertrial(trials)); 205 | end 206 | 207 | catch me 208 | ShowCursor; 209 | Screen('CloseAll'); 210 | rethrow(me); %rethrow reproduces the original error, stored in the object 'me' 211 | end 212 | 213 | ShowCursor; 214 | Screen('CloseAll'); 215 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ### Citation 4 | 5 | Nunez, M. D., Vandekerckhove, J., & Srinivasan, R. (2017). 6 | [How attention influences perceptual decision making: Single-trial EEG correlates of drift-diffusion model parameters.](https://sci-hub.st/https://www.sciencedirect.com/science/article/abs/pii/S0022249616000316) 7 | Journal of Mathematical Psychology, 76, 117-130. 8 | 9 | [Preprint](https://www.researchgate.net/publication/298275031_How_attention_influences_perceptual_decision_making_Single-trial_EEG_correlates_of_drift-diffusion_model_parameters) 10 | 11 | [Elsevier source](https://www.sciencedirect.com/science/article/abs/pii/S0022249616000316) 12 | 13 | # mcntoolbox 14 | #### (Repository version 0.3.4) 15 | The Mathematical Cognitive Neuroscience Toolbox (mcntoolbox). 16 | 17 | **Authors: Michael D. Nunez, Joachim Vandekerckhove, and Ramesh Srinivasan from the Cognitive Sciences Department at the University of California, Irvine** 18 | 19 | ### Description 20 | 21 | Mcntoolbox provides users interested in EEG and quick decision making a set of example scripts for steady-state visual evoked potential (SSVEP) stimulus generation and integrated drift-diffusion model fitting with EEG using MATLAB. All example scripts are written in MATLAB. One R script is included as an example of single-trial ERP estimation. 22 | 23 | Please see the repository [pyhddmjags](https://github.com/mdnunez/pyhddmjags) for cleaner implementations using Python. 24 | 25 | ### Data 26 | 27 | The shortcut to the pre-calculated EEG measures and raw behavioral data presented in Nunez et al. (2017) JMP paper is [here](https://github.com/mdnunez/mcntoolbox/raw/master/nunez_etal2017_mathpsych/jagsins.mat). 28 | 29 | ### Prerequisites 30 | 31 | [MATLAB](https://www.mathworks.com/) 32 | 33 | [MCMC Sampling Program: JAGS](http://mcmc-jags.sourceforge.net/) 34 | 35 | [Program: JAGS Wiener module](https://sourceforge.net/projects/jags-wiener/) 36 | 37 | [MATLAB Repository Trinity for calling JAGS from MATLAB](https://github.com/joachimvandekerckhove/trinity) 38 | 39 | ### Possible prerequisites 40 | 41 | [DMAT](https://ppw.kuleuven.be/okp/software/dmat/) ( Now unnecessary but was previously necessary for the exponential moving average function ewmav2() in previous versions ) 42 | 43 | [R](https://www.r-project.org/) (for single-trial ERP estimation) 44 | 45 | ### License 46 | 47 | mcntoolbox is licensed under the GNU General Public License v3.0 and written by Michael D. Nunez, Joachim Vandekerckhove, and Ramesh Srinivasan from the Cognitive Sciences Department at the University of California, Irvine. 48 | 49 | ### Further Reading 50 | 51 | Nunez, M. D., Gosai, A., Vandekerckhove, J., & Srinivasan, R. (2019). 52 | [The latency of a visual evoked potential tracks the onset of decision making.](https://sci-hub.st/https://www.sciencedirect.com/science/article/pii/S1053811919303386) NeuroImage. doi: 10.1016/j.neuroimage.2019.04.052 53 | 54 | Lui, K. K., Nunez, M. D., Cassidy, J. M., Vandekerckhove, J., Cramer, S. C., & Srinivasan, R. (2020). 55 | [Timing of readiness potentials reflect a decision-making process in the human brain.](https://sci-hub.st/https://link.springer.com/article/10.1007/s42113-020-00097-5) Computational Brain & Behavior. 56 | 57 | Nunez, M. D., Srinivasan, R., & Vandekerckhove, J. (2015). 58 | [Individual differences in attention influence perceptual decision making.](https://www.frontiersin.org/articles/10.3389/fpsyg.2015.00018/full) 59 | Frontiers in Psychology, 8. 60 | -------------------------------------------------------------------------------- /extra/small_cidlab_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdnunez/mcntoolbox/6471f712dd7710ccb0505dbbd74c2db69c7267ce/extra/small_cidlab_logo.png -------------------------------------------------------------------------------- /extra/small_hnl_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdnunez/mcntoolbox/6471f712dd7710ccb0505dbbd74c2db69c7267ce/extra/small_hnl_logo.png -------------------------------------------------------------------------------- /nunez_etal2017_mathpsych/EEG_R/svderp.R: -------------------------------------------------------------------------------- 1 | ## svderp.R provides an example of how to use singular value decomposition (SVD) to find single-trial event-related potentials (ERPs) 2 | 3 | ##Embedded in the script is a simple function to compute single-trial ERPs in R 4 | 5 | ## Citation: 6 | # Nunez, M. D., Vandekerckhove, J., & Srinivasan, R. (2017) How attention influences perceptual decision making: Single-trial EEG correlates of drift-diffusion model parameters. Journal of Mathematical Psychology, 76, 117-130. 7 | 8 | ## Copyright 2015 Michael D. Nunez 9 | 10 | #This program is free software: you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation, either version 3 of the License, or 13 | # (at your option) any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program. If not, see . 22 | 23 | ###Record of Revisions### 24 | # Date Authors Description of change 25 | # ==== ================= ===================== 26 | # 12/11/15 Michael D. Nunez Original Code 27 | 28 | ####### 29 | ###This function calculates single trial ERPs using the SVD method### 30 | svderp <- function(eeg,trialmarks,trialsamps,baseline=NULL,comp=1) { 31 | #eeg is a vector that marks the point of reference of each trial 32 | #trialsamps + trialmarks[i] gives the indices of specific trials 33 | #baseline + trialmarks[i] are the indices for baselining each trial 34 | #comp is the component number to compute, comp = 1 will have the highest percent of variance explained 35 | 36 | ntrials <- length(trialmarks) 37 | eegsum <- array(data=0,dim=c(length(trialsamps),dim(eeg)[2])) 38 | 39 | #Calculate ERP 40 | if(is.null(baseline)) { 41 | #No baseline 42 | for (i in 1:ntrials) { 43 | eegsum <- eegsum + eeg[trialmarks[i] + trialsamps,] 44 | } 45 | } else { 46 | #Baseline 47 | for (i in 1:ntrials) { 48 | baseline <- t(as.array(apply(eeg[trialmarks[i] + trialsamps,],2,mean))) 49 | eegsum <- eegsum + eeg[trialmarks[i] + trialsamps,] - baseline[rep(1,length(trialsamps)),] 50 | } 51 | } 52 | 53 | erp <- eegsum/ntrials #The ERP is the mean of EEG across trials, time-locked to specific events 54 | 55 | #SVD of ERP (equivalent to PCA) 56 | svdouts <- svd(erp) 57 | 58 | #Percent of variance explained by each principal component 59 | perexp = (svdouts$d^2)/sum(svdouts$d^2); 60 | 61 | #nchan*1 weights for each electrode is just the right singular vector for the specific component 62 | #Note that the weight vector's sign is arbitrary, it may have to be changed to reflect the ERP 63 | weights <- svdouts$v[,comp] 64 | 65 | 66 | #Single-trial ERPs 67 | sterp = eeg %*% weights 68 | 69 | #Use trialmarks to find single-trial ERPs in svderp$sterp via svderp$sterp[trialmarks(i) + trialsamps,] 70 | 71 | #Return ERP, percent of variance explained by component comp, nchan*1 weight vector, and single-trial erps 72 | outs <- list("erp" = erp, "pexp" = perexp, "w"=weights,"sterp" = sterp) 73 | return(outs) 74 | 75 | } 76 | ####### 77 | 78 | ##The following code simulates EEG data with an embedded response to external stimuli and compares the raw EEG at one channel with a high signal-to-noise ratio to the single-trial ERP 79 | 80 | set.seed(380) 81 | 82 | ntrials <- 100 83 | nchans <- 128 84 | triallen <- 1000 85 | 86 | trialt <- 1:triallen 87 | 88 | #Simulated ERP 89 | trueerp <- 1000*sin(trialt*2*pi*(4/triallen))*dnorm(trialt,mean=triallen/5,sd=triallen*.15)-sin(trialt*2*pi*(1/triallen)) 90 | 91 | #Simulated EEG 92 | eeg <- array(dim = c(triallen*ntrials,nchans)) 93 | 94 | chanweights <- rep(0,1,nchans) 95 | chanweights[21:30] <- -c(rep(5,5),rep(10,5)) 96 | chanweights[81:90] <- c(rep(5,5),rep(10,5)) 97 | 98 | for (k in 1:ntrials) { 99 | for (c in 1:nchans) { 100 | eeg[(1:triallen)+(k-1)*triallen,c] <- trueerp*chanweights[c] + rnorm(triallen,sd = 30) 101 | } 102 | } 103 | 104 | trialmarks <- seq(1,triallen*ntrials,triallen) #This vector marks the point of reference of each trial 105 | trialsamps <- 0:(triallen-1) #This vector + trialmarks[i] gives the indices of specific trials 106 | 107 | svdouts <- svderp(eeg,trialmarks,trialsamps,comp=1) #Compute the single-trial ERP 108 | 109 | 110 | ####Plots 111 | par(mfrow=c(3,1)) 112 | #Plots the first trial of EEG of one of the best electrodes for the stimulus response 113 | plot(1:triallen,eeg[1:triallen,90],'l',xlab='',ylab=expression(paste(mu,"V")),main = '1st Trial and Best Channel of Raw EEG',cex.lab=2,cex.axis=2,cex.main=2,cex.sub=2) 114 | #Plots the ERP at one of the best electrodes 115 | plot(1:triallen,svdouts$erp[,90],'l',xlab='',ylab=expression(paste(mu,"V")),main = 'Best Channel of ERP',cex.lab=2,cex.axis=2,cex.main=2,cex.sub=2) 116 | #Plots the first trial of the single-trial ERP 117 | plot(1:triallen,svdouts$sterp[1:triallen,],'l',xlab='Time Post-Stimulus (ms)',ylab=expression(paste(mu,"V")),main = '1st Trial of Single-trial ERP',cex.lab=2,cex.axis=2,cex.main=2,cex.sub=2) 118 | 119 | -------------------------------------------------------------------------------- /nunez_etal2017_mathpsych/ewmav2.m: -------------------------------------------------------------------------------- 1 | function [cutoff,dmatewmaplot]=ewmav2(data,L,l,s) 2 | % EWMAV2 Determine RT cut-off with the EWMA method 3 | % [CUTOFF, DMATEWMAPLOT] = EWMAV2(DATA,LIMITS,LAMBDA,SIGMA), where DATA 4 | % is a regular N-by-3 data matrix, and LIMITS, LAMBDA, and SIGMA are 5 | % parameters for the Exponentially Weighted Moving Average algorithm as 6 | % described in the DMAT Manual. 7 | % CUTOFF is the cut-off value below which RT values are censored. 8 | % DMATEWMAPLOT is a structure that can be used as input for PLOTEWMA. 9 | % 10 | % See also PLOTEWMA, OUTLIERTREATMENT. 11 | % 12 | % Author: Joachim Vandekerckhove (joachim.vandekerckhove@psy.kuleuven.be) 13 | % Part of the DMA Toolbox. Please read the End User License Agreement, 14 | % contained in 'dmateula.txt' or by invoking the DMATLICENSE command. 15 | % See also http://ppw.kuleuven.be/okp/dmatoolbox. 16 | 17 | % Note: If you like one-liners, sort the data into XX. Then, 18 | % cutoff=T(find(diff(filter(l,[1 (l-1)],XX,(1-l)/2)'<.5+L*s*... 19 | % sqrt(l/(2-l)*(1-(1-l).^(2*(1:size(XX,1))))))==-1,1,'first')); 20 | % jv 21 | 22 | % %% Check input 23 | % if ~isvaliddataset(data,3) && ~isvaliddataset(data,2) 24 | % error('DMAT:ewmav2:invalidDataSet',... 25 | % 'Data set is not valid Nx3 data matrix.') 26 | % end 27 | % if ~isscalar(l) 28 | % error('DMAT:ewmav2:incorrectInput','''Lambda'' should be a scalar.') 29 | % end 30 | % if ~isscalar(L) 31 | % error('DMAT:ewmav2:incorrectInput','''Limits'' should be a scalar.') 32 | % end 33 | % if ~isscalar(s) 34 | % error('DMAT:ewmav2:incorrectInput','''Sigma'' should be a scalar.') 35 | % end 36 | 37 | %% Sort data 38 | [T,I]=sort(data(:,end)); 39 | X=data(I,end-1); 40 | 41 | %% Define constants 42 | cutoff=0; 43 | 44 | %% Apply EWMA filter 45 | ucl=.5+L*s*sqrt(l/(2-l)*(1-(1-l).^(2*(1:size(X,1))))); 46 | lcl=.5-L*s*sqrt(l/(2-l)*(1-(1-l).^(2*(1:size(X,1))))); 47 | z=filter(l,[1 (l-1)],X,(1-l)/2)'; 48 | vv=find(diff(zcutoff)],... 62 | 'BlueY',[ucl(vv) z(T>cutoff)],... 63 | 'RedX',[T(T. 20 | 21 | model { 22 | # No effect on b (bias between responses) 23 | # b <- .5 24 | # Boundary separation kept constant 25 | # a <- 1 26 | 27 | # Effect on T_er (preprocessing /nondecision time) 28 | # Varies by subject 29 | tsd ~ dgamma(5, 20) 30 | ttau <- pow(tsd, -2) 31 | for (c2 in 1:3) { 32 | tmu[c2] ~ dnorm(.3, 1)T(0,3) 33 | for (sub in 1:nsubs) { 34 | t[c2,sub] ~ dnorm(tmu[c2], ttau) 35 | } 36 | } 37 | 38 | # Effect on s (diffusion coefficient) 39 | # Varies by subject 40 | ssd ~ dgamma(5, 20) 41 | stau <- pow(ssd, -2) 42 | for (c2 in 1:3) { 43 | smu[c2] ~ dnorm(.6, 1/4)T(0,4) 44 | for (sub in 1:nsubs) { 45 | s[c2,sub] ~ dnorm(smu[c2], stau) 46 | } 47 | } 48 | 49 | # Effect on v (drift rate) 50 | # Varies by subject 51 | vsd ~ dgamma(5, 5) 52 | vtau <- pow(vsd, -2) 53 | for (c2 in 1:3) { 54 | vmu[c2] ~ dnorm(1.5, 1/16)T(-9,9) 55 | for (sub in 1:nsubs) { 56 | v[c2,sub] ~ dnorm(vmu[c2], vtau) 57 | } 58 | } 59 | 60 | # Likelihood 61 | for (i in 1:n) 62 | { 63 | 64 | y[i] ~ dwiener(1/s[noise[i],subject[i]], t[noise[i],subject[i]], 0.5, v[noise[i],subject[i]]/s[noise[i],subject[i]]) 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /nunez_etal2017_mathpsych/model2.jags: -------------------------------------------------------------------------------- 1 | ## Citation 2 | # Nunez, M. D., Vandekerckhove, J., & Srinivasan, R. 3 | # How attention influences perceptual decision making: Single-trial EEG correlates of drift-diffusion model parameters. 4 | # Journal of Mathematical Psychology, 76, 117-130. (2017). 5 | 6 | ## Copyright 2015 Michael D. Nunez 7 | 8 | #This program is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU General Public License as published by 10 | # the Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program. If not, see . 20 | 21 | model { 22 | # No effect on b (bias between responses) 23 | # b <- .5 24 | # Boundary separation kept constant 25 | # a <- 1 26 | 27 | # 1 unit increase of eegfield{f} is associated with this additive effect on t 28 | for (f in 1:4) { 29 | tbetasd[f] ~ dgamma(5, .2) 30 | tbetatau[f] <- pow(tbetasd[f], -2) 31 | for (c2 in 1:3) { 32 | tbetamu[c2,f] ~ dnorm(0,.0001) 33 | for (sub in 1:nsubs) { 34 | tbeta[c2,sub,f] ~ dnorm(tbetamu[c2,f],tbetatau[f]) 35 | } 36 | } 37 | } 38 | 39 | # Effect on Ter (non-decision time) 40 | # Varies by subject 41 | tsd ~ dgamma(5, .2) 42 | ttau <- pow(tsd, -2) 43 | for (c2 in 1:3) { 44 | tmu[c2] ~ dnorm(0,.0001) 45 | for (sub in 1:nsubs) { 46 | talpha[c2,sub] ~ dnorm(tmu[c2], ttau) 47 | } 48 | } 49 | 50 | # Effect on s (diffusion coefficient) 51 | # Varies by subject 52 | ssd ~ dgamma(5, 20) 53 | stau <- pow(ssd, -2) 54 | for (c2 in 1:3) { 55 | smu[c2] ~ dnorm(.6, 1/4)T(0,4) 56 | for (sub in 1:nsubs) { 57 | s[c2,sub] ~ dnorm(smu[c2], stau) 58 | } 59 | } 60 | 61 | # 1 unit increase of eegfield{f} is associated with this additive effect on v 62 | for (f in 1:4) { 63 | vbetasd[f] ~ dgamma(5, .2) 64 | vbetatau[f] <- pow(vbetasd[f], -2) 65 | for (c2 in 1:3) { 66 | vbetamu[c2,f] ~ dnorm(0,.0001) 67 | for (sub in 1:nsubs) { 68 | vbeta[c2,sub,f] ~ dnorm(vbetamu[c2,f],vbetatau[f]) 69 | } 70 | } 71 | } 72 | 73 | # Effect on v (diffusion process between trials) 74 | # Varies by condition and subject 75 | vsd ~ dgamma(5, .2) 76 | vtau <- pow(vsd, -2) 77 | for (c2 in 1:3) { 78 | vmu[c2] ~ dnorm(0,.0001) 79 | for (sub in 1:nsubs) { 80 | valpha[c2,sub] ~ dnorm(vmu[c2], vtau) 81 | } 82 | } 83 | 84 | # Likelihood 85 | for (i in 1:n) 86 | { 87 | 88 | v[i] <- valpha[noise[i],subject[i]] + p200trialerpc1n[i]*vbeta[noise[i],subject[i],1] + p200trialerplatc1n[i]*vbeta[noise[i],subject[i],2] + n200trialerpc1r[i]*vbeta[noise[i],subject[i],3] + n200trialerplatc1r[i]*vbeta[noise[i],subject[i],4] 89 | 90 | 91 | t[i] <- talpha[noise[i],subject[i]] + p200trialerpc1n[i]*tbeta[noise[i],subject[i],1] + p200trialerplatc1n[i]*tbeta[noise[i],subject[i],2] + n200trialerpc1r[i]*tbeta[noise[i],subject[i],3] + n200trialerplatc1r[i]*tbeta[noise[i],subject[i],4] 92 | 93 | y[i] ~ dwiener(1/s[noise[i],subject[i]], t[i], 0.5, v[i]/s[noise[i],subject[i]]) 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /nunez_etal2017_mathpsych/model3.jags: -------------------------------------------------------------------------------- 1 | ## Citation 2 | # Nunez, M. D., Vandekerckhove, J., & Srinivasan, R. 3 | # How attention influences perceptual decision making: Single-trial EEG correlates of drift-diffusion model parameters. 4 | # Journal of Mathematical Psychology, 76, 117-130. (2017). 5 | 6 | ## Copyright 2015 Michael D. Nunez 7 | 8 | #This program is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU General Public License as published by 10 | # the Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program. If not, see . 20 | 21 | model { 22 | # No effect on b (bias between responses) 23 | # b <- .5 24 | # Boundary separation kept constant 25 | # a <- 1 26 | 27 | # 1 unit increase of eegfield{f} is associated with this additive effect on t 28 | for (f in 1:4) { 29 | tbetasd[f] ~ dgamma(5, .2) 30 | tbetatau[f] <- pow(tbetasd[f], -2) 31 | for (c2 in 1:3) { 32 | tbetamu[c2,f] ~ dnorm(0,.0001) 33 | for (sub in 1:nsubs) { 34 | tbeta[c2,sub,f] ~ dnorm(tbetamu[c2,f],tbetatau[f]) 35 | } 36 | } 37 | } 38 | 39 | # Effect on Ter (non-decision time) 40 | # Varies by subject 41 | tsd ~ dgamma(5, .2) 42 | ttau <- pow(tsd, -2) 43 | for (c2 in 1:3) { 44 | tmu[c2] ~ dnorm(0,.0001) 45 | for (sub in 1:nsubs) { 46 | talpha[c2,sub] ~ dnorm(tmu[c2], ttau) 47 | } 48 | } 49 | 50 | # 1 unit increase of eegfield{f} is associated with this additive effect on s 51 | for (f in 1:4) { 52 | sbetasd[f] ~ dgamma(5, .2) 53 | sbetatau[f] <- pow(sbetasd[f], -2) 54 | for (c2 in 1:3) { 55 | sbetamu[c2,f] ~ dnorm(0,.0001) 56 | for (sub in 1:nsubs) { 57 | sbeta[c2,sub,f] ~ dnorm(sbetamu[c2,f],sbetatau[f]) 58 | } 59 | } 60 | } 61 | 62 | # Effect on s (diffusion coefficient) 63 | # Varies by subject 64 | ssd ~ dgamma(5, .2) 65 | stau <- pow(ssd, -2) 66 | for (c2 in 1:3) { 67 | smu[c2] ~ dnorm(0,.0001) 68 | for (sub in 1:nsubs) { 69 | salpha[c2,sub] ~ dnorm(smu[c2], stau) 70 | } 71 | } 72 | 73 | # 1 unit increase of eegfield{f} is associated with this additive effect on v 74 | for (f in 1:4) { 75 | vbetasd[f] ~ dgamma(5, .2) 76 | vbetatau[f] <- pow(vbetasd[f], -2) 77 | for (c2 in 1:3) { 78 | vbetamu[c2,f] ~ dnorm(0,.0001) 79 | for (sub in 1:nsubs) { 80 | vbeta[c2,sub,f] ~ dnorm(vbetamu[c2,f],vbetatau[f]) 81 | } 82 | } 83 | } 84 | 85 | # Effect on v (diffusion process between trials) 86 | # Varies by condition and subject 87 | vsd ~ dgamma(5, .2) 88 | vtau <- pow(vsd, -2) 89 | for (c2 in 1:3) { 90 | vmu[c2] ~ dnorm(0,.0001) 91 | for (sub in 1:nsubs) { 92 | valpha[c2,sub] ~ dnorm(vmu[c2], vtau) 93 | } 94 | } 95 | 96 | # Likelihood 97 | for (i in 1:n) 98 | { 99 | 100 | v[i] <- valpha[noise[i],subject[i]] + p200trialerpc1n[i]*vbeta[noise[i],subject[i],1] + p200trialerplatc1n[i]*vbeta[noise[i],subject[i],2] + n200trialerpc1r[i]*vbeta[noise[i],subject[i],3] + n200trialerplatc1r[i]*vbeta[noise[i],subject[i],4] 101 | 102 | 103 | t[i] <- talpha[noise[i],subject[i]] + p200trialerpc1n[i]*tbeta[noise[i],subject[i],1] + p200trialerplatc1n[i]*tbeta[noise[i],subject[i],2] + n200trialerpc1r[i]*tbeta[noise[i],subject[i],3] + n200trialerplatc1r[i]*tbeta[noise[i],subject[i],4] 104 | 105 | 106 | s[i] <- salpha[noise[i],subject[i]] + p200trialerpc1n[i]*sbeta[noise[i],subject[i],1] + p200trialerplatc1n[i]*sbeta[noise[i],subject[i],2] + n200trialerpc1r[i]*sbeta[noise[i],subject[i],3] + n200trialerplatc1r[i]*sbeta[noise[i],subject[i],4] 107 | 108 | y[i] ~ dwiener(1/s[i], t[i], 0.5, v[i]/s[i]) 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /nunez_etal2017_mathpsych/paper_figures/pdm3b_trialsortplot.m: -------------------------------------------------------------------------------- 1 | %pdm3b_trialsortplot - Script to create single-trial evoked responses plot, Figure 5 of Nunez et al., 2017 Journal of Mathematical Psychology 2 | % 3 | % Copyright (C) 2016 Michael D. Nunez, 4 | % 5 | % This program is free software: you can redistribute it and/or modify 6 | % it under the terms of the GNU General Public License as published by 7 | % the Free Software Foundation, either version 3 of the License, or 8 | % (at your option) any later version. 9 | % 10 | % This program is distributed in the hope that it will be useful, 11 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | % GNU General Public License for more details. 14 | % 15 | % You should have received a copy of the GNU General Public License 16 | % along with this program. If not, see . 17 | 18 | %% Record of Revisions 19 | % Date Programmers Description of change 20 | % ==== ================= ===================== 21 | % 9/28/15 Michael Nunez Original code 22 | % 12/15/15 Michael Nunez Save high quality image 23 | % 2/26/16 Michael Nunez Color bar 24 | 25 | %% Sort single-trial EEG 26 | 27 | load('sublist.mat'); 28 | prepdata = load('svdins3b_5.mat'); 29 | load('svdinputs8.mat'); 30 | 31 | noisetrials = nan(768,540*17); 32 | resptrials = nan(1024,540*17); 33 | noisetrialsrt = nan(768,540*17); 34 | resptrialsrt =nan(1024,540*17); 35 | for s=1:17 36 | thesetrials = (1:540) + 540*(s-1); 37 | 38 | %Sort by max magnitude 39 | [~,tempindx] = sort(prepdata.p200trialerp_c1n(prepdata.subject == s)); 40 | noisetrials(:,thesetrials) = squeeze(trialerp{1,s}(:,1,tempindx)); 41 | [~,tempindx2] = sort(prepdata.p200trialerp_c1r(prepdata.subject == s)); 42 | resptrials(:,thesetrials) = squeeze(trialerp{2,s}(:,1,tempindx2)); 43 | 44 | % %Sort by min magnitude 45 | % [~,tempindxrth] = sort(prepdata.rt(prepdata.subject == s & prepdata.noise == .6),2,'descend'); 46 | % [~,tempindxrtm] = sort(prepdata.rt(prepdata.subject == s & prepdata.noise == .45),2,'descend'); 47 | % [~,tempindxrtl] = sort(prepdata.rt(prepdata.subject == s & prepdata.noise == .3),2,'descend'); 48 | % tempindxrt = [tempindxrth tempindxrtm tempindxrtl]; 49 | % noisetrialsrt(:,thesetrials) = squeeze(trialerp{1,s}(:,1,tempindxrt)); 50 | % resptrialsrt(:,thesetrials) = squeeze(trialerp{2,s}(:,1,tempindxrt)); 51 | 52 | %Organize by RT tertiles magnitude 53 | noises = [.6 .45 .3]; 54 | for n=1:3 55 | temprt = prepdata.rt(prepdata.subject == s & prepdata.noise == noises(n)); 56 | % tert = prctile(temprt,[33 67]); 57 | % noisetrialsrt(:,(1:180)+180*(n-1) + 540*(s-1)) = ... 58 | % [noisetrials(:,(temprt > tert(2))) noisetrials(:,(temprt <= tert(2)) & (temprt > tert(1))) ... 59 | % noisetrials(:,(temprt <= tert(1))) noisetrials(:,isnan(temprt))]; 60 | % resptrialsrt(:,(1:180)+180*(n-1) + 540*(s-1)) = ... 61 | % [resptrials(:,(temprt > tert(2))) resptrials(:,(temprt <= tert(2)) & (temprt > tert(1))) ... 62 | % resptrials(:,(temprt <= tert(1))) resptrials(:,isnan(temprt))]; 63 | rtmedian = nanmedian(temprt); 64 | noisetrialsrt(:,(1:180)+180*(n-1) + 540*(s-1)) = ... 65 | [noisetrials(:,(temprt > rtmedian)) ... 66 | noisetrials(:,(temprt <= rtmedian)) noisetrials(:,isnan(temprt))]; 67 | resptrialsrt(:,(1:180)+180*(n-1) + 540*(s-1)) = ... 68 | [resptrials(:,(temprt > rtmedian)) ... 69 | resptrials(:,(temprt <= rtmedian)) resptrials(:,isnan(temprt))]; 70 | end 71 | end 72 | 73 | 74 | %%Find p200 and n200 locations and magnitudes 75 | 76 | n200 = round(150*1.024):round(275*1.024); 77 | p200 = round(150*1.024):round(275*1.024); 78 | 79 | noisetrials = flipud(noisetrials'); 80 | resptrials = flipud(resptrials'); 81 | noisetrialsrt = flipud(noisetrialsrt'); 82 | resptrialsrt = flipud(resptrialsrt'); 83 | 84 | noisedelaysrt = zeros(size(noisetrialsrt)); 85 | respdelaysrt = zeros(size(resptrialsrt)); 86 | [~,nind] = max(noisetrialsrt(:,p200),[],2); 87 | [~,rind] = min(-resptrialsrt(:,n200),[],2); 88 | for n=1:540 89 | noisedelaysrt(n,nind(n)) = 1; 90 | respdelaysrt(n,rind(n)) = 1; 91 | end 92 | 93 | %% Plot single-trial EEG for one subject 94 | 95 | windowsize = round(300*1.024); 96 | 97 | %%Paper figure 98 | whichsub = 12; 99 | thisindx = (1:540) + (whichsub-1)*540; 100 | 101 | xms = [0:50:300]; 102 | xsamps = round(xms*1.024); 103 | 104 | fontsize = 20; 105 | 106 | f1 = figure('units','normalized','outerposition',[0 .5 1 .5]); 107 | % f1 = figure('units','normalized','outerposition',[0 0 1 1]); 108 | 109 | subplot(1,2,1); 110 | % subplot(2,2,1); 111 | %sub1 = imagesc(noisetrials(thisindx,1:windowsize),[-100 100]); 112 | sub1 = imagesc(noisetrials(thisindx,1:windowsize),[-90 90]); 113 | set(gca,'XLim',[0 windowsize],'XTick',xsamps,'XTickLabel',xms,'YTickLabel',[],'Fontsize',16); 114 | ylabel('Cue Intervals','Fontsize',fontsize); 115 | xlabel('Delay (ms) following noise onset','Fontsize',fontsize); 116 | line(round([150 150]*1.024),[1 540],'Color','k','LineWidth',2,'Linestyle','--'); 117 | line(round([275 275]*1.024),[1 540],'Color','k','LineWidth',2,'Linestyle','--'); 118 | %line(round([p200loc(whichsub) p200loc(whichsub)]*1.024),[1 540],'Color',[1 1 1],'LineWidth',2,'Linestyle','--'); 119 | %line(round([p200loc2(whichsub) p200loc2(whichsub)]*1.024),[1 540],'Color',[0 1 0],'LineWidth',2,'Linestyle','--'); 120 | 121 | subplot(1,2,2); 122 | % subplot(2,2,2); 123 | %sub2 = imagesc(-resptrials(thisindx,1:windowsize),[-100 100]); 124 | sub2 = imagesc(-resptrials(thisindx,1:windowsize),[-90 90]); 125 | set(gca,'XLim',[0 windowsize],'XTick',xsamps,'XTickLabel',xms,'YTickLabel',[],'Fontsize',16); 126 | ylabel('Response Intervals','Fontsize',fontsize); 127 | xlabel('Delay (ms) following signal onset','Fontsize',fontsize); 128 | line(round([150 150]*1.024),[1 540],'Color','k','LineWidth',2,'Linestyle','--'); 129 | line(round([275 275]*1.024),[1 540],'Color','k','LineWidth',2,'Linestyle','--'); 130 | %line(round([n200loc(whichsub) n200loc(whichsub)]*1.024),[1 540],'Color',[1 1 1],'LineWidth',2,'Linestyle','--'); 131 | %line(round([n200loc2(whichsub) n200loc2(whichsub)]*1.024),[1 540],'Color',[0 1 0],'LineWidth',2,'Linestyle','--'); 132 | sub2ax = gca; 133 | originalsize = get(sub2ax,'Position'); 134 | cb = colorbar('EastOutside','Fontsize',fontsize,'YTick',[-90 -45 0 45 90]); 135 | yl = ylabel(cb,'\muV','Fontsize',fontsize); 136 | set(yl,'Rotation',270); 137 | set(sub2ax,'Position',originalsize); 138 | 139 | 140 | % subplot(2,2,3); 141 | % %sub3 = imagesc(noisetrialsrt(thisindx,1:windowsize),[-100 100]); 142 | % sub3 = imagesc(noisetrialsrt(thisindx,1:windowsize),[-90 90]); 143 | % %sub3 = imagesc(noisedelaysrt(thisindx,1:windowsize)); 144 | % set(gca,'XLim',[0 windowsize],'XTick',xsamps,'XTickLabel',xms,'YTickLabel',[],'Fontsize',16); 145 | % ylabel('Noise Intervals','Fontsize',fontsize); 146 | % xlabel('Delay (ms) following noise onset','Fontsize',fontsize); 147 | % line(round([150 150]*1.024),[1 540],'Color','k','LineWidth',2,'Linestyle','--'); 148 | % line(round([275 275]*1.024),[1 540],'Color','k','LineWidth',2,'Linestyle','--'); 149 | % % line(round([p200loc(whichsub) p200loc(whichsub)]*1.024),[1 540],'Color',[1 1 1],'LineWidth',2,'Linestyle','--'); 150 | % % line(round([p200loc2(whichsub) p200loc2(whichsub)]*1.024),[1 540],'Color',[0 1 0],'LineWidth',2,'Linestyle','--'); 151 | % templine = downsample(nind(thisindx),10)+153; 152 | % %line(templine,10:10:540,'Color',[0 0 0],'LineWidth',1.5); 153 | % line([0 windowsize], [181 181],'Color','k','LineWidth',2); 154 | % line([0 windowsize], [361 361],'Color','k','LineWidth',2); 155 | % 156 | % subplot(2,2,4); 157 | % %sub4 = imagesc(-resptrialsrt(thisindx,1:windowsize),[-100 100]); 158 | % sub4 = imagesc(-resptrialsrt(thisindx,1:windowsize),[-90 90]); 159 | % set(gca,'XLim',[0 windowsize],'XTick',xsamps,'XTickLabel',xms,'YTickLabel',[],'Fontsize',16); 160 | % ylabel('Response Intervals','Fontsize',fontsize); 161 | % xlabel('Delay (ms) following signal onset','Fontsize',fontsize); 162 | % line(round([150 150]*1.024),[1 540],'Color','k','LineWidth',2,'Linestyle','--'); 163 | % line(round([275 275]*1.024),[1 540],'Color','k','LineWidth',2,'Linestyle','--'); 164 | % % line(round([n200loc(whichsub) n200loc(whichsub)]*1.024),[1 540],'Color',[1 1 1],'LineWidth',2,'Linestyle','--'); 165 | % % line(round([n200loc2(whichsub) n200loc2(whichsub)]*1.024),[1 540],'Color',[0 1 0],'LineWidth',2,'Linestyle','--'); 166 | % templine = downsample(rind(thisindx),10) + 153; 167 | % %line(templine,10:10:540,'Color',[0 0 0],'LineWidth',1.5); 168 | % line([0 windowsize], [181 181],'Color','k','LineWidth',2); 169 | % line([0 windowsize], [361 361],'Color','k','LineWidth',2); 170 | 171 | %% Save figure 172 | 173 | export_fig(f1,'ERPs_single_trials','-opengl','-png','-r200'); -------------------------------------------------------------------------------- /nunez_etal2017_mathpsych/pdm3b_demo.m: -------------------------------------------------------------------------------- 1 | %% README 2 | 3 | %THIS SCRIPT WILL NOT WORK WITHOUT SPECIFIC PACKAGES AND PROGRAMS 4 | % 5 | %JAGS - Just Another Gibbs Sampler 6 | %http://sourceforge.net/projects/mcmc-jags/ 7 | % 8 | %jags-wiener - Wiener distribution functions for JAGS 9 | %http://sourceforge.net/projects/jags-wiener/ 10 | % 11 | %DMAT - Diffusion Model Analysis Toolbox (needed function is already included in this repo) 12 | %https://ppw.kuleuven.be/okp/software/dmat/ 13 | % 14 | %Trinity 15 | %https://github.com/joachimvandekerckhove/trinity 16 | % 17 | %Others? 18 | 19 | %% Citation 20 | % Nunez, M. D., Vandekerckhove, J., & Srinivasan, R. (2017) How attention influences perceptual decision making: Single-trial EEG correlates of drift-diffusion model parameters. Journal of Mathematical Psychology, 76, 117-130. 21 | 22 | %% Copyright 2015 Michael D. Nunez 23 | 24 | %This program is free software: you can redistribute it and/or modify 25 | % it under the terms of the GNU General Public License as published by 26 | % the Free Software Foundation, either version 3 of the License, or 27 | % (at your option) any later version. 28 | % 29 | % This program is distributed in the hope that it will be useful, 30 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 31 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 32 | % GNU General Public License for more details. 33 | % 34 | % You should have received a copy of the GNU General Public License 35 | % along with this program. If not, see . 36 | 37 | %% Record of Revisions 38 | % Date Programmers Description of change 39 | % ==== ================= ===================== 40 | % 12/29/15 Michael Nunez Original code 41 | 42 | %% Training/Test Split 43 | 44 | %2/3 - 1/3 Training/Test split 45 | oneszeros1 = [zeros(1,360) ones(1,180)]; 46 | oneszeros2 = [zeros(1,320) ones(1,160)]; 47 | 48 | rng('default'); 49 | rng(11); 50 | splitdata1 = []; 51 | for j=1:17 52 | splitdata1 = [splitdata1 oneszeros1(randperm(length(oneszeros1)))]; 53 | end 54 | 55 | splitdata2 = []; 56 | for j=1:3 57 | splitdata2 = [splitdata2 oneszeros2(randperm(length(oneszeros2)))]; 58 | end 59 | 60 | whichsubs1 = 1:17; 61 | %Note that randperm's use changed after a specific MATLAB version 62 | randsubs1 = whichsubs1(randperm(17,4)); 63 | 64 | for j = randsubs1 65 | splitdata1([1:540] + 540*(j-1)) = ones(1,540); 66 | end 67 | 68 | %% Code 69 | 70 | pdm3b_model1('jagsins.mat',splitdata1); 71 | 72 | pdm3b_model2('jagsins.mat',splitdata1,... 73 | {'p200trialerp_c1n' 'p200trialerplat_c1n' 'n200trialerp_c1r' 'n200trialerplat_c1r'}); 74 | 75 | pdm3b_model3('jagsins.mat',splitdata1,... 76 | {'p200trialerp_c1n' 'p200trialerplat_c1n' 'n200trialerp_c1r' 'n200trialerplat_c1r'}); 77 | -------------------------------------------------------------------------------- /nunez_etal2017_mathpsych/pdm3b_model1.m: -------------------------------------------------------------------------------- 1 | function pdm3b_model1(inputfile,rmtrials,varargin) 2 | %PDM3B_MODEL1 - Runs a new JAGS model without EEG inputs 3 | % 4 | %load jagsins.mat to see structure 5 | % 6 | %Usage: pdm3b_model1('jagsins.mat',rmtrials); 7 | % 8 | % 9 | %Inputs: 10 | % inputfile: name of file that contains .eeg structure with subject 11 | % level EEG fields (i.e. jagsins.mat) 12 | % 13 | %% README 14 | 15 | %THIS PROGRAM WILL NOT WORK WITHOUT SPECIFIC PACKAGES AND PROGRAMS 16 | % 17 | %JAGS - Just Another Gibbs Sampler 18 | %http://sourceforge.net/projects/mcmc-jags/ 19 | % 20 | %jags-wiener - Wiener distribution functions for JAGS 21 | %http://sourceforge.net/projects/jags-wiener/ 22 | % 23 | %DMAT - Diffusion Model Analysis Toolbox 24 | %https://ppw.kuleuven.be/okp/software/dmat/ 25 | % 26 | %Trinity 27 | %https://github.com/joachimvandekerckhove/trinity 28 | % 29 | %GNU Parallel (Optional): 30 | %https://www.gnu.org/software/parallel/ 31 | 32 | %% Citation 33 | % Nunez, M. D., Vandekerckhove, J., & Srinivasan, R. (2017) How attention influences perceptual decision making: Single-trial EEG correlates of drift-diffusion model parameters. Journal of Mathematical Psychology, 76, 117-130. 34 | 35 | %% Copyright 2015 Michael D. Nunez 36 | 37 | %This program is free software: you can redistribute it and/or modify 38 | % it under the terms of the GNU General Public License as published by 39 | % the Free Software Foundation, either version 3 of the License, or 40 | % (at your option) any later version. 41 | % 42 | % This program is distributed in the hope that it will be useful, 43 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 44 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 45 | % GNU General Public License for more details. 46 | % 47 | % You should have received a copy of the GNU General Public License 48 | % along with this program. If not, see . 49 | 50 | %% Record of Revisions 51 | % Date Programmers Description of change 52 | % ==== ================= ===================== 53 | % 8/26/15 Michael Nunez Original code 54 | % 3/04/16 Michael Nunez Added thinning parameter that 55 | % exists in the original fits for the paper, but forgotten here 56 | % 5/03/16 Michael Nunez Works with the new version of Trinity 57 | 58 | %% Initial 59 | 60 | data = load(inputfile); 61 | 62 | %Organize date and time into a string 63 | rightnow = clock; 64 | rightnow = num2cell(rightnow)'; 65 | timestr = sprintf('_%i',rightnow{1:5}); 66 | 67 | modelname = timestr; 68 | nsamples = 5e3; 69 | nburnin = 2e3; 70 | thin = 10; 71 | nchains =6; 72 | verbosity =1; 73 | parallelit = 0; %Set this to 1 if GNU Parallel is installed 74 | maxcores = 3; 75 | modules = {'wiener' 'dic'}; 76 | 77 | %% JAGS code for the diffusion model 78 | 79 | model = { 80 | 'model {' 81 | '# No effect on b (bias between responses)' 82 | '# b <- .5' 83 | '# Boundary separation kept constant' 84 | '# a <- 1' 85 | '' 86 | '# Effect on Ter (preprocessing /nondecision time)' 87 | '# Varies by subject' 88 | 'tsd ~ dgamma(5, 20)' %x=linspace(0, 1, 100); plot(x, gampdf(x, 5, .05)) 89 | 'ttau <- pow(tsd, -2)' 90 | 'for (c2 in 1:3) {' %noise 91 | ' tmu[c2] ~ dnorm(.3, 1)T(0,3)' %std = 1 92 | ' for (sub in 1:nsubs) {' %subject 93 | ' t[c2,sub] ~ dnorm(tmu[c2], ttau)' 94 | ' }' 95 | '}' 96 | '' 97 | '# Effect on s (diffusion coefficient)' 98 | '# Varies by subject' 99 | 'ssd ~ dgamma(5, 20)' % x=linspace(0, 1, 100); plot(x, gampdf(x, 5, .05)) 100 | 'stau <- pow(ssd, -2)' 101 | 'for (c2 in 1:3) {' %noise 102 | ' smu[c2] ~ dnorm(.6, 1/4)T(0,4)' %std = 2 103 | ' for (sub in 1:nsubs) {' %subject 104 | ' s[c2,sub] ~ dnorm(smu[c2], stau)' 105 | ' }' 106 | '}' 107 | '' 108 | '# Effect on v (drift rate)' 109 | '# Varies by subject' 110 | 'vsd ~ dgamma(5, 5)' % x=linspace(0, 4, 100); plot(x, gampdf(x, 5, .2)) 111 | 'vtau <- pow(vsd, -2)' 112 | 'for (c2 in 1:3) {' %noise 113 | ' vmu[c2] ~ dnorm(1.5, 1/16)T(-9,9)' %std = 4 114 | ' for (sub in 1:nsubs) {' %subject 115 | ' v[c2,sub] ~ dnorm(vmu[c2], vtau)' 116 | ' }' 117 | '}' 118 | '' 119 | '# Likelihood' 120 | 'for (i in 1:n)' 121 | '{' 122 | '' 123 | ' y[i] ~ dwiener(1/s[noise[i],subject[i]], t[noise[i],subject[i]], 0.5, v[noise[i],subject[i]]/s[noise[i],subject[i]])' 124 | '}' 125 | '}' 126 | }; 127 | 128 | %% Code for Trinity 129 | 130 | params = {'tsd' 'tmu' 't' 'ssd' 'smu' 's' 'vsd' 'vmu' 'v'}; 131 | 132 | samprt = data.rt; 133 | rt = samprt/1024; %Reaction time in samples to seconds (not milliseconds) 134 | ntrials = length(data.correct); 135 | 136 | %Remove no answer trials and subjects that were taken out of this model 137 | tremove = isnan(data.correct) | (data.goodtrials == 0); %Remove this last flag if imputing bad trials 138 | 139 | %Remove RTs less than cutoff given by ewmav2 140 | for j=1:length(data.subname) 141 | [cutoff] = ewmav2([data.correct(data.subject == j & ~isnan(rt))' rt(data.subject == j & ~isnan(rt))'],2,.01,.5); 142 | tremove = tremove | (rt < cutoff & data.subject == j); 143 | cutoffs(j) = cutoff; 144 | end 145 | nremove = sum(tremove); 146 | 147 | correct = data.correct; 148 | correct(correct == 0) = -1; 149 | y = correct(~tremove).*rt(~tremove); 150 | 151 | R.subject = data.subject(~tremove); 152 | R.subject = R.subject(:); 153 | 154 | tempc = data.noise; 155 | tempc = tempc(~tremove); 156 | [~, ~, noise] = unique(tempc); 157 | 158 | tempj = data.jitter; 159 | tempj = tempj(~tremove); 160 | [~, ~, jitter] = unique(tempj); 161 | 162 | R.n = ntrials - nremove; 163 | R.nsubs = length(data.subname); %Keep this fixed for the total number of subjects even if removing subjects from modeling 164 | R.y = y(:); 165 | R.jitter = jitter(:); 166 | R.noise = noise(:); 167 | 168 | initstruct = @()struct(... 169 | 'v', randn(3,R.nsubs)); 170 | 171 | 172 | %Setup data split index for cross-validation 173 | rmindex = logical(rmtrials(~tremove)); 174 | 175 | %Training data 176 | S.nsubs = R.nsubs; 177 | S.subject = R.subject(~rmindex); 178 | S.n = R.n - sum(rmindex); 179 | S.y = R.y(~rmindex); 180 | S.jitter = R.jitter(~rmindex); 181 | S.noise = R.noise(~rmindex); 182 | 183 | %Test data 184 | T.nsubs = R.nsubs; 185 | T.subject = R.subject(rmindex); 186 | T.n = R.n - sum(~rmindex); 187 | T.y = R.y(rmindex); 188 | T.jitter = R.jitter(rmindex); 189 | T.noise = R.noise(rmindex); 190 | 191 | %% Run JAGS 192 | fprintf('Building JAGS model %s and saving output...',modelname); 193 | 194 | tic 195 | [stats, chains, diagnostics, info] = callbayes('jags', ... 196 | 'model', model, ... 197 | 'data', S, ... 198 | 'nsamples', nsamples, ... 199 | 'nburnin', nburnin, ... 200 | 'nchains', nchains, ... 201 | 'thin',thin,... 202 | 'verbosity', verbosity, ... 203 | 'workingdir','wdir', ... 204 | 'monitorparams', params, ... 205 | 'parallel',parallelit, ... 206 | 'maxcores',maxcores, ... 207 | 'modules',modules, ... 208 | 'init', initstruct, ... 209 | varargin{:}); 210 | 211 | info.comptime = toc/60; 212 | fprintf('JAGS took %f minutes!\n', info.comptime) 213 | 214 | save(sprintf('jagsmodel%s.mat',modelname),'stats', 'chains', 'diagnostics',... 215 | 'cutoffs','info','params','S','T'); 216 | 217 | -------------------------------------------------------------------------------- /nunez_etal2017_mathpsych/pdm3b_model2.m: -------------------------------------------------------------------------------- 1 | function pdm3b_model2(inputfile,rmtrials,eegfields,varargin) 2 | %PDM3B_MODEL2 - Runs a new JAGS Model Type 2 with EEG inputs 3 | % 4 | %load jagsins.mat to see structure 5 | % 6 | %Usage: pdm3b_model2('jagsins.mat',rmtrials,eegfields); 7 | % 8 | % 9 | %Inputs: 10 | % inputfile: name of file that contains .eeg structure with subject 11 | % level EEG fields (i.e. jagsins.mat) 12 | % eegfields: EEG fields of (eeginputfile) to include in model 13 | % 14 | %% README 15 | 16 | %THIS PROGRAM WILL NOT WORK WITHOUT SPECIFIC PACKAGES AND PROGRAMS 17 | % 18 | %JAGS - Just Another Gibbs Sampler 19 | %http://sourceforge.net/projects/mcmc-jags/ 20 | % 21 | %jags-wiener - Wiener distribution functions for JAGS 22 | %http://sourceforge.net/projects/jags-wiener/ 23 | % 24 | %DMAT - Diffusion Model Analysis Toolbox 25 | %https://ppw.kuleuven.be/okp/software/dmat/ 26 | % 27 | %Trinity 28 | %https://github.com/joachimvandekerckhove/trinity 29 | % 30 | %GNU Parallel (Optional): 31 | %https://www.gnu.org/software/parallel/ 32 | 33 | %% Citation 34 | % Nunez, M. D., Vandekerckhove, J., & Srinivasan, R. (2017) How attention influences perceptual decision making: Single-trial EEG correlates of drift-diffusion model parameters. Journal of Mathematical Psychology, 76, 117-130. 35 | 36 | %% Copyright 2015 Michael D. Nunez 37 | 38 | %This program is free software: you can redistribute it and/or modify 39 | % it under the terms of the GNU General Public License as published by 40 | % the Free Software Foundation, either version 3 of the License, or 41 | % (at your option) any later version. 42 | % 43 | % This program is distributed in the hope that it will be useful, 44 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 45 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 46 | % GNU General Public License for more details. 47 | % 48 | % You should have received a copy of the GNU General Public License 49 | % along with this program. If not, see . 50 | 51 | %% Record of Revisions 52 | % Date Programmers Description of change 53 | % ==== ================= ===================== 54 | % 8/31/15 Michael Nunez Original code 55 | % 3/04/16 Michael Nunez Added thinning parameter that 56 | % exists in the original fits for the paper, but forgotten here 57 | % 5/03/16 Michael Nunez Works with the new version of Trinity 58 | 59 | %% Initial 60 | 61 | data = load(inputfile); 62 | 63 | %Organize date and time into a string 64 | rightnow = clock; 65 | rightnow = num2cell(rightnow)'; 66 | timestr = sprintf('_%i',rightnow{1:5}); 67 | 68 | %EEG effect on model parameters? 69 | for t=1:length(eegfields) 70 | defaulttsv{t} = [1 1 1]; 71 | end 72 | 73 | tsv = defaulttsv; 74 | modelname = timestr; 75 | nsamples = 5e3; 76 | nburnin = 2e3; 77 | nchains =6; 78 | thin = 10; 79 | verbosity =1; 80 | parallelit = 0; %Set this to 1 if GNU Parallel is installed 81 | maxcores = 3; 82 | modules = {'wiener' 'dic'}; 83 | 84 | 85 | %% JAGS code for the diffusion model 86 | 87 | %Set up string cell array with proper indexing 88 | %Set up cell structure for creating mu equations 89 | tarray = []; 90 | sarray = []; 91 | varray = []; 92 | for f=1:numel(eegfields) 93 | neweegfields{f} = strrep(eegfields{f},'_',''); %JAGS does not like the underscore in a data variable name 94 | covariates{f} = [neweegfields{f} '[i]']; %Subscripts for the .jags code 95 | if tsv{f}(1) 96 | tarray = cat(2,tarray,[covariates(f) num2cell(f)]'); 97 | end 98 | if tsv{f}(2) 99 | sarray = cat(2,sarray,[covariates(f) num2cell(f)]'); 100 | end 101 | if tsv{f}(3) 102 | varray = cat(2,varray,[covariates(f) num2cell(f)]'); 103 | end 104 | end 105 | 106 | model = { 107 | 'model {' 108 | '# No effect on b (bias between responses)' 109 | '# b <- .5' 110 | '# Boundary separation kept constant' 111 | '# a <- 1' 112 | '' 113 | '# 1 unit increase of eegfield{f} is associated with this additive effect on t' 114 | sprintf('for (f in 1:%i) {',size(tarray,2)) 115 | 'tbetasd[f] ~ dgamma(5, .2)' % x=linspace(0, 100, 100); plot(x, gampdf(x, 5, 5)) 116 | 'tbetatau[f] <- pow(tbetasd[f], -2)' 117 | ' for (c2 in 1:3) {' %noise 118 | ' tbetamu[c2,f] ~ dnorm(0,.0001)' %std = 100 119 | ' for (sub in 1:nsubs) {' 120 | ' tbeta[c2,sub,f] ~ dnorm(tbetamu[c2,f],tbetatau[f])' %std = 100, These should be drawn from a EEG parameter specific distribution with some std parameter 121 | ' }' 122 | ' }' 123 | '}' 124 | '' 125 | '# Effect on Ter (non-decision time)' 126 | '# Varies by subject' 127 | 'tsd ~ dgamma(5, .2)' % x=linspace(0, 100, 100); plot(x, gampdf(x, 5, 5)) 128 | 'ttau <- pow(tsd, -2)' 129 | 'for (c2 in 1:3) {' %noise 130 | ' tmu[c2] ~ dnorm(0,.0001)' %std = 100 131 | ' for (sub in 1:nsubs) {' 132 | ' talpha[c2,sub] ~ dnorm(tmu[c2], ttau)' 133 | ' }' 134 | '}' 135 | '' 136 | '# Effect on s (diffusion coefficient)' 137 | '# Varies by subject' 138 | 'ssd ~ dgamma(5, 20)' % x=linspace(0, 1, 100); plot(x, gampdf(x, 5, .05)) 139 | 'stau <- pow(ssd, -2)' 140 | 'for (c2 in 1:3) {' %noise 141 | ' smu[c2] ~ dnorm(.6, 1/4)T(0,4)' %std = 2 142 | ' for (sub in 1:nsubs) {' %subject 143 | ' s[c2,sub] ~ dnorm(smu[c2], stau)' 144 | ' }' 145 | '}' 146 | '' 147 | '# 1 unit increase of eegfield{f} is associated with this additive effect on v' 148 | sprintf('for (f in 1:%i) {',size(tarray,2)) 149 | 'vbetasd[f] ~ dgamma(5, .2)' % x=linspace(0, 100, 100); plot(x, gampdf(x, 5, 5)) 150 | 'vbetatau[f] <- pow(vbetasd[f], -2)' 151 | ' for (c2 in 1:3) {' %noise 152 | ' vbetamu[c2,f] ~ dnorm(0,.0001)' %std = 100 153 | ' for (sub in 1:nsubs) {' %subject 154 | ' vbeta[c2,sub,f] ~ dnorm(vbetamu[c2,f],vbetatau[f])' %std = 100, These should be drawn from a EEG parameter specific distribution with some std parameter 155 | ' }' 156 | ' }' 157 | '}' 158 | '' 159 | '# Effect on v (diffusion process between trials)' 160 | '# Varies by condition and subject' 161 | 'vsd ~ dgamma(5, .2)' % x=linspace(0, 100, 100); plot(x, gampdf(x, 5, 5)) 162 | 'vtau <- pow(vsd, -2)' 163 | 'for (c2 in 1:3) {' %noise 164 | ' vmu[c2] ~ dnorm(0,.0001)' %std = 100 165 | ' for (sub in 1:nsubs) {' 166 | ' valpha[c2,sub] ~ dnorm(vmu[c2], vtau)' 167 | ' }' 168 | '}' 169 | '' 170 | '# Likelihood' 171 | 'for (i in 1:n)' 172 | '{' 173 | '' 174 | sprintf('v[i] <- valpha[noise[i],subject[i]]%s',sprintf(' + %s*vbeta[noise[i],subject[i],%i]',sarray{:})) 175 | '' 176 | '' 177 | sprintf('t[i] <- talpha[noise[i],subject[i]]%s',sprintf(' + %s*tbeta[noise[i],subject[i],%i]',sarray{:})) 178 | '' 179 | ' y[i] ~ dwiener(1/s[noise[i],subject[i]], t[i], 0.5, v[i]/s[noise[i],subject[i]])' 180 | '}' 181 | '}' 182 | }; 183 | 184 | %% Code for Trinity 185 | 186 | params = {'tsd' 'tmu' 'talpha' 'tbeta' 'tbetamu' 'tbetasd' 'ssd' 'smu' 's' ... 187 | 'vsd' 'vmu' 'valpha' 'vbeta' 'vbetamu' 'vbetasd'}; 188 | 189 | samprt = data.rt; 190 | rt = samprt/1024; %Reaction time in samples to seconds (not milliseconds) 191 | ntrials = length(data.correct); 192 | 193 | %Remove no answer trials and subjects that weretaken out of this model 194 | tremove = isnan(data.correct) | (data.goodtrials == 0); %Remove this last flag if imputing bad trials 195 | 196 | %Remove RTs less than cutoff given by ewmav2 197 | for j=1:length(data.subname) 198 | [cutoff] = ewmav2([data.correct(data.subject == j & ~isnan(rt))' rt(data.subject == j & ~isnan(rt))'],2,.01,.5); 199 | tremove = tremove | (rt < cutoff & data.subject == j); 200 | cutoffs(j) = cutoff; 201 | end 202 | nremove = sum(tremove); 203 | 204 | correct = data.correct; 205 | correct(correct == 0) = -1; 206 | y = correct(~tremove).*rt(~tremove); 207 | 208 | R.subject = data.subject(~tremove); 209 | R.subject = R.subject(:); 210 | 211 | tempc = data.noise; 212 | tempc = tempc(~tremove); 213 | [~, ~, noise] = unique(tempc); 214 | 215 | tempj = data.jitter; 216 | tempj = tempj(~tremove); 217 | [~, ~, jitter] = unique(tempj); 218 | 219 | R.n = ntrials - nremove; 220 | R.nsubs = length(data.subname); %Keep this fixed for the total number of subjects even if removing subjects from modeling 221 | R.y = y(:); 222 | R.jitter = jitter(:); 223 | R.noise = noise(:); 224 | 225 | initstruct = @()struct(... 226 | 'valpha', randn(3,R.nsubs),'talpha', .1 + rand(3,R.nsubs)*.2); 227 | 228 | 229 | for f=1:numel(eegfields) 230 | R.(neweegfields{f}) = data.(eegfields{f})(~tremove)'; 231 | end 232 | 233 | 234 | %Setup data split index for cross-validation 235 | rmindex = logical(rmtrials(~tremove)); 236 | 237 | %Training data 238 | S.nsubs = R.nsubs; 239 | S.subject = R.subject(~rmindex); 240 | S.n = R.n - sum(rmindex); 241 | S.y = R.y(~rmindex); 242 | S.jitter = R.jitter(~rmindex); 243 | S.noise = R.noise(~rmindex); 244 | for f=1:numel(eegfields) 245 | S.(neweegfields{f}) = R.(neweegfields{f})(~rmindex); 246 | end 247 | 248 | %Test data 249 | T.nsubs = R.nsubs; 250 | T.subject = R.subject(rmindex); 251 | T.n = R.n - sum(~rmindex); 252 | T.y = R.y(rmindex); 253 | T.jitter = R.jitter(rmindex); 254 | T.noise = R.noise(rmindex); 255 | for f=1:numel(eegfields) 256 | T.(neweegfields{f}) = R.(neweegfields{f})(rmindex); 257 | end 258 | 259 | %% Run JAGS 260 | 261 | fprintf('Building JAGS model %s and saving output...',modelname); 262 | 263 | tic 264 | [stats, chains, diagnostics, info] = callbayes('jags', ... 265 | 'model', model, ... 266 | 'data', S, ... 267 | 'nsamples', nsamples, ... 268 | 'nburnin', nburnin, ... 269 | 'nchains', nchains, ... 270 | 'thin',thin,... 271 | 'verbosity', verbosity, ... 272 | 'workingdir','wdir', ... 273 | 'monitorparams', params, ... 274 | 'parallel',parallelit, ... 275 | 'maxcores',maxcores, ... 276 | 'modules',modules, ... 277 | 'init', initstruct, ... 278 | varargin{:}); 279 | 280 | info.comptime = toc/60; 281 | fprintf('JAGS took %f minutes!\n', info.comptime) 282 | 283 | save(sprintf('jagsmodel%s.mat',modelname),'stats', 'chains', 'diagnostics',... 284 | 'cutoffs','info','params','S','T','tsv'); 285 | 286 | -------------------------------------------------------------------------------- /nunez_etal2017_mathpsych/pdm3b_model3.m: -------------------------------------------------------------------------------- 1 | function pdm3b_model3(inputfile,rmtrials,eegfields,varargin) 2 | %PDM3B_MODEL3 - Runs a new JAGS Model Type 3 with EEG inputs 3 | % 4 | %load jagsins.mat to see structure 5 | % 6 | %Usage: pdm3b_model3('jagsins.mat',rmtrials,eegfields); 7 | % 8 | % 9 | %Inputs: 10 | % inputfile: name of file that contains .eeg structure with subject 11 | % level EEG fields (i.e. jagsins.mat) 12 | % eegfields: EEG fields of (eeginputfile) to include in model 13 | % 14 | %% README 15 | 16 | %THIS PROGRAM WILL NOT WORK WITHOUT SPECIFIC PACKAGES AND PROGRAMS 17 | % 18 | %JAGS - Just Another Gibbs Sampler 19 | %http://sourceforge.net/projects/mcmc-jags/ 20 | % 21 | %jags-wiener - Wiener distribution functions for JAGS 22 | %http://sourceforge.net/projects/jags-wiener/ 23 | % 24 | %DMAT - Diffusion Model Analysis Toolbox 25 | %https://ppw.kuleuven.be/okp/software/dmat/ 26 | % 27 | %Trinity 28 | %https://github.com/joachimvandekerckhove/trinity 29 | % 30 | %GNU Parallel (Optional): 31 | %https://www.gnu.org/software/parallel/ 32 | 33 | %% Citation 34 | % Nunez, M. D., Vandekerckhove, J., & Srinivasan, R. (2017) How attention influences perceptual decision making: Single-trial EEG correlates of drift-diffusion model parameters. Journal of Mathematical Psychology, 76, 117-130. 35 | 36 | %% Copyright 2015 Michael D. Nunez 37 | 38 | %This program is free software: you can redistribute it and/or modify 39 | % it under the terms of the GNU General Public License as published by 40 | % the Free Software Foundation, either version 3 of the License, or 41 | % (at your option) any later version. 42 | % 43 | % This program is distributed in the hope that it will be useful, 44 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 45 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 46 | % GNU General Public License for more details. 47 | % 48 | % You should have received a copy of the GNU General Public License 49 | % along with this program. If not, see . 50 | 51 | %% Record of Revisions 52 | % Date Programmers Description of change 53 | % ==== ================= ===================== 54 | % 8/31/15 Michael Nunez Original code 55 | % 3/04/16 Michael Nunez Added thinning parameter that 56 | % exists in the original fits for the paper, but forgotten here 57 | % 5/03/16 Michael Nunez Works with the new version of Trinity 58 | 59 | %% Initial 60 | 61 | data = load(inputfile); 62 | 63 | %Organize date and time into a string 64 | rightnow = clock; 65 | rightnow = num2cell(rightnow)'; 66 | timestr = sprintf('_%i',rightnow{1:5}); 67 | 68 | %EEG effect on model parameters? 69 | for t=1:length(eegfields) 70 | defaulttsv{t} = [1 1 1]; 71 | end 72 | 73 | tsv = defaulttsv; 74 | modelname = timestr; 75 | nsamples = 5e3; 76 | nburnin = 2e3; 77 | nchains =6; 78 | thin =10; 79 | verbosity =1; 80 | parallelit = 0; %Set this to 1 if GNU Parallel is installed 81 | maxcores = 3; 82 | modules = {'wiener' 'dic'}; 83 | 84 | %% JAGS code for the diffusion model 85 | 86 | %Set up string cell array with proper indexing 87 | %Set up cell structure for creating mu equations 88 | tarray = []; 89 | sarray = []; 90 | varray = []; 91 | for f=1:numel(eegfields) 92 | neweegfields{f} = strrep(eegfields{f},'_',''); %JAGS does not like the underscore in a data variable name 93 | covariates{f} = [neweegfields{f} '[i]']; %Subscripts for the .jags code 94 | if tsv{f}(1) 95 | tarray = cat(2,tarray,[covariates(f) num2cell(f)]'); 96 | end 97 | if tsv{f}(2) 98 | sarray = cat(2,sarray,[covariates(f) num2cell(f)]'); 99 | end 100 | if tsv{f}(3) 101 | varray = cat(2,varray,[covariates(f) num2cell(f)]'); 102 | end 103 | end 104 | 105 | model = { 106 | 'model {' 107 | '# No effect on b (bias between responses)' 108 | '# b <- .5' 109 | '# Boundary separation kept constant' 110 | '# a <- 1' 111 | '' 112 | '# 1 unit increase of eegfield{f} is associated with this additive effect on t' 113 | sprintf('for (f in 1:%i) {',size(tarray,2)) 114 | 'tbetasd[f] ~ dgamma(5, .2)' % x=linspace(0, 100, 100); plot(x, gampdf(x, 5, 5)) 115 | 'tbetatau[f] <- pow(tbetasd[f], -2)' 116 | ' for (c2 in 1:3) {' %noise 117 | ' tbetamu[c2,f] ~ dnorm(0,.0001)' %std = 100 118 | ' for (sub in 1:nsubs) {' 119 | ' tbeta[c2,sub,f] ~ dnorm(tbetamu[c2,f],tbetatau[f])' %std = 100, These should be drawn from a EEG parameter specific distribution with some std parameter 120 | ' }' 121 | ' }' 122 | '}' 123 | '' 124 | '# Effect on Ter (non-decision time)' 125 | '# Varies by subject' 126 | 'tsd ~ dgamma(5, .2)' % x=linspace(0, 100, 100); plot(x, gampdf(x, 5, 5)) 127 | 'ttau <- pow(tsd, -2)' 128 | 'for (c2 in 1:3) {' %noise 129 | ' tmu[c2] ~ dnorm(0,.0001)' %std = 100 130 | ' for (sub in 1:nsubs) {' 131 | ' talpha[c2,sub] ~ dnorm(tmu[c2], ttau)' 132 | ' }' 133 | '}' 134 | '' 135 | '# 1 unit increase of eegfield{f} is associated with this additive effect on s' 136 | sprintf('for (f in 1:%i) {',size(tarray,2)) 137 | 'sbetasd[f] ~ dgamma(5, .2)' % x=linspace(0, 100, 100); plot(x, gampdf(x, 5, 5)) 138 | 'sbetatau[f] <- pow(sbetasd[f], -2)' 139 | ' for (c2 in 1:3) {' %noise 140 | ' sbetamu[c2,f] ~ dnorm(0,.0001)' %std = 100 141 | ' for (sub in 1:nsubs) {' 142 | ' sbeta[c2,sub,f] ~ dnorm(sbetamu[c2,f],sbetatau[f])' %std = 100, These should be drawn from a EEG parameter specific distribution with some std parameter 143 | ' }' 144 | ' }' 145 | '}' 146 | '' 147 | '# Effect on s (diffusion coefficient)' 148 | '# Varies by subject' 149 | 'ssd ~ dgamma(5, .2)' % x=linspace(0, 100, 100); plot(x, gampdf(x, 5, 5)) 150 | 'stau <- pow(ssd, -2)' 151 | 'for (c2 in 1:3) {' %noise 152 | ' smu[c2] ~ dnorm(0,.0001)' %std = 100 153 | ' for (sub in 1:nsubs) {' 154 | ' salpha[c2,sub] ~ dnorm(smu[c2], stau)' 155 | ' }' 156 | '}' 157 | '' 158 | '# 1 unit increase of eegfield{f} is associated with this additive effect on v' 159 | sprintf('for (f in 1:%i) {',size(tarray,2)) 160 | 'vbetasd[f] ~ dgamma(5, .2)' % x=linspace(0, 100, 100); plot(x, gampdf(x, 5, 5)) 161 | 'vbetatau[f] <- pow(vbetasd[f], -2)' 162 | ' for (c2 in 1:3) {' %noise 163 | ' vbetamu[c2,f] ~ dnorm(0,.0001)' %std = 100 164 | ' for (sub in 1:nsubs) {' %subject 165 | ' vbeta[c2,sub,f] ~ dnorm(vbetamu[c2,f],vbetatau[f])' %std = 100, These should be drawn from a EEG parameter specific distribution with some std parameter 166 | ' }' 167 | ' }' 168 | '}' 169 | '' 170 | '# Effect on v (diffusion process between trials)' 171 | '# Varies by condition and subject' 172 | 'vsd ~ dgamma(5, .2)' % x=linspace(0, 100, 100); plot(x, gampdf(x, 5, 5)) 173 | 'vtau <- pow(vsd, -2)' 174 | 'for (c2 in 1:3) {' %noise 175 | ' vmu[c2] ~ dnorm(0,.0001)' %std = 100 176 | ' for (sub in 1:nsubs) {' 177 | ' valpha[c2,sub] ~ dnorm(vmu[c2], vtau)' 178 | ' }' 179 | '}' 180 | '' 181 | '# Likelihood' 182 | 'for (i in 1:n)' 183 | '{' 184 | '' 185 | sprintf('v[i] <- valpha[noise[i],subject[i]]%s',sprintf(' + %s*vbeta[noise[i],subject[i],%i]',sarray{:})) 186 | '' 187 | '' 188 | sprintf('t[i] <- talpha[noise[i],subject[i]]%s',sprintf(' + %s*tbeta[noise[i],subject[i],%i]',sarray{:})) 189 | '' 190 | '' 191 | sprintf('s[i] <- salpha[noise[i],subject[i]]%s',sprintf(' + %s*sbeta[noise[i],subject[i],%i]',sarray{:})) 192 | '' 193 | ' y[i] ~ dwiener(1/s[i], t[i], 0.5, v[i]/s[i])' 194 | '}' 195 | '}' 196 | }; 197 | 198 | %% Code for Trinity 199 | 200 | params = {'tsd' 'tmu' 'talpha' 'tbeta' 'tbetamu' 'tbetasd' ... 201 | 'ssd' 'smu' 'salpha' 'sbeta' 'sbetamu' 'sbetasd' ... 202 | 'vsd' 'vmu' 'valpha' 'vbeta' 'vbetamu' 'vbetasd'}; 203 | 204 | samprt = data.rt; 205 | rt = samprt/1024; %Reaction time in samples to seconds (not milliseconds) 206 | ntrials = length(data.correct); 207 | 208 | %Remove no answer trials and subjects that weretaken out of this model 209 | tremove = isnan(data.correct) | (data.goodtrials == 0); %Remove this last flag if imputing bad trials 210 | 211 | %Remove RTs less than cutoff given by ewmav2 212 | for j=1:length(data.subname) 213 | [cutoff] = ewmav2([data.correct(data.subject == j & ~isnan(rt))' rt(data.subject == j & ~isnan(rt))'],2,.01,.5); 214 | tremove = tremove | (rt < cutoff & data.subject == j); 215 | cutoffs(j) = cutoff; 216 | end 217 | nremove = sum(tremove); 218 | 219 | correct = data.correct; 220 | correct(correct == 0) = -1; 221 | y = correct(~tremove).*rt(~tremove); 222 | 223 | R.subject = data.subject(~tremove); 224 | R.subject = R.subject(:); 225 | 226 | tempc = data.noise; 227 | tempc = tempc(~tremove); 228 | [~, ~, noise] = unique(tempc); 229 | 230 | tempj = data.jitter; 231 | tempj = tempj(~tremove); 232 | [~, ~, jitter] = unique(tempj); 233 | 234 | R.n = ntrials - nremove; 235 | R.nsubs = length(data.subname); %Keep this fixed for the total number of subjects even if removing subjects from modeling 236 | R.y = y(:); 237 | R.jitter = jitter(:); 238 | R.noise = noise(:); 239 | 240 | initstruct = @()struct(... 241 | 'valpha', randn(3,R.nsubs),'talpha', .1 + rand(3,R.nsubs)*.2, ... 242 | 'salpha', .5 + rand(3,R.nsubs)*.5); 243 | 244 | for f=1:numel(eegfields) 245 | R.(neweegfields{f}) = data.(eegfields{f})(~tremove)'; 246 | end 247 | 248 | 249 | %Setup data split index for cross-validation 250 | rmindex = logical(rmtrials(~tremove)); 251 | 252 | %Training data 253 | S.nsubs = R.nsubs; 254 | S.subject = R.subject(~rmindex); 255 | S.n = R.n - sum(rmindex); 256 | S.y = R.y(~rmindex); 257 | S.jitter = R.jitter(~rmindex); 258 | S.noise = R.noise(~rmindex); 259 | for f=1:numel(eegfields) 260 | S.(neweegfields{f}) = R.(neweegfields{f})(~rmindex); 261 | end 262 | 263 | %Test data 264 | T.nsubs = R.nsubs; 265 | T.subject = R.subject(rmindex); 266 | T.n = R.n - sum(~rmindex); 267 | T.y = R.y(rmindex); 268 | T.jitter = R.jitter(rmindex); 269 | T.noise = R.noise(rmindex); 270 | for f=1:numel(eegfields) 271 | T.(neweegfields{f}) = R.(neweegfields{f})(rmindex); 272 | end 273 | 274 | %% Run JAGS 275 | 276 | fprintf('Building JAGS model %s and saving output...',modelname); 277 | 278 | tic 279 | [stats, chains, diagnostics, info] = callbayes('jags', ... 280 | 'model', model, ... 281 | 'data', S, ... 282 | 'nsamples', nsamples, ... 283 | 'nburnin', nburnin, ... 284 | 'nchains', nchains, ... 285 | 'thin',thin,... 286 | 'verbosity', verbosity, ... 287 | 'workingdir','wdir', ... 288 | 'monitorparams', params, ... 289 | 'parallel',parallelit, ... 290 | 'maxcores',maxcores, ... 291 | 'modules',modules, ... 292 | 'init', initstruct, ... 293 | varargin{:}); 294 | 295 | info.comptime = toc/60; 296 | fprintf('JAGS took %f minutes!\n', info.comptime) 297 | 298 | save(sprintf('jagsmodel%s.mat',modelname),'stats', 'chains', 'diagnostics',... 299 | 'cutoffs','info','params','S','T','tsv'); 300 | 301 | -------------------------------------------------------------------------------- /nunez_etal2017_mathpsych/visual_stimuli/makebardirec.m: -------------------------------------------------------------------------------- 1 | function barimage = makebardirec(imagesize,barsize,imagetype,jitter,preload, graphit) 2 | %makebardirec - Builds a bar patch oriented in two ways 3 | % 4 | % This function creates a matrix of bars with mean rotation directed 5 | % either north-east or north-west on average 6 | % 7 | %Useage: 8 | % >> barimage = makebardirec(imagesize,density,imagetype,jitter,preload,graphit); 9 | % 10 | %Useage Example: 11 | % >> barimage = makebardirec(600,12,1,0,0,1); 12 | % 13 | %To test try: 14 | % >> a = randi(2,1); b = rand(1)*90; makebardirec(600,12,a,b,0,1); 15 | % 16 | %Inputs: 17 | % imagesize = number of pixels for each side of the image (pixels = imagesize*imagesize) (e.g., 600) 18 | % 19 | % density = density parameter (use of 6 in pdmexp2) 20 | % 21 | % imagetype (optional): default is random 22 | % 1 - lines directed north-east / south-west on average 23 | % 2 - lines directed north-west / south-east on average 24 | % 25 | % jitter (optional): default is 0, which is a figure with 'exact' rotations 26 | % Acceptable values on the range [0 120], corresponding to possible 27 | % degrees of random rotation 28 | % 29 | % preload (optional): default is 0, 1 calls preloaded/(45/135)_(jitter).mat 30 | % file to load the bar image maps 31 | % 32 | % graphit (optional): Graphs the image in grayscale if = 1 33 | 34 | %% README 35 | 36 | %For use with pdmexp3_public 37 | 38 | %% Possible Citations 39 | % Nunez, M. D., Srinivasan, R., & Vandekerckhove, J. (2015). Individual differences in attention influence perceptual decision making. Frontiers in psychology, 8. 40 | % Nunez, M. D., Vandekerckhove, J., & Srinivasan, R. (2017) How attention influences perceptual decision making: Single-trial EEG correlates of drift-diffusion model parameters. Journal of Mathematical Psychology, 76, 117-130. 41 | 42 | %% Copyright 2015 Michael D. Nunez 43 | 44 | %This program is free software: you can redistribute it and/or modify 45 | % it under the terms of the GNU General Public License as published by 46 | % the Free Software Foundation, either version 3 of the License, or 47 | % (at your option) any later version. 48 | % 49 | % This program is distributed in the hope that it will be useful, 50 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 51 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 52 | % GNU General Public License for more details. 53 | % 54 | % You should have received a copy of the GNU General Public License 55 | % along with this program. If not, see . 56 | % 57 | %% Record of revisions: 58 | % Date Programmers Description of change 59 | % ==== ================= ===================== 60 | % 5/20/13 Michael Nunez Original code 61 | % 1/1/16 Michael Nunez Defaults better reflect stimuli used in experiments 62 | 63 | %% Arguments 64 | 65 | switch nargin 66 | case 0 67 | imagesize = 600; 68 | barsize = 6; 69 | imagetype = randsample(1:2,1); 70 | jitter = 60; 71 | preload = 0; 72 | graphit = 1; 73 | case 1 74 | barsize = 6; 75 | imagetype = randsample(1:2,1); 76 | jitter = 60; 77 | preload = 0; 78 | graphit = 1; 79 | case 2 80 | imagetype = randsample(1:2,1); 81 | jitter = 60; 82 | preload = 0; 83 | graphit = 1; 84 | case 3 85 | jitter = 60; 86 | preload = 0; 87 | graphit = 1; 88 | case 4 89 | preload = 0; 90 | graphit = 1; 91 | case 5 92 | graphit = 0; 93 | end 94 | 95 | if isempty(imagetype) 96 | imagetype = randsample(1:2,1); 97 | end; 98 | 99 | %% Load Preloaded Bars 100 | if preload 101 | if imagetype == 1 102 | anglefilename = '45'; 103 | else 104 | anglefilename = '135'; 105 | end 106 | if exist(['preloaded/',anglefilename,'_',num2str(jitter),'.mat']) == 2 107 | load(['preloaded/',anglefilename,'_',num2str(jitter),'.mat']); 108 | eval(['loadedbars = m',anglefilename,'j',num2str(jitter),';']); 109 | else 110 | error('These specific bar image maps do not exist in the subdirectory ''preloaded''.'); 111 | end 112 | end 113 | 114 | %% Useful pre-code calculations 115 | halfimage = round(imagesize/2); 116 | halfbar = floor(barsize/2); 117 | halfbarwidth = round(barsize/12); 118 | halfbarlength = floor(barsize/2); 119 | 120 | 121 | %Density calculation 122 | density = 3*barsize; %Density calculation 123 | 124 | %Jitter to radians 125 | jitterrad = jitter*(pi/180); 126 | 127 | %% Circular Display 128 | circlech = ones(imagesize); 129 | xc = 1:imagesize; 130 | yc = 1:imagesize; 131 | z = nan(imagesize); 132 | for i = 1:imagesize 133 | for j = 1:imagesize 134 | z(i,j) = sqrt((xc(i)-halfimage)^2 + (yc(j)-halfimage)^2); 135 | if z(i,j) > round(5*imagesize/12); 136 | circlech(i,j) = 0; 137 | end 138 | end 139 | end 140 | 141 | %% Build a unrotated bar 142 | %patch = zeros(barsize); 143 | patch = zeros(12); 144 | %Contrust bar with length of barsize and width 145 | %2*round(barsize/12) 146 | %patch((halfbar - halfbarlength+1):(halfbar + halfbarlength),(halfbar - halfbarwidth+1):(halfbar + halfbarwidth))= 1; 147 | patch(1:12,6:7) = 1; 148 | 149 | %% Build an oriented bar patch 150 | barimage = zeros(imagesize); 151 | 152 | 153 | [xg,yg]=meshgrid(-halfbar:halfbar,-halfbar:halfbar); 154 | 155 | 156 | %Draw the image with bar patches 157 | for i= 1:(round(imagesize/density)-1) %No longer pixel by pixel (as is in the egg paradigm) 158 | for j = 1:(round(imagesize/density)-1) 159 | %Put some random placement into the bars 160 | randplacex = randi(round(1.5*barsize),1) - round(.75*barsize); 161 | randplacey = randi(round(1.5*barsize),1) - round(.75*barsize); 162 | 163 | %Find the correct indicies 164 | wherey = i*density + randplacey; 165 | wherex = j*density + randplacex; 166 | if all(all(circlech((wherey-halfbar):(wherey+halfbar),(wherex-halfbar):(wherex+halfbar)))) 167 | 168 | %Here we insert our rand jitter to the figure angles 169 | randjitter = (2*rand(1)-1)*jitterrad; 170 | 171 | %Radians to angles 172 | randjitter = randjitter*(180/pi); 173 | if imagetype == 1 174 | figangle(i,j) = -45 + randjitter; 175 | elseif imagetype == 2 176 | figangle(i,j) = 45 + randjitter; 177 | end 178 | 179 | if ~preload 180 | %Draw the figure-bar 181 | rotpatch = imrotate(patch, figangle(i,j)); 182 | else 183 | %Draw from prerotated images 184 | randindex = randi(length(loadedbars),1); 185 | rotpatch = loadedbars{randindex}; 186 | end 187 | 188 | %Find size of rotpatch 189 | [row column] = size(rotpatch); 190 | 191 | %Place the figure-bar into the bar patch 192 | barimage((wherey-floor(row/2)+1):(wherey+ceil(row/2)),(wherex-floor(column/2)+1):(wherex+ceil(row/2))) = rotpatch; 193 | end 194 | end 195 | end 196 | 197 | barimage(barimage == 1) = .5; 198 | 199 | %% Graph the image 200 | 201 | if graphit == 1 202 | %figure; 203 | imagesc(barimage,[0 1]); 204 | colormap(gray); 205 | screensize = get(0,'ScreenSize'); 206 | set(gcf,'Position', [1 1 screensize(3) screensize(4)]); 207 | axis('square'); 208 | end -------------------------------------------------------------------------------- /nunez_etal2017_mathpsych/visual_stimuli/pdmexp3_public.m: -------------------------------------------------------------------------------- 1 | function pdmexp3_public(varargin) 2 | %% README 3 | 4 | %THIS PROGRAM WILL NOT WORK WITHOUT SPECIFIC CHANGES FOR YOUR SOFTWARE AND HARDWARE 5 | 6 | %We used this MATLAB program in a visual decision making experiment for the 7 | %two papers below. This program serves as examples of steady-state visual evoked 8 | %potential (SSVEP) stimuli. See the two papers for a description of the 9 | %experimental paradigm 10 | % 11 | %We ran this on a Windows XP machine with Psychtoolbox 2 with a particular 12 | %setup for auditory experiments. Subjects used a Cedrus button box to give responses. 13 | %http://psychtoolbox.org/ 14 | %http://cedrus.com/responsepads/rb530.htm 15 | 16 | %In order to replicate this experimental stimulus, you may need to port 17 | %this code to Psychtoolbox 3 on Linux with a good video card, and then test 18 | %the frequency of the "photocell" squares in each corner of the screen to 19 | %ensure the intended frequencies of the flickering stimuli and thus possible SSVEP 20 | %responses (SSVEPs could also depend upon subject behavior, brain state, 21 | %contrast, luminance, etc. and must be tested with preliminary studies) 22 | 23 | %% Possible Citations 24 | % Nunez, M. D., Srinivasan, R., & Vandekerckhove, J. (2015). Individual differences in attention influence perceptual decision making. Frontiers in psychology, 8. 25 | % Nunez, M. D., Vandekerckhove, J., & Srinivasan, R. (2017) How attention influences perceptual decision making: Single-trial EEG correlates of drift-diffusion model parameters. Journal of Mathematical Psychology, 76, 117-130. 26 | 27 | %% Copyright 2015 Michael D. Nunez 28 | 29 | %This program is free software: you can redistribute it and/or modify 30 | % it under the terms of the GNU General Public License as published by 31 | % the Free Software Foundation, either version 3 of the License, or 32 | % (at your option) any later version. 33 | % 34 | % This program is distributed in the hope that it will be useful, 35 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 36 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 37 | % GNU General Public License for more details. 38 | % 39 | % You should have received a copy of the GNU General Public License 40 | % along with this program. If not, see . 41 | % 42 | %% Record of revisions: 43 | % Date Programmers Description of change 44 | % ==== ================= ===================== 45 | % 12/?/2013 Michael Nunez Original code 46 | % 12/27/2015 Michael Nunez Public comments 47 | 48 | %% Code 49 | if nargin == 1 50 | rundemo = 1; 51 | elseif nargin > 1 52 | error('Too many function inputs.'); 53 | else 54 | rundemo = 0; 55 | end 56 | 57 | PTB2; 58 | 59 | %Inputs Prompt and Output Setup 60 | %Experimenter Prompt 61 | Screenres = get(0,'Screensize'); 62 | 63 | prompt1={'Subject Number (must begin with letter):','Session Number:','Window Pointer:',... 64 | 'Screen Length (x-axis):','Screen Width (y-axis):','Refresh Rate (fps):','Stimulus Frequencies (Hz <= Refresh Rate):',... 65 | 'Noise Frequency:','Number of Trials:','Trials per Block:','Jitter Levels:','Noise Levels:','Cedrus Port [COM2 ...] or null'}; 66 | if rundemo 67 | def1={'SZZ_test','0','0',num2str(Screenres(3)),num2str(Screenres(4)),'120','15','8','36','90','[30 40 50]','[.3 .45 .6]',''}; 68 | studytitle='PDM DEMO'; 69 | else 70 | def1={'SZZ_test','1','0',num2str(Screenres(3)),num2str(Screenres(4)),'120','15','8','540','90','[60 70 80]','[.3 .45 .6]',''}; 71 | studytitle='PDM Experiment 3'; 72 | end 73 | 74 | lineNo=1; 75 | answer=inputdlg(prompt1,studytitle,lineNo,def1); 76 | %Subject Number 77 | subnum = answer{1}; 78 | %ExpSession Number 79 | sesnum = str2num(answer{2}); 80 | output.sesnum = sesnum; 81 | %Window Pointer / 'Home Screen'. 0 - the primary monitor; 1 - the secondary monitor. 82 | whichScreen = str2num(answer{3}); 83 | %Screen resolution on the x-axis 84 | xres = str2num(answer{4}); 85 | output.xres = xres; 86 | %Screen resolution on the y-axis 87 | yres = str2num(answer{5}); 88 | output.yres = yres; 89 | %This should be the same as the Refresh Rate shown in the Display 90 | %Properties on the computer. Always check before running the experiment to 91 | %match flicker frequency. 92 | %This code is currently set up to only handle multiples of 60 fps. 93 | refrate = str2num(answer{6}); 94 | realrefrate = Screen(0,'FrameRate'); 95 | if refrate ~= Screen(0,'FrameRate') 96 | error(['The real screen refresh rate is set to ',num2str(realrefrate),... 97 | 'Hz while the proposed screen refresh rate is ',num2str(refrate),'Hz.']); 98 | end 99 | output.refrate = refrate; 100 | %Stimulus frequencies(Hz) 101 | flickfreqs = str2num(answer{7}); 102 | output.flickfreqs = flickfreqs; 103 | if ~all(round(refrate./flickfreqs) == (refrate./flickfreqs)) 104 | %error('The stimulus frequencies should be divisors of the refresh rate.'); 105 | end 106 | %Noise frequency (Hz) 107 | noisehz = str2num(answer{8}); 108 | output.noisehz = noisehz; 109 | if round(refrate/noisehz) ~= refrate/noisehz 110 | error('The noise frequency should be divisor of the refresh rate.'); 111 | end 112 | %Number of Trials 113 | trialnum = str2num(answer{9}); 114 | 115 | %Trials per block 116 | output.tperb = str2num(answer{10}); 117 | if output.tperb > trialnum 118 | output.tperb = trialnum; 119 | end 120 | block = 1; 121 | %Jitter levels 122 | jitterlvls = str2num(answer{11}); 123 | output.jitterlvls = jitterlvls; 124 | 125 | %noise levels 126 | noiselvls = str2num(answer{12}); 127 | output.noiselvls = noiselvls; 128 | 129 | %Number of trials should be a multiple of the number of cells 130 | ncells = length(jitterlvls)*length(noiselvls); 131 | if round(trialnum/ncells) ~= trialnum/ncells 132 | error(['The number of trials should be a multiple of ',num2str(ncells)]); 133 | end 134 | 135 | %Cedrus Handle 136 | cport = answer{13}; 137 | chandle = CedrusResponseBox('Open',cport); 138 | 139 | %% Code 140 | %Subject Prompt 141 | prompt2={'What is your gender? (''f'' or ''m'')',... 142 | 'Age:','Do you consider yourself right handed, left handed, or both? (''r'',''l'', or''b'')',... 143 | 'Do you have near 20/20 vision or is your vision corrected to near 20/20? (''y'' or ''n'')',... 144 | 'Do you have any personal or family history of epilepsy? (''y'' or ''n'')' 145 | }; 146 | demographtitle='Subject Demographics'; 147 | lineNo=1; 148 | subdemo=inputdlg(prompt2,demographtitle,lineNo); 149 | switch subdemo{5} 150 | case 'n' 151 | otherwise 152 | error('You have indicated that you have a personal or family history of epilepsy. This experiment involves a fast flickering image. It is recommended that you NOT participate in this study due to a possible risk of seizure. Please discuss your options with the experimenters.'); 153 | end 154 | output.gender = subdemo{1}; 155 | output.age = str2num(subdemo{2}); 156 | output.hand = subdemo{3}; 157 | output.vision = subdemo{4}; 158 | 159 | %Get date and time that the session begins 160 | output.date = date; 161 | output.start_time = clock; 162 | 163 | %number of rows and columns of image 164 | nCols = 600; 165 | nRows = 600; 166 | 167 | %Initialize estimated accuracy vector, for speed 168 | estcorrect = zeros(1,trialnum); 169 | 170 | %Keyboard keypress variables 171 | advancechar = ' '; 172 | escapechar = 27; 173 | 174 | %Lower bound to wait between trials, in seconds 175 | lboundwait = 2.5; 176 | 177 | 178 | %%%%%THE FOLLOWING IS UNNECESSARY%%%%%% 179 | % Initialize the sound driver: 180 | InitializePsychSound; 181 | 182 | %Load sounds 183 | [ygood, Fsgood] = wavread('chimes.wav'); %Example sounds should be changed to different sound files 184 | [ybad, Fsbad ] = wavread('critical.wav'); 185 | ygood = ygood'; 186 | ybad = ybad'; 187 | 188 | % Open the default audio device [], with default mode [] (==Only playback), 189 | % and a required latencyclass of zero 0 == no low-latency mode, as well as 190 | % a frequency of freq and nrchannels sound channels. 191 | % This returns a handle to the audio device: 192 | goodhand = PsychPortAudio('Open', [], [], 0, Fsgood, size(ygood,1)); 193 | badhand = PsychPortAudio('Open', [], [], 0, Fsbad, size(ybad,1)); 194 | 195 | % Fill the audio playback buffers with the audio data 196 | PsychPortAudio('FillBuffer', goodhand , ygood); 197 | PsychPortAudio('FillBuffer', badhand, ybad); 198 | %%%%%%%%%USE THIS INSTEAD%%%%%% 199 | 200 | %[ygood, Fsgood] = audioread('chimes.wav'); 201 | 202 | %[ybad, Fsbad ] = audioread('critical.wav'); 203 | 204 | %goodsound = audioplayer(ygood,Fsgood); 205 | %badsound = audioplayer(ybad,Fsbad); 206 | %%%%%%%% 207 | 208 | %Flush Cedrus Events 209 | CedrusResponseBox('FlushEvents',chandle); 210 | 211 | 212 | %The following TRY, CATCH, END statement ends psychtoolbox if an error 213 | %occurs 214 | try 215 | %opens home window 216 | [wptr windowRect]= Screen(whichScreen ,'OpenWindow',[255*sqrt(.5) 255*sqrt(.5) 255*sqrt(.5)]); 217 | 218 | %sets size of gabor field that will be pasted onto Screen 219 | imageRect=SetRect(0,0,nCols,nRows); 220 | destRect=CenterRect(imageRect,windowRect); 221 | 222 | %Define photocell placement 223 | PhotoSize = 75; 224 | photorect = [0 0 PhotoSize PhotoSize]; 225 | %Photo{4} = [0 0 PhotoSize PhotoSize]; 226 | %Photo{3} = [xres-PhotoSize 0 xres PhotoSize]; 227 | Photo{2} = [xres-PhotoSize yres-PhotoSize xres yres]; 228 | Photo{1} = [0 yres-PhotoSize PhotoSize yres]; 229 | 230 | %Creates windows for photocells 231 | owPCWhite = Screen(wptr, 'OpenOffScreenWindow', [255*sqrt(.5) 255*sqrt(.5) 255*sqrt(.5)], [0 0 PhotoSize PhotoSize]); 232 | Screen(owPCWhite,'FillRect',[255 255 255],[0 0 PhotoSize PhotoSize]); 233 | owPCBlack = Screen(wptr, 'OpenOffScreenWindow', [255*sqrt(.5) 255*sqrt(.5) 255*sqrt(.5)], [0 0 PhotoSize PhotoSize]); 234 | Screen(owPCBlack,'FillRect',[0 0 0],[0 0 PhotoSize PhotoSize]); 235 | 236 | %Create cross 237 | CrossWidth = 4; 238 | crossx1 = (round(nRows/2 - 3*CrossWidth/2):round(nRows/2 + 3*CrossWidth/2)); 239 | crossy1 = (round((nCols)/2 - CrossWidth/2):round((nCols)/2 + CrossWidth/2)); 240 | crossx2 = (round(nRows/2 - CrossWidth/2):round(nRows/2 + CrossWidth/2)); 241 | crossy2 = (round((nCols)/2 - 3*CrossWidth/2):round((nCols)/2 + 3*CrossWidth/2)); 242 | 243 | %Create white cross for flickering image 244 | whitecross = ones(600)*255*sqrt(.5); %Approximately accounts for monitor gamma 245 | whitecross(crossx1,crossy1) = ones(length(crossx1),length(crossy1))*255; 246 | whitecross(crossx2,crossy2) = ones(length(crossx2),length(crossy2))*255; 247 | 248 | %Creates window for white fixation cross with black photocells 249 | ow3 = Screen(wptr,'OpenOffScreenWindow',[255*sqrt(.5) 255*sqrt(.5) 255*sqrt(.5)]); 250 | Screen(ow3,'PutImage',whitecross,destRect); 251 | Screen(ow3,'FillRect',[1 1 1],Photo{1}); 252 | Screen(ow3,'FillRect',[1 1 1],Photo{2}); 253 | %Screen(ow3,'FillRect',[1 1 1],Photo{3}); 254 | %Screen(ow3,'FillRect',[1 1 1],Photo{4}); 255 | 256 | %Black cross for beginning of stimulus 257 | blackcross = whitecross; 258 | blackcross(whitecross == 255) = 1; 259 | 260 | %Creates window for black fixation cross with black photocells 261 | ow2 = Screen(wptr,'OpenOffScreenWindow',[255*sqrt(.5) 255*sqrt(.5) 255*sqrt(.5)]); 262 | Screen(ow2,'PutImage',blackcross,destRect); 263 | Screen(ow2,'FillRect',[1 1 1],Photo{1}); 264 | Screen(ow2,'FillRect',[1 1 1],Photo{2}); 265 | %Screen(ow2,'FillRect',[1 1 1],Photo{3}); 266 | %Screen(ow2,'FillRect',[1 1 1],Photo{4}); 267 | 268 | %Creates a window of a blank gray screen with black photocells 269 | ow4 = Screen(wptr,'OpenOffScreenWindow',[255*sqrt(.5) 255*sqrt(.5) 255*sqrt(.5)]); 270 | Screen(ow4,'FillRect', 255*sqrt(.5), [0 0 xres yres]); 271 | Screen(ow4,'FillRect',[1 1 1],Photo{1}); 272 | Screen(ow4,'FillRect',[1 1 1],Photo{2}); 273 | %Screen(ow4,'FillRect',[1 1 1],Photo{3}); 274 | %Screen(ow4,'FillRect',[1 1 1],Photo{4}); 275 | 276 | %This matrix defines the flicker frequencies for our image 277 | stimflic = zeros( length(flickfreqs) , (round(.75*refrate)+ceil(refrate*2)) ); 278 | for j=1:length(flickfreqs) 279 | particflick = []; 280 | for i=1:ceil(flickfreqs(j)*2) 281 | particflick = [particflick 2*ones(1,ceil(refrate/(2*flickfreqs(j)))) ones(1,floor(refrate/(2*flickfreqs(j))))]; 282 | end 283 | stimflic(j,:) = [ones(1,round(.75*refrate)) particflick(1:ceil(refrate*2))]; %Does not display flickering bars until 750ms into stimulus 284 | end 285 | 286 | %This vector defines the noise frequency for our image 287 | noiseflic = []; 288 | for i=1:ceil(noisehz*3) 289 | noiseflic = [noiseflic 1 zeros(1,(round(refrate/noisehz)- 1))]; 290 | end 291 | noiseflic = noiseflic(1:ceil(refrate*3)); 292 | 293 | %Set seed based on the time. Backwards compatible with older MATLAB 294 | %versions 295 | output.seed = sum(100*clock); 296 | rand('state',output.seed); 297 | 298 | %Randomize frequency display 299 | whichfreq = []; 300 | for freq=1:length(flickfreqs) 301 | whichfreq = [whichfreq freq*ones(1,ceil(trialnum/length(flickfreqs)))]; 302 | end 303 | whichfreq = whichfreq(randperm(length(whichfreq))); 304 | output.whichfreq = whichfreq; 305 | 306 | %Define jitter and noise vectors, ensure even cell counts 307 | jitnoise = []; 308 | for j=1:ncells 309 | jitnoise = [jitnoise ones(1,trialnum/ncells)*j]; 310 | end 311 | jitnoise = jitnoise(randperm(length(jitnoise))); 312 | jittervec = zeros(1,length(jitnoise)); 313 | noisevec = zeros(1,length(jitnoise)); 314 | cellmat = reshape(1:ncells,length(jitterlvls),length(noiselvls)); 315 | for j=1:length(jitterlvls) 316 | for k=1:length(noiselvls) 317 | jittervec(jitnoise == cellmat(j,k)) = jitterlvls(j); 318 | noisevec(jitnoise == cellmat(j,k)) = noiselvls(k); 319 | end 320 | end 321 | for j=1:length(noiselvls) 322 | end 323 | output.jittervec = jittervec; 324 | output.noisevec = noisevec; 325 | 326 | %Get vector of jitter values 327 | directions = [ones(1,round(trialnum/2)) ones(1,round(trialnum/2))*2]; 328 | directions = directions(randperm(length(directions))); 329 | output.directions = directions; 330 | 331 | cut = 0; %Counter for ESC 332 | 333 | %Creates windows for fullimage 334 | for h=1:2 335 | for d=1:ceil(noisehz*3) %3 seconds of display 336 | owf{h,d} = Screen(wptr,'OpenOffScreenWindow',[255*sqrt(.5) 255*sqrt(.5) 255*sqrt(.5)]); 337 | %Place bar photocells in these offscreen windows 338 | if h==1 339 | Screen(owf{h,d},'FillRect',[1 1 1],Photo{2}); 340 | else 341 | Screen(owf{h,d},'FillRect',[255 255 255],Photo{2}); 342 | end 343 | end 344 | end 345 | 346 | %Set rush loop prioritys to Max 347 | priorityLevel=MaxPriority(whichScreen,'WaitBlanking'); 348 | 349 | %Calculate the number of frames in a cycle of an image flicker 350 | numCycleFrames1 = round(.75*refrate) + (round(refrate)+round(refrate*rand(1,trialnum))); 351 | numCycleFrames2 = round(.5*refrate); 352 | 353 | %Output stimulus display time in milliseconds 354 | output.stimtime = (numCycleFrames1./60)*1000; 355 | 356 | %Rush Loop a: Black fixation cross for 750 ms 357 | rushloopa = { 358 | 'Screen(''CopyWindow'', ow2, wptr);' 359 | 'for frames = 1:round(.75*refrate);' 360 | 'Screen(wptr,''WaitBlanking'');' 361 | 'end;' 362 | }; 363 | 364 | %Rush Loop 1: Noise for 750ms, noise with bars for 1000ms - 2000ms, accept responses 365 | rushloop1 = { 366 | 'Screen(wptr,''WaitBlanking'');' 367 | 'for i = 1:numCycleFrames1(trials);' 368 | 'if noiseflic(i);' 369 | 'previousnoise = previousnoise + 1;' 370 | 'Screen(''CopyWindow'',owf{stimflic(whichfreq(trials),i),previousnoise},wptr);' 371 | 'Screen(''CopyWindow'',owPCWhite,wptr,photorect,Photo{1});' 372 | 'else;' 373 | 'Screen(''CopyWindow'',owf{stimflic(whichfreq(trials),i),previousnoise},wptr);' 374 | 'Screen(''CopyWindow'',owPCBlack,wptr,photorect,Photo{1});' 375 | 'end;' 376 | 'Screen(wptr,''WaitBlanking'');' 377 | 'end;' 378 | }; 379 | 380 | %Rush Loop 2: Keep displaying black fixation cross (only) for 250ms 381 | rushloop2 = { 382 | 'Screen(''CopyWindow'', ow2, wptr);' 383 | 'for frames = 1:round(refrate/4);' 384 | 'Screen(wptr,''WaitBlanking'');' 385 | 'end;' 386 | }; 387 | 388 | Screen(wptr,'TextFont','Arial'); 389 | Screen(wptr,'TextSize',18); 390 | ShowCursor(0); % arrow cursor 391 | sessiontext = 'Loading images...'; 392 | sessiontext2 = 'The experiment will begin shortly'; 393 | sessiontext3 = 'The experiment has started! Good luck!'; 394 | 395 | Screen('CopyWindow', ow4, wptr); 396 | HideCursor; 397 | Screen(wptr, 'DrawText',sessiontext,(xres - length(sessiontext)*9)/2,yres/2,[1 1 1]); 398 | 399 | 400 | %Load first block's bar field images 401 | for b=1:output.tperb 402 | barimage(:,:,b) = makebardirec(600,6,directions(b),jittervec(b),0); %Get the gabor image color data using makebarimage.m 403 | barimage(barimage == .5) = .15; 404 | end 405 | 406 | %Display second text screen 407 | Screen('CopyWindow', ow4, wptr); 408 | Screen(wptr, 'DrawText',sessiontext2,(xres - length(sessiontext2)*9)/2,yres/2,[1 1 1]); 409 | 410 | %Wait for spacebar 411 | FlushEvents('keyDown'); 412 | [char,when] = GetChar; %Wait for keypress to continue 413 | notspace=1; 414 | while notspace 415 | switch char 416 | case ' ' 417 | notspace =0; 418 | otherwise 419 | [char,when] = GetChar; %Wait for keypress to continue 420 | notspace =1; 421 | end 422 | end 423 | 424 | %Display third text screen 425 | Screen('CopyWindow', ow4, wptr); 426 | Screen(wptr, 'DrawText',sessiontext3,(xres - length(sessiontext3)*9)/2,yres/2,[1 1 1]); 427 | 428 | %Initialize timer 429 | tic; 430 | 431 | for trials = 1:trialnum 432 | if ~cut %ESC key track 433 | 434 | imageset = cell(2,ceil(noisehz)); 435 | trialind = trials-(block-1)*output.tperb; 436 | for f=1:ceil(noisehz) 437 | %Create image of 5% contrast (defined as contrast ratio 438 | %whitest/darkest) 439 | imageset{1,f} = (.5 - (noisevec(trials)/2)) + noisevec(trials)*rand(600); 440 | imageset{2,f} = barimage(:,:,trialind) + imageset{1,f}; 441 | %transformation for barimage color values, takes into account 442 | %monitor gamma 443 | imageset{1,f} = 255*sqrt(imageset{1,f}); %The square root is in order to account for monitor gamma. That is, the monitor approximately squares the input stimulus color value 444 | imageset{2,f} = 255*sqrt(imageset{2,f}); 445 | %Create black cross ontop of fullimage 446 | imageset{1,f}(crossx1,crossy1) = ones(length(crossx1),length(crossy1)); 447 | imageset{1,f}(crossx2,crossy2) = ones(length(crossx2),length(crossy2)); 448 | imageset{2,f}(crossx1,crossy1) = ones(length(crossx1),length(crossy1)); 449 | imageset{2,f}(crossx2,crossy2) = ones(length(crossx2),length(crossy2)); 450 | end 451 | 452 | %Creates windows for fullimage 453 | for q=1:3 %3 seconds of frames 454 | for d=1:ceil(noisehz) 455 | frameind = d + noisehz*(q-1); 456 | Screen(owf{1,frameind},'PutImage',imageset{1,d},destRect); 457 | Screen(owf{2,frameind},'PutImage',imageset{2,d},destRect); 458 | end 459 | end 460 | 461 | %Initialize previous noise 462 | previousnoise = 0; 463 | 464 | %Wait at least lboundwait seconds between trials 465 | output.elapsedtime(trials) = toc; 466 | if output.elapsedtime(trials) < lboundwait 467 | pause(lboundwait-output.elapsedtime(trials)); 468 | end 469 | output.fixedtime(trials) = toc; 470 | 471 | CedrusResponseBox('FlushEvents',chandle); 472 | 473 | %Display rush loops 474 | Rush(rushloopa,priorityLevel); 475 | Rush(rushloop1,priorityLevel); 476 | Rush(rushloop2,priorityLevel); 477 | 478 | %Timer to calculate time between the last trial and the next 479 | tic; 480 | 481 | %Show the blank gray Screen 482 | Screen('CopyWindow', ow4, wptr); 483 | Screen(wptr,'WaitBlanking'); 484 | 485 | %Play feedback sound 486 | evt = CedrusResponseBox('GetButtons',chandle); 487 | if isempty(evt) 488 | correct = 0; 489 | elseif (evt.button == 5 && directions(trials) == 1) || ... 490 | (evt.button == 3 && directions(trials) == 2) 491 | correct = 1; 492 | else 493 | correct = 0; 494 | end 495 | estcorrect(trials) = correct; 496 | if correct 497 | %play(goodsound,[1 length(ygood)]); 498 | PsychPortAudio('Start', goodhand , 1, 0, 1); 499 | 500 | else 501 | %play(badsound,[1 length(ybad)]); 502 | PsychPortAudio('Start', badhand , 1, 0, 1); 503 | end 504 | 505 | if ~cut 506 | if trials == trialnum 507 | %Show ending screen for 5 seconds 508 | percorrect = sum(estcorrect((trials-output.tperb+1):trials))/output.tperb; 509 | endtext = ['Done! ',... 510 | num2str(round(percorrect*100)),'% correct this block. Thank you for participating!']; 511 | Screen('CopyWindow', ow4, wptr,[0 0 xres yres]); 512 | Screen(wptr, 'DrawText',endtext,(xres - length(endtext)*9)/2,yres/2,[1 1 1]); 513 | %Wait for spacebar to end program 514 | FlushEvents('keyDown'); 515 | [char,~] = GetChar; %Wait for keypress to continue 516 | notspace=1; 517 | while notspace 518 | switch char 519 | case advancechar 520 | notspace =0; 521 | otherwise 522 | [char,~] = GetChar; %Wait for keypress to continue 523 | notspace =1; 524 | end 525 | end 526 | elseif trials/output.tperb == round(trials/output.tperb) 527 | %Take a break every 'output.tperb' trials and show ending Screens 528 | percorrect = sum(estcorrect((trials-output.tperb+1):trials))/output.tperb; 529 | trialtext = ['Block ',num2str(block),' complete! ',... 530 | num2str(round(percorrect*100)),'% correct this block. You may now take a break!']; 531 | block = block + 1; 532 | trialtext2 = 'Please wait for the experimenter'; 533 | Screen('CopyWindow', ow4, wptr,[0 0 xres yres]); 534 | Screen(wptr, 'DrawText',trialtext,(xres - length(trialtext)*9)/2,yres/2,[1 1 1]); 535 | Screen(wptr, 'DrawText',trialtext2,(xres - length(trialtext2)*9)/2,yres/2 + 32,[1 1 1]); 536 | 537 | %Load first block's images 538 | for b=1:output.tperb %Load first block's images 539 | barimage(:,:,b) = makebardirec(600,6,directions(b+trials),jittervec(b+trials),1); %Get the gabor image color data using makebarimage.m 540 | barimage(barimage == .5) = .15; 541 | end 542 | 543 | %Wait for spacebar 544 | FlushEvents('keyDown'); 545 | [char,~] = GetChar; %Wait for keypress to continue 546 | notspace=1; 547 | while notspace 548 | switch char 549 | case advancechar 550 | notspace =0; 551 | Screen('CopyWindow', ow4, wptr); 552 | Screen(wptr, 'DrawText',sessiontext3,(xres - length(sessiontext3)*9)/2,yres/2,[1 1 1]); 553 | %Timer to calculate time between the last trial and the next 554 | tic; 555 | case escapechar %Escape from experiment and save current data (for experimenter) 556 | notspace =0; 557 | RestoreScreen(whichScreen); 558 | ShowCursor; 559 | Screen('Closeall'); 560 | output.ESC_time = clock; 561 | output.estcorrect = estcorrect; 562 | eval([subnum,'_ExpSession',num2str(sesnum),'=output;']); 563 | if ~exist('data','dir') 564 | mkdir('data'); 565 | end 566 | eval(['save(''data/',subnum,'_Exp_',num2str(output.sesnum),'_',date,'.mat'',''-struct'', ''',subnum,'_ExpSession',num2str(sesnum),''');']); 567 | warning on all; 568 | CedrusResponseBox('Close',chandle); 569 | PsychPortAudio('Close', goodhand); 570 | PsychPortAudio('Close', badhand); 571 | return 572 | otherwise 573 | [char,when] = GetChar; %Wait for keypress to continue 574 | notspace =1; 575 | end 576 | end 577 | end 578 | 579 | end 580 | end 581 | end 582 | catch me 583 | RestoreScreen(whichScreen); 584 | ShowCursor; 585 | Screen('Closeall'); 586 | output.error_time = clock; 587 | output.estcorrect = estcorrect; 588 | eval([subnum,'_ExpSession',num2str(sesnum),'=output;']); 589 | if ~exist('data','dir') 590 | mkdir('data'); 591 | end 592 | eval(['save(''data/',subnum,'_Exp_',num2str(output.sesnum),'_',date,'.mat'',''-struct'', ''',subnum,'_ExpSession',num2str(sesnum),''');']); 593 | CedrusResponseBox('Close',chandle); 594 | PsychPortAudio('Close', goodhand); 595 | PsychPortAudio('Close', badhand); 596 | rethrow(me); %rethrow reproduces the original error, stored in the object 'me' 597 | end 598 | 599 | RestoreScreen(whichScreen); 600 | ShowCursor; 601 | Screen('Closeall'); 602 | 603 | %Output time finished 604 | output.finish_time = clock; 605 | 606 | %Estimated accuracy 607 | output.estcorrect = estcorrect; 608 | 609 | eval([subnum,'_ExpSession',num2str(sesnum),'=output;']); 610 | if ~exist('data','dir') 611 | mkdir('data'); 612 | end 613 | eval(['save(''data/',subnum,'_Exp_',num2str(output.sesnum),'_',date,'.mat'',''-struct'', ''',subnum,'_ExpSession',num2str(sesnum),''');']); 614 | warning on all; 615 | CedrusResponseBox('Close',chandle); 616 | %PsychPortAudio('Close', goodhand); 617 | %PsychPortAudio('Close', badhand); 618 | 619 | 620 | --------------------------------------------------------------------------------