diff --git a/.admin/tapas_find_dependencies.m b/.admin/tapas_find_dependencies.m
new file mode 100644
index 00000000..032638de
--- /dev/null
+++ b/.admin/tapas_find_dependencies.m
@@ -0,0 +1,61 @@
+function tapas_find_dependencies()
+ % function finding dependencies of tapas toolboxes
+ %
+ %
+ % (C) 2020 Matthias Müller-Schrader TNU-IBT Universität Zürich & ETH Zürich
+ %
+
+ % parameters
+ exclDir = {'.','..','.admin','.git','misc'};
+ useAg = false; % otherwise use ack
+ ignoreInds = [7,6]; %Ignore the first and last indices (strange output from ag)
+ printCommands = true;
+
+ cutInds = @(x) x(ignoreInds(1)+1:end - ignoreInds(2) - 1);
+ f = mfilename('fullpath');
+ [tdir, ~, ~] = fileparts(f);
+ pdir = tdir(1:end-7); % '/.admin' -> is tapas folder (without last '/')
+ curr_dir = pwd;
+ cd(pdir);
+ dr = dir(pdir);
+ dr = dr([dr.isdir]); % only folders
+
+ dr = dr(~ismember({dr.name},exclDir));
+
+ nDir = numel(dr);
+ needAlso = cell(1,nDir);
+ for iDir = 1:nDir
+ fprintf(1,'==========%s===============\n',dr(iDir).name)
+ drPath = strcat(pdir,filesep,dr(iDir).name);
+ functs = tapas_get_functions_in_sub_dirs(drPath,false);
+ for iFun = 1:numel(functs)
+ funct = functs{iFun};
+ funct = strrep(funct,'.m','');
+ if useAg
+ cmd_s = 'ag';
+ else
+ cmd_s = 'ack';
+ end
+ cmd = sprintf('%s %s -l -w --ignore-dir %s',cmd_s,funct,dr(iDir).name);
+ % --range-start=''^sub \\w+''
+ [stat,ret] = system(cmd);
+ if stat && isempty(ret)
+ continue;
+ end
+ %disp(ret)
+ retc = split(ret,newline);
+ if useAg
+ retc = cellfun(cutInds,retc,'UniformOutput',false);
+ end
+ ise = cellfun(@isempty,retc);
+ if all(ise)
+ continue;
+ end
+ retc = retc(~ise);
+ fprintf(1,'%s\n',funct)
+ fprintf(1,'\t%s\n',retc{:});
+ end
+ end
+
+
+ cd(curr_dir);
diff --git a/.admin/tapas_get_functions_in_sub_dirs.m b/.admin/tapas_get_functions_in_sub_dirs.m
new file mode 100644
index 00000000..159183e0
--- /dev/null
+++ b/.admin/tapas_get_functions_in_sub_dirs.m
@@ -0,0 +1,47 @@
+function functs = tapas_get_functions_in_sub_dirs(parDir,getFullPath)
+ % Function returning the names of matlab functions in dir and subdirs.
+ %
+ % IN
+ % parDir default: pwd
+ % Starting here.
+ % getFullPath default: true
+ % Return full path to file (otherwise just function name).
+ %
+ % OUT
+ % functs
+ % Function names/paths in cell array
+ %
+ % Author(s): Matthias Mueller-Schrader
+ % (c) Institute for Biomedical Engineering, ETH and University of Zurich, Switzerland
+
+ % TODO: Include also .p, .mlx and .mex files
+
+
+ if nargin < 1 || isempty(parDir)
+ parDir = pwd;
+ end
+
+ if nargin < 2 || isempty(getFullPath)
+ getFullPath = true;
+ end
+
+ ret = dir(parDir);
+ names = {ret.name};
+ isdirs = [ret.isdir];
+ dirnames = names(isdirs);
+ dirnames(strcmp(dirnames,'.')|strcmp(dirnames,'..')) = []; % get rid of '.' and '..' in unix.
+ mfilenames = names(endsWith(names,'.m'));
+ if ~getFullPath
+ mfilenames = replace(mfilenames,'.m','');
+ else
+ % = {ret.folder};
+ folders = cell(1,numel(mfilenames));
+ folders(:) = {[ret(1).folder,filesep]};
+ mfilenames = join([folders;mfilenames],'',1);
+ end
+ functs = mfilenames;
+ for iDir = 1:numel(dirnames)
+ functs = [functs,getFunctionsInSubDirs([parDir,filesep,dirnames{iDir}],getFullPath)];%#ok
+ end
+
+
diff --git a/.gitignore b/.gitignore
index eb152edc..06080ae7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,4 +16,5 @@ lib
*.asv
*.DS_Store
.idea
-.idea/*
\ No newline at end of file
+.idea/*
+examples
\ No newline at end of file
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 807ae8d8..7a6b5b07 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,25 @@
# Changelog
TAPAS toolbox
+## [4.0.0] 2020-09-09
+
+### Added
+- [ceode](ceode/README.md): Toolbox to integrate delay differential equations (DDEs) underlying convolution based Dynamic Causal Models for ERPs.
+- task/FDT: Filter Detection Task [version 0.2.2](task/FDT/README.md)
+- [citation information](CITATION.cff)
+
+### Changed
+- rDCM: [version v1.2](rDCM/CHANGELOG.md)
+- HUGE: removed deprecated functions
+- external toolboxes are now managed as matlab packages
+
+### Fixed
+- Fixed name collision issue due to mcmcdiag toolbox (see [issue 106](https://github.com/translationalneuromodeling/tapas/issues/106))
+
+### Known issues
+- h2gf (beta): demo script currently does not work
+
+
## [3.3.0] 2020-07-17
### Added
@@ -12,7 +31,7 @@ TAPAS toolbox
### Changed
- HGF: v6.0 released
- SERIA: The constraints matrix is now automatically plot by
- tapas\_sem_\display_posterior.m
+ tapas_sem_display_posterior.m
- SERIA: Python code is now updated to python 3.7 and the requirement file
now uses the latest libraries (numpy, scipy, cython).
- SERIA: Posterior plots includes fits of the complete group.
@@ -78,11 +97,11 @@ TAPAS toolbox
## [3.0.0] 2018-09-09
### Added
-- tapas\_get\_tapas\_revision.m outputs the branch and hash of the repository.
+- tapas_get_tapas_revision.m outputs the branch and hash of the repository.
- Revision is printed when initiliazing tapas.
- Contributor License Agreement (CLA) file
- CONTRIBUTING.md explaining coding and style guidelines, signing procedure for CLA file
-- Include the function tapas\_get\_current\_version.m.
+- Include the function tapas_get_current_version.m.
- Implements download of example data from the server using
tapas_download_example_data.
- Now there is log file that list the versions of tapas, the download link
@@ -97,7 +116,7 @@ TAPAS toolbox
### Changed
- README.md to include reference to CONTRIBUTING.md and explanation of CLA
- Dropped 4 digits versioning for 3.
-- The version of tapas is now read from misc/log\_tapas.txt. It is the first
+- The version of tapas is now read from misc/log_tapas.txt. It is the first
line of this file.
- Updated the documentation of SEM.
- Updated SEM to include hierarchical models for inference.
diff --git a/CITATION.cff b/CITATION.cff
new file mode 100644
index 00000000..81e02580
--- /dev/null
+++ b/CITATION.cff
@@ -0,0 +1,27 @@
+cff-version: 1.1.0
+message: If you use this software, please cite it as below.
+authors:
+ - family-names: Aponte
+ given-names: Eduardo
+ - family-names: Brodersen
+ given-names: Kay
+ - family-names: Frässle
+ given-names: Stephan
+ - family-names: Harrison
+ given-names: Olivia
+ - family-names: Kaspers
+ given-names: Lars
+ - family-names: Mathys
+ given-names: Christoph
+ - family-names: Müller-Schrader
+ given-names: Matthias
+ - family-names: Schöbi
+ given-names: Dario
+ - family-names: Yao
+ given-names: Yu
+title: "TAPAS - Translational Algorithms for Psychiatry-Advancing Science"
+version: 4.0.0
+date-released: 2020-09-09
+repository-code: "https://github.com/translationalneuromodeling/tapas"
+url: "http://www.translationalneuromodeling.org/tapas"
+license: GPL-3.0-or-later
\ No newline at end of file
diff --git a/README.md b/README.md
index 98c7972d..fa478f0d 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
![TAPAS Logo](misc/TapasLogo.png?raw=true "TAPAS Logo")
-*Version 3.3.0*
+*Version 4.4.0*
T A P A S - Translational Algorithms for Psychiatry-Advancing Science.
========================================================================
@@ -21,6 +21,7 @@ psychiatry, computational neurology, and computational psychosomatics.
Currently, TAPAS includes the following packages:
+- [ceode](ceode/README.md): Continuous Extension of ODE methods. A toolbox for robust estimation of convolution based Dynamic Causal Models (DCMs) for evoked responses (ERPs).
- [HGF](HGF/README.md): The Hierarchical Gaussian Filter; Bayesian inference
on computational processes from observed behaviour.
- [HUGE](huge/README.md): Variational Bayesian inversion for hierarchical
@@ -32,6 +33,9 @@ unsupervised generative embedding (HUGE).
- [SEM](sem/README.md): SERIA Model for Eye Movements (saccades and anti-saccades) and Reaction Times.
- [VBLM](VBLM/README.txt): Variational Bayesian Linear Regression.
+And the following tasks:
+- [FDT](task/FDT/README.md): Filter Detection Task.
+
TAPAS is written in MATLAB and distributed as open source code under
the GNU General Public License (GPL, Version 3).
diff --git a/ceode/CHANGELOG.md b/ceode/CHANGELOG.md
new file mode 100644
index 00000000..9713ac09
--- /dev/null
+++ b/ceode/CHANGELOG.md
@@ -0,0 +1,14 @@
+# Changelog
+Toolbox to integrate delay differential equations (DDEs) underlying convolution based Dynamic Causal Models for ERPs.
+The method uses a continuous extension of an Euler method, resulting in a robust and fast integration of the DDE.
+
+
+## [1.0] 25-08-2020
+
+### Added
+- Original release of the ceode toolbox as part of the open-source software package TAPAS.
+- MATLAB functions implementing the necessary steps to use ceode within the functionality of SPM.
+- A brief tutorial tapas_ceode_compare_integrators_erp.m and tapas_ceode_compare_integrators_cmc.m that demonstrate
+the confound of the standard, default integration scheme in SPM12.
+- Documentation has been added in the README.md, and throughout the code
+
diff --git a/ceode/LICENSE b/ceode/LICENSE
new file mode 100644
index 00000000..94a9ed02
--- /dev/null
+++ b/ceode/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/ceode/README.md b/ceode/README.md
new file mode 100644
index 00000000..c8dc4f04
--- /dev/null
+++ b/ceode/README.md
@@ -0,0 +1,211 @@
+TAPAS ceode toolbox
+====================
+
+*Current Version: Release 09.2020*
+
+> Copyright (C) 2020
+> Dario Schöbi
+>
+>
+> Translational Neuromodeling Unit (TNU)
+> Institute for Biomedical Engineering
+> University of Zurich and ETH Zurich
+
+
+Download
+--------
+
+- Please download the latest stable versions of the ceode Toolbox on GitHub as part of the
+ [TAPAS software releases of the TNU](https://github.com/translationalneuromodeling/tapas/releases).
+- The latest bugfixes can be found in the
+ [development branch of TAPAS](https://github.com/translationalneuromodeling/tapas/tree/development)
+ and are announced in the [GitHub Issue Forum](https://github.com/translationalneuromodeling/tapas/issues).
+
+
+Purpose
+-------
+
+The general purpose of this Matlab toolbox is the robust estimation of convolution based Dynamic Causal Models (DCMs) for evoked responses (ERPs).
+Core goals for the toolbox are: *flexibility*, *robustness*, and *quality assurance*.
+It ties modularly into the existing software suite (SPM12) for the estimation of Dynamic Causal Models for ERP.
+
+
+Some highlights:
+1. Efficient integration of delay differential equations underlying convolution based DCMs for ERPs for three (ERP model) and four (canonical microcircuit (CMC)) populations. The integration method uses the concept of a Continuous Extension of ODE methods (CEODE).
+
+
+Installation and Usage
+----------------------
+
+1. Start MATLAB
+3. Add SPM12 -> EEG toolboxes (e.g. type *spm eeg* in command window) to the MATLAB path
+4. Replace *y{c} = spm_int_L(Q, M, U)* with *y{c} = tapas_ceode_int_euler(Q, M, U)* in *spm_gen_erp* (line 84)
+
+ For three (ERP) / four (CMC) population DCMs
+
+ Replace f = 'spm_fx_erp' with f = 'tapas_ceode_fx_erp' in spm_dcm_x_neural.m (line 53)
+ Replace f = 'spm_fx_cmc' with f = 'tapas_ceode_fx_cmc' in spm_dcm_x_neural.m (line 79)
+
+5. Run tapas_ceode_init()
+
+ Your setup is compatible, if all of the following information is displayed:
+
+
+ - Checking for SPM version: *You are currently using SPM version: SPM12 (XXXX)*
+
+ - Running test scripts:
+ *Successful test for your model (ERP/CMC).*
+
+ - Checking integrator settings:
+ *Your setup currently runs with the tapas/ceode integrator.*
+ (No compatibility warning with your model (ERP/CMC))
+
+
+
+Tutorial
+--------
+
+To see the overall predictions by the integrators, run
+
+ tapas_ceode_compare_integrators_erp()
+or
+
+ tapas_ceode_compare_integrators_cmc()
+
+This will create a figure showing the impact of the delays to the responses in a simple two region setup.
+We assume a delay on the forward connection (from region 1 to region 2).
+
+To **change the delay magnitude**, adjust the spacing of tau in line 35 of
+
+ tapas_ceode_compare_integrators_erp.m
+and
+
+ tapas_ceode_compare_integrators_cmc.m
+
+respectively.
+
+To **change the parameters of the synthetic setup**, change
+
+ tapas_ceode_synData_erp.m
+or
+
+ tapas_ceode_synData_cmc.m
+
+
+Notes and Troubleshooting
+-------------------------
+
+### Failed test script
+
+If only the test scripts fail, compare the scaling factors of the dynamical equations between the integration scheme.
+(see *spm_fx_erp/tapas_ceode_fx_erp* or *spm_fx_cmc/tapas_ceode_fx_cmc*, respectively).
+also see: *Contact/Support*
+
+
+### Changing the integration step size
+
+By default, the stepsize of the integration for ceode is set to 1 ms .
+
+To change the integration stepsize, either:
+
+a) Add field DCM.M.intstep to the DCM.M structure.
+This defines a sampling rate for the integration.
+
+b) In *tapas_ceode_int_euler.m* (line 44):
+Replace default = 1E-3 to the desired subsampling rate.
+
+
+### Scaling parameters for delays
+
+To change the scaling parameters, either
+
+a) Add field DCM.M.pF.D to the DCM.M structure.
+This should define a 1x2 matrix with the desired scaling factors for delays.
+
+b) In *tapas_ceode_compute_itau.m* (line 24):
+Replace D = [2, 16] (ERP) or D = [1, 8] (CMC) to the desired scaling factors.
+
+
+
+Contact/Support
+---------------
+
+In case you encouter problems with this toolbox, please refer to the [GitHub Issue Forum](https://github.com/translationalneuromodeling/tapas/issues).
+
+
+Documentation
+-------------
+
+Documentation for this toolbox is provided in the following forms
+
+1. Overview and guide to further documentation: README.md and CHANGELOG.md
+ - [README.md](README.md): this file, purpose, installation, getting started, pointer to more help
+ - [CHANGELOG.md](CHANGELOG.md): List of all toolbox versions and the respective release notes,
+ i.e. major changes in functionality, bugfixes etc.
+2. For the general purpose documentation of DCM for ERPs, we refer to the SPM manual.
+
+
+Compatibility
+-------------
+- MATLAB (tested with MATLAB R2017b)
+- SPM12 (tested with SPM12, ver.7219 and ver.7771)
+
+
+Contributors
+------------
+
+- Lead Programmer:
+ - [Dario Schöbi](https://www.tnu.ethz.ch/en/team/faculty-and-scientific-staff/schoebi),
+ TNU, University of Zurich & ETH Zurich
+- Coding and Revision:
+ - Cao Tri Do, TNU Zürich
+- Project Team:
+ - Jakob Heinzle, TNU Zurich
+ - Klaas Enno Stephan, TNU Zurich
+
+
+
+Requirements
+------------
+- MATLAB
+- SPM12
+(also see *Compatibility*)
+
+References
+----------
+
+### Main Toolbox Reference
+
+Schöbi D., Do C.T., Heinzle J., Stephan K.E.,
+*Technical Note: A novel delay differential integration method for DCM for ERP*
+(in prep)
+
+Schöbi D.
+*Dynamic causal models for inference on neuromodulatory processes in neural circuits.*
+ETH Zürich (Dissertation; Chapter 2)
+
+
+### Related Papers
+
+1. Schöbi D., Jung F., Frässle S., Endepols H., Moran R.J., Friston K.J., Tittgemeyer M., Heinzle J., Stephan K.E.
+Model-based prediction of muscarinic receptor function from auditory mismatch negativity responses.
+bioRXiv. https://doi.org/10.1101/2020.06.08.139550
+
+
+
+Copying/License
+---------------
+
+The ceode Toolbox is free software: you can redistribute it and/or
+modify it under the terms of the GNU General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or (at your option) any later version.
+
+This program is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program (see the file [LICENSE](LICENSE)). If not, see
+.
diff --git a/ceode/code/integrators/tapas_ceode_compute_itau.m b/ceode/code/integrators/tapas_ceode_compute_itau.m
new file mode 100644
index 00000000..f35335ca
--- /dev/null
+++ b/ceode/code/integrators/tapas_ceode_compute_itau.m
@@ -0,0 +1,59 @@
+function [itau] = tapas_ceode_compute_itau(P, M, U)
+% [itau] = tapas_ceode_compute_itau(P, M, U)
+%
+% Computation of delays (in samples).
+%
+% iD = delay matrix / sampling Rate
+%
+% The resulting sample-delay matrix is read FROM (column) TO (row)
+%
+%
+% INPUT
+% P struct parameter structure
+% M struct model specification
+% U struct design specification
+%
+% OUTPUT
+% itau matrix delays in sample space
+%
+%
+% -------------------------------------------------------------------------
+%
+% Author: Dario Schöbi
+% Created: 2020-08-10
+% Copyright (C) 2020 TNU, Institute for Biomedical Engineering, University of Zurich and ETH Zurich.
+%
+% This file is part of the TAPAS ceode Toolbox, which is released under the terms of the GNU General Public
+% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
+% (either version 3 or, at your option, any later version). For further details, see the file
+% COPYING or .
+% -------------------------------------------------------------------------
+
+
+% Get the scaling factors for delays
+if isfield(M, 'pF')
+ D = M.pF.D;
+else
+ % Default scaling values
+ switch M.f
+ case 'tapas_ceode_fx_erp'
+ D = [2, 16];
+ case 'tapas_ceode_fx_cmc'
+ D = [1, 8];
+ end
+end
+
+% Get number of regions sampling rate
+n = size(M.x, 1);
+dt = U.dt;
+
+% Construct delay matrix for extrinsic (De) and intrinsic (Di) delays
+% (also see spm_fx_erp.m)
+De = (ones(n, n) - eye(n)) .* D(2).*exp(P.D)/1000;
+Di = eye(n) .* D(1) ./1000;
+D = De + Di;
+
+% Compute delays in samples
+itau = D ./ dt;
+
+end
diff --git a/ceode/code/integrators/tapas_ceode_compute_xtau.m b/ceode/code/integrators/tapas_ceode_compute_xtau.m
new file mode 100644
index 00000000..ef32875b
--- /dev/null
+++ b/ceode/code/integrators/tapas_ceode_compute_xtau.m
@@ -0,0 +1,79 @@
+function [xx] = tapas_ceode_compute_xtau(tn, xhist, itau)
+% [xx] = tapas_ceode_compute_xtau(P, M, U)
+%
+% Computation of delayed states according to the continuous extension for
+% ODE methods. Delayed states are computed as a linear interpolation
+% between sampled time points
+%
+% xhat(t-tau) = x_{i-1} + (t-tau)/dt * (x_{i}-x_{i-1})
+%
+%
+% INPUT
+% tn int current sample of integration
+% xhist xhist history of states
+% itau itau delays in sample space
+%
+% OUTPUT
+% xx cell delayed states. Cell read as from (columns)
+% to (rows)
+%
+%
+% -------------------------------------------------------------------------
+%
+% Author: Dario Schöbi
+% Created: 2020-08-10
+% Copyright (C) 2020 TNU, Institute for Biomedical Engineering, University of Zurich and ETH Zurich.
+%
+% This file is part of the TAPAS ceode Toolbox, which is released under the terms of the GNU General Public
+% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
+% (either version 3 or, at your option, any later version). For further details, see the file
+% COPYING or .
+% -------------------------------------------------------------------------
+
+
+% Initialize auxiliary variables and allocate space
+xt = cell(size(itau));
+nStates = size(xhist, 1);
+nSources = size(itau, 1);
+nx = nStates / nSources;
+
+% Iterate over all delays, and compute the linear interpolation to the
+% activity
+for i = 1 : size(itau, 1)
+ for j = 1 : size(itau, 2)
+
+ lxt = zeros(size(xhist, 1), 1);
+ uxt = zeros(size(xhist, 1), 1);
+
+ % Samples immediately before and after the delayed state
+ uitau = ceil(itau);
+ litau = floor(itau);
+
+ % Normalize delay to the interval between samples
+ tp = mod(itau, 1);
+
+ % If current time < delays, initialize to 0 activity (initial
+ % conditions)
+ if tn - uitau(j, i) <= 0
+ uxt = zeros(nStates, 1);
+ lxt = zeros(nStates, 1);
+ else
+ lxt = xhist(:, tn - uitau(j, i));
+ uxt = xhist(:, tn -litau(j, i));
+ end
+
+ % Interpolation step
+ xt{j, i} = spm_unvec(lxt + tp(j, i) .* (uxt - lxt), ...
+ zeros(nSources, nx));
+
+ end
+end
+
+% Reshape the delayed states into a compressed format
+for i = 1 : nSources
+ for j = 1 : nSources
+ xx{i}(j, :) = xt{i, j}(j, :);
+ end
+end
+
+end
diff --git a/ceode/code/integrators/tapas_ceode_fx_cmc.m b/ceode/code/integrators/tapas_ceode_fx_cmc.m
new file mode 100644
index 00000000..73b4c9b2
--- /dev/null
+++ b/ceode/code/integrators/tapas_ceode_fx_cmc.m
@@ -0,0 +1,222 @@
+function [f,J,D] = tapas_ceode_fx_cmc(x, u, P, M, xtau)
+% [f,J,D] = tapas_ceode_fx_cmc(x, u, P, M, xtau)
+%
+% Computation of the dynamical (state) equation for a neural mass model
+% (canonical microcircuit). Compatibile with continuous extension for ODE
+% methods. Adapted from spm_fx_cmc.m (original function license below).
+% Function output signature kept the same to ensure compatibility.
+%
+%
+% INPUT
+% x mat vector of current state activity
+% u mat vector of current driving input
+% P struct parameter structure
+% M struct model specification
+% xtau mat vector of delayed state activity
+%
+% OUTPUT
+% f mat matrix of dx/dt
+% J mat Jacobian of the system df/dx. Fixed to 0
+% since irrelevant for this integration
+% scheme.
+% D mat matrix of delays. Empty since irrelevant
+% for this integration scheme.
+
+% -------------------------------------------------------------------------
+%
+% Author: Dario Schöbi
+% Created: 2020-08-10
+% Copyright (C) 2020 TNU, Institute for Biomedical Engineering, University of Zurich and ETH Zurich.
+%
+% This file is part of the TAPAS ceode Toolbox, which is released under the terms of the GNU General Public
+% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
+% (either version 3 or, at your option, any later version). For further details, see the file
+% COPYING or .
+% -------------------------------------------------------------------------
+%
+% ORIGINAL FUNCTION LICENSE
+%
+% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging
+%
+% Karl Friston
+% $Id: spm_fx_cmc.m 6720 2016-02-15 21:06:55Z karl $
+%--------------------------------------------------------------------------
+
+
+% get dimensions and configure state variables
+%--------------------------------------------------------------------------
+if nargin < 5
+ xtau = x;
+end
+
+% get dimensions and configure state variables
+%--------------------------------------------------------------------------
+x = spm_unvec(x,M.x); % neuronal states
+xtau = spm_unvec(xtau, M.x);
+n = size(x,1); % number of sources
+
+% [default] fixed parameters
+%--------------------------------------------------------------------------
+E = [1 1/2 1 1/2]*200; % extrinsic (forward and backward)
+G = [4 4 8 4 4 2 4 4 2 1]*200; % intrinsic connections
+T = [2 2 16 28]; % synaptic time constants
+R = 2/3; % slope of sigmoid activation function
+B = 0; % bias or background (sigmoid)
+
+% [specified] fixed parameters
+%--------------------------------------------------------------------------
+if isfield(M,'pF')
+ try, E = M.pF.E; end
+ try, G = M.pF.G; end
+ try, T = M.pF.T; end
+ try, R = M.pF.R; end
+end
+
+
+% Extrinsic connections
+%--------------------------------------------------------------------------
+% ss = spiny stellate
+% sp = superficial pyramidal
+% dp = deep pyramidal
+% ii = inhibitory interneurons
+%--------------------------------------------------------------------------
+if n > 1
+ A{1} = exp(P.A{1})*E(1); % forward connections (sp -> ss)
+ A{2} = exp(P.A{2})*E(2); % forward connections (sp -> dp)
+ A{3} = exp(P.A{3})*E(3); % backward connections (dp -> sp)
+ A{4} = exp(P.A{4})*E(4); % backward connections (dp -> ii)
+else
+ A = {0,0,0,0};
+end
+
+% detect and reduce the strength of reciprocal (lateral) connections
+%--------------------------------------------------------------------------
+for i = 1:length(A)
+ L = (A{i} > exp(-8)) & (A{i}' > exp(-8));
+ A{i} = A{i}./(1 + 4*L);
+end
+
+% input connections
+%--------------------------------------------------------------------------
+C = exp(P.C);
+
+% pre-synaptic inputs: s(V)
+%--------------------------------------------------------------------------
+R = R.*exp(P.S); % gain of activation function
+F = 1./(1 + exp(-R*xtau + B)); % firing rate
+S = F - 1/(1 + exp(B)); % deviation from baseline firing
+
+% input
+%==========================================================================
+if isfield(M,'u')
+
+ % endogenous input
+ %----------------------------------------------------------------------
+ U = u(:)*512;
+
+else
+ % exogenous input
+ %----------------------------------------------------------------------
+ U = C*u(:)*32;
+
+end
+
+
+% time constants and intrinsic connections
+%==========================================================================
+T = ones(n,1)*T/1000;
+G = ones(n,1)*G;
+
+% extrinsic connections
+%--------------------------------------------------------------------------
+% forward (i) 2 sp -> ss (+ve)
+% forward (ii) 1 sp -> dp (+ve)
+% backward (i) 2 dp -> sp (-ve)
+% backward (ii) 1 dp -> ii (-ve)
+%--------------------------------------------------------------------------
+% free parameters on time constants and intrinsic connections
+%--------------------------------------------------------------------------
+% G(:,1) ss -> ss (-ve self) 4
+% G(:,2) sp -> ss (-ve rec ) 4
+% G(:,3) ii -> ss (-ve rec ) 4
+% G(:,4) ii -> ii (-ve self) 4
+% G(:,5) ss -> ii (+ve rec ) 4
+% G(:,6) dp -> ii (+ve rec ) 2
+% G(:,7) sp -> sp (-ve self) 4
+% G(:,8) ss -> sp (+ve rec ) 4
+% G(:,9) ii -> dp (-ve rec ) 2
+% G(:,10) dp -> dp (-ve self) 1
+%--------------------------------------------------------------------------
+% Neuronal states (deviations from baseline firing)
+%--------------------------------------------------------------------------
+% S(:,1) - voltage (spiny stellate cells)
+% S(:,2) - conductance (spiny stellate cells)
+% S(:,3) - voltage (superficial pyramidal cells)
+% S(:,4) - conductance (superficial pyramidal cells)
+% S(:,5) - current (inhibitory interneurons)
+% S(:,6) - conductance (inhibitory interneurons)
+% S(:,7) - voltage (deep pyramidal cells)
+% S(:,8) - conductance (deep pyramidal cells)
+%--------------------------------------------------------------------------
+j = [1 2 3 4];
+for i = 1:size(P.T,2)
+ T(:,j(i)) = T(:,j(i)).*exp(P.T(:,i));
+end
+j = [7 2 3 4];
+for i = 1:size(P.G,2)
+ G(:,j(i)) = G(:,j(i)).*exp(P.G(:,i));
+end
+
+% Modulatory effects of dp depolarisation on intrinsic connection j(1)
+%--------------------------------------------------------------------------
+if isfield(P,'M')
+ G(:,j(1)) = G(:,j(1)).*exp(-P.M*32*S(:,7));
+end
+
+
+% Motion of states: f(x)
+%--------------------------------------------------------------------------
+
+% Conductance
+%==========================================================================
+
+% Granular layer (excitatory interneurons): spiny stellate: Hidden causes
+%--------------------------------------------------------------------------
+u = A{1}*S(:,3) + U;
+u = - G(:,1).*S(:,1) - G(:,3).*S(:,5) - G(:,2).*S(:,3) + u;
+f(:,2) = (u - 2*x(:,2) - x(:,1)./T(:,1))./T(:,1);
+
+% Supra-granular layer (superficial pyramidal cells): Hidden causes - error
+%--------------------------------------------------------------------------
+u = - A{3}*S(:,7);
+u = G(:,8).*S(:,1) - G(:,7).*S(:,3) + u;
+f(:,4) = (u - 2*x(:,4) - x(:,3)./T(:,2))./T(:,2);
+
+% Supra-granular layer (inhibitory interneurons): Hidden states - error
+%--------------------------------------------------------------------------
+u = - A{4}*S(:,7);
+u = G(:,5).*S(:,1) + G(:,6).*S(:,7) - G(:,4).*S(:,5) + u;
+f(:,6) = (u - 2*x(:,6) - x(:,5)./T(:,3))./T(:,3);
+
+% Infra-granular layer (deep pyramidal cells): Hidden states
+%--------------------------------------------------------------------------
+u = A{2}*S(:,3);
+u = - G(:,10).*S(:,7) - G(:,9).*S(:,5) + u;
+f(:,8) = (u - 2*x(:,8) - x(:,7)./T(:,4))./T(:,4);
+
+% Voltage
+%==========================================================================
+f(:,1) = x(:,2);
+f(:,3) = x(:,4);
+f(:,5) = x(:,6);
+f(:,7) = x(:,8);
+
+if nargout < 2; return, end
+
+% Jacobian and delay matrix (will be properly computed in
+% tnudcm_compute_xtau)
+%==========================================================================
+J = 0;
+D = [];
+
+
diff --git a/ceode/code/integrators/tapas_ceode_fx_erp.m b/ceode/code/integrators/tapas_ceode_fx_erp.m
new file mode 100644
index 00000000..47c6aaf8
--- /dev/null
+++ b/ceode/code/integrators/tapas_ceode_fx_erp.m
@@ -0,0 +1,157 @@
+function [f,J,D] = tapas_ceode_fx_erp(x,u,P,M, xtau)
+% [f,J,D] = tapas_ceode_fx_erp(x, u, P, M, xtau)
+%
+% Computation of the dynamical (state) equation for a neural mass model
+% (ERP model). Compatibile with continuous extension for ODE
+% methods. Adapted from spm_fx_erp.m (original function license below).
+% Function output signature kept the same to ensure compatibility.
+%
+%
+% INPUT
+% x mat vector of current state activity
+% u mat vector of current driving input
+% P struct parameter structure
+% M struct model specification
+% xtau mat vector of delayed state activity
+%
+% OUTPUT
+% f mat matrix of dx/dt
+% J mat Jacobian of the system df/dx. Fixed to 0
+% since irrelevant for this integration
+% scheme.
+% D mat matrix of delays. Empty since irrelevant
+% for this integration scheme.
+%
+% -------------------------------------------------------------------------
+%
+% Author: Dario Schöbi
+% Created: 2020-08-10
+% Copyright (C) 2020 TNU, Institute for Biomedical Engineering, University of Zurich and ETH Zurich.
+%
+% This file is part of the TAPAS ceode Toolbox, which is released under the terms of the GNU General Public
+% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
+% (either version 3 or, at your option, any later version). For further details, see the file
+% COPYING or .
+% -------------------------------------------------------------------------
+%
+% ORIGINAL FUNCTION LICENSE
+%
+% Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging
+%
+% Karl Friston
+% $Id: spm_fx_erp.m 6720 2016-02-15 21:06:55Z karl $
+%--------------------------------------------------------------------------
+
+x = spm_unvec(x,M.x); % neuronal states
+n = size(x,1); % number of sources
+
+
+if nargin < 5
+ xtau = x;
+ xtau = spm_unvec(xtau, M.x);
+end
+
+% [default] fixed parameters
+%--------------------------------------------------------------------------
+E = [1 1/2 1/8]*32; % extrinsic rates (forward, backward, lateral)
+G = [1 4/5 1/4 1/4]*128; % intrinsic rates (g1 g2 g3 g4)
+D = [2 16]; % propogation delays (intrinsic, extrinsic)
+H = [4 32]; % receptor densities (excitatory, inhibitory)
+T = [8 16]; % synaptic constants (excitatory, inhibitory)
+R = [2 1]/3; % parameters of static nonlinearity
+
+% [specified] fixed parameters
+%--------------------------------------------------------------------------
+if isfield(M,'pF')
+ try, E = M.pF.E; end
+ try, G = M.pF.H; end
+ try, D = M.pF.D; end
+ try, H = M.pF.G; end
+ try, T = M.pF.T; end
+ try, R = M.pF.R; end
+end
+
+% test for free parameters on intrinsic connections
+%--------------------------------------------------------------------------
+try
+ G = G.*exp(P.H);
+end
+G = ones(n,1)*G;
+
+% exponential transform to ensure positivity constraints
+%--------------------------------------------------------------------------
+if n > 1
+ A{1} = exp(P.A{1})*E(1);
+ A{2} = exp(P.A{2})*E(2);
+ A{3} = exp(P.A{3})*E(3);
+else
+ A = {0,0,0};
+end
+C = exp(P.C);
+
+% intrinsic connectivity and parameters
+%--------------------------------------------------------------------------
+Te = T(1)/1000*exp(P.T(:,1)); % excitatory time constants
+Ti = T(2)/1000*exp(P.T(:,2)); % inhibitory time constants
+He = H(1)*exp(P.G(:,1)); % excitatory receptor density
+Hi = H(2)*exp(P.G(:,2)); % inhibitory receptor density
+
+% pre-synaptic inputs: s(V)
+%--------------------------------------------------------------------------
+R = R.*exp(P.S);
+S = 1./(1 + exp(-R(1)*(xtau - R(2)))) - 1./(1 + exp(R(1)*R(2)));
+
+% input
+%==========================================================================
+if isfield(M,'u')
+
+ % endogenous input
+ %----------------------------------------------------------------------
+ U = u(:)*64;
+
+else
+ % exogenous input
+ %----------------------------------------------------------------------
+ U = C*u(:)*2;
+end
+
+
+% State: f(x)
+%==========================================================================
+
+% Supragranular layer (inhibitory interneurons): Voltage & depolarizing current
+%--------------------------------------------------------------------------
+f(:,7) = x(:,8);
+f(:,8) = (He.*((A{2} + A{3})*S(:,9) + G(:,3).*S(:,9)) - 2*x(:,8) - x(:,7)./Te)./Te;
+
+% Granular layer (spiny stellate cells): Voltage & depolarizing current
+%--------------------------------------------------------------------------
+f(:,1) = x(:,4);
+f(:,4) = (He.*((A{1} + A{3})*S(:,9) + G(:,1).*S(:,9) + U) - 2*x(:,4) - x(:,1)./Te)./Te;
+
+% Infra-granular layer (pyramidal cells): depolarizing current
+%--------------------------------------------------------------------------
+f(:,2) = x(:,5);
+f(:,5) = (He.*((A{2} + A{3})*S(:,9) + G(:,2).*S(:,1)) - 2*x(:,5) - x(:,2)./Te)./Te;
+
+% Infra-granular layer (pyramidal cells): hyperpolarizing current
+%--------------------------------------------------------------------------
+f(:,3) = x(:,6);
+f(:,6) = (Hi.*G(:,4).*S(:,7) - 2*x(:,6) - x(:,3)./Ti)./Ti;
+
+% Infra-granular layer (pyramidal cells): Voltage
+%--------------------------------------------------------------------------
+f(:,9) = x(:,5) - x(:,6);
+
+if nargout < 2; return, end
+
+% Jacobian and delay matrix (will be properly computed in
+% tnudcm_compute_xtau)
+%==========================================================================
+J = 0;
+D = [];
+
+
+
+
+
diff --git a/ceode/code/integrators/tapas_ceode_gen_erp.m b/ceode/code/integrators/tapas_ceode_gen_erp.m
new file mode 100644
index 00000000..5698f6cb
--- /dev/null
+++ b/ceode/code/integrators/tapas_ceode_gen_erp.m
@@ -0,0 +1,102 @@
+function [y, pst] = tapas_ceode_gen_erp(P, M, U)
+% [y, pst] = tapas_ceode_gen_erp(P, M, U)
+%
+% Compute predicted data based on a specified DCM, with variable integrator
+% specification.
+%
+% Adapted from spm_gen_erp.m (original function lincense below).
+%
+%
+% INPUT
+% P struct parameter structure
+% M struct model specification
+% U struct design specification
+%
+% OUTPUT
+% y mat Integrated activity in sensor space
+%
+% -------------------------------------------------------------------------
+%
+% Author: Dario Schöbi
+% Created: 2020-08-10
+% Copyright (C) 2020 TNU, Institute for Biomedical Engineering, University of Zurich and ETH Zurich.
+%
+% This file is part of the TAPAS ceode Toolbox, which is released under the terms of the GNU General Public
+% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
+% (either version 3 or, at your option, any later version). For further details, see the file
+% COPYING or .
+% -------------------------------------------------------------------------
+%
+% ORIGINAL FUNCTION LICENSE
+%
+% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
+%
+% Karl Friston
+% $Id: spm_gen_erp.m 5758 2013-11-20 21:04:01Z karl $
+%--------------------------------------------------------------------------
+
+
+% default inputs - one trial (no between-trial effects)
+%--------------------------------------------------------------------------
+if nargin < 3, U.X = sparse(1,0); end
+
+
+% peristimulus time
+%--------------------------------------------------------------------------
+if nargout > 1
+ pst = (1:M.ns)*U.dt - M.ons/1000;
+end
+
+% within-trial (exogenous) inputs
+%==========================================================================
+if ~isfield(U,'u')
+
+ % peri-stimulus time inputs
+ %----------------------------------------------------------------------
+ U.u = feval(M.fu,(1:M.ns)*U.dt,P,M);
+
+end
+
+if isfield(M,'u')
+
+ % remove M.u to preclude endogenous input
+ %----------------------------------------------------------------------
+ M = rmfield(M,'u');
+
+end
+
+% between-trial (experimental) inputs
+%==========================================================================
+if isfield(U,'X')
+ X = U.X;
+else
+ X = sparse(1,0);
+end
+
+if ~size(X,1)
+ X = sparse(1,0);
+end
+
+% cycle over trials
+%==========================================================================
+y = cell(size(X,1),1);
+for c = 1:size(X,1)
+
+ % condition-specific parameters
+ %----------------------------------------------------------------------
+ Q = spm_gen_Q(P, X(c, :));
+
+ % solve for steady-state - for each condition
+ %----------------------------------------------------------------------
+ M.x = spm_dcm_neural_x(Q,M);
+
+ % integrate DCM - for this condition
+ %----------------------------------------------------------------------
+ y{c} = feval(M.int, Q, M, U);
+
+end
+
+
+
+
+
diff --git a/ceode/code/integrators/tapas_ceode_int_euler.m b/ceode/code/integrators/tapas_ceode_int_euler.m
new file mode 100644
index 00000000..6177e6c8
--- /dev/null
+++ b/ceode/code/integrators/tapas_ceode_int_euler.m
@@ -0,0 +1,143 @@
+function [y] = tapas_ceode_int_euler(P, M, U)
+% [y] = tapas_ceode_int_euler(P, M, U)
+%
+% Integration of a (delayed) dynamical system (convolution based DCM)
+% based on the continuous extension for ODE methods. ODE step follows a
+% forward Euler scheme:
+%
+% x_{n+1} = x_{n} + dt .* f(xhat_{n-taun})
+%
+% Also see ceode_compute_xtau.m.
+% Adapted from spm_fx_erp.m (original function lincense below).
+%
+%
+% INPUT
+% P struct parameter structure
+% M struct model specification
+% U struct design specification
+%
+% OUTPUT
+% y mat Integrated activity in sensor space
+%
+% -------------------------------------------------------------------------
+%
+% Author: Dario Schöbi
+% Created: 2020-08-10
+% Copyright (C) 2020 TNU, Institute for Biomedical Engineering, University of Zurich and ETH Zurich.
+%
+% This file is part of the TAPAS ceode Toolbox, which is released under the terms of the GNU General Public
+% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
+% (either version 3 or, at your option, any later version). For further details, see the file
+% COPYING or .
+% -------------------------------------------------------------------------
+%
+% ORIGINAL FUNCTION LICENSE
+%
+% Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging
+% Karl Friston
+% $Id: spm_int_L.m 6110 2014-07-21 09:36:13Z karl $
+%--------------------------------------------------------------------------
+
+if isfield(M, 'intstep')
+ N = ceil(U.dt / M.intstep);
+else
+ N = ceil(U.dt / 1E-3);
+end
+
+% If subsampling is needed, re-evaluate driving input
+ if N > 1
+ U.dt = U.dt / N;
+ U.u = feval(M.fu, U.dt .* [1 : M.ns*N], P, M);
+ end
+
+% convert U to U.u if necessary
+%--------------------------------------------------------------------------
+if ~isstruct(U), u.u = U; U = u; end
+try, dt = U.dt; catch, dt = 1; end
+
+% Initial states and inputs
+%--------------------------------------------------------------------------
+try
+ x = M.x;
+catch
+ x = sparse(0,1);
+ M.x = x;
+end
+
+try
+ u = U.u(1,:);
+catch
+ u = sparse(1,M.m);
+end
+
+% add [0] states if not specified
+%--------------------------------------------------------------------------
+try
+ f = spm_funcheck(M.f);
+catch
+ f = @(x,u,P,M) sparse(0,1);
+ M.n = 0;
+ M.x = sparse(0,0);
+ M.f = f;
+end
+
+
+% output nonlinearity, if specified
+%--------------------------------------------------------------------------
+try
+ g = spm_funcheck(M.g);
+catch
+ g = @(x,u,P,M) x;
+ M.g = g;
+end
+
+
+% dx(t)/dt and Jacobian df/dx and check for delay operator
+%--------------------------------------------------------------------------
+if nargout(f) >= 3
+ [fx, ~, ~] = f(x,u,P,M);
+
+elseif nargout(f) == 2
+ [fx, dfdx] = f(x,u,P,M);
+
+else
+ dfdx = spm_cat(spm_diff(f,x,u,P,M,1));
+end
+
+
+% initialize states, history and delays
+%==========================================================================
+xhist = zeros(length(spm_vec(x)), M.ns*N);
+v = spm_vec(x);
+xhist(:, 1) = v;
+itau = tapas_ceode_compute_itau(P, M, U);
+
+% integrate
+%==========================================================================
+for i = 1 : size(U.u,1)
+
+ % input
+ %----------------------------------------------------------------------
+ u = U.u(i,:);
+
+ xtau = tapas_ceode_compute_xtau(i, xhist, itau);
+ xhist(:, i + 1) = ...
+ tapas_ceode_update_euler(xhist(:, i), u, P, M, xtau, dt);
+
+
+end
+
+% output - implement g(x)
+%------------------------------------------------------------------
+% back to the original trace length after subsampling
+
+idx = 1:N:size(xhist,2)-1;
+y = zeros(size(xhist,1),numel(idx));
+for j = 1:length(idx)
+ y(:, j) = g(xhist(:,idx(j)), u, P, M);
+end
+
+% transpose
+%--------------------------------------------------------------------------
+y = real(y');
+
diff --git a/ceode/code/integrators/tapas_ceode_update_euler.m b/ceode/code/integrators/tapas_ceode_update_euler.m
new file mode 100644
index 00000000..327f51d7
--- /dev/null
+++ b/ceode/code/integrators/tapas_ceode_update_euler.m
@@ -0,0 +1,45 @@
+function [ v, ff ] = tapas_ceode_update_euler( v, u, P, M, xtau, dt)
+% [ v, ff ] = tapas_ceode_update_euler( v, u, P, M, xtau, dt)
+%
+% Computes an euler update step for the delayed euler integrator, i.e.
+%
+% x(t + dt) = x(t) + dt * f(t-tau)
+%
+% INPUT
+% v mat vectorized state value x(t) at time t
+% u mat value u(t) from driving input at time t
+% P struct parameter structure
+% M struct model specification
+% xtau mat delayed state matrix as returned from
+% tnudcm_compute_xtau.m
+% dt mat sampling rate of signal
+%
+% OUTPUT
+% v mat vectorized state value x(t + dt) at time t + 1
+% ff mat f(t-tau) computed for delayed states
+%
+%
+% -------------------------------------------------------------------------
+%
+% Author: Dario Schöbi
+% Created: 2020-08-10
+% Copyright (C) 2020 TNU, Institute for Biomedical Engineering, University of Zurich and ETH Zurich.
+%
+% This file is part of the TAPAS ceode Toolbox, which is released under the terms of the GNU General Public
+% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
+% (either version 3 or, at your option, any later version). For further details, see the file
+% COPYING or .
+% -------------------------------------------------------------------------
+
+
+f = str2func(M.f);
+
+for j = 1 : numel(xtau)
+ fx = full(f(v, u, P, M, xtau{j}));
+ ff(j, :, :) = fx(j, :, :);
+end
+
+ff = spm_vec(ff);
+v = v + dt * ff;
+
+end
diff --git a/ceode/code/testing/tapas_ceode_testData_cmc.m b/ceode/code/testing/tapas_ceode_testData_cmc.m
new file mode 100644
index 00000000..cca50bc2
--- /dev/null
+++ b/ceode/code/testing/tapas_ceode_testData_cmc.m
@@ -0,0 +1,92 @@
+function [ DCM ] = tapas_ceode_testData_cmc()
+% [ DCM ] = tapas_ceode_testData_cmc()
+%
+% THIS IS A SCRIPT SOLELY FOR TESTING THE SPM/TAPAS SETUP. DO NOT CHANGE!
+%
+% Sets parameters and function handles to create a synthetic DCM
+% structure. The resulting structure can then be used to generate
+% artificial data with tapas_ceode_gen_erp.m
+%
+% INPUT
+%
+% OUTPUT
+% DCM struct DCM structure with all necessary fields to
+% generate synthetic data.
+%
+% -------------------------------------------------------------------------
+%
+% Author: Dario Schöbi
+% Created: 2020-08-10
+% Copyright (C) 2020 TNU, Institute for Biomedical Engineering, University of Zurich and ETH Zurich.
+%
+% This file is part of the TAPAS ceode Toolbox, which is released under the terms of the GNU General Public
+% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
+% (either version 3 or, at your option, any later version). For further details, see the file
+% COPYING or .
+% -------------------------------------------------------------------------
+
+
+% ---------------------- MODEL SPECIFICATION ------------------------------
+M = struct();
+
+% Handles to specify integration scheme, dynamical equation, forward model
+% and input
+M.IS = 'tapas_ceode_gen_erp';
+M.f = 'spm_fx_cmc';
+M.int = 'spm_int_L';
+M.G = 'spm_lx_erp';
+M.FS = 'spm_fy_erp';
+M.fu = 'spm_erp_u';
+
+% Design/Parameter values of the driving input (see spm_erp_u.m)
+M.dur = 16;
+M.ons = 64;
+M.ns = 500;
+M.x = zeros(2, 8);
+M.m = 1;
+
+
+% ---------------------- DESIGN SPECIFICATION -----------------------------
+xU = struct();
+
+% No condition specific effec
+xU.X = [0]';
+xU.name = {'std'};
+
+% Sampling rate of the artificial signal
+xU.dt = 1e-03;
+
+
+% ---------------------- PARAMETER VALUES ---------------------------------
+% Neuronal parameters (also see spm_fx_cmc.m / tapas_ceode_fx_cmc.m)
+Ep = struct();
+
+Ep.M = zeros(2, 2);
+Ep.T = [0 0 0 0];
+Ep.G = zeros(2, 3);
+Ep.A{1} = [-32, -32; 0, -32];
+Ep.A{2} = [-32, -32; 0, -32];
+Ep.A{3} = [-32, 0; -32, -32];
+Ep.A{4} = [-32, 0; -32, -32];
+Ep.B{1} = [0 0; 1 0];
+Ep.N{1} = zeros(2, 2);
+Ep.C = [0; -32];
+Ep.D = -32 * ones(2, 2);
+Ep.S = 0;
+Ep.R = [0 0];
+
+% Leadfield parameters (also see spm_lx_erp.m)
+Eg.L = [-1 0];
+Eg.J = [0 0 4 0 0 0 2 0];
+
+
+% ---------------------- CREATE OUTPUT ------------------------------------
+% Combine all structures into single DCM structure
+DCM.Ep = Ep;
+DCM.Eg = Eg;
+DCM.M = M;
+DCM.xU = xU;
+
+
+end
+
diff --git a/ceode/code/testing/tapas_ceode_testData_erp.m b/ceode/code/testing/tapas_ceode_testData_erp.m
new file mode 100644
index 00000000..89a5d17e
--- /dev/null
+++ b/ceode/code/testing/tapas_ceode_testData_erp.m
@@ -0,0 +1,90 @@
+function [ DCM ] = tapas_ceode_testData_erp()
+% [ DCM ] = tapas_ceode_testData_erp()
+%
+% THIS IS A SCRIPT SOLELY FOR TESTING THE SPM/TAPAS SETUP. DO NOT CHANGE!
+%
+% Sets parameters and function handles to create a synthetic DCM
+% structure. The resulting structure can then be used to generate
+% artificial data with tapas_ceode_gen_erp.m
+%
+% INPUT
+%
+% OUTPUT
+% DCM struct DCM structure with all necessary fields to
+% generate synthetic data.
+%
+% -------------------------------------------------------------------------
+%
+% Author: Dario Schöbi
+% Created: 2020-08-10
+% Copyright (C) 2020 TNU, Institute for Biomedical Engineering, University of Zurich and ETH Zurich.
+%
+% This file is part of the TAPAS ceode Toolbox, which is released under the terms of the GNU General Public
+% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
+% (either version 3 or, at your option, any later version). For further details, see the file
+% COPYING or .
+% -------------------------------------------------------------------------
+
+
+% ---------------------- MODEL SPECIFICATION ------------------------------
+M = struct();
+
+% Handles to specify integration scheme, dynamical equation, forward model
+% and input
+M.IS = 'tapas_ceode_gen_erp';
+M.f = 'spm_fx_cmc';
+M.int = 'spm_int_L';
+M.G = 'spm_lx_erp';
+M.FS = 'spm_fy_erp';
+M.fu = 'spm_erp_u';
+
+% Design/Parameter values of the driving input (see spm_erp_u.m)
+M.dur = 16;
+M.ons = 64;
+M.ns = 500;
+M.x = zeros(2, 9);
+
+
+% ---------------------- DESIGN SPECIFICATION -----------------------------
+xU = struct();
+
+% No condition specific effec
+xU.X = [0]';
+xU.name = {'std'};
+
+% Sampling rate of the artificial signal
+xU.dt = 1e-03;
+
+
+% ---------------------- PARAMETER VALUES ---------------------------------
+% Neuronal parameters (also see spm_fx_erp.m / tapas_ceode_fx_erp.m)
+Ep = struct();
+
+Ep.T = [0, 0; 0 0];
+Ep.G = [0, 0; 0 0];
+Ep.S = [0, 0];
+Ep.A{1} = [-4, -4; 1, -4];
+Ep.A{2} = [-4, 0; -4, -4];
+Ep.A{3} = -4 * ones(2, 2);
+Ep.B{1} = zeros(2, 2);
+Ep.C = [0; -4];
+Ep.H = [0 0 0 0];
+Ep.D = -10 * ones(2, 2);
+Ep.R = [0 0];
+
+% Leadfield parameters (also see spm_lx_erp.m)
+Eg.L = [1, 1];
+Eg.J = [1, zeros(1, 5), 1, 0, 1];
+
+
+% ---------------------- CREATE OUTPUT ------------------------------------
+% Combine all structures into single DCM structure
+DCM.Ep = Ep;
+DCM.Eg = Eg;
+DCM.M = M;
+DCM.xU = xU;
+
+
+
+end
+
diff --git a/ceode/code/testing/tapas_ceode_testScript_cmc.m b/ceode/code/testing/tapas_ceode_testScript_cmc.m
new file mode 100644
index 00000000..d55f1b32
--- /dev/null
+++ b/ceode/code/testing/tapas_ceode_testScript_cmc.m
@@ -0,0 +1,119 @@
+function [ testResult ] = tapas_ceode_testScript_cmc()
+% [ ] = tapas_ceode_testScript_cmc()
+%
+% THIS IS A SCRIPT SOLELY FOR TESTING THE SPM/TAPAS SETUP. DO NOT CHANGE!
+%
+% Takes a synthetic dataset (3 population ERP model), and computes the
+% predicted response for different integrators and levels of delays. The
+% continuous extension for ODE method (ceode)is taken as reference.
+%
+% INPUT
+%
+% OUTPUT
+% testResult struct Result of the setup-check
+%
+% -------------------------------------------------------------------------
+%
+% Author: Dario Schöbi
+% Created: 2020-08-10
+% Copyright (C) 2020 TNU, Institute for Biomedical Engineering, University of Zurich and ETH Zurich.
+%
+% This file is part of the TAPAS ceode Toolbox, which is released under the terms of the GNU General Public
+% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
+% (either version 3 or, at your option, any later version). For further details, see the file
+% COPYING or .
+% -------------------------------------------------------------------------
+
+
+% Load DCM template
+DCM = tapas_ceode_testData_cmc();
+
+% Integrators
+intSpec = {...
+ 'spm_int_L', 'spm_fx_cmc'; ...
+ 'tapas_ceode_int_euler', 'tapas_ceode_fx_cmc'};
+nIntegrators = size(intSpec, 1);
+
+% Sets of Delays
+tau = linspace(-1, -0.5, 5);
+
+% Threshold for testing the setup (in terms of a correlation coefficient)
+BENCHMARK = [0.9932, 0.9785, 0.9730, 0.8489, 0.4162];
+ERRORMARGIN = 1E-2;
+
+% Pyramidal cell voltage states
+vPyramids = [7, 8];
+
+% Preallocate signals
+x = cell(length(intSpec), 1);
+for i = 1 : length(x)
+ x{i} = zeros(length(tau), length(vPyramids) * DCM.M.ns);
+end
+
+
+%------------------------- GENERATE PREDICTIONS ---------------------------
+
+% Integrate the DDE with the different integrators
+tau_idx = 1;
+for delays = tau
+
+ % Add delay to forward connection (read as FROM (columns) TO (rows))
+ DCM.Ep.D(2, 1) = delays;
+
+ % Iterate over integrator specs in DCM structure and generate signal
+ for i = 1 : size(intSpec, 1)
+ DCM.M.int = intSpec{i, 1};
+ DCM.M.f = intSpec{i, 2};
+
+ y = tapas_ceode_gen_erp(DCM.Ep, DCM.M, DCM.xU);
+ x{i}(tau_idx, :) = spm_vec(y{1}(:, vPyramids));
+ end
+
+ % Increase index for storing signal in single structure
+ tau_idx = tau_idx + 1;
+end
+
+
+%------------------------------ TESTING ----------------------------------
+
+% Time samples to compute pearson correlation (only the signal from the
+% second (delayed region is used))
+rsamples = DCM.M.ns + 1 : 2 * DCM.M.ns;
+
+for i = 1 : nIntegrators-1
+
+ % X-Axis offset for dot-plot
+ xoffs = linspace(-0.2, 0.2, length(tau));
+
+ for j = 1 : length(tau)
+ rho = corrcoef(x{i}(j, rsamples), ...
+ x{nIntegrators}(j, rsamples));
+ rCoeff(i, j) = rho(1, 2);
+ end
+
+end
+
+% Check regression coefficients against threshold
+testResult = struct();
+
+if any(abs(rCoeff - BENCHMARK) > ERRORMARGIN)
+ testResult.score = 0;
+ testResult.msg = ...
+ sprintf(['There is a larger than expected error in the CMC model. \n ' ...
+ 'Compatiblity with your SPM setup can not be guaranteed. ' ...
+ 'Please check the README.md.']);
+else
+ testResult.score = 1;
+ testResult.msg = ['The CMC test was successful'];
+end
+
+
+end
+
+
+
+
+
+
+
+
diff --git a/ceode/code/testing/tapas_ceode_testScript_erp.m b/ceode/code/testing/tapas_ceode_testScript_erp.m
new file mode 100644
index 00000000..a47d5e72
--- /dev/null
+++ b/ceode/code/testing/tapas_ceode_testScript_erp.m
@@ -0,0 +1,112 @@
+function [ testResult ] = tapas_ceode_testScript_erp()
+% [ testResult ] = tapas_ceode_testScript_erp()
+%
+% THIS IS A SCRIPT SOLELY FOR TESTING THE SPM/TAPAS SETUP. DO NOT CHANGE!
+%
+% Takes a synthetic dataset (3 population ERP model), and computes the
+% predicted response for different integrators and levels of delays. The
+% continuous extension for ODE method (ceode)is taken as reference.
+%
+%
+% INPUT
+%
+% OUTPUT
+% testResult struct Result of the setup-check
+%
+%
+%
+% -------------------------------------------------------------------------
+%
+% Author: Dario Schöbi
+% Created: 2020-08-10
+% Copyright (C) 2020 TNU, Institute for Biomedical Engineering, University of Zurich and ETH Zurich.
+%
+% This file is part of the TAPAS ceode Toolbox, which is released under the terms of the GNU General Public
+% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
+% (either version 3 or, at your option, any later version). For further details, see the file
+% COPYING or .
+% -------------------------------------------------------------------------
+
+
+% Load DCM template
+DCM = tapas_ceode_testData_erp();
+
+% Specify Integrators and dynamical equations as tupels
+intSpec = {...
+ 'spm_int_L', 'spm_fx_erp'; ...
+ 'tapas_ceode_int_euler', 'tapas_ceode_fx_erp'};
+nIntegrators = size(intSpec, 1);
+
+% Sets of Delays
+tau = linspace(0, 0.5, 5);
+
+% Threshold for testing the setup (in terms of a correlation coefficient)
+BENCHMARK = [0.9213, 0.9037, 0.8962, 0.8695, 0.8427];
+ERRORMARGIN = 1E-2;
+
+% Pyramidal cell voltage states
+vPyramids = [17:18];
+
+% Preallocate signals
+x = cell(length(intSpec), 1);
+for i = 1 : length(x)
+ x{i} = zeros(length(tau), length(vPyramids) * DCM.M.ns);
+end
+
+
+%------------------------- GENERATE PREDICTIONS ---------------------------
+
+% Integrate the DDE with the different integrators
+tau_idx = 1;
+for delays = tau
+
+ % Add delay to forward connection (read as FROM (columns) TO (rows)
+ DCM.Ep.D(2, 1) = delays;
+
+ % Iterate over integrator specs in DCM structure and generate signal
+ for i = 1 : size(intSpec, 1)
+ DCM.M.int = intSpec{i, 1};
+ DCM.M.f = intSpec{i, 2};
+
+ y = tapas_ceode_gen_erp(DCM.Ep, DCM.M, DCM.xU);
+ x{i}(tau_idx, :) = spm_vec(y{1}(:, vPyramids));
+ end
+
+ % Increase index for storing signal in single structure
+ tau_idx = tau_idx + 1;
+end
+
+%------------------------------ TESTING ----------------------------------
+
+% Time samples to compute pearson correlation (only the signal from the
+% second (delayed region is used))
+rsamples = DCM.M.ns + 1 : 2 * DCM.M.ns;
+
+for i = 1 : nIntegrators-1
+
+ for j = 1 : length(tau)
+ rho = corrcoef(x{i}(j, rsamples), ...
+ x{nIntegrators}(j, rsamples));
+ rCoeff(i, j) = rho(1, 2);
+ end
+
+end
+
+% Check regression coefficients against threshold
+testResult = struct();
+
+if any(abs(rCoeff - BENCHMARK) > ERRORMARGIN)
+ testResult.score = 0;
+ testResult.msg = ...
+ sprintf(['There is a larger than expected error in the ERP model. \n ' ...
+ 'Compatiblity with your SPM setup can not be guaranteed. ' ...
+ 'Please check the README.md.']);
+else
+ testResult.score = 1;
+ testResult.msg = ['The ERP test was successful'];
+end
+
+
+end
+
+
diff --git a/ceode/code/tutorial/tapas_ceode_compare_integrators_cmc.m b/ceode/code/tutorial/tapas_ceode_compare_integrators_cmc.m
new file mode 100644
index 00000000..b36aaa8f
--- /dev/null
+++ b/ceode/code/tutorial/tapas_ceode_compare_integrators_cmc.m
@@ -0,0 +1,204 @@
+function [ ] = tapas_ceode_compare_integrators_cmc()
+% [ ] = tapas_ceode_compare_integrators_cmc()
+%
+% Takes a synthetic dataset (3 population ERP model), and computes the
+% predicted response for different integrators and levels of delays. The
+% continuous extension for ODE method (ceode)is taken as reference.
+%
+% INPUT
+%
+% OUTPUT
+%
+%
+% -------------------------------------------------------------------------
+%
+% Author: Dario Schöbi
+% Created: 2020-08-10
+% Copyright (C) 2020 TNU, Institute for Biomedical Engineering, University of Zurich and ETH Zurich.
+%
+% This file is part of the TAPAS ceode Toolbox, which is released under the terms of the GNU General Public
+% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
+% (either version 3 or, at your option, any later version). For further details, see the file
+% COPYING or .
+% -------------------------------------------------------------------------
+
+
+% Load DCM template
+DCM = tapas_ceode_synData_cmc();
+
+% Integrators
+intSpec = {...
+ 'spm_int_L', 'spm_fx_cmc'; ...
+ 'tapas_ceode_int_euler', 'tapas_ceode_fx_cmc'};
+
+% Sets of Delays
+tau = linspace(-1, -0.5, 10);
+
+% Pyramidal cell voltage states
+vPyramids = [7, 8];
+
+% Preallocate signals
+x = cell(length(intSpec), 1);
+for i = 1 : length(x)
+ x{i} = zeros(length(tau), length(vPyramids) * DCM.M.ns);
+end
+
+
+%------------------------- GENERATE PREDICTIONS ---------------------------
+
+% Integrate the DDE with the different integrators
+tau_idx = 1;
+for delays = tau
+
+ % Add delay to forward connection (read as FROM (columns) TO (rows)
+ DCM.Ep.D(2, 1) = delays;
+
+ % Iterate over integrator specs in DCM structure and generate signal
+ for i = 1 : size(intSpec, 1)
+ DCM.M.int = intSpec{i, 1};
+ DCM.M.f = intSpec{i, 2};
+
+ y = tapas_ceode_gen_erp(DCM.Ep, DCM.M, DCM.xU);
+ x{i}(tau_idx, :) = spm_vec(y{1}(:, vPyramids));
+ end
+
+ % Increase index for storing signal in single structure
+ tau_idx = tau_idx + 1;
+end
+
+
+%---------------------------- VISUALIZATION--------------------------------
+figure();
+
+% Color code
+cc = jet(length(tau));
+
+% Plot the predicted pyramidal voltages
+nIntegrators = length(x);
+
+for i = 1 : nIntegrators
+
+ subplot(2, nIntegrators, i);
+ hold on;
+ title(intSpec{i, 1}, 'Interpreter', 'none');
+
+ % Plot the predictions
+ for j = 1 : length(tau)
+ y = reshape(x{i}(j, :), [], length(vPyramids));
+ plot_prediction(DCM.xU.dt .* [0 : DCM.M.ns-1], y, cc(j, :));
+
+ end
+
+ % Configure axes to create a nice plot
+ config_prediction(gca, 'raw');
+
+end
+
+% Plot the difference to last integration scheme
+for i = 1 : nIntegrators-1
+
+ subplot(2, nIntegrators, i + nIntegrators);
+ hold on;
+ title([intSpec{i, 1} ' - ' intSpec{end, 1}], 'Interpreter', 'none');
+
+ % Plot signal difference
+ for j = 1 : length(tau)
+ y = reshape(x{i}(j, :) - x{nIntegrators}(j, :), ...
+ [], length(vPyramids));
+ plot_prediction(DCM.xU.dt .* [0 : DCM.M.ns-1], y, cc(j, :));
+ end
+
+ % Configure axes to create a nice plot
+ config_prediction(gca, 'delta');
+
+end
+
+% Plot regression coefficient
+
+% Time samples to compute pearson correlation (only the signal from the
+% second (delayed region is used))
+rsamples = DCM.M.ns + 1 : 2 * DCM.M.ns;
+
+subplot(2, nIntegrators, 2 * nIntegrators);
+hold on;
+
+xx = 1;
+tickLabels = {};
+for i = 1 : nIntegrators-1
+
+ % X-Axis offset for dot-plot
+ xoffs = xx + linspace(-0.2, 0.2, length(tau));
+
+ for j = 1 : length(tau)
+
+ rCoeff = corrcoef(x{i}(j, rsamples), x{nIntegrators}(j, rsamples));
+ plot(xoffs(j), rCoeff(1, 2), 'o', ...
+ 'MarkerFaceColor', cc(j, :), ...
+ 'MarkerEdgeColor', 'none', ...
+ 'MarkerSize', 10);
+ end
+
+ xx = xx + 1;
+
+end
+
+% Configure the axes of the regression plot
+config_regression(gca, xoffs, round(8 * exp(tau), 1));
+
+end
+
+
+% ------------------------- CONFIGURATIONS--------------------------------
+
+function plot_prediction(t, y, cc)
+% Plot the predictions from the two regions
+
+h = plot(t, y,...
+ 'Color', cc);
+h(1).LineStyle = '--';
+h(2).LineStyle = '-';
+
+end
+
+function config_prediction(h, plotFlag)
+% Configure the prediction plot (prediction and difference)
+
+set(h, 'TickDir', 'out', ...
+ 'XGrid', 'on', ...
+ 'XLim', [0, 0.51], ...
+ 'XTick', [0 : 0.1 : 0.5], ...
+ 'YGrid', 'on', ...
+ 'PlotBoxAspectRatio', [1 1 1], ...
+ 'FontSize', 14);
+
+% Set axes labels
+h.XLabel.String = 'Time [s]';
+switch plotFlag
+ case 'raw'
+ h.YLabel.String = 'predicted signal (y_p)';
+ case 'delta'
+ h.YLabel.String = '\Delta y_p';
+end
+
+% Increase LineWidth
+hh = findobj(h.Children, 'Type', 'Line');
+set(hh, 'LineWidth', 2);
+
+end
+
+
+function config_regression(h, xticks, tickLabels)
+% Configure the regression plot
+
+set(h, 'XTick', xticks, ...
+ 'XTickLabels', tickLabels, ...
+ 'XTickLabelRotation', 45, ...
+ 'XGrid', 'on', ...
+ 'YGrid', 'on', ...
+ 'PlotBoxAspectRatio', [1 1 1]);
+
+
+h.YLabel.String = 'Pearson Correlation btw. integrators';
+h.XLabel.String = 'Delays [ms]';
+
+end
diff --git a/ceode/code/tutorial/tapas_ceode_compare_integrators_erp.m b/ceode/code/tutorial/tapas_ceode_compare_integrators_erp.m
new file mode 100644
index 00000000..c35f0fe2
--- /dev/null
+++ b/ceode/code/tutorial/tapas_ceode_compare_integrators_erp.m
@@ -0,0 +1,203 @@
+function [ ] = tapas_ceode_compare_integrators_erp()
+% [ ] = tapas_ceode_compare_integrators_erp()
+%
+% Takes a synthetic dataset (3 population ERP model), and computes the
+% predicted response for different integrators and levels of delays. The
+% continuous extension for ODE method (ceode)is taken as reference.
+%
+% INPUT
+%
+% OUTPUT
+%
+%
+% -------------------------------------------------------------------------
+%
+% Author: Dario Schöbi
+% Created: 2020-08-10
+% Copyright (C) 2020 TNU, Institute for Biomedical Engineering, University of Zurich and ETH Zurich.
+%
+% This file is part of the TAPAS ceode Toolbox, which is released under the terms of the GNU General Public
+% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
+% (either version 3 or, at your option, any later version). For further details, see the file
+% COPYING or .
+% -------------------------------------------------------------------------
+
+
+% Load DCM template
+DCM = tapas_ceode_synData_erp();
+
+% Specify Integrators and dynamical equations as tupels
+intSpec = {...
+ 'spm_int_L', 'spm_fx_erp'; ...
+ 'tapas_ceode_int_euler', 'tapas_ceode_fx_erp'};
+
+% Sets of Delays
+tau = linspace(0, 2, 10);
+
+% Pyramidal cell voltage states
+vPyramids = [17:18];
+
+% Preallocate signals
+x = cell(length(intSpec), 1);
+for i = 1 : length(x)
+ x{i} = zeros(length(tau), length(vPyramids) * DCM.M.ns);
+end
+
+%------------------------- GENERATE PREDICTIONS ---------------------------
+
+% Integrate the DDE with the different integrators
+tau_idx = 1;
+for delays = tau
+
+ % Add delay to forward connection (read as FROM (columns) TO (rows)
+ DCM.Ep.D(2, 1) = delays;
+
+ % Iterate over integrator specs in DCM structure and generate signal
+ for i = 1 : size(intSpec, 1)
+ DCM.M.int = intSpec{i, 1};
+ DCM.M.f = intSpec{i, 2};
+
+ y = tapas_ceode_gen_erp(DCM.Ep, DCM.M, DCM.xU);
+ x{i}(tau_idx, :) = spm_vec(y{1}(:, vPyramids));
+ end
+
+ % Increase index for storing signal in single structure
+ tau_idx = tau_idx + 1;
+end
+
+
+%---------------------------- VISUALIZATION--------------------------------
+figure();
+
+% Color code
+cc = jet(length(tau));
+
+% Plot the predicted pyramidal voltages
+nIntegrators = size(x, 1);
+
+for i = 1 : nIntegrators
+
+ subplot(2, nIntegrators, i);
+ hold on;
+ title(intSpec{i, 1}, 'Interpreter', 'none');
+
+ % Plot the predictions
+ for j = 1 : length(tau)
+ y = reshape(x{i}(j, :), [], length(vPyramids));
+ plot_signals(DCM.xU.dt .* [0 : DCM.M.ns-1], y, cc(j, :));
+ end
+
+ % Configure axes to create a nice plot
+ config_prediction(gca, 'raw');
+
+end
+
+% Plot the difference to last integration scheme
+for i = 1 : nIntegrators-1
+
+ subplot(2, nIntegrators, i + nIntegrators);
+ hold on;
+ title([intSpec{i, 1} ' - ' intSpec{end, 1}], 'Interpreter', 'none');
+
+ % Plot signal difference
+ for j = 1 : length(tau)
+ y = reshape(x{i}(j, :) - x{nIntegrators}(j, :), ...
+ [], length(vPyramids));
+ plot_signals(DCM.xU.dt .* [0 : DCM.M.ns-1], y, cc(j, :));
+ end
+
+ % Configure axes to create a nice plot
+ config_prediction(gca, 'delta');
+
+end
+
+% Plot regression coefficient
+
+% Time samples to compute pearson correlation (only the signal from the
+% second (delayed region is used))
+rsamples = DCM.M.ns + 1 : 2 * DCM.M.ns;
+
+subplot(2, nIntegrators, 2 * nIntegrators);
+hold on;
+
+xx = 1;
+for i = 1 : nIntegrators-1
+
+ % X-Axis offset for dot-plot
+ xoffs = xx + linspace(-0.2, 0.2, length(tau));
+
+ for j = 1 : length(tau)
+ rCoeff = corrcoef(x{i}(j, :), x{nIntegrators}(j, :));
+ plot(xoffs(j), rCoeff(1, 2), 'o', ...
+ 'MarkerFaceColor', cc(j, :), ...
+ 'MarkerEdgeColor', 'none', ...
+ 'MarkerSize', 10);
+ end
+
+ xx = xx + 1;
+
+end
+
+% Configure the axes of the regression plot
+config_regression(gca, xoffs, round(16 * exp(tau), 0));
+
+end
+
+
+% ------------------------- CONFIGURATIONS--------------------------------
+
+function plot_signals(t, y, cc)
+% Plot the predictions from the two regions
+
+h = plot(t, y,...
+ 'Color', cc);
+h(1).LineStyle = '--';
+h(2).LineStyle = '-';
+
+end
+
+function config_prediction(h, plotFlag)
+% Configure the prediction plot (prediction and difference)
+
+set(h, 'TickDir', 'out', ...
+ 'XGrid', 'on', ...
+ 'XLim', [0, 0.51], ...
+ 'XTick', [0 : 0.1 : 0.5], ...
+ 'YGrid', 'on', ...
+ 'PlotBoxAspectRatio', [1 1 1], ...
+ 'FontSize', 14);
+
+% Set axes labels
+h.XLabel.String = 'Time [s]';
+switch plotFlag
+ case 'raw'
+ h.YLabel.String = 'predicted signal (y_p)';
+ case 'delta'
+ h.YLabel.String = '\Delta y_p';
+end
+
+% Increase LineWidth
+hh = findobj(h.Children, 'Type', 'Line');
+set(hh, 'LineWidth', 2);
+
+end
+
+
+function config_regression(h, xticks, tickLabels)
+% Configure the regression plot
+
+set(h, 'XTick', xticks, ...
+ 'XTickLabels', tickLabels, ...
+ 'XTickLabelRotation', 45, ...
+ 'XGrid', 'on', ...
+ 'YGrid', 'on', ...
+ 'PlotBoxAspectRatio', [1 1 1]);
+
+
+h.YLabel.String = 'Pearson Correlation btw. integrators';
+h.XLabel.String = 'Delays [ms]';
+
+end
+
+
+
diff --git a/ceode/code/tutorial/tapas_ceode_synData_cmc.m b/ceode/code/tutorial/tapas_ceode_synData_cmc.m
new file mode 100644
index 00000000..1bde35ec
--- /dev/null
+++ b/ceode/code/tutorial/tapas_ceode_synData_cmc.m
@@ -0,0 +1,90 @@
+function [ DCM ] = tapas_ceode_synData_cmc()
+% [ DCM ] = tapas_ceode_synData_cmc()
+%
+% Sets parameters and function handles to create a synthetic DCM
+% structure. The resulting structure can then be used to generate
+% artificial data with tapas_ceode_gen_erp.m
+%
+% INPUT
+%
+% OUTPUT
+% DCM struct DCM structure with all necessary fields to
+% generate synthetic data.
+%
+% -------------------------------------------------------------------------
+%
+% Author: Dario Schöbi
+% Created: 2020-08-10
+% Copyright (C) 2020 TNU, Institute for Biomedical Engineering, University of Zurich and ETH Zurich.
+%
+% This file is part of the TAPAS ceode Toolbox, which is released under the terms of the GNU General Public
+% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
+% (either version 3 or, at your option, any later version). For further details, see the file
+% COPYING or .
+% -------------------------------------------------------------------------
+
+
+% ---------------------- MODEL SPECIFICATION ------------------------------
+M = struct();
+
+% Handles to specify integration scheme, dynamical equation, forward model
+% and input
+M.IS = 'tapas_ceode_gen_erp';
+M.f = 'spm_fx_cmc';
+M.int = 'spm_int_L';
+M.G = 'spm_lx_erp';
+M.FS = 'spm_fy_erp';
+M.fu = 'spm_erp_u';
+
+% Design/Parameter values of the driving input (see spm_erp_u.m)
+M.dur = 16;
+M.ons = 64;
+M.ns = 500;
+M.x = zeros(2, 8);
+M.m = 1;
+
+
+% ---------------------- DESIGN SPECIFICATION -----------------------------
+xU = struct();
+
+% No condition specific effec
+xU.X = [0]';
+xU.name = {'std'};
+
+% Sampling rate of the artificial signal
+xU.dt = 1e-03;
+
+
+% ---------------------- PARAMETER VALUES ---------------------------------
+% Neuronal parameters (also see spm_fx_cmc.m / tapas_ceode_fx_cmc.m)
+Ep = struct();
+
+Ep.M = zeros(2, 2);
+Ep.T = [0 0 0 0];
+Ep.G = zeros(2, 3);
+Ep.A{1} = [-32, -32; 0, -32];
+Ep.A{2} = [-32, -32; 0, -32];
+Ep.A{3} = [-32, 0; -32, -32];
+Ep.A{4} = [-32, 0; -32, -32];
+Ep.B{1} = [0 0; 1 0];
+Ep.N{1} = zeros(2, 2);
+Ep.C = [0; -32];
+Ep.D = -32 * ones(2, 2);
+Ep.S = 0;
+Ep.R = [0 0];
+
+% Leadfield parameters (also see spm_lx_erp.m)
+Eg.L = [1 1];
+Eg.J = [0 0 4 0 0 0 2 0];
+
+
+% ---------------------- CREATE OUTPUT ------------------------------------
+% Combine all structures into single DCM structure
+DCM.Ep = Ep;
+DCM.Eg = Eg;
+DCM.M = M;
+DCM.xU = xU;
+
+
+end
+
diff --git a/ceode/code/tutorial/tapas_ceode_synData_erp.m b/ceode/code/tutorial/tapas_ceode_synData_erp.m
new file mode 100644
index 00000000..5eb04d03
--- /dev/null
+++ b/ceode/code/tutorial/tapas_ceode_synData_erp.m
@@ -0,0 +1,88 @@
+function [ DCM ] = tapas_ceode_synData_erp()
+% [ DCM ] = tapas_ceode_synData_erp()
+%
+% Sets parameters and function handles to create a synthetic DCM
+% structure. The resulting structure can then be used to generate
+% artificial data with tapas_ceode_gen_erp.m
+%
+% INPUT
+%
+% OUTPUT
+% DCM struct DCM structure with all necessary fields to
+% generate synthetic data.
+%
+% -------------------------------------------------------------------------
+%
+% Author: Dario Schöbi
+% Created: 2020-08-10
+% Copyright (C) 2020 TNU, Institute for Biomedical Engineering, University of Zurich and ETH Zurich.
+%
+% This file is part of the TAPAS ceode Toolbox, which is released under the terms of the GNU General Public
+% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
+% (either version 3 or, at your option, any later version). For further details, see the file
+% COPYING or .
+% -------------------------------------------------------------------------
+
+
+% ---------------------- MODEL SPECIFICATION ------------------------------
+M = struct();
+
+% Handles to specify integration scheme, dynamical equation, forward model
+% and input
+M.IS = 'tapas_ceode_gen_erp';
+M.f = 'spm_fx_cmc';
+M.int = 'spm_int_L';
+M.G = 'spm_lx_erp';
+M.FS = 'spm_fy_erp';
+M.fu = 'spm_erp_u';
+
+% Design/Parameter values of the driving input (see spm_erp_u.m)
+M.dur = 16;
+M.ons = 64;
+M.ns = 500;
+M.x = zeros(2, 9);
+
+
+% ---------------------- DESIGN SPECIFICATION -----------------------------
+xU = struct();
+
+% No condition specific effec
+xU.X = [0]';
+xU.name = {'std'};
+
+% Sampling rate of the artificial signal
+xU.dt = 1e-03;
+
+
+% ---------------------- PARAMETER VALUES ---------------------------------
+% Neuronal parameters (also see spm_fx_erp.m / tapas_ceode_fx_erp.m)
+Ep = struct();
+
+Ep.T = [0, 0; 0 0];
+Ep.G = [0, 0; 0 0];
+Ep.S = [0, 0];
+Ep.A{1} = [-4, -4; 1, -4];
+Ep.A{2} = [-4, 0; -4, -4];
+Ep.A{3} = -4 * ones(2, 2);
+Ep.B{1} = zeros(2, 2);
+Ep.C = [0; -4];
+Ep.H = [0 0 0 0];
+Ep.D = -10 * ones(2, 2);
+Ep.R = [0 0];
+
+% Leadfield parameters (also see spm_lx_erp.m)
+Eg.L = [1, 2];
+Eg.J = [1, zeros(1, 5), 1, 0, 1];
+
+
+% ---------------------- CREATE OUTPUT ------------------------------------
+% Combine all structures into single DCM structure
+DCM.Ep = Ep;
+DCM.Eg = Eg;
+DCM.M = M;
+DCM.xU = xU;
+
+
+
+end
+
diff --git a/ceode/tapas_ceode_init.m b/ceode/tapas_ceode_init.m
new file mode 100644
index 00000000..0dcfeeed
--- /dev/null
+++ b/ceode/tapas_ceode_init.m
@@ -0,0 +1,154 @@
+function [ ] = tapas_ceode_init()
+% [ ] = tapas_ceode_init()
+%
+% Intitialization function of the tapas/ceode toolbox. It adds the relevant
+% toolbox function to the path. Additionally, it tests for the availability
+% of an SPM version, and performs a simple test to investigate
+% compatibility between the toolboxes used.
+%
+% INPUT
+%
+% OUTPUT
+%
+% -------------------------------------------------------------------------
+%
+% Author: Dario Schöbi
+% Created: 2020-08-10
+% Copyright (C) 2020 TNU, Institute for Biomedical Engineering, University of Zurich and ETH Zurich.
+%
+% This file is part of the TAPAS ceode Toolbox, which is released under the terms of the GNU General Public
+% Licence (GPL), version 3. You can redistribute it and/or modify it under the terms of the GPL
+% (either version 3 or, at your option, any later version). For further details, see the file
+% COPYING or .
+% -------------------------------------------------------------------------
+
+
+% Adds tapas/ceode/code folder to the current path
+ceode_root = fileparts(which('tapas_ceode_init'));
+addpath(genpath(fullfile(ceode_root, 'code')));
+
+
+%------------------------- Check for SPM ----------------------------------
+fprintf(['\n---------------------------------------------------------' ...
+ '\n Checking for SPM version \n' ...
+ '--------------------------------------------------------- \n'])
+try
+ spm_version = spm('version');
+ fprintf(['You are currently using SPM version: ' spm_version]);
+catch
+ spm_version = [];
+ error(['Please add the SPM EEG toolboxes to your path']);
+end
+
+
+%-------------------------- Test Scripts ----------------------------------
+fprintf(['\n\n---------------------------------------------------------' ...
+ '\n Running test scripts \n' ...
+ '--------------------------------------------------------- \n'])
+
+try
+ erp_test = tapas_ceode_testScript_erp();
+catch
+ erp_test.score = 0;
+ erp_test.msg = sprintf(['ERP test unsuccessful: \n' ...
+ 'Please make sure that the SPM EEG toolboxes are in your ' ...
+ 'MATLAB path.\n' ...
+ 'Please make sure that the test scripts have not been changed.']);
+end
+
+try
+ cmc_test = tapas_ceode_testScript_cmc();
+catch
+ cmc_test.score = 0;
+ cmc_test.msg = sprintf(['CMC test unsuccessful: \n' ...
+ 'Please make sure that the SPM EEG toolboxes are in your ' ...
+ 'MATLAB path.\n' ...
+ 'Please make sure that the test scripts have not been changed.']);
+end
+
+% Check the Test results
+if erp_test.score
+ fprintf('%s \n', erp_test.msg);
+else
+ warning('%s \n', erp_test.msg);
+end
+if cmc_test.score
+ fprintf('%s', cmc_test.msg);
+else
+ warning('%s', cmc_test.msg);
+end
+
+
+%------------------------ Current Integrator Specs ------------------------
+if spm_version
+ fprintf(['\n\n---------------------------------------------------------' ...
+ '\n Checking integrator settings \n' ...
+ '--------------------------------------------------------- \n'])
+
+ [fx_erp, fx_cmc, int_spec] = check_integrator_specification();
+ fprintf(['The current integration runs with: ' ...
+ '\n Integrator: %s' ...
+ '\n Dynamical Equations ERP: %s' ...
+ '\n Dynamical Equations CMC: %s \n'], ...
+ int_spec, fx_erp, fx_cmc);
+
+ check_integrator_compatibility(fx_erp, fx_cmc, int_spec)
+
+end
+
+
+end
+
+
+function [fx_erp, fx_cmc, int_spec] = ...
+ check_integrator_specification()
+% Checks the current dynamical equation function and the integrator used
+
+% Create a dummy parameter
+P.A{1} = zeros(2, 2);
+[~, fx_erp] = spm_dcm_x_neural(P, 'erp');
+[~, fx_cmc] = spm_dcm_x_neural(P, 'cmc');
+
+% Get the dependencies of spm_gen_erp
+[fList] = matlab.codetools.requiredFilesAndProducts('spm_gen_erp.m', ...
+ 'toponly');
+
+% Find the integrator
+int_spec = '';
+for i = 1 : length(fList)
+ [~, tmp] = fileparts(fList{i});
+ if strcmp(tmp, 'spm_int_L')
+ int_spec = tmp;
+ elseif strcmp(tmp, 'tapas_ceode_int_euler')
+ int_spec = tmp;
+ end
+end
+
+end
+
+
+function check_integrator_compatibility(fx_erp, fx_cmc, int_spec)
+% Check the combination of the dynamical equations and the integrator for
+% compatiblity
+
+if ~strcmp(int_spec, 'tapas_ceode_int_euler')
+ error(sprintf(['\nYour setup currently does not run the tapas/ceode integrator.' ...
+ '\nPlease consult the README.md how to enable ceode.\n']));
+else
+ fprintf('\nYour setup currently runs with the tapas/ceode integrator.\n');
+end
+
+if ~strcmp(fx_erp, 'tapas_ceode_fx_erp')
+ warning('Dynamical Equations: ERP are not compatible with integrator');
+end
+
+if ~strcmp(fx_cmc, 'tapas_ceode_fx_cmc')
+ warning('Dynamical Equations: CMC are not compatible with integrator');
+end
+
+fprintf('\nPlease consult the README.md if you want to change the settings.\n');
+
+
+end
+
+
diff --git a/external/JavaMD5/JavaMD5.m b/external/+JavaMD5/JavaMD5.m
similarity index 97%
rename from external/JavaMD5/JavaMD5.m
rename to external/+JavaMD5/JavaMD5.m
index d7e7d0cd..4acf9fab 100644
--- a/external/JavaMD5/JavaMD5.m
+++ b/external/+JavaMD5/JavaMD5.m
@@ -1,19 +1,19 @@
-function [md5hash] = JavaMD5(filename)
-%% [md5hash] = JavaMD5(filename)
-% Use a java routine to calculate MD5 hash of a file
-% Based on http://stackoverflow.com/a/304350/2531987
-% Written by Marcin Konowalczyk
-% Timmel Group @ Oxford University
-
-narginchk(1,1);
-assert(exist(filename,'file')==2,'JavaMD5:FileNotFoud','File not found');
-try
- md = java.security.MessageDigest.getInstance('MD5');
- fid = fopen(filename); % <- this is much faster than java i/o stream
- digest = dec2hex(typecast(md.digest(fread(fid, inf, '*uint8')),'uint8'));
- fclose(fid);
- md5hash = lower(reshape(digest',1,[]));
-catch me
- error('JavaMD5:HashError','Failed to calculate the MD5 hash');
-end
-end
+function [md5hash] = JavaMD5(filename)
+%% [md5hash] = JavaMD5(filename)
+% Use a java routine to calculate MD5 hash of a file
+% Based on http://stackoverflow.com/a/304350/2531987
+% Written by Marcin Konowalczyk
+% Timmel Group @ Oxford University
+
+narginchk(1,1);
+assert(exist(filename,'file')==2,'JavaMD5:FileNotFoud','File not found');
+try
+ md = java.security.MessageDigest.getInstance('MD5');
+ fid = fopen(filename); % <- this is much faster than java i/o stream
+ digest = dec2hex(typecast(md.digest(fread(fid, inf, '*uint8')),'uint8'));
+ fclose(fid);
+ md5hash = lower(reshape(digest',1,[]));
+catch me
+ error('JavaMD5:HashError','Failed to calculate the MD5 hash');
+end
+end
diff --git a/external/JavaMD5/license.txt b/external/+JavaMD5/license.txt
similarity index 100%
rename from external/JavaMD5/license.txt
rename to external/+JavaMD5/license.txt
diff --git a/external/mcmcdiag/ChangeLog b/external/mcmcdiag/ChangeLog
deleted file mode 100644
index 0fd2f835..00000000
--- a/external/mcmcdiag/ChangeLog
+++ /dev/null
@@ -1,119 +0,0 @@
-2014-02-24 Aki Vehtari
-
- * psrf.m: Updated to follow changes in BDA3.
-
- * cpsrf.m: Ditto.
-
-
-2006-02-14 Aki Vehtari
-
- * join.m: Special handling for type and rstate fields.
-
-2005-12-09 Aki Vehtari
-
- * ksstat.m: Fixed a bug.
-
-2004-10-20 Aki Vehtari
-
- * ksstat.m: Rewrote of ks.
-
-2004-01-22 Aki Vehtari
-
- * ipsrf.m: New function: Interval PSRF.
-
- * cipsrf.m: New function: Cumulative interval PSRF.
-
- * psrf.m: Added neff, changed R^2->R, and some cleaning.
-
- * cpsrf.m: Ditto.
-
- * mpsrf.m: Ditto.
-
- * cmpsrf.m: Ditto.
-
-2003-11-05 Aki Vehtari
-
- * kernelp.m: Define normpdf because not everyone has Statistical
- toolbox.
-
-2003-11-04 Aki Vehtari
-
- * geyer_imse.m: Add this because not everyone has Optimization
- toolbox.
-
- * kernel1.m: Define normpdf because not everyone has Statistical
- toolbox.
-
- * kernelp.m: Define gminus so that genops need not be installed .
-
-2003-09-15 Aki Vehtari
-
- * thin.m: rmfield(x,'rstate');
-
-2003-05-14 Aki Vehtari
-
- * Release 1.0: Document updates, bug fixes.
-
-2002-10-15 Aki Vehtari
-
- * geyer_icse.m: New function, Geyer's intial convex sequence
- estimator for autocorrelation time.
-
-2002-08-09 Aki Vehtari
-
- * kernel1.m: Make sure P >= 0.
-
-2001-06-17 Aki Vehtari
-
- * acorrtime.m: maxlag was not passed...
-
-2001-01-25 Aki Vehtari
-
- * ks.m: New function, Kolmogorov-Smirnov test.
-
-2000-05-22 Aki Vehtari
-
- * ndhist.m: Use 'hist' option when calling bar.
-
-2000-04-26 Aki Vehtari
-
- * acorrtime.m: New function.
-
- * acorr.m: Use xcorr for estimating autocorrelations.
-
- * diagg.m: use acorr.m
-
-2000-04-25 Aki Vehtari
-
- * autodens.m: Use lags.
-
- * autog.m: Fixed same things as in diagg.m previosly.
-
-2000-04-19 Aki Vehtari
-
- * diagg.m: Another legend fix.
-
-2000-04-18 Aki Vehtari
-
- * thin.m: General thinnig function from fbmtools.
-
- * diagg.m: Now works with vector
- + check if T is horizontal vector
- + Removed thinning arguments. Use thin.m instead.
-
-2000-03-27 Aki Vehtari
-
- * kernel1.m: Get size of T only once
- and check if T is horizontal vector.
-
-
-1999-11-03 Simo Särkkä
-
- * psrf.m: Added argument nlast and fixed couple of bugs.
-
- * kernel1.m: Removed possiblity to give probabilities as
- an argument.
-
- * qtiles.m: Function now takes two alpha values
- and their meaning has changed.
-
diff --git a/external/mcmcdiag/Contents.m b/external/mcmcdiag/Contents.m
deleted file mode 100644
index 8108853b..00000000
--- a/external/mcmcdiag/Contents.m
+++ /dev/null
@@ -1,46 +0,0 @@
-% MCMC Diagnostics Toolbox for Matlab 6.x
-% Version 1.1 2004-01-23
-% Copyright (C) 1999 Simo Särkkä
-% Copyright (C) 2000-2004 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-%
-% Covergence diagnostics
-% PSRF - Potential Scale Reduction Factor
-% CPSRF - Cumulative Potential Scale Reduction Factor
-% MPSRF - Multivariate Potential Scale Reduction Factor
-% CMPSRF - Cumulative Multivariate Potential Scale Reduction Factor
-% IPSRF - Interval-based Potential Scale Reduction Factor
-% CIPSRF - Cumulative Interval-based Potential Scale Reduction Factor
-% KSSTAT - Kolmogorov-Smirnov goodness-of-fit hypothesis test
-% HAIR - Brooks' hairiness convergence diagnostic
-% CUSUM - Yu-Mykland convergence diagnostic for MCMC
-% SCORE - Calculate score-function convergence diagnostic
-% GBINIT - Initial iterations for Gibbs iteration diagnostic
-% GBITER - Estimate number of additional Gibbs iterations
-%
-% Time series analysis
-% ACORR - Estimate autocorrelation function of time series
-% ACORRTIME - Estimate autocorrelation evolution of time series (simple)
-% GEYER_ICSE - Compute autocorrelation time tau using Geyer's
-% initial convex sequence estimator
-% (requires Optimization toolbox)
-% GEYER_IMSE - Compute autocorrelation time tau using Geyer's
-% initial monotone sequence estimator
-%
-% Kernel density estimation etc.:
-% KERNEL1 - 1D Kernel density estimation of data
-% KERNELS - Kernel density estimation of independent components of data
-% KERNELP - 1D Kernel density estimation, with automatic kernel width
-% NDHIST - Normalized histogram of N-dimensional data
-% HPDI - Estimates the Bayesian HPD intervals
-%
-% Manipulation of MCMC chains
-% THIN - Delete burn-in and thin MCMC-chains
-% JOIN - Join similar structures of arrays to one structure of arrays
-%
-% Misc:
-% CUSTATS - Calculate cumulative statistics of data
-%
diff --git a/external/mcmcdiag/License.txt b/external/mcmcdiag/License.txt
deleted file mode 100644
index 60549be5..00000000
--- a/external/mcmcdiag/License.txt
+++ /dev/null
@@ -1,340 +0,0 @@
- GNU GENERAL PUBLIC LICENSE
- Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.
- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users. This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it. (Some other Free Software Foundation software is covered by
-the GNU Library General Public License instead.) You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
- To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have. You must make sure that they, too, receive or can get the
-source code. And you must show them these terms so they know their
-rights.
-
- We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
- Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software. If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
- Finally, any free program is threatened constantly by software
-patents. We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary. To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- GNU GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License. The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language. (Hereinafter, translation is included without limitation in
-the term "modification".) Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
- 1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
- 2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) You must cause the modified files to carry prominent notices
- stating that you changed the files and the date of any change.
-
- b) You must cause any work that you distribute or publish, that in
- whole or in part contains or is derived from the Program or any
- part thereof, to be licensed as a whole at no charge to all third
- parties under the terms of this License.
-
- c) If the modified program normally reads commands interactively
- when run, you must cause it, when started running for such
- interactive use in the most ordinary way, to print or display an
- announcement including an appropriate copyright notice and a
- notice that there is no warranty (or else, saying that you provide
- a warranty) and that users may redistribute the program under
- these conditions, and telling the user how to view a copy of this
- License. (Exception: if the Program itself is interactive but
- does not normally print such an announcement, your work based on
- the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
- a) Accompany it with the complete corresponding machine-readable
- source code, which must be distributed under the terms of Sections
- 1 and 2 above on a medium customarily used for software interchange; or,
-
- b) Accompany it with a written offer, valid for at least three
- years, to give any third party, for a charge no more than your
- cost of physically performing source distribution, a complete
- machine-readable copy of the corresponding source code, to be
- distributed under the terms of Sections 1 and 2 above on a medium
- customarily used for software interchange; or,
-
- c) Accompany it with the information you received as to the offer
- to distribute corresponding source code. (This alternative is
- allowed only for noncommercial distribution and only if you
- received the program in object code or executable form with such
- an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it. For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable. However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License. Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
- 5. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Program or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
- 6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
- 7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all. For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded. In such case, this License incorporates
-the limitation as if written in the body of this License.
-
- 9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation. If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
- 10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission. For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this. Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
- NO WARRANTY
-
- 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
- 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-
- Copyright (C) 19yy
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
- Gnomovision version 69, Copyright (C) 19yy name of author
- Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the program
- `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
- , 1 April 1989
- Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs. If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library. If this is what you want to do, use the GNU Library General
-Public License instead of this License.
diff --git a/external/mcmcdiag/Readme.txt b/external/mcmcdiag/Readme.txt
deleted file mode 100644
index 7d4a6681..00000000
--- a/external/mcmcdiag/Readme.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-MCMC Diagnostics Toolbox for Matlab 6.x
-
-Copyright (C) 1999 Simo Särkkä
-Copyright (C) 2000-2004 Aki Vehtari
-Maintainer: Aki Vehtari
-
-In 1999 Simo Särkkä implemented several MCMC diagnostics in Matlab
-at Helsinki University of Technology, Laboratory of Computational
-Engineering . Later Aki Vehtari added a few
-additonal utilities, fixed bugs and improved the documentation.
-
-This software is distributed under the GNU General Public Licence
-(version 2 or later); please refer to the file Licence.txt,
-included with the software, for details.
diff --git a/external/mcmcdiag/acorr.m b/external/mcmcdiag/acorr.m
deleted file mode 100644
index fbec86d4..00000000
--- a/external/mcmcdiag/acorr.m
+++ /dev/null
@@ -1,30 +0,0 @@
-function c = acorr(x,maxlag)
-%ACORR Estimate autocorrelation function of time series
-%
-% C = ACORR(X,MAXLAG) returns normalized autocorrelation
-% sequences for each column of X using
-% C(:,i)=XCORR(X(:,i)-MEAN(X(:,i)),MAXLAG,'coeff'), but returns only
-% lags 1:MAXLAG. Default MAXLAG = M-1;
-%
-% See also
-% XCORR
-
-% Copyright (C) 2000 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-if nargin < 1
- error('Not enough input arguments.');
-end
-if nargin < 2
- maxlag=length(x)-1;
-end
-[m,n]=size(x);
-c=zeros(maxlag,n);
-for i1=1:n
- ct=xcorr(x(:,i1)-mean(x(:,i1)),maxlag,'coeff');
- ct=ct(maxlag+2:end);
- c(:,i1)=ct;
-end
diff --git a/external/mcmcdiag/acorrtime.m b/external/mcmcdiag/acorrtime.m
deleted file mode 100644
index 60692752..00000000
--- a/external/mcmcdiag/acorrtime.m
+++ /dev/null
@@ -1,42 +0,0 @@
-function t = acorrtime(x,maxlag)
-% ACORRTIME Estimate autocorrelation evolution of time series
-%
-% T = ACORRTIME(X,MAXLAG) returns estimate for autocorrelation
-% time defined as MAXLAG
-% t = 1 + 2 sum r(l),
-% l=1
-% where r(l) is the sample autocorrelation at the lag l.
-% Sum is cutted of at a finite value L beyond which the
-% autocorrelation estimate is close to zero, since adding
-% autocorrelations for higher lags will only add in excess noise.
-% Autocorrelation sequence is estimated using r=ACORR(X,MAXLAG).
-%
-% If MAXLAG is not given, maximum autocorrelation time over all possible
-% MAXLAG values is returned. This serves as a pessimistic estimate.
-%
-% See also
-% ACORR
-
-% References:
-% [1] R. Neal, "Probabilistic Inference Using Markov Chain
-% Monte Carlo Methods", Technical Report CRG-TR-93-1,
-% Dept. of Computer Science, University of Toronto, 1993. p.105.
-% [2] R. E. Kass et al., "Markov chain Monte Carlo in practice:
-% A roundtable discussion", American Statistician,
-% 52:93-100, 1998. p. 99.
-% [3] L. Zhu and B. P. Carlin, "Comparing hierarchical models
-% for spatio-temporally misaligned data using DIC
-% criterion. Technical report, Division of Biostatistics,
-% University of Minnesota, 1999. p. 9.
-
-% Copyright (C) 2000-2001 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-if nargin > 1
- t=1+2*sum(acorr(x,maxlag));
-else
- t=1+2*max(cumsum(acorr(x)));
-end
diff --git a/external/mcmcdiag/cipsrf.m b/external/mcmcdiag/cipsrf.m
deleted file mode 100644
index 433f808d..00000000
--- a/external/mcmcdiag/cipsrf.m
+++ /dev/null
@@ -1,52 +0,0 @@
-function R = cipsrf(varargin)
-%CIPSRF Cumulative Interval Potential Scale Reduction Factor
-%
-% [R] = CIPSRF(X,[n0]) or
-% [R] = CIPSRF(x1,x2,x3,...[,n0])
-% returns Cumulative Interval Potential Scale Reduction Factor
-% for collection of MCMC-simulations. Analysis is first based on
-% PSRF-analysis of samples 1 to n0. Then for samples 1 to n0+1
-% and so on.
-%
-% Default value for parameter n0 is |X|/2.
-%
-% See also
-% IPSRF
-
-% Copyright (C) 1999 Simo Särkkä
-% Copyright (C) 2004 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-
-% Handle the input arguments
-if prod(size(varargin{nargin}))==1
- count = nargin-1;
- n0 = varargin{nargin};
-else
- count = nargin;
- n0 = [];
-end
-
-if count<=1
- X = varargin{1};
-else
- X = zeros([size(varargin{1}) count]);
- for i=1:count
- X(:,:,i) = varargin{i};
- end
-end
-if isempty(n0)
- n0 = floor(size(X,1)/2) + 1;
-end
-if n0 < 2
- error('n0 should be at least 2');
-end
-
-[N,D,M]=size(X);
-R = zeros(N-n0+1,D);
-for i=n0:N
- R(i-n0+1,:)=ipsrf(X(1:i,:,:));
-end
diff --git a/external/mcmcdiag/cmpsrf.m b/external/mcmcdiag/cmpsrf.m
deleted file mode 100644
index 72abf894..00000000
--- a/external/mcmcdiag/cmpsrf.m
+++ /dev/null
@@ -1,54 +0,0 @@
-function [R,neff] = cmpsrf(varargin)
-%CMPSRF Cumulative Multivariate Potential Scale Reduction Factor
-%
-% [R,neff] = CMPSRF(X,[n0])
-% [R,neff] = CMPSRF(x1,x2,x3,...[,n0])
-% returns Cumulative Multivariate Potential Scale Reduction
-% Factor for collection of MCMC-simulations. Analysis is first
-% based on MPSRF-analysis of samples 1 to n0. Then for samples
-% 1 to n0+1 and so on.
-%
-% Default value for parameter n0 is |X|/2.
-%
-% See also
-% MPSRF, PSRF, CPSRF
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-% 2004-01-22 Aki.Vehtari@hut.fi Added neff, R^2->R, and cleaning
-
-% Handle the input arguments
-if prod(size(varargin{nargin}))==1
- count = nargin-1;
- n0 = varargin{nargin};
-else
- count = nargin;
- n0 = [];
-end
-
-if count<=1
- X = varargin{1};
-else
- X = zeros([size(varargin{1}) count]);
- for i=1:count
- X(:,:,i) = varargin{i};
- end
-end
-if isempty(n0)
- n0 = floor(size(X,1)/2) + 1;
-end
-if n0 < 2
- error('n0 should be at least 2');
-end
-
-% Calculate the reduction factors
-[m,n]=size(X);
-R = zeros(m-n0+1,n);
-neff = R;
-for i=n0:size(X,1)
- [R(i-n0+1,:),neff(i-n0+1,:)]=mpsrf(X(1:i,:,:));
-end
diff --git a/external/mcmcdiag/cpsrf.m b/external/mcmcdiag/cpsrf.m
deleted file mode 100644
index dce7f290..00000000
--- a/external/mcmcdiag/cpsrf.m
+++ /dev/null
@@ -1,47 +0,0 @@
-function [R,neff,V,W,B] = cpsrf(varargin)
-%CPSRF Cumulative Potential Scale Reduction Factor
-%
-% [R,neff,V,W,B] = CPSRF(X,[n0]) or
-% [R,neff,V,W,B] = CPSRF(x1,x2,x3,...[,n0])
-% returns Cumulative Potential Scale Reduction Factor for
-% collection of MCMC-simulations. Analysis is first based
-% on PSRF-analysis of samples 1 to n0. Then for samples
-% 1 to n0+1 and so on.
-%
-% Default value for parameter n0 is |X|/2.
-%
-% See also
-% PSRF, MPSRF, CMPSRF
-
-% Copyright (C) 1999 Simo Särkkä
-% Copyright (C) 2013 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 3 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-% 2004-01-22 Aki.Vehtari@hut.fi Added neff, R^2->R, and cleaning
-% 2013-10-20 Aki.Vehtari@aalto.fi Updated according to BDA3
-
-% Handle the input arguments
-if nargin>1 && isscalar(varargin{end})
- X=cat(3,varargin{1:end-1});
- n0 = varargin{end};
-else
- X=cat(3,varargin{:});
- n0 = floor(size(X,1)/2) + 1;
-end
-if n0 < 2
- error('n0 should be at least 2');
-end
-
-[N,D,M]=size(X);
-R = zeros(N-n0+1,D);
-neff = R;
-V = R;
-W = R;
-for i=n0:N
- [R(i-n0+1,:),neff(i-n0+1,:),V(i-n0+1,:),W(i-n0+1,:),B(i-n0+1,:)]=...
- psrf(X(1:i,:,:));
-end
-
diff --git a/external/mcmcdiag/custats.m b/external/mcmcdiag/custats.m
deleted file mode 100644
index 0a63badd..00000000
--- a/external/mcmcdiag/custats.m
+++ /dev/null
@@ -1,23 +0,0 @@
-function [CA,CS] = custats(X,n0)
-%CUSTATS Calculate cumulative statistics of data
-%
-% [CA,CS] = custats(X) or [CA,CS] = custats(X,n0)
-% returns cumulative statistics of X. CA is the
-% cumulative average and CS is the cumulative variance.
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-
-if nargin==1
- n0 = 0;
-end
-
-X = X((n0+1):end,:,:);
-X2 = X .* X;
-CA = cumsum(X)./ repmat((1:size(X,1))',[1 size(X,2) size(X,3)]);
-CS = cumsum(X2)./ repmat((1:size(X,1))',[1 size(X,2) size(X,3)]);
-CS = CS - CA.*CA;
diff --git a/external/mcmcdiag/cusum.m b/external/mcmcdiag/cusum.m
deleted file mode 100644
index d386e465..00000000
--- a/external/mcmcdiag/cusum.m
+++ /dev/null
@@ -1,38 +0,0 @@
-function C = cusum(W,n0)
-%CUSUM Yu-Mykland convergence diagnostic for MCMC
-%
-% C = cusum(W,n0) or C = cusum(W) returns
-% cumulative sum of each column of W as:
-%
-% n
-% ___
-% \
-% C(i) = /__( W(i) - S ),
-% i=n0+1
-%
-% where S is "empirical average":
-% n
-% ___
-% \
-% S = 1/T /__ W(i)
-% i=n0+1
-%
-% Default value for "burn-in" variable n0 is 0.
-%
-% See also
-% HAIR
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-if nargin==2
- W = W(n0+1:end,:);
-end
-T = size(W,1);
-S = sum(W) / T;
-C = cumsum(W-repmat(S,size(W,1),1));
-
-
diff --git a/external/mcmcdiag/gbinit.m b/external/mcmcdiag/gbinit.m
deleted file mode 100644
index 5dd848d0..00000000
--- a/external/mcmcdiag/gbinit.m
+++ /dev/null
@@ -1,28 +0,0 @@
-function nmin = gbinit(q,r,s)
-%GBINIT Initial iterations for Gibbs iteration diagnostic
-%
-% nmin = gbinit(q,r,s) returns number of
-% initial iterations needed for estimating how
-% many additional iterations are needed for
-% given precision.
-%
-% The definition of the precisions parameters:
-%
-% "Suppose that U is function of theta, which is the
-% parameter to be estimated. We want to estimate
-% P[U <= u | y] to within +-r with probability s.
-% We will find the approximate number of iterations
-% needed to do this when the correct answer is q."
-%
-% Use q=0.025, r=0.005, s=0.95 if you are unsure.
-%
-% See also
-% GBITER
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-nmin = round(norminv((s+1)/2)^2*q*(1-q)/r^2);
diff --git a/external/mcmcdiag/gbiter.m b/external/mcmcdiag/gbiter.m
deleted file mode 100644
index cb7812db..00000000
--- a/external/mcmcdiag/gbiter.m
+++ /dev/null
@@ -1,162 +0,0 @@
-function [M,N,k] = gbiter(X,q,r,s)
-%GBITER Estimate number of additional Gibbs iterations
-%
-% [M,N,k] = gbiter(X,[q,r,s]) or returns number of
-% additional iterations required for accurate result
-% and of what portion of the samples should be used.
-% The returned values are as follows:
-%
-% M defines how many of the first iterations should be
-% thrown away. N is the number of iterations should be done
-% (after the first M). Only every k'th sample should be used
-%
-% X has the initial >Nmin iterations which are
-% used for estimation. Parameters q, r and s
-% are defined as follows:
-%
-% "Suppose that U is function of theta, which is the
-% parameter to be estimated. We want to estimate
-% P[U <= u | y] to within +-r with probability s.
-% We will find the approximate number of iterations
-% needed to do this when the correct answer is q."
-%
-% Use q=0.025, r=0.005, s=0.95 (defaults) if you are unsure.
-% Thus, it could be reasonable to try different q-values
-% instead of selecting the default 0.025. See Brooks and
-% Roberts (1999) for more detailed discussion.
-%
-% References
-% Brooks, S.P. and Roberts, G.O. (1999) On Quantile Estimation
-% and MCMC Convergence. Biometrika.
-%
-% See also
-% GBINIT
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-
-if nargin < 4
- s = 0.95;
-end
-if nargin < 3
- r = 0.005;
-end
-if nargin < 2
- q = 0.025;
-end
-
-% Estimate q-quontiles u(:) for each variable and
-% create binary sequences Z(:,n).
-% (Method is from "gibbsit"-program.)
-e = 0.001;
-Z = zeros(size(X,1),size(X,2));
-for n=1:size(X,2)
- x = sort(X(:,n));
- order = q * (size(X,1)-1) + 1;
- fract = mod(order,1.0);
- low = max(floor(order),1);
- high = min(low+1, size(X,1));
- u = (1 - fract) * x(low) + fract * x(high);
- Z(:,n) = (X(:,n) <= u);
-end
-
-k1 = zeros(1,size(Z,2));
-alpha = zeros(1,size(Z,2));
-beta = zeros(1,size(Z,2));
-k2 = zeros(1,size(Z,2));
-
-for m=1:size(Z,2)
-
- % Find out when sequence turns from second
- % order Markov to first order
- bic = 1;
- kthin = 0;
- while bic >= 0
- kthin = kthin + 1;
- z = Z(1:kthin:end,m);
-
- % Estimate second order Markov chain
- M = zeros(2,2,2);
- for n=3:size(z,1)
- M(z(n-2)+1, z(n-1)+1, z(n)+1) = ...
- M(z(n-2)+1, z(n-1)+1, z(n)+1) + 1;
- end
-
- % Do g2 test
- count = size(z,1)-2;
- g2 = 0;
- for i=1:2
- for j=1:2
- for k=1:2
- if M(i,j,k) ~= 0
- fitted = sum(M(i,j,:)) * sum(M(:,j,k));
- fitted = fitted / sum(sum(M(:,j,:)));
- g2 = g2 + log( M(i,j,k) / fitted) * M(i,j,k);
- end
- end
- end
- end
- g2 = 2*g2;
- bic = g2 - 2*log(count);
- end
- k2(m) = kthin;
-
- % Estimate first order Markov chain
- M = zeros(2,2);
- for n=2:size(z,1)
- M(z(n-1)+1, z(n)+1) = ...
- M(z(n-1)+1, z(n)+1) + 1;
- end
- alpha(m) = M(1,2) / (M(1,1) + M(1,2));
- beta(m) = M(2,1) / (M(2,1) + M(2,2));
-
- % Find out when sequence turns from first
- % order Markov to independent sequence
- bic = 1;
- kthin = kthin-1;
-
- while bic >= 0
- kthin = kthin + 1;
- z = Z(1:kthin:end,m);
-
- % Estimate first order Markov chain
- M = zeros(2,2);
- for n=2:size(z,1)
- M(z(n-1)+1, z(n)+1) = ...
- M(z(n-1)+1, z(n)+1) + 1;
- end
-
- % Do g2 test
- count = size(z,1)-1;
- g2 = 0;
- for i=1:2
- for j=1:2
- if M(i,j) ~= 0
- fitted = sum(M(i,:)) * sum(M(:,j)) / count;
- g2 = g2 + log( M(i,j) / fitted) * M(i,j);
- end
- end
- end
- g2 = 2*g2;
- bic = g2 - log(count);
- end
-
- k1(m) = kthin;
-end
-
-% Calculate k, N and nburn
-tmp = log((alpha + beta) * e ./ ...
- max(alpha,beta)) ./ log(abs(1 - alpha - beta));
-nburn = round(tmp) .* k2;
-
-phi = norminv((s+1)/2);
-tmp = (2-alpha-beta) .* alpha .* beta ./ (alpha+beta).^3;
-tmp = tmp * (phi/r)^2;
-N = max(round(max(1,tmp)) .* k2);
-k = max(k2);
-M = max(nburn);
-
diff --git a/external/mcmcdiag/geyer_icse.m b/external/mcmcdiag/geyer_icse.m
deleted file mode 100644
index 64aaeff4..00000000
--- a/external/mcmcdiag/geyer_icse.m
+++ /dev/null
@@ -1,74 +0,0 @@
-function [t,t1] = geyer_icse(x,maxlag)
-% GEYER_ICSE - Compute autocorrelation time tau using Geyer's
-% initial convex sequence estimator
-%
-% C = GEYER_ICSE(X) returns autocorrelation time tau.
-% C = GEYER_ICSE(X,MAXLAG) returns autocorrelation time tau with
-% MAXLAG . Default MAXLAG = M-1.
-%
-% References:
-% [1] C. J. Geyer, (1992). "Practical Markov Chain Monte Carlo",
-% Statistical Science, 7(4):473-511
-
-% Copyright (C) 2002 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-% compute autocorrelation
-if nargin > 1
- cc=acorr(x,maxlag);
-else
- cc=acorr(x);
-end
-[n,m]=size(cc);
-
-% acorr returns values starting from lag 1, so add lag 0 here
-cc=[ones(1,m);cc];
-n=n+1;
-
-% now make n even
-if mod(n,2)
- n=n-1;
- cc(end,:)=[];
-end
-
-% loop through variables
-t=zeros(1,m);
-t1=zeros(1,m);
-opt=optimset('LargeScale','off','display','off');
-for i1=1:m
- c=cc(:,i1);
- c=sum(reshape(c,2,n/2),1);
- ci=find(c<0);
- if isempty(ci)
- warning(sprintf('Inital positive could not be found for variable %d, using maxlag value',i1));
- ci=n/2;
- else
- ci=ci(1)-1; % initial positive
- end
- c=[c(1:ci) 0]; % initial positive sequence
- t1(i1)=-1+2*sum(c); % initial positive sequence estimator
- if ci>2
- ca=fmincon(@se,c,[],[],[],[],0*c,c,@sc,opt,c); % monotone convex sequence
- else
- ca=c;
- end
- t(i1)=-1+2*sum(ca); % monotone convex sequence estimator
-end
-
-function e = se(x,xx)
-% SE - Error in monotone convex sequene estimator
-e=sum((xx-x).^2);
-
-function [c,ceq] = sc(x,xx)
-% SE - Constraint in monotone convex sequene estimator
-ceq=0*x;
-c=ceq;
-d=diff(x);
-dd=-diff(d);
-d(d<0)=0;d=d.^2;
-dd(dd<0)=0;dd=dd.^2;
-c(1:end-1)=d;c(2:end)=c(2:end)+d;
-c(1:end-2)=dd;c(2:end-1)=c(2:end-1)+dd;c(3:end)=c(3:end)+dd;
diff --git a/external/mcmcdiag/geyer_imse.m b/external/mcmcdiag/geyer_imse.m
deleted file mode 100644
index 938074e1..00000000
--- a/external/mcmcdiag/geyer_imse.m
+++ /dev/null
@@ -1,67 +0,0 @@
-function [t,t1] = geyer_imse(x,maxlag)
-% GEYER_IMSE - Compute autocorrelation time tau using Geyer's
-% initial monotone sequence estimator
-%
-% C = GEYER_IMSE(X) returns autocorrelation time tau.
-% C = GEYER_IMSE(X,MAXLAG) returns autocorrelation time tau with
-% MAXLAG . Default MAXLAG = M-1.
-%
-% References:
-% [1] C. J. Geyer, (1992). "Practical Markov Chain Monte Carlo",
-% Statistical Science, 7(4):473-511
-%
-% This function is replacment for GEYER_ICSE, when Optimization
-% toolbox is not available
-%
-% See also
-% GEYER_ICSE
-
-% Copyright (C) 2002-2003 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-
-% compute autocorrelation
-if nargin > 1
- cc=acorr(x,maxlag);
-else
- cc=acorr(x);
-end
-[n,m]=size(cc);
-
-% acorr returns values starting from lag 1, so add lag 0 here
-cc=[ones(1,m);cc];
-n=n+1;
-
-% now make n even
-if mod(n,2)
- n=n-1;
- cc(end,:)=[];
-end
-
-% loop through variables
-t=zeros(1,m);
-t1=zeros(1,m);
-for i1=1:m
- c=cc(:,i1);
- c=sum(reshape(c,2,n/2),1);
- ci=find(c<0);
- if isempty(ci)
- warning(sprintf('Inital positive could not be found for variable %d, using maxlag value',i1));
- ci=n/2;
- else
- ci=ci(1)-1; % initial positive
- end
- c=[c(1:ci) 0]; % initial positive sequence
- t1(i1)=-1+2*sum(c); % initial positive sequence estimator
- if ci>2
- for i2=length(c):-1:2
- if c(i2)>c(i2-1)
- c(i2-1)=c(i2); % monotone sequence
- end
- end
- end
- t(i1)=-1+2*sum(c); % monotone sequence estimator
-end
diff --git a/external/mcmcdiag/hair.m b/external/mcmcdiag/hair.m
deleted file mode 100644
index 9ffb75af..00000000
--- a/external/mcmcdiag/hair.m
+++ /dev/null
@@ -1,42 +0,0 @@
-function [DA,DS] = hair(W,n0)
-%HAIR Brooks' hairiness convergence diagnostic
-%
-% [DA,DS] = hair(W,n0) or [DA,DS] = hair(W)
-% returns a measurements of hairiness calculated
-% separately for every column of W
-% n
-% __
-% \
-% DA(t) = 1/t /__ d(i)
-% i=n0+1
-%
-% n
-% __
-% \
-% DS(t) = -DA(t)^2 + 1/t /__ d(i)^2
-% i=n0+1
-%
-% where d(i) is 1 if there is local maximum/
-% minimum in CUSUM C(i) of the column of W,
-% 0 otherwise. DA is the empirical average and
-% DS variance.
-%
-% Default value for "burn-in" variable n0 is 0.
-%
-% See also
-% CUSUM
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-if nargin==2
- C = cusum(W,n0);
-else
- C = cusum(W,0);
-end
-s = sign(C(1:end-1,:) - C(2:end,:));
-d = s(1:end-1,:) .* s(2:end,:) < 0;
-[DA,DS] = custats(d);
diff --git a/external/mcmcdiag/hpdi.m b/external/mcmcdiag/hpdi.m
deleted file mode 100644
index b3d8cfe8..00000000
--- a/external/mcmcdiag/hpdi.m
+++ /dev/null
@@ -1,33 +0,0 @@
-function hpdi = hpdi(x, p)
-% HPDI - Estimates the Bayesian HPD intervals
-%
-% Y = HPDI(X,P) returns a Highest Posterior Density (HPD) interval
-% for each column of X. P must be a scalar. Y is a 2 row matrix
-% where ith column is HPDI for ith column of X.
-
-% References:
-% [1] Chen, M.-H., Shao, Q.-M., and Ibrahim, J. Q., (2000).
-% Monte Carlo Methods in Bayesian Computation. Springer-Verlag.
-
-% Copyright (C) 2001 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-if nargin < 2
- error('Not enough arguments')
-end
-
-m=size(x,2);
-pts=linspace(0.1,99.9-p,20);
-pt1=prctile(x,pts);
-pt2=prctile(x,p+pts);
-cis=abs(pt2-pt1);
-[foo,hpdpi]=min(cis);
-if m==1
- hpdi=[pt1(hpdpi); pt2(hpdpi)];
-else
- hpdpi=sub2ind(size(pt1),hpdpi,1:m);
- hpdi=[pt1(hpdpi); pt2(hpdpi)];
-end
diff --git a/external/mcmcdiag/ipsrf.m b/external/mcmcdiag/ipsrf.m
deleted file mode 100644
index fed81f12..00000000
--- a/external/mcmcdiag/ipsrf.m
+++ /dev/null
@@ -1,74 +0,0 @@
-function [R] = ipsrf(varargin)
-%IPSRF Interavl Potential Scale Reduction Factor
-%
-% [R] = IPSRF(X) or
-% [R] = IPSRF(x1,x2,...,xs)
-% returns "Potential Scale Reduction Factor" (PSRF) for
-% collection of MCMC-simulations. X is a NxDxM matrix
-% which contains M MCMC simulations of length N, each with
-% dimension D. MCMC-simulations can be given as separate
-% arguments x1,x2,... which should have the same length.
-%
-% Returns
-% R PSRF in a row vector of length D
-%
-% The idea of the PSRF is that if R is not near 1 (below 1.1 for
-% example) one may conclude that the tested samples were not from
-% the same distribution (chain might not have been converged
-% yet). Instead of normality assumption, 80% empirical intervals
-% are used to compute R.
-%
-% If only one simulation is given, the factor is calculated
-% between first and last third of the chain. Note that use of
-% only one chain will produce over-optimistic result.
-%
-% Method is from:
-% Brooks, S.P. and Gelman, A. (1998) General methods for
-% monitoring convergence of iterative simulations. Journal of
-% Computational and Graphical Statistics. 7, 434-455.
-%
-% See also
-% CIPSRF, PSRF
-
-% Copyright (C) 1999 Simo Särkkä
-% Copyright (C) 2004 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-% In case of one argument split to two halves (first and last thirds)
-onechain=0;
-if nargin==1
- X = varargin{1};
- if size(X,3)==1
- n = floor(size(X,1)/3);
- x = zeros([n size(X,2) 2]);
- x(:,:,1) = X(1:n,:);
- x(:,:,2) = X((end-n+1):end,:);
- X = x;
- onechain=1;
- end
-elseif nargin==0
- error('Cannot calculate PSRF of scalar');
-else
- X = zeros([size(varargin{1}) nargin]);
- for i=1:nargin
- X(:,:,i) = varargin{i};
- end
-end
-
-[N,D,M]=size(X);
-
-if N<1
- error('Too few samples');
-end
-
-W = zeros(1,D);
-V = zeros(1,D);
-for d=1:D
- x=X(:,d,:);
- W(1,d)=mean(diff(prctile(x,[10 90])));
- V(1,d)=diff(prctile(x(:),[10 90]));
-end
-R = V./W;
diff --git a/external/mcmcdiag/join.m b/external/mcmcdiag/join.m
deleted file mode 100644
index 14cf2200..00000000
--- a/external/mcmcdiag/join.m
+++ /dev/null
@@ -1,63 +0,0 @@
-function r = join(rs, joinall)
-%JOIN Join similar structures of arrays to one structure of arrays
-%
-% JOIN can be used to combine statistics collected from several
-% independent simulations which collect samples to structure
-% of arrays.
-%
-% R = JOIN(RS) returns structure of arrays R, RS is array or
-% cell-array of similar structures of arrays. Arrays of R are
-% contanation of arrays in RS. Arrays having first dimension 1
-% are not concataned, but copied from the first element of RS.
-%
-% R = JOIN(RS, JOINALL) if JOINALL is 1, arrays having first
-% dimension 1 are concataned.
-%
-% See also
-% THIN
-
-% Copyright (C) 2000-2006 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-if nargin <2
- joinall=false;
-end
-
-[m,n]=size(rs);
-
-r=[];
-if (m==1 & n==1)
- r=rs;
-else
- if iscell(rs)
- rs=[rs{:}];
- end
- if isstruct(rs)
- r=rs(1);
- names = fieldnames(r);
- for i1=1:size(names,1)
- switch names{i1}
- case 'rstate'
- continue
- case 'type'
- r.type=rs(1).(names{1});
- continue
- end
- tmp1=getfield(r,names{i1});
- if iscell(tmp1)
- %tmp2=eval(['cat(1,rs(:).' names{i1} ')']);
- tmp2=cat(1,rs(:).(names{i1}));
- for i2=1:length(tmp1(:))
- %eval(['r.' names{i1} '{i2}=cat(1,tmp2{:,i2});']);
- r.(names{i1}){i2}=cat(1,tmp2{:,i2});
- end
- elseif length(tmp1) > 1 || joinall
- %eval(['r.' names{i1} '=cat(1,rs.' names{i1} ');']);
- r.(names{i1})=cat(1,rs.(names{i1}));
- end
- end
- end
-end
diff --git a/external/mcmcdiag/kernel1.m b/external/mcmcdiag/kernel1.m
deleted file mode 100644
index 38a43fe1..00000000
--- a/external/mcmcdiag/kernel1.m
+++ /dev/null
@@ -1,112 +0,0 @@
-function [P,X,sigma] = kernel1(T,sigma,bins,extra)
-%KERNEL1 1D Kernel density estimation of data
-%
-% [P,X,sigma] = kernel1(T,sigma,bins,extra) returns kernel based
-% marginal density estimate of each column of T. Default value
-% for the number of bins is min{50,sqrt(|T|)}. Default value
-% for the standard deviation sigma is max(STD(T)/2). Default
-% value for fraction of empty extra space is 0.2 (that is 20%).
-%
-% If no output arguments is given, functions plots the
-% graphs of each density component. Otherwise smoothed
-% and normalized densities are returned in P and the
-% corresponding coordinates in X.
-%
-% See also
-% NDHIST
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-% 2000-03-27 Aki Vehtari
-% Get size of T only once and check if T is horizontal vector.
-% 2002-08-09 Aki Vehtari
-% Make sure P >= 0
-% 2003-11-04 Aki Vehtari
-% Define normpdf because not everyone has Statistics toolbox
-
- [s1,s2]=size(T);
- if s1==1
- T=T(:);
- [s1,s2]=size(T);
- end
-
- if nargin < 2
- sigma = [];
- end
- if nargin < 3
- bins = [];
- end
- if nargin < 4
- extra = [];
- end
-
- if isempty(sigma)
- sigma = std(T)/2;
- else
- sigma = sigma(:)';
- end
- if isempty(bins)
- bins = max(50,floor(sqrt(s1))+1);
- end
- if isempty(extra)
- extra = 0.2;
- end
- if size(sigma,2)~=s2
- sigma = ones(1,s2)*sigma;
- end
-
- if s2 > 1
- P = zeros(bins,s2);
- X = zeros(bins,s2);
- for i=1:s2
- [P(:,i),X(:,i),sigma(i)] = kernel1(T(:,i),sigma(i),bins,extra);
- end
- else
- mx = max(T);
- mn = min(T);
- delta = extra * (mx - mn);
- mn = mn - delta/2;
- mx = mx + delta/2;
- dx = (mx - mn) / bins;
- [H,X] = ndhist(T,bins,mn,mx);
- H = H(:) / sum(H);
- x = 2*(max(X)-min(X))*(0:(2*size(H,1)-1))'/size(H,1);
- G = normpdf(x,mean(x),sigma);
- G = ifftshift(G(:));
- P = real(ifft(fft(G,size(G,1)) .* fft(H,size(G,1))));
- P = P(1:size(H,1));
- P = P / (sum(P) * dx);
- P(P<0)=0; % Make sure P >= 0
- end
-
- if nargout == 0
- m = 2;
- n = ceil(size(X,2)/m);
- while m*m < n
- m = m + 1;
- n = ceil(size(X,2)/m);
- end
- if s2 > 1
- for i=1:s2
- subplot(m,n,i);
- plot(X(:,i),P(:,i));
- set(gca,'XLim',minmax(X(:,i)'));
- ylim = get(gca,'YLim');
- set(gca,'YLim',[0 ylim(2)]);
- title(['T_' num2str(i)]);
- end
- else
- plot(X,P);
- end
- clear X;
- clear P;
- clear sigma;
- end
-
-function y = normpdf(x,mu,sigma)
-y = -0.5 * ((x-mu)./sigma).^2 -log(sigma) -log(2*pi)/2;
-y=exp(y);
diff --git a/external/mcmcdiag/kernelp.m b/external/mcmcdiag/kernelp.m
deleted file mode 100644
index 19c47dc6..00000000
--- a/external/mcmcdiag/kernelp.m
+++ /dev/null
@@ -1,91 +0,0 @@
-function [p,xx]=kernelp(x,xx)
-%KERNELP 1D Kernel density estimation of data, with automatic kernel width
-%
-% [P,XX]=KERNELP(X,XX) return density estimates P in points XX,
-% given data and optionally ecvaluation points XX. Density
-% estimate is based on simple Gaussian kernel density estimate
-% where all kernels have equal width and this width is selected by
-% optimising plug-in partial predictive density. Works well with
-% reasonable sized X.
-%
-
-% Copyright (C) 2001-2003 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-if nargin < 1
- error('Too few arguments');
-end
-[n,m]=size(x);
-if n>1 && m>1
- error('X must be a vector');
-end
-x=x(:);
-
-if nargin < 2
- n=200;
- xa=min(x);xb=max(x);xd=xb-xa;
- xa=xa-xd/20;xb=xb+xd/20;
- xx=linspace(xa,xb,n);
-else
- [n,m]=size(xx);
- if n>1 && m>1
- error('XX must be a vector');
- end
- xx=xx(:);
-end
-m=length(x)/2;
-stdx=std(x);
-xd=gminus(x(1:m),x(m+1:end)');
-sh=fminbnd(@err,stdx/5,stdx*20,[],xd);
-p=mean(normpdf(gminus(x(1:m),xx),0,sh));
-
-function e=err(s,xd)
-e=-sum(log(sum(normpdf(xd,0,s))));
-
-function y = normpdf(x,mu,sigma)
-y = -0.5 * ((x-mu)./sigma).^2 -log(sigma) -log(2*pi)/2;
-y=exp(y);
-
-function y=gminus(x1,x2)
-%GMINUS Generalized minus.
-y=genop(@minus,x1,x2);
-
-function y=genop(f,x1,x2)
-% GENOP - Generalized operation
-%
-% C = GENOP(F,A,B) Call function F with exapanded matrices Y and X.
-% The dimensions of the two operands are compared and singleton
-% dimensions in one are copied to match the size of the other.
-% Returns a matrix having dimension lengths equal to
-% MAX(SIZE(A),SIZE(B))
-%
-% See also GENOPS
-
-% Copyright (C) 2003 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-s1=size(x1);
-s2=size(x2);
-ls1=numel(s1);
-ls2=numel(s2);
-l=max(ls1,ls2);
-d=ls1-ls2;
-if d<0
- s1(ls1+1:ls1+d)=1;
-elseif d>0
- s2(ls2+1:ls2+d)=1;
-end
-if any(s1>1 & s2>1 & s1~=s2)
- error('Array dimensions are not appropriate.');
-end
-r1=ones(1,l);
-r2=r1;
-r1(s1==1)=s2(s1==1);
-r2(s2==1)=s1(s2==1);
-y=feval(f,repmat(x1,r1),repmat(x2,r2));
diff --git a/external/mcmcdiag/kernels.m b/external/mcmcdiag/kernels.m
deleted file mode 100644
index dd66a592..00000000
--- a/external/mcmcdiag/kernels.m
+++ /dev/null
@@ -1,49 +0,0 @@
-function [P,X,V,D] = kernels(T,varargin)
-%KERNELS Kernel density estimation of principal components of data
-%
-% [P,X,V,D] = kernels(T,[sigma,bins]) returns kernel based
-% marginal density estimate of each pricipal component of T.
-% Default value for the number of bins is min{50,sqrt(|T|)}.
-% Default value for the standard deviation sigma is the STD(T*)/2
-% where T* is the independent component of T.
-%
-% If no output arguments is given, functions plots the
-% graphs of each density component. Otherwise densities are
-% returned in P, the corresponding coordinates in X, directions
-% of principal components in V and variances of the principal
-% components in diagonal of D.
-%
-% Returned pricipal components are the uncorrelated (but not
-% independent) directions of the density. Relationship between
-% T and coordinates in X is X = T*V.
-%
-% See also
-% KERNEL1
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-
-m = mean(T);
-[V,D] = eig(cov(T));
-[C,A,W] = fastica((T-repmat(m,size(T,1),1))','verbose','off',...
- 'displayMode','off');
-V = A';
-V = V ./ repmat(sqrt(sum(V.*V)),size(V,1),1);
-[P,X] = kernel1(C'+repmat(m,size(T,1),1),varargin{:});
-if nargout == 0
- m = 2;
- n = ceil(size(X,2)/m);
- while m*m < n
- m = m + 1;
- n = ceil(size(X,2)/m);
- end
- for i=1:size(X,2)
- subplot(m,n,i);
- plot(X(:,i),P(:,i));
- title(['T^*_' num2str(i) ' = ' '[ ' num2str(V(:,i)',' %.2f') ' ]']);
- end
-end
diff --git a/external/mcmcdiag/ksstat.m b/external/mcmcdiag/ksstat.m
deleted file mode 100644
index 182c9d08..00000000
--- a/external/mcmcdiag/ksstat.m
+++ /dev/null
@@ -1,105 +0,0 @@
-function [snks, snkss] = ksstat(varargin)
-%KSSTAT Kolmogorov-Smirnov statistics
-%
-% ks = KSSTAT(X) or
-% ks = KSSTAT(X1,X2,...,XJ)
-% returns Kolmogorov-Smirnov statistics in form sqrt(N)*K
-% where M is number of samples. X is a NxMxJ matrix which
-% contains J MCMC simulations of length N, each with
-% dimension M. MCMC-simulations can be given as separate
-% arguments X1,X2,... which should have the same length.
-%
-% When comparing more than two simulations, maximum of all the
-% comparisons for each dimension is returned (Brooks et al,
-% 2003).
-%
-% Function returns ks-values in vector KS of length M.
-% An approximation of the 95% quantile for the limiting
-% distribution of sqrt(N)*K with M>=100 is 1.36. ks-values
-% can be compared against this value (Robert & Casella, 2004).
-% In case of comparing several chains, maximum of all the
-% comparisons can be compared to simulated distribution of
-% the maximum of all comparisons obtained using indpendent
-% random random numbers (e.g. using randn(size(X))).
-%
-% If only one simulation is given, the factor is calculated
-% between first and last third of the chain.
-%
-% Note that for this test samples have to be approximately
-% independent. Use thinning or batching for Markov chains.
-%
-% Example:
-% How to estimate the limiting value when comparing several
-% chains stored in (thinned) variable R. Simulate 100 times
-% independent samples. kss contains then 100 simulations of the
-% maximum of all the comparisons for independent samples.
-% Compare actual value for R to 95%-percentile of kss.
-%
-% kss=zeros(1,100);
-% for i1=1:100
-% kss(i1)=ksstat(randn(size(R)));
-% end
-% ks95=prctile(kss,95);
-%
-% References:
-% Robert, C. P, and Casella, G. (2004) Monte Carlo Statistical
-% Methods. Springer. p. 468-470.
-% Brooks, S. P., Giudici, P., and Philippe, A. (2003)
-% "Nonparametric Convergence Assessment for MCMC Model
-% Selection". Journal of Computational & Graphical Statistics,
-% 12(1):1-22.
-%
-% See also
-% PSRF, GEYER_IMSE, THIN
-
-% Copyright (C) 2001-2005 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-% In case of one argument split to two halves (first and last thirds)
-if nargin==1
- X = varargin{1};
- if size(X,3)==1
- n = floor(size(X,1)/3);
- x = zeros([n size(X,2) 2]);
- x(:,:,1) = X(1:n,:);
- x(:,:,2) = X((end-n+1):end,:);
- X = x;
- end
-else
- X = zeros([size(varargin{1}) nargin]);
- for i1=1:nargin
- X(:,:,i1) = varargin{i1};
- end
-end
-
-if (size(X,1)<1)
- error('X has zero rows');
-end
-
-[n1,n2,n3]=size(X);
-%if n1<=100
-% warning('Too few samples for reliable analysis');
-%end
-P = zeros(1,n2);
-snkss=zeros(sum(1:(n3-1)),1);
-for j1=1:size(X,2)
- ii=0;
- for i1=1:n3-1
- for i2=i1+1:n3
- ii=ii+1;
- snkss(ii,j1)=ksc(X(:,j1,i1),X(:,j1,i2));
- end
- end
- snks(j1)=max(snkss(:,j1));
-end
-
-function snks = ksc(x1,x2)
-n=numel(x1);
-edg=sort([x1; x2]);
-c1=histc(x1,edg);
-c2=histc(x2,edg);
-K=max(abs(cumsum(c1)-cumsum(c2))/n);
-snks=sqrt(n)*K;
diff --git a/external/mcmcdiag/mpsrf.m b/external/mcmcdiag/mpsrf.m
deleted file mode 100644
index dd3ad7f7..00000000
--- a/external/mcmcdiag/mpsrf.m
+++ /dev/null
@@ -1,92 +0,0 @@
-function [R,neff,V,W,B] = mpsrf(varargin)
-%MPSRF Multivariate Potential Scale Reduction Factor
-%
-% [R,neff,V,W,B] = MPSRF(X) or
-% [R,neff,V,W,B] = MPSRF(x1,x2,...,xs)
-% returns "Multivariate Potential Scale Reduction Factor"
-% (MPSRF) for collection of MCMC-simulations. X is a NxMxS
-% matrix which contains S MCMC simulations of length M with
-% dimension M. MCMC-simulations can be given as separate
-% arguments x1,x2,... which should have the same length.
-%
-% Returns
-% R PSRF (R=sqrt(V/W)) in row vector of length D
-% neff estimated effective number of samples mean(diag(M*N*V./B))
-% V estimated mixture-of-sequences cvariance
-% W estimated within sequence covariance
-% B estimated between sequence covariance
-%
-% If only one simulation is given, the factor is calculated
-% between first and last third of the chain. Note that use of
-% only one chain will produce over-optimistic result.
-%
-% Method is from:
-% Method is from:
-% Brooks, S.P. and Gelman, A. (1998) General methods for
-% monitoring convergence of iterative simulations. Journal of
-% Computational and Graphical Statistics. 7, 434-455. Note that
-% this function returns square-root definiton of R (see Gelman
-% et al (2003), Bayesian Data Analsyis p. 297).
-%
-% See also
-% CMPSRF, PSRF, CPSRF
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-% 2004-01-22 Aki.Vehtari@hut.fi Added neff, R^2->R, and cleaning
-
-
-% In case of one argument split to two halves
-onechain=0;
-if nargin==1
- X = varargin{1};
- if size(X,3)==1
- n = floor(size(X,1)/3);
- x = zeros([n size(X,2) 2]);
- x(:,:,1) = X(1:n,:);
- x(:,:,2) = X((end-n+1):end,:);
- X = x;
- onechain=1;
- end
-elseif nargin==0
- error('Cannot calculate PSRF of scalar');
-else
- X = zeros([size(varargin{1}) nargin]);
- for i=1:nargin
- X(:,:,i) = varargin{i};
- end
-end
-
-[N,D,M]=size(X);
-
-% Calculate mean W of the covariances
-W = zeros(D);
-for n=1:M
- x = X(:,:,n) - repmat(mean(X(:,:,n)),N,1);
- W = W + x'*x;
-end
-W = W / ((N-1) * M);
-
-% Calculate covariance B (in fact B/n) of the means.
-Bpn = zeros(D);
-m = mean(reshape(mean(X),D,M)');
-for n=1:M
- x = mean(X(:,:,n)) - m;
- Bpn = Bpn + x'*x;
-end
-Bpn = Bpn / (M-1);
-
-% Calculate reduction factor R
-E = sort(abs(eig(W \ Bpn)));
-R = (N-1)/N + E(end) * (M+1)/M;
-V = (N-1) / N * W + (1 + 1/M) * Bpn;
-R = sqrt(R);
-B = Bpn*N;
-neff = mean(min(diag(M*N*V./B),M*N));
-if onechain & (nargout>1)
- neff=neff*3/2;
-end
diff --git a/external/mcmcdiag/ndhist.m b/external/mcmcdiag/ndhist.m
deleted file mode 100644
index 776a4b67..00000000
--- a/external/mcmcdiag/ndhist.m
+++ /dev/null
@@ -1,176 +0,0 @@
-function [H,varargout] = ndhist(X,bins,mins,maxs,cdim)
-%NDHIST Normalized histogram of N-dimensional data
-%
-% [H,P] = ndhist(X,bins,[mins,maxs])
-% [H,x1,x2,...] = ndhist(X,bins,[mins,maxs])
-%
-% Returns normalized N-dimensional histogram H and the bin center
-% coordinates in P or variables x1,x2,... which all are of the
-% same size as H and contain the coordinates in same form as
-% output of ndgrid.
-%
-% Histogram is calculated for the points in argument X..
-% bins is a vector containing number of bins for each dimension.
-% Optional arguments mins and maxx specify the maximum allowed
-% values for each dimension.
-%
-% If no output arguments are given the function plots
-% graph of the histogram.
-%
-% Examples:
-% >> X = gamrnd(3,3,1000,1);
-% >> [H,x] = ndhist(X,50);
-% >> bar(x,H);
-%
-% >> X = mvnrnd([1 1],eye(2),1000) + round(rand(1000,1))*[-2 -2];
-% >> [H,x,y] = ndhist(X,[20 20]);
-% >> surf(x,y,H);
-%
-% See also
-% KERNEL1, HIST, NDGRID
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-
-% Check input and output arguments
-if nargin < 2
- bins = [];
-end
-if nargin < 3
- mins = [];
-end
-if nargin < 4
- maxs = [];
-end
-if nargin < 5
- cdim = 1;
- if size(X,1)==1
- X = X';
- end
-end
-
-if isempty(bins)
- bins = 10;
-end
-if isempty(mins)
- mins = min(X);
-end
-if isempty(maxs)
- maxs = max(X);
-end
-
-tmp = (maxs - mins) ./ bins;
-mins = mins - tmp/2;
-maxs = maxs + tmp/2;
-dx = (maxs - mins) ./ bins;
-
-if (nargout~=0) & (nargout~=1) & (nargout~=2) & (nargout~=size(X,2)+1)
- error('Illegal number of output arguments');
-end
-
-bins = reshape(bins,1,prod(size(bins)));
-if size(bins,2)~=size(X,2)
- if size(bins,2)==1
- bins = bins * ones(1,size(X,2));
- else
- error('Wrong number of bin sizes');
- end
-end
-
-% Create histogram for this dimension and
-% recursively for each sub-dimension.
-[tmpx,tmpi] = sort(X(:,cdim));
-X = X(tmpi,:);
-if cdim < size(X,2)
- H = zeros(bins(cdim),prod(bins(cdim+1:end)));
-else
- H = zeros(bins(cdim),1);
-end
-bnd = mins(cdim)+dx(cdim);
-beg = 1;
-ind = 1;
-k = 1;
-
-while (k <= size(X,1)) & (X(k,cdim) < mins(cdim))
- k = k + 1;
-end
-beg = k;
-while (k <= size(X,1)) & (X(k,cdim) <= maxs(cdim)) & (ind <= size(H,1))
- if X(k,cdim) <= bnd
- k = k + 1;
- else
- if k-beg > 0
- if cdim < size(X,2)
- H(ind,:) = ndhist(X(beg:k-1,:),bins,mins,maxs,cdim+1);
- else
- H(ind) = k-beg;
- end
- end
- bnd = bnd + dx(cdim);
- ind = ind + 1;
- beg = k;
- end
-end
-
-% Handle the last bin
-if (ind <= size(H,1))
- if cdim < size(X,2)
- H(ind,:) = ndhist(X(beg:k-1,:),bins,mins,maxs,cdim+1);
- else
- H(ind) = k-beg;
- end
-end
-
-% Reshape H to linear or multidimensional and
-% determine point positions and set output variables
-if cdim == 1
- if size(X,2)==1
- H = H(:);
- x = (0:(bins-1))'*(maxs-mins)/bins+mins+dx/2;
- varargout{1} = x;
- else
- H = reshape(H,bins);
- k = 0;
- tmp = cell(size(X,2),1);
- for i=1:size(X,2)
- x = (0:(bins(i)-1))'/bins(i)*(maxs(i)-mins(i))+mins(i)+dx(i)/2;
- args = cell(size(X,2),1);
- for j=1:size(X,2)
- args{j} = x;
- end
- tmp{i} = shiftdim(ndgrid(args{:}),k);
- k = mod(k + size(X,2)-1,size(X,2));
- end
- if nargout==2
- P = zeros(size(X,2),prod(bins));
- for i=1:size(X,2)
- P(i,:) = reshape(tmp{i},1,prod(bins));
- end
- varargout{1} = reshape(P,[size(X,2) bins]);
- else
- varargout = tmp;
- end
- end
- c = sum(reshape(H,1,prod(bins)));
- H = H/c;
-else
- H = reshape(H,1,prod(bins(cdim:end)));
-end
-
-% If there were no output arguments, draw a graph
-if nargout==0
- if size(X,2)==1
- bar(varargout{1},H,'hist');
- elseif size(X,2)==2
- surf(varargout{1},varargout{2},H);
- else
- error('Unable to draw >2 dimensional densities');
- end
- clear H;
- clear varargout;
-end
-
diff --git a/external/mcmcdiag/psrf.m b/external/mcmcdiag/psrf.m
deleted file mode 100644
index 2da70417..00000000
--- a/external/mcmcdiag/psrf.m
+++ /dev/null
@@ -1,107 +0,0 @@
-function [R,neff,Vh,W,B,tau,thin] = psrf(varargin)
-%PSRF Potential Scale Reduction Factor
-%
-% [R,NEFF,V,W,B,TAU,THIN] = PSRF(X) or
-% [R,NEFF,V,W,B,TAU,THIN] = PSRF(x1,x2,...,xs)
-% returns "Potential Scale Reduction Factor" (PSRF) for collection
-% of MCMC-simulations. X is a NxDxM matrix which contains M MCMC
-% simulations of length N, each with dimension D. MCMC-simulations
-% can be given as separate arguments x1,x2,... which should have the
-% same length.
-%
-% Returns
-% R PSRF (R=sqrt(V/W)) in row vector of length D
-% neff estimated effective number of samples M*N/(1+2*sum(rhohat))
-% V estimated mixture-of-sequences variances
-% W estimated within sequence variances
-% B estimated between sequence variances
-% TAU estimated autocorrelation time
-% THIN Geyer's initial positive sequence lag (useful for thinning)
-%
-% The idea of the PSRF is that if R is not close to 1 (below 1.1 for
-% example) one may conclude that the tested samples were not from
-% the same distribution (chain might not have been converged yet).
-%
-% Original method:
-% Brooks, S.P. and Gelman, A. (1998) General methods for
-% monitoring convergence of iterative simulations. Journal of
-% Computational and Graphical Statistics. 7, 434-455.
-% Current version:
-% Split chains, return square-root definiton of R, and compute
-% n_eff using variogram estimate and Geyer's initial positive
-% sequence as described in Gelman et al (2013), Bayesian Data
-% Analsyis, 3rd ed, sections 11.4-11.5.
-%
-% See also
-% CPSRF, MPSRF, IPSRF
-
-% Copyright (C) 1999 Simo Särkkä
-% Copyright (C) 2003-2004,2013 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 3 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-% 2004-01-22 Aki.Vehtari@hut.fi Added neff, R^2->R, and cleaning
-% 2013-10-20 Aki.Vehtari@aalto.fi Updated according to BDA3
-
-X=cat(3,varargin{:});
-mid=floor(size(X,1)/2);
-X=cat(3,X(1:mid,:,:),X((end-mid+1):end,:,:));
-
-[N,D,M]=size(X);
-
-if N<=2
- error('Too few samples');
-end
-
-% Calculate means W of the variances
-W = zeros(1,D);
-for mi=1:M
- x = bsxfun(@minus,X(:,:,mi),mean(X(:,:,mi)));
- W = W + sum(x.*x);
-end
-W = W / ((N-1) * M);
-
-% Calculate variances B (in fact B/n) of the means.
-Bpn = zeros(1,D);
-m = mean(reshape(mean(X),D,M)');
-for mi=1:M
- x = mean(X(:,:,mi)) - m;
- Bpn = Bpn + x.*x;
-end
-Bpn = Bpn / (M-1);
-
-% Calculate reduction factors
-B = Bpn*N;
-Vh = (N-1)/N*W + Bpn;
-R = sqrt(Vh./W);
-
-if nargout>1
- % compute autocorrelation
- for t=1:N-1
- % variogram
- Vt(t,:)=sum(sum((X(1:end-t,:,:)-X(1+t:end,:,:)).^2,1),3)/M/(N-t);
- end
- % autocorrelation
- rho=1-bsxfun(@rdivide,Vt./2,Vh);
- % add zero lag autocorrelation
- rho=[ones(1,D);rho];
-
- mid=floor(N/2);
- neff=zeros(1,D);
- for di=1:D
- cp=sum(reshape(rho(1:2*mid,di),2,mid),1);
- ci=find(cp<0,1);
- if isempty(ci)
- warning(sprintf('Inital positive could not be found for variable %d, using maxlag value',di));
- ci=mid;
- else
- ci=ci-1; % last positive
- end
- cp=[cp(1:ci) 0]; % initial positive sequence
- tau(di)=-1+2*sum(cp); % initial positive sequence estimator
- neff(di)=M*N/tau(di); % initial positive sequence estimator for neff
- thin(di)=ci*2;
- end
-end
diff --git a/external/mcmcdiag/score.m b/external/mcmcdiag/score.m
deleted file mode 100644
index e5d38757..00000000
--- a/external/mcmcdiag/score.m
+++ /dev/null
@@ -1,34 +0,0 @@
-function [CA,CS] = score(X,gradF,n0,varargin)
-%SCORE Calculate score-function convergence diagnostic
-%
-% [CA,CS] = score(X,gradF,n0,P1,P2,...)
-% returns convergence diagnostic based on score-functions
-% d ln(p(x))/dx_k that should should approach 0 as n increases.
-%
-% gradF is name of the gradient logarithm function (or
-% its opposite) and X's are the sampled values. n0 is length
-% of "burn-in" and defaults to 0.
-%
-% The idea is from:
-% Anne Philippe and Christian P. Robert (Oct, 1998)
-% Riemann Sums for MCMC Estimation and
-% Convergence Monitoring. EP CNRS
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-if (nargin < 3) | isempty(n0)
- n0 = 0;
-end
-X = X((n0+1):end,:,:);
-G = zeros(size(X));
-for i=1:size(X,1)
- for j=1:size(X,3)
- G(i,:,j) = feval(gradF,X(i,:,j),varargin{:});
- end
-end
-
-[CA,CS] = custats(G);
diff --git a/external/mcmcdiag/thin.m b/external/mcmcdiag/thin.m
deleted file mode 100644
index c2eb1374..00000000
--- a/external/mcmcdiag/thin.m
+++ /dev/null
@@ -1,74 +0,0 @@
-function x = thin(x,nburn,nthin,nlast)
-%THIN Delete burn-in and thin in MCMC-chains
-%
-% x = thin(x,nburn,nthin,nlast) returns chain containing only
-% every nthin:th simulation sample starting from sample number
-% nburn+1 and continuing to sample number nlast.
-%
-% See also
-% JOIN
-
-% Copyright (c) 1999 Simo Särkkä
-% Copyright (c) 2000 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% License (version 2 or later); please refer to the file
-% License.txt, included with the software, for details.
-
-if nargin < 4
- nlast = [];
-end
-if nargin < 3
- nthin = [];
-end
-if nargin < 2
- nburn = [];
-end
-
-[m,n]=size(x);
-if isfield(x,'rstate')
- x=rmfield(x,'rstate');
-end
-
-if isstruct(x)
- if (m>1 | n>1)
- % array of structures
- for i=1:(m*n)
- x(i) = thin(x(i),nburn,nthin,nlast);
- end
- else
- % single structure
- names = fieldnames(x);
- for i=1:size(names,1)
- value = getfield(x,names{i});
- if length(value) > 1
- x = setfield(x,names{i},thin(value,nburn,nthin,nlast));
- elseif iscell(value)
- x = setfield(x,names{i},{thin(value{1},nburn,nthin,nlast)});
- end
- end
- end
-elseif iscell(x)
- % cell array
- for i=1:(m*n)
- x{i} = thin(x{i},nburn,nthin,nlast);
- end
-elseif m > 1
- % field array
- if isempty(nburn)
- nburn = 0;
- elseif (nburn < 0) | (nburn >= m)
- error('Illegal burn-in value');
- end
- if isempty(nthin)
- nthin = 1;
- elseif (nthin < 1) | (nthin > m)
- error('Illegal thinning value');
- end
- if isempty(nlast)
- nlast = m;
- elseif (nlast < 1) | (nlast > m)
- error('Illegal last index');
- end
- x = x((nburn+1):nthin:nlast,:);
-end
diff --git a/h2gf/h2gf_demo.m b/h2gf/h2gf_demo.m
index 3f131977..bd71967a 100644
--- a/h2gf/h2gf_demo.m
+++ b/h2gf/h2gf_demo.m
@@ -203,7 +203,8 @@
end
clear i j
%%
-%load('h2gf_demo_est.mat')
+% [example_dir] = tapas_download_example_data();
+% load(fullfile(example_dir,'h2gf','h2gf_demo_est.mat'));
%%
% We gather the estimates of $\omega_2$ and $\omega_3$ for all grid points,
% noise levels, and simulated datasets.
diff --git a/h2gf/h2gf_demo_est.mat b/h2gf/h2gf_demo_est.mat
deleted file mode 100644
index 41841831..00000000
Binary files a/h2gf/h2gf_demo_est.mat and /dev/null differ
diff --git a/h2gf/tapas_h2gf_summary.m b/h2gf/tapas_h2gf_summary.m
index 5569fafc..56c9c466 100644
--- a/h2gf/tapas_h2gf_summary.m
+++ b/h2gf/tapas_h2gf_summary.m
@@ -100,7 +100,7 @@
subjects(i).optim.LME = trapz(T(i, :), mean(llh(i, :, :), 3));
% Get R-hat
- r_hat = psrf(values')';
+ r_hat = tapas_huge_psrf(values',2);
subjects(i).optim.r_hat = r_hat;
end
diff --git a/huge/@tapas_Huge/bold_gen.m b/huge/@tapas_Huge/bold_gen.m
index acbe301e..c215fb40 100644
--- a/huge/@tapas_Huge/bold_gen.m
+++ b/huge/@tapas_Huge/bold_gen.m
@@ -2,7 +2,7 @@
% Generate predicted fMRI BOLD time series..
%
% This is a protected method of the tapas_Huge class. It cannot be called
-% from outsite the class.
+% from outside the class.
%
% Author: Yu Yao (yao@biomed.ee.ethz.ch)
@@ -36,13 +36,16 @@
kappa = theta.decay;
epsilon = theta.epsilon;
else
- [A, B, C, D, tau, kappa, epsilon] = obj.theta2abcd( theta, idx, R, L);
+ [A, B, C, D, tau, kappa, epsilon] = obj.theta2abcd( theta, idx, R, L );
end
-% % transform C matrix into exp domain
-% if obj.options.bPositiveInput
-% C = exp(C);
-% end
+% transform C matrix
+if obj.options.nvp.transforminput
+ C(logical(obj.dcm.c(:)))=.5*exp(C(logical(obj.dcm.c(:))));
+end
+% baseline for self-connections
+A = A + obj.const.baseSc*eye(obj.R);
+
% generate BOLD response
pred = tapas_huge_bold( A, B, C, D, tau, kappa, epsilon, R, inputs.u, L, ...
diff --git a/huge/@tapas_Huge/bold_grad_cd.m b/huge/@tapas_Huge/bold_grad_cd.m
index f728ce89..6a46b4ff 100644
--- a/huge/@tapas_Huge/bold_grad_cd.m
+++ b/huge/@tapas_Huge/bold_grad_cd.m
@@ -3,7 +3,7 @@
% DCM parameters using central difference method.
%
% This is a protected method of the tapas_Huge class. It cannot be called
-% from outsite the class.
+% from outside the class.
%
% Author: Yu Yao (yao@biomed.ee.ethz.ch)
diff --git a/huge/@tapas_Huge/bold_grad_fd.m b/huge/@tapas_Huge/bold_grad_fd.m
index 4ecb60cb..d6db9cfd 100644
--- a/huge/@tapas_Huge/bold_grad_fd.m
+++ b/huge/@tapas_Huge/bold_grad_fd.m
@@ -3,7 +3,7 @@
% DCM parameters using forward difference method.
%
% This is a protected method of the tapas_Huge class. It cannot be called
-% from outsite the class.
+% from outside the class.
%
% Author: Yu Yao (yao@biomed.ee.ethz.ch)
diff --git a/huge/@tapas_Huge/default_options.m b/huge/@tapas_Huge/default_options.m
index 19ae0306..9e3239e7 100644
--- a/huge/@tapas_Huge/default_options.m
+++ b/huge/@tapas_Huge/default_options.m
@@ -2,7 +2,7 @@
% Set default options for tapas_Huge class.
%
% This is a protected method of the tapas_Huge class. It cannot be called
-% from outsite the class.
+% from outside the class.
%
% Author: Yu Yao (yao@biomed.ee.ethz.ch)
@@ -47,11 +47,10 @@
'startingvaluedcm' , 'prior', ...
'startingvaluegmm' , 'prior', ...
'tag' , '', ...
+ 'transforminput' , false, ...
'verbose' , false ...
);
-% options.bPositiveInput = 0; % force entries of C to be positive
-
% starting values
options.start = struct(...
'dcm', .1, ...
@@ -81,20 +80,21 @@
options.mh.nSteps = struct( ...
'weights' , 1, ...
'clusters', 1, ...
- 'dcm' , 1e4, ... %%%
- 'knGmm' , 1e10); %%% % propose from alternative (GMM) kernel
+ 'dcm' , 1, ...
+ 'knGmm' , 10, ... % GMM kernel
+ 'knKm' , 1000 ); % k-means mode hopping
% initial MH step size
options.mh.stepSize = struct( ...
'pi' , 0.5, ....
'mu' , 0.01, ....
- 'kappa' , 0.005, ....
+ 'kappa' , 0.025, ....
'theta' , 0.01, ....
- 'lambda' , 0.1);
+ 'lambda' , 0.05);
% use single precision for Monte Carlo-based inversion
options.bSinglePrec = false;
-% quatile levels for posterior summary
+% quantile levels for posterior summary
options.quantiles = (.025:.025:.975)';
% hemodynamic constants %%% TODO move to dcm
diff --git a/huge/@tapas_Huge/estimate.m b/huge/@tapas_Huge/estimate.m
index 7faae62d..5aef6cd6 100644
--- a/huge/@tapas_Huge/estimate.m
+++ b/huge/@tapas_Huge/estimate.m
@@ -59,12 +59,17 @@
seed = rng();
% check if filename for storing result is valid
-if ~isempty(obj.options.nvp.saveto)
- [pathStr, fileStr] = fileparts(obj.options.nvp.saveto);
+filename = obj.options.nvp.saveto;
+if ~isempty(filename)
+ [pathStr, fileStr, extStr] = fileparts(filename);
+ if ~strcmpi(extStr,'.mat')
+ filename = [filename '.mat'];
+ [pathStr, fileStr, extStr] = fileparts(filename);
+ end
if isempty(fileStr)
fileStr = ['huge' datestr(now,'-yyyymmdd-HHMMSS')];
end
- filename = fullfile(pathStr, [fileStr, '.mat']);
+ filename = fullfile(pathStr, [fileStr, extStr]);
save(filename, obj);
end
@@ -130,7 +135,7 @@
obj.posterior.seed = seed;
% save result
-if ~isempty(obj.options.nvp.saveto)
+if ~isempty(filename)
save(filename, obj);
fprintf('Saved result to "%s".\n', filename);
end
@@ -170,13 +175,14 @@
% nu_0
prior.nu_0 = obj.options.nvp.priordegree;
-assert(prior.nu_0 > 0, 'TAPAS:HUGE:Prior', ...
+assert(all(prior.nu_0(:) > 0), 'TAPAS:HUGE:Prior', ...
'PriorDegree must be positive scalar.');
% tau_0
prior.tau_0 = obj.options.nvp.priorvarianceratio;
-assert(prior.tau_0 > 0, 'TAPAS:HUGE:Prior', ...
+assert(all(prior.tau_0(:) > 0), 'TAPAS:HUGE:Prior', ...
'PriorCovarianceRatio must be positive scalar.');
+% xxxTODO check size consistent
% mu_h
prior.mu_h = obj.options.prior.mu_h;
diff --git a/huge/@tapas_Huge/export.m b/huge/@tapas_Huge/export.m
index cfcd2a74..c151dff7 100644
--- a/huge/@tapas_Huge/export.m
+++ b/huge/@tapas_Huge/export.m
@@ -78,12 +78,12 @@
obj.idx.P_c + obj.idx.P_h, obj.N);
try % estimate covariances from samples
theta = ...
- [reshape([obj.trace(:).theta_c], obj.N, obj.idx.P_c, []), ...
- reshape([obj.trace(:).theta_h], obj.N, obj.idx.P_h, [])];
+ [reshape([obj.trace.smp(:).theta_c], obj.N, obj.idx.P_c, []), ...
+ reshape([obj.trace.smp(:).theta_h], obj.N, obj.idx.P_h, [])];
for n = 1:obj.N
Sigma_n(:,:,n) = cov(permute(theta(n,:,:), [3 2 1]));
end
- mu = reshape([obj.trace(:).mu], obj.K, obj.idx.P_c, []);
+ mu = reshape([obj.trace.smp(:).mu], obj.K, obj.idx.P_c, []);
for k = 1:obj.K
S_k(:,:,k) = cov(permute(mu(k,:,:), [3 2 1]));
end
@@ -155,6 +155,10 @@
% subject-level
[A, B, C, D, tau, kappa, epsilon] = obj.theta2abcd(mu_n, obj.idx,...
obj.R, obj.L);
+ % transform C matrix
+ if obj.options.nvp.transforminput
+ C = .5*exp(C);
+ end
dcm.Ep = struct('A', A, 'B', B, 'C', C, 'D', D, 'transit', tau, ...
'decay', kappa, 'epsilon', epsilon);
idx = [obj.idx.clustering; obj.idx.homogenous];
@@ -166,6 +170,10 @@
% cluster-level
[A, B, C, D, tau, kappa, epsilon] = obj.theta2abcd([m_k mu_h],...
obj.idx, obj.R, obj.L);
+ % transform C matrix
+ if obj.options.nvp.transforminput
+ C = .5*exp(C);
+ end
dcm.M.pE = struct('A', A, 'B', B, 'C', C, 'D', D, 'transit', tau, ...
'decay', kappa, 'epsilon', epsilon);
diff --git a/huge/@tapas_Huge/optional_inputs.m b/huge/@tapas_Huge/optional_inputs.m
index 198e85e5..4d6e458a 100644
--- a/huge/@tapas_Huge/optional_inputs.m
+++ b/huge/@tapas_Huge/optional_inputs.m
@@ -3,7 +3,7 @@
% estimate method.
%
% This is a protected method of the tapas_Huge class. It cannot be called
-% from outsite the class.
+% from outside the class.
%
% Author: Yu Yao (yao@biomed.ee.ethz.ch)
@@ -52,6 +52,7 @@
nvp.omitfromclustering = [];
end
+
% number of clusters
obj.K = nvp.k;
@@ -102,7 +103,7 @@
if ischar(val) && strcmpi(val, 'default')
nvp.priorvarianceratio = defaultOptions.nvp.priorvarianceratio;
else
- assert( isnumeric(val) && val(1) > 0, 'TAPAS:HUGE:Nvp:PriorTau', ...
+ assert( isnumeric(val) && any(val(:) > 0), 'TAPAS:HUGE:Nvp:PriorTau', ...
'PriorVarianceRatio must be a positive scalar.');
end
diff --git a/huge/@tapas_Huge/parse_labels.m b/huge/@tapas_Huge/parse_labels.m
new file mode 100644
index 00000000..90d04a36
--- /dev/null
+++ b/huge/@tapas_Huge/parse_labels.m
@@ -0,0 +1,82 @@
+function [ tickLabels ] = parse_labels( dcm, labels, idx )
+% Generate labels for axis ticks.
+%
+% This is a protected method of the tapas_Huge class. It cannot be called
+% from outsite the class.
+%
+
+% Author: Yu Yao (yao@biomed.ee.ethz.ch)
+% Copyright (C) 2020 Translational Neuromodeling Unit
+% Institute for Biomedical Engineering,
+% University of Zurich and ETH Zurich.
+%
+% This file is part of TAPAS, which is released under the terms of the GNU
+% General Public Licence (GPL), version 3. For further details, see
+% .
+%
+% This software is provided "as is", without warranty of any kind, express
+% or implied, including, but not limited to the warranties of
+% merchantability, fitness for a particular purpose and non-infringement.
+%
+% This software is intended for research only. Do not use for clinical
+% purpose. Please note that this toolbox is under active development.
+% Considerable changes may occur in future releases. For support please
+% refer to:
+% https://github.com/translationalneuromodeling/tapas/issues
+%
+
+L = size(dcm.c, 2);
+R = dcm.n;
+
+% linear connections
+a = cell(size(dcm.a));
+for rSource = 1:R
+ for rTarget = 1:R
+ a{rTarget, rSource} = [labels.regions{rSource} ' => ' ...
+ labels.regions{rTarget}];
+ end
+end
+
+% driving connections
+c = cell(size(dcm.c));
+for lSource = 1:L
+ for rTarget = 1:R
+ c{rTarget, lSource} = [labels.inputs{lSource} ' => ' ...
+ labels.regions{rTarget}];
+ end
+end
+
+% modulatory connections
+b = cell(size(dcm.b));
+for l = 1:L
+ for rSource = 1:R
+ for rTarget = 1:R
+ b{rTarget, rSource, l} = [labels.inputs{lSource} ' MOD ' ...
+ labels.regions{rSource} ' => ' labels.regions{rTarget}];
+ end
+ end
+end
+
+% nonlinear connections
+d = cell(size(dcm.d));
+for rMod = 1:size(d,3)
+ for rSource = 1:R
+ for rTarget = 1:R
+ d{rTarget, rSource, rMod} = [labels.regions{rMod} ' MOD ' ...
+ labels.regions{rSource} ' => ' labels.regions{rTarget}];
+ end
+ end
+end
+
+% hemodynamic parameters
+hemo = cell(R, 2);
+for r = 1:R
+ hemo{r, 1} = ['transit ' labels.regions{r}];
+ hemo{r, 2} = ['decay ' labels.regions{r}];
+end
+
+tmp = [a(:); b(:); c(:); d(:); hemo(:); {'epsilon'}];
+tickLabels = tmp([idx.clustering(:); idx.homogenous(:)]);
+
+end
+
diff --git a/huge/@tapas_Huge/plot.m b/huge/@tapas_Huge/plot.m
index e23d1186..49cee378 100644
--- a/huge/@tapas_Huge/plot.m
+++ b/huge/@tapas_Huge/plot.m
@@ -44,7 +44,7 @@
subjects = [];
end
-tickLabels = parse_labels( obj.dcm, obj.labels );
+tickLabels = obj.parse_labels( obj.dcm, obj.labels, obj.idx );
%% assignments/boxplot
% figure;
@@ -114,11 +114,11 @@
postSmp = randn(nSmp,obj.idx.P_c + obj.idx.P_h);
postSmp = bsxfun(@plus, postSmp*postStd, postMean);
case 'MH'
- nTrace = length(obj.trace);
+ nTrace = length(obj.trace.smp);
nSmp = min(nSmp, nTrace);
idx = randsample(nTrace, nSmp);
- tmp = [reshape([obj.trace(idx).theta_c], obj.N, obj.idx.P_c, []), ...
- reshape([obj.trace(idx).theta_h], obj.N, obj.idx.P_h, [])];
+ tmp = [reshape([obj.trace.smp(idx).theta_c], obj.N, obj.idx.P_c, []), ...
+ reshape([obj.trace.smp(idx).theta_h], obj.N, obj.idx.P_h, [])];
postSmp = permute(tmp(n,:,:), [3 2 1]);
end
legends = {'measured'};
@@ -142,62 +142,3 @@
end
-
-function [ tickLabels ] = parse_labels( dcm, labels )
-
-L = size(dcm.c, 2);
-R = dcm.n;
-
-% linear connections
-a = cell(size(dcm.a));
-for rSource = 1:R
- for rTarget = 1:R
- a{rTarget, rSource} = [labels.regions{rSource} ' => ' ...
- labels.regions{rTarget}];
- end
-end
-
-% driving connections
-c = cell(size(dcm.c));
-for lSource = 1:L
- for rTarget = 1:R
- c{rTarget, lSource} = [labels.inputs{lSource} ' => ' ...
- labels.regions{rTarget}];
- end
-end
-
-% modulatory connections
-b = cell(size(dcm.b));
-for l = 1:L
- for rSource = 1:R
- for rTarget = 1:R
- b{rTarget, rSource, l} = [labels.inputs{lSource} ' MOD ' ...
- labels.regions{rSource} ' => ' labels.regions{rTarget}];
- end
- end
-end
-
-% nonlinear connections
-d = cell(size(dcm.d));
-for rMod = 1:R
- for rSource = 1:R
- for rTarget = 1:R
- d{rTarget, rSource, rMod} = [labels.regions{rMod} ' MOD ' ...
- labels.regions{rSource} ' => ' labels.regions{rTarget}];
- end
- end
-end
-
-% hemodynamic parameters
-hemo = cell(R, 2);
-for r = 1:R
- hemo{r, 1} = ['transit ' labels.regions{r}];
- hemo{r, 2} = ['decay ' labels.regions{r}];
-end
-
-tmp = [a(:); b(:); c(:); d(:)];
-idx = [dcm.a(:); dcm.b(:); dcm.c(:); dcm.d(:)];
-
-tickLabels = [tmp(logical(idx)); hemo(:); {'epsilon'}];
-
-end
diff --git a/huge/@tapas_Huge/tapas_Huge.m b/huge/@tapas_Huge/tapas_Huge.m
index b7e6bf3a..f1d30d6e 100644
--- a/huge/@tapas_Huge/tapas_Huge.m
+++ b/huge/@tapas_Huge/tapas_Huge.m
@@ -110,10 +110,10 @@
'mhAdapt', 3e3, ... % interval for adapting step sizes
'mhTrans', 2^10, ... % sample size for adapting transform
'mhReg', 9, ... % regularizer for adapting step sizes
- 'nPsrf', 1e5) % rate for convergence monitoring via PSRF
-
- version = '2019-10'; % Toolbox version
+ 'nPsrf', 1e5, ... % rate for convergence monitoring via PSRF
+ 'baseSc', -.5) % baseline self-connection
+ version = '2020-09'; % Toolbox version
end
@@ -191,6 +191,7 @@
% plot posterior
[ fHdl ] = plot( obj, subjects )
+
% save object properties to disk
[ ] = save( filename, obj, varargin )
@@ -221,17 +222,13 @@
% VB initialization
[ obj ] = vb_init( obj )
- % MH sampling
- [ obj ] = mh_invert( obj )
- % MH initialization
- [ obj ] = mh_init( obj )
-
end
methods (Static, Access = protected)
% de-multiplex parameter vector
[A, B, C, D, tau, kappa, epsilon] = theta2abcd(theta, idx, R, L)
-
+ % generate labels for axis ticks
+ [ tickLabels ] = parse_labels( dcm, labels, idx )
end
end
\ No newline at end of file
diff --git a/huge/@tapas_Huge/test.m b/huge/@tapas_Huge/test.m
index 5bcd5518..026ba4ef 100644
--- a/huge/@tapas_Huge/test.m
+++ b/huge/@tapas_Huge/test.m
@@ -260,33 +260,5 @@
fprintf('passed.\n')
-%% test: compatibility
-fprintf('Testing compatibility with version 201903: \n')
-
-[ priorsOld, DCM ] = tapas_huge_build_prior( listDcms );
-assert(all(abs(priorsOld.clustersTau(:) - prior.tau_0(:))<1e-14), ...
- 'tapas:huge:test', 'aux compatibility');
-assert(all(abs(priorsOld.clustersDeg(:) - prior.nu_0(:))<1e-14), ...
- 'tapas:huge:test', 'aux compatibility');
-assert(all(abs(priorsOld.clustersSigma(:) - prior.S_0(:))<1e-14), ...
- 'tapas:huge:test', 'aux compatibility');
-assert(all(abs(priorsOld.hemMean(:) - prior.mu_h(:))<1e-14), ...
- 'tapas:huge:test', 'aux compatibility');
-assert(all(abs(priorsOld.hemSigma(:) - prior.Sigma_h(:))<1e-14), ...
- 'tapas:huge:test', 'aux compatibility');
-
-priorsOld.clustersMean = 0.0;
-[dr] = tapas_huge_invert(listDcms, 3, priorsOld, 0, 0, posterior.seed);
-assert(all(abs(dr.posterior.dcmMean(:) - posterior.mu_n(:))<1e-14), ...
- 'tapas:huge:test', 'aux compatibility');
-assert(all(abs(dr.posterior.dcmSigma(:) - posterior.Sigma_n(:))<1e-14), ...
- 'tapas:huge:test', 'aux compatibility');
-assert(all(abs(dr.posterior.softAssign(:) - posterior.q_nk(:))<1e-14), ...
- 'tapas:huge:test', 'aux compatibility');
-
-fprintf('passed.\n')
-
-
-
diff --git a/huge/@tapas_Huge/theta2abcd.m b/huge/@tapas_Huge/theta2abcd.m
index 614f671a..4664e91f 100644
--- a/huge/@tapas_Huge/theta2abcd.m
+++ b/huge/@tapas_Huge/theta2abcd.m
@@ -1,8 +1,8 @@
-function [A, B, C, D, tau, kappa, epsilon] = theta2abcd(theta, idx, R, L)
+function [A, B, C, D, tau, kappa, epsilon] = theta2abcd(theta, idx, R, L )
% Transform DCM parameters from vectorized to structured format
%
% This is a protected method of the tapas_Huge class. It cannot be called
-% from outsite the class.
+% from outside the class.
%
% Author: Yu Yao (yao@biomed.ee.ethz.ch)
diff --git a/huge/@tapas_Huge/vb_init.m b/huge/@tapas_Huge/vb_init.m
index a57e3bff..96602fc1 100644
--- a/huge/@tapas_Huge/vb_init.m
+++ b/huge/@tapas_Huge/vb_init.m
@@ -3,7 +3,7 @@
% Requires obj.dcm and obj.prior to be intialized.
%
% This is a protected method of the tapas_Huge class. It cannot be called
-% from outsite the class.
+% from outside the class.
%
% Author: Yu Yao (yao@biomed.ee.ethz.ch)
@@ -190,7 +190,7 @@
obj.trace = struct();
obj.trace.nfe = NaN;
obj.trace.nDcmUpdate = zeros(obj.N, 1);
-
+obj.trace.nRetract = zeros(obj.N,1);
end
diff --git a/huge/@tapas_Huge/vb_invert.m b/huge/@tapas_Huge/vb_invert.m
index 450af741..b88fad1d 100644
--- a/huge/@tapas_Huge/vb_invert.m
+++ b/huge/@tapas_Huge/vb_invert.m
@@ -2,7 +2,7 @@
% Run VB update equations until convergence.
%
% This is a protected method of the tapas_Huge class. It cannot be called
-% from outsite the class.
+% from outside the class.
%
% Author: Yu Yao (yao@biomed.ee.ethz.ch)
@@ -82,7 +82,9 @@
if ~bUpdateClusters
% start updating clustering parameters and confound coefficients
bUpdateClusters = (dNfe < obj.options.convergence.dDcm && dNfe >= 0);% || iIt > 32;
- obj.trace.convergence(1) = iIt;
+ if bUpdateClusters
+ obj.trace.convergence(1) = iIt;
+ end
elseif ~bUpdateAssignments
% start updating assignment labels
@@ -312,6 +314,7 @@
mu_prime_c = mu_prime_c + m_k(k,:)*tmps;
end
+
% Eq (19)
% posterior covariance
Lambda_bar = repmat(obj.aux.lambda_bar(n,:), obj.aux.q_r(n), 1);
@@ -322,14 +325,14 @@
Pi_n(obj.idx.P_c+1:end, obj.idx.P_c+1:end) = obj.aux.Pi_h + ...
Pi_n(obj.idx.P_c+1:end, obj.idx.P_c+1:end);
obj.posterior.Sigma_n(:,:,n) = inv(Pi_n); %%% TODO Pi + diag(delta)
+ obj.aux.ldSigma(n) = - tapas_huge_logdet(Pi_n);
% posterior mean
tmp = obj.aux.epsilon{n}(:) + obj.aux.G{n}*obj.posterior.mu_n(n,:)';
+ % regularization factor
+ tmp = tmp*(.9.^mod(obj.trace.nRetract(n),5));
obj.posterior.mu_n(n,:) = ...
((G_Lambda*tmp)' + [mu_prime_c, obj.aux.mu_prime_h])/Pi_n;
-
- obj.aux.ldSigma(n) = - tapas_huge_logdet(Pi_n);
-
- % jacobian and residual
+ % recalculate jacobian and residual
obj = obj.options.fncBold(obj, n);
% Eq (22)
@@ -343,7 +346,7 @@
newNfe = obj.vb_nfe( );
% check negative free energy (during first few iterations, accept
- % decease in F if fit improves)
+ % decrease in F if fit improves)
bUnstable = any(isnan(obj.aux.G{n}(:))) || any(isinf(obj.aux.G{n}(:)));
bOverride = bCheckNfe || varEps < sum(var(obj.aux.epsilon{n}));
if bUnstable || (tmpNfe > newNfe && bOverride)
@@ -356,10 +359,12 @@
obj.posterior.b(n,:) = tmpB(n,:);
obj.aux.b_prime(n,:) = tmpBp(n,:);
obj.aux.lambda_bar(n,:) = tmpLb(n,:);
+ obj.trace.nRetract(n) = obj.trace.nRetract(n) + 1;
else
% otherwise accept update
tmpNfe = newNfe;
obj.trace.nDcmUpdate(n) = obj.trace.nDcmUpdate(n) + 1;
+ obj.trace.nRetract(n) = 0;
end
end
diff --git a/huge/@tapas_Huge/vb_nfe.m b/huge/@tapas_Huge/vb_nfe.m
index 47c588e0..43dca82a 100644
--- a/huge/@tapas_Huge/vb_nfe.m
+++ b/huge/@tapas_Huge/vb_nfe.m
@@ -3,7 +3,7 @@
% estimates.
%
% This is a protected method of the tapas_Huge class. It cannot be called
-% from outsite the class.
+% from outside the class.
%
% Author: Yu Yao (yao@biomed.ee.ethz.ch)
diff --git a/huge/tapas_huge_bold.m b/huge/tapas_huge_bold.m
index 82323fad..cf696a3d 100644
--- a/huge/tapas_huge_bold.m
+++ b/huge/tapas_huge_bold.m
@@ -66,9 +66,6 @@
nt = size(u, 1);
rSmp = TR/dt;
C = C'/rSmp;
-
-% transform self-connections
-A = A - .5*eye(R);
if isempty(D)
D = zeros(R, R, R);
end
diff --git a/huge/tapas_huge_build_prior.m b/huge/tapas_huge_build_prior.m
deleted file mode 100644
index 3f643089..00000000
--- a/huge/tapas_huge_build_prior.m
+++ /dev/null
@@ -1,99 +0,0 @@
-function [ priors, DCM ] = tapas_huge_build_prior( DCM )
-% WARNING: This function is deprecated and will be removed in a future
-% version of this toolbox. Please use the new object-oriented interface
-% provided by the tapas_Huge class.
-%
-% Generate values for prior parameters for HUGE. Prior mean of cluster
-% centers and prior mean and covariance of hemodynamic parameters follow
-% SPM convention (SPM8 r6313).
-%
-% INPUT:
-% DcmInfo - cell array of DCM in SPM format
-%
-% OUTPUT:
-% priors - struct containing priors
-% DcmInfo - struct containing DCM model specification and BOLD time
-% series in DcmInfo format
-%
-% See also tapas_Huge, tapas_Huge.estimate, tapas_huge_demo
-%
-
-% Author: Yu Yao (yao@biomed.ee.ethz.ch)
-% Copyright (C) 2019 Translational Neuromodeling Unit
-% Institute for Biomedical Engineering,
-% University of Zurich and ETH Zurich.
-%
-% This file is part of TAPAS, which is released under the terms of the GNU
-% General Public Licence (GPL), version 3. For further details, see
-% .
-%
-% This software is provided "as is", without warranty of any kind, express
-% or implied, including, but not limited to the warranties of
-% merchantability, fitness for a particular purpose and non-infringement.
-%
-% This software is intended for research only. Do not use for clinical
-% purpose. Please note that this toolbox is under active development.
-% Considerable changes may occur in future releases. For support please
-% refer to:
-% https://github.com/translationalneuromodeling/tapas/issues
-%
-
-wnMsg = ['This function is deprecated and will be removed in a future ' ...
- 'version of this toolbox. Please use the new object-oriented ' ...
- 'interface provided by the tapas_Huge class.'];
-warning('tapas:huge:deprecated',wnMsg)
-
-%% check input format
-if isvector(DCM)&&isstruct(DCM)
- try
- DCM = {DCM(:).DCM}';
- catch
- DCM = num2cell(DCM);
- end
-else
- assert(iscell(DCM),'TAPAS:HUGE:inputFormat',...
- 'DCM must be cell array of DCMs in SPM format');
-end
-
-dcm = DCM{1};
-
-
-%% set priors
-priors = struct();
-% parameter of Dirichlet prior (alpha_0 in Figure 1 of REF [1])
-priors.alpha = 1;
-
-tmp = dcm.a/64/dcm.n;
-tmp = tmp - diag(diag(tmp)) - .5*eye(dcm.n);
-tmp = [tmp(:); dcm.b(:)*0; dcm.c(:)*0; ...
- dcm.d(:)*0];
-
-connectionIndicator = find([dcm.a(:);dcm.b(:);dcm.c(:);dcm.d(:)]);
-% prior mean of clusters (m_0 in Figure 1 of REF [1])
-priors.clustersMean = tmp(connectionIndicator)';
-% tau_0 in Figure 1 of REF [1]
-priors.clustersTau = 0.1;
-% degrees of freedom of inverse-Wishart prior (nu_0 in Figure 1 of REF [1])
-priors.clustersDeg = max(100,1.5^length(connectionIndicator));
-priors.clustersDeg = min(priors.clustersDeg,double(realmax('single')));
-
-% scale matrix of inverse-Wishart prior (S_0 in Figure 1 of REF [1])
-priors.clustersSigma = 0.01*eye(length(connectionIndicator))*...
- (priors.clustersDeg - length(connectionIndicator) - 1);
-
-% prior mean of hemodynamic parameters (mu_h in Figure 1 of REF [1])
-priors.hemMean = zeros(1,dcm.n*2 + 1);
-
-% prior Covariance of hemodynamic parameters(Sigma_h in Figure 1 of
-% REF [1])
-priors.hemSigma = diag(zeros(1,dcm.n*2 + 1)+exp(-6));
-
-% prior inverse scale of observation noise (b_0 in Figure 1 of REF [1])
-priors.noiseInvScale = .025;
-
-% prior shape parameter of observation noise (a_0 in Figure 1 of REF [1])
-priors.noiseShape = 1.28;
-
-
-end
-
diff --git a/huge/tapas_huge_invert.m b/huge/tapas_huge_invert.m
deleted file mode 100644
index b16f535a..00000000
--- a/huge/tapas_huge_invert.m
+++ /dev/null
@@ -1,176 +0,0 @@
-function [DcmResults] = tapas_huge_invert(DCM, K, priors, verbose, randomize, seed)
-% WARNING: This function is deprecated and will be removed in a future
-% version of this toolbox. Please use the new object-oriented interface
-% provided by the tapas_Huge class.
-%
-% Invert hierarchical unsupervised generative embedding (HUGE) model.
-%
-% INPUT:
-% DCM - cell array of DCM in SPM format
-% K - number of clusters (set K to one for empirical Bayes)
-%
-% OPTIONAL INPUT:
-% priors - model priors stored in a struct containing the
-% following fields:
-% alpha: parameter of Dirichlet prior (alpha_0 in Fig.1 of
-% REF [1])
-% clustersMean: prior mean of clusters (m_0 in Fig.1 of REF [1])
-% clustersTau: tau_0 in Fig.1 of REF [1]
-% clustersDeg: degrees of freedom of inverse-Wishart prior (nu_0 in
-% Fig.1 of REF [1])
-% clustersSigma: scale matrix of inverse-Wishart prior (S_0 in Fig.1
-% of REF [1])
-% hemMean: prior mean of hemodynamic parameters (mu_h in Fig.1
-% of REF [1])
-% hemSigma: prior covariance of hemodynamic parameters (Sigma_h
-% in Fig.1 of REF [1])
-% noiseInvScale: prior inverse scale of observation noise (b_0 in
-% Fig.1 of REF [1])
-% noiseShape: prior shape parameter of observation noise (a_0 in
-% Fig.1 of REF [1])
-% verbose - activates command line output (prints free energy
-% difference, default: false)
-% randomize - randomize starting values (default: false). WARNING:
-% randomizing starting values can cause divergence of DCM.
-% seed - seed for random number generator
-%
-% OUTPUT:
-% DcmResults - struct used for storing the results from VB. Posterior
-% parameters are stored in DcmResults.posterior, which is a
-% struct containing the following fields:
-% alpha: parameter of posterior over cluster weights
-% (alpha_k in Eq.(15) of REF [1])
-% softAssign: posterior assignment probability of subjects
-% to clusters (q_nk in Eq.(18) in REF [1])
-% clustersMean: posterior mean of clusters (m_k in Eq.(16) of
-% REF [1])
-% clustersTau: tau_k in Eq.(16) of REF [1]
-% clustersDeg: posterior degrees of freedom (nu_k in Eq.(16)
-% of REF [1])
-% clustersSigma: posterior scale matrix (S_k in Eq.(16) of
-% REF [1])
-% logDetClustersSigma: log-determinant of S_k
-% dcmMean: posterior mean of DCM parameters (mu_n in
-% Eq.(19) of REF [1])
-% dcmSigma: posterior covariance of hemodynamic
-% parameters (Sigma_n in Eq.(19) of REF [1])
-% logDetPostDcmSigma: log-determinant of Sigma_n
-% noiseInvScale: posterior inverse scale of observation noise
-% (b_n,r in Eq.(21) of REF [1])
-% noiseShape: posterior shape parameter of observation noise
-% (a_n,r in Eq.(21) of REF [1])
-% meanNoisePrecision: posterior mean of precision of observation
-% noise (lambda_n,r in Eq.(23) of REF [1])
-% modifiedSumSqrErr: b'_n,r in Eq.(22) of REF [1]
-%
-% See also tapas_Huge, tapas_Huge.estimate, tapas_huge_demo
-%
-
-% Author: Yu Yao (yao@biomed.ee.ethz.ch)
-% Copyright (C) 2019 Translational Neuromodeling Unit
-% Institute for Biomedical Engineering,
-% University of Zurich and ETH Zurich.
-%
-% This file is part of TAPAS, which is released under the terms of the GNU
-% General Public Licence (GPL), version 3. For further details, see
-% .
-%
-% This software is provided "as is", without warranty of any kind, express
-% or implied, including, but not limited to the warranties of
-% merchantability, fitness for a particular purpose and non-infringement.
-%
-% This software is intended for research only. Do not use for clinical
-% purpose. Please note that this toolbox is under active development.
-% Considerable changes may occur in future releases. For support please
-% refer to:
-% https://github.com/translationalneuromodeling/tapas/issues
-%
-
-
-wnMsg = ['This function is deprecated and will be removed in a future ' ...
- 'version of this toolbox. Please use the new object-oriented ' ...
- 'interface provided by the tapas_Huge class.'];
-warning('tapas:huge:deprecated',wnMsg)
-
-%% check input
-if isvector(DCM)&&isstruct(DCM)
- try
- DCM = {DCM(:).DCM}';
- catch
- DCM = num2cell(DCM);
- end
-else
- assert(iscell(DCM),'TAPAS:HUGE:inputFormat',...
- 'DCM must be cell array of DCMs in SPM format');
-end
-
-%% settings
-opts = {'K', K};
-opts = [opts, {'Dcm', DCM}];
-
-if nargin >= 6
- opts = [opts, {'Seed', seed}];
-end
-
-if nargin >= 5
- opts = [opts, {'Randomize', randomize}];
-end
-
-if nargin >= 4
- opts = [opts, {'Verbose', verbose}];
-end
-
-if nargin >= 3
- dcm = DCM{1};
- nConnections = nnz([dcm.a(:);dcm.b(:);dcm.c(:);dcm.d(:)]);
- priors.clustersSigma = priors.clustersSigma/...
- (priors.clustersDeg - nConnections - 1);
-
- opts = [opts, {'PriorVarianceRatio', priors.clustersTau, ...
- 'PriorDegree', priors.clustersDeg, ...
- 'PriorClusterVariance', priors.clustersSigma, ...
- 'PriorClusterMean', priors.clustersMean}];
-end
-
-assert(K>0,'TAPAS:HUGE:clusterSize',...
- 'Cluster size K must to be positive integer');
-
-%% invert model
-obj = tapas_Huge(opts{:});
-obj = obj.estimate();
-
-DcmResults.freeEnergy = obj.posterior.nfe;
-DcmResults.maxClusters = K;
-DcmResults.rngSeed = obj.posterior.seed;
-DcmResults.posterior = struct( ...
- 'alpha', obj.posterior.alpha, ...
- 'softAssign', obj.posterior.q_nk, ...
- 'clustersMean' , obj.posterior.m , ...
- 'clustersTau', obj.posterior.tau , ...
- 'clustersDeg' , obj.posterior.nu , ...
- 'clustersSigma' , obj.posterior.S , ...
- 'logDetClustersSigma', [] , ...
- 'dcmMean', obj.posterior.mu_n , ...
- 'dcmSigma', obj.posterior.Sigma_n , ...
- 'logDetPostDcmSigma', [] , ...
- 'noiseShape', obj.posterior.a, ...
- 'noiseInvScale', obj.posterior.b , ...
- 'meanNoisePrecision', obj.posterior.a./obj.posterior.b , ...
- 'modifiedSumSqrErr', []);
-DcmResults.residuals = obj.trace.epsilon;
-
-end
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/huge/tapas_huge_manual.pdf b/huge/tapas_huge_manual.pdf
index 62bfd6e7..31bd407e 100644
Binary files a/huge/tapas_huge_manual.pdf and b/huge/tapas_huge_manual.pdf differ
diff --git a/huge/tapas_huge_manual.tex b/huge/tapas_huge_manual.tex
index 3e85e7d9..6f165e84 100644
--- a/huge/tapas_huge_manual.tex
+++ b/huge/tapas_huge_manual.tex
@@ -5,17 +5,17 @@
\documentclass{article}
\usepackage{graphicx}
\usepackage[table]{xcolor}
-\usepackage[utf8]{inputenc}
-\usepackage{natbib}
-\usepackage{lmodern}
-\usepackage{enumitem}
\sloppy
\definecolor{lgray}{gray}{0.65}
\definecolor{llgray}{gray}{0.85}
\setlength{\parindent}{0pt}
-\setlength\arrayrulewidth{0.8pt}
+\usepackage[utf8]{inputenc}
+\usepackage{natbib}
+\usepackage{lmodern}
+\usepackage{enumitem}
+\setlength\arrayrulewidth{0.8pt}
\title{User Manual Hierarchical Unsupervised Generative Embedding}
\author{\\Yu Yao\\%
@@ -29,6 +29,7 @@
+
\section{Introduction}
\begin{par}
@@ -49,15 +50,15 @@ \section{The \texttt{tapas\_Huge} Class}
\end{par} \vspace{1em}
\begin{par}
Instances of the \texttt{tapas\_Huge} class are created by calling the class constructor \texttt{tapas\_Huge()}. The constructor is a function that can be called without arguments, which creates an empty \texttt{tapas\_Huge} object:
-\end{par}
+\end{par}
\begin{verbatim}obj = tapas_Huge()\end{verbatim}
\begin{par}
-However, the constructor also accepts optional arguments in the form of name-value pairs. For example, one can add a short description using the \texttt{Tag} property
-\end{par}
+However, the constructor also accepts optional arguments in the form of name-value pairs. For example, one can add a short description using the \texttt{tag} property
+\end{par}
\begin{verbatim}obj = tapas_Huge('Tag','my model')\end{verbatim}
\begin{par}
or import data using the \texttt{Dcm} property
-\end{par}
+\end{par}
\begin{verbatim}obj = tapas_Huge('Dcm',dcms)\end{verbatim}
\begin{par}
For more examples, see the demo script \texttt{tapas\_huge\_demo.mlx}.
@@ -68,7 +69,7 @@ \section{Class Properties}
\begin{par}
Each instance of the \texttt{tapas\_Huge} class stores data, options and results in class properties, which are documented below. Properties can be accessed using dot notation:
-\end{par}
+\end{par}
\begin{verbatim}value = obj.property\end{verbatim}
\begin{par}
where \texttt{obj} is a class instance and \texttt{property} is the name of the property.
@@ -288,11 +289,11 @@ \section{Class Methods}
\begin{par}
The main functionalities of the HUGE toolbox are implemented as methods of the \texttt{tapas\_Huge} class. These methods are documented below. There are two equivalent ways to call class methods:
-\end{par}
+\end{par}
\begin{verbatim}obj = obj.method( ... )\end{verbatim}
\begin{par}
or
-\end{par}
+\end{par}
\begin{verbatim}obj = method( obj, ... )\end{verbatim}
\begin{par}
where \texttt{obj} is an instance of the \texttt{tapas\_Huge} class and \texttt{method} is the class method you want to call.
@@ -301,7 +302,7 @@ \section{Class Methods}
\subsection*{ \texttt{tapas\_Huge.estimate}}
- \begin{verbatim} Estimate parameters of the HUGE model.
+ \begin{verbatim} Estimate parameters of the HUGE model.
INPUTS:
obj - A tapas_Huge object containing fMRI time series.
@@ -332,13 +333,13 @@ \subsection*{ \texttt{tapas\_Huge.estimate}}
\end{verbatim} \color{black}
\begin{par}
-Note that the HUGE toolbox uses a parameterization such that the DCM networks are self-inhibiting by default. This is achieved by subtracting 0.5 from the self-connections. Hence, specifying a prior mean of zero for all DCM connections implies that the effective self-connectivity is -0.5. This parametrization has been chosen for the convenience of the user, since it eliminates the need to identify the position of the self-connections in the parameter vector.
+Note that the HUGE toolbox uses a parameterization such that the DCM networks are self-inhibiting by default. This is achieved by subtracting 0.5 from the self-connections. Hence, specifying a prior mean of zero for all DCM connections implies that the effective self-connectivity is -0.5. This is similar to DCM self-connections in SPM12. This parametrization has been chosen for the convenience of the user, since it eliminates the need to identify the position of the self-connections in the parameter vector.
\end{par} \vspace{1em}
\subsection*{ \texttt{tapas\_Huge.simulate}}
- \begin{verbatim} Generate synthetic task-based fMRI time series data, using HUGE as a
+ \begin{verbatim} Generate synthetic task-based fMRI time series data, using HUGE as a
generative model.
INPUTS:
@@ -396,7 +397,7 @@ \subsection*{ \texttt{tapas\_Huge.simulate}}
\subsection*{ \texttt{tapas\_Huge.plot}}
- \begin{verbatim} Plot cluster and subject-level estimation result from HUGE model.
+ \begin{verbatim} Plot cluster and subject-level estimation result from HUGE model.
INPUTS:
obj - A tapas_Huge object containing estimation results.
@@ -416,7 +417,7 @@ \subsection*{ \texttt{tapas\_Huge.plot}}
\subsection*{ \texttt{tapas\_Huge.save}}
- \begin{verbatim} Save properties of HUGE object to mat file.
+ \begin{verbatim} Save properties of HUGE object to mat file.
INPUTS:
filename - File name.
@@ -437,7 +438,7 @@ \subsection*{ \texttt{tapas\_Huge.save}}
\subsection*{ \texttt{tapas\_Huge.import}}
- \begin{verbatim} Import fMRI time series data into HUGE object.
+ \begin{verbatim} Import fMRI time series data into HUGE object.
WARNING: Importing data into a HUGE object will delete any data and
results which are already stored in that object.
@@ -483,7 +484,7 @@ \subsection*{ \texttt{tapas\_Huge.import}}
\subsection*{ \texttt{tapas\_Huge.export}}
- \begin{verbatim} Export results and data from HUGE object to SPM's DCM format.
+ \begin{verbatim} Export results and data from HUGE object to SPM's DCM format.
INPUTS:
obj - A tapas_Huge object containing data.
@@ -509,7 +510,7 @@ \subsection*{ \texttt{tapas\_Huge.export}}
\subsection*{ \texttt{tapas\_Huge.remove}}
- \begin{verbatim} Remove data (fMRI time series, confounds, DCM network structure, ... )
+ \begin{verbatim} Remove data (fMRI time series, confounds, DCM network structure, ... )
and estimation results from HUGE object.
INPUTS:
@@ -747,6 +748,17 @@ \section{Name-Value Pair Arguments}
\vspace{1em}
\begin{tabular}{|l|p{10cm}|}
\hline
+\rowcolor{lgray} Name: & \verb+TransformInput+ \\
+\hline
+\rowcolor{llgray} Value: & bool (default: false)\\
+\hline
+ \rowcolor{llgray} Description: & Transform input strength (C matrix) to log-domain.
+\\
+\hline
+\end{tabular}
+\vspace{1em}
+\begin{tabular}{|l|p{10cm}|}
+\hline
\rowcolor{lgray} Name: & \verb+Verbose+ \\
\hline
\rowcolor{llgray} Value: & bool (default: \verb+false+)\\
@@ -770,7 +782,7 @@ \section{Other Functions}
\subsection*{ \texttt{tapas\_huge\_boxcar}}
- \begin{verbatim} Generate a boxcar function for use as experimental stimulus. All
+ \begin{verbatim} Generate a boxcar function for use as experimental stimulus. All
timing-related arguments must be specified in seconds.
INPUTS:
@@ -797,29 +809,9 @@ \subsection*{ \texttt{tapas\_huge\_boxcar}}
\end{verbatim} \color{black}
-\subsection*{ \texttt{tapas\_huge\_bpurity}}
-
- \begin{verbatim} Calculate balanced purity (see Brodersen2014 Eq. 13 and 14) for a set of
- ground truth labels and a set of estimated labels
-
- INPUTS:
- labels - Vector of ground truth class labels.
- estimates - Clustering result as array of assignment probabilities or
- vector of cluster indices.
-
- OUTPUTS:
- balancedPurity - Balanced purity score according to Brodersen (2014)
-
- EXAMPLES:
- bp = TAPAS_HUGE_BPURITY(labels,estimates)
-
-
-\end{verbatim} \color{black}
-
-
\subsection*{ \texttt{tapas\_huge\_bold}}
- \begin{verbatim} Integrates the DCM forward equations to generate the predicted fMRI bold
+ \begin{verbatim} Integrates the DCM forward equations to generate the predicted fMRI bold
time series.
INPUTS:
@@ -851,6 +843,26 @@ \subsection*{ \texttt{tapas\_huge\_bold}}
q1 - time series of deoxyhemoglobin content.
+\end{verbatim} \color{black}
+
+
+\subsection*{ \texttt{tapas\_huge\_bpurity}}
+
+ \begin{verbatim} Calculate balanced purity (see Brodersen2014 Eq. 13 and 14) for a set of
+ ground truth labels and a set of estimated labels
+
+ INPUTS:
+ labels - Vector of ground truth class labels.
+ estimates - Clustering result as array of assignment probabilities or
+ vector of cluster indices.
+
+ OUTPUTS:
+ balancedPurity - Balanced purity score according to Brodersen (2014)
+
+ EXAMPLES:
+ bp = TAPAS_HUGE_BPURITY(labels,estimates)
+
+
\end{verbatim} \color{black}
\begin{par}
For more information on the fMRI BOLD model, please refer to \cite{stephan2007}.
@@ -868,8 +880,8 @@ \subsection*{ \texttt{tapas\_huge\_logdet}}
\begin{par}
This function is intended for internal use only. Do not call directly
-\end{par}
- \begin{verbatim} Numerical stable calculation of log-determinant for positive-definite
+\end{par} \vspace{1em}
+ \begin{verbatim} Numerical stable calculation of log-determinant for positive-definite
matrix.
INPUT:
@@ -886,12 +898,29 @@ \subsection*{ \texttt{tapas\_huge\_logdet}}
\end{verbatim} \color{black}
+\subsection*{ \texttt{tapas\_huge\_logit}}
+
+\begin{par}
+This function is intended for internal use only. Do not call directly
+\end{par} \vspace{1em}
+ \begin{verbatim} Numerical stable calculation of logit function.
+
+ INPUTS:
+ x - Array of double.
+
+ OUTPUTS:
+ y - logit of x.
+
+
+\end{verbatim} \color{black}
+
+
\subsection*{ \texttt{tapas\_huge\_parse\_inputs}}
\begin{par}
This function is intended for internal use only. Do not call directly
-\end{par}
- \begin{verbatim} Parse name-value pair type arguments into a struct.
+\end{par} \vspace{1em}
+ \begin{verbatim} Parse name-value pair type arguments into a struct.
INPUTS:
opts - Struct containing all valid names as field names and
@@ -909,105 +938,6 @@ \subsection*{ \texttt{tapas\_huge\_parse\_inputs}}
for 'a'.
-\end{verbatim} \color{black}
- \begin{par}
-The following two functions provide backward compatibility to the interface of the previous version of the HUGE toolbox (version 201903).
-\end{par} \vspace{1em}
-
-
-\subsection*{ \texttt{tapas\_huge\_invert}}
-
- \begin{verbatim} WARNING: This function is deprecated and will be removed in a future
- version of this toolbox. Please use the new object-oriented interface
- provided by the tapas_Huge class.
-
- Invert hierarchical unsupervised generative embedding (HUGE) model.
-
- INPUT:
- DCM - cell array of DCM in SPM format
- K - number of clusters (set K to one for empirical Bayes)
-
- OPTIONAL INPUT:
- priors - model priors stored in a struct containing the
- following fields:
- alpha: parameter of Dirichlet prior (alpha_0 in Fig.1 of
- REF [1])
- clustersMean: prior mean of clusters (m_0 in Fig.1 of REF [1])
- clustersTau: tau_0 in Fig.1 of REF [1]
- clustersDeg: degrees of freedom of inverse-Wishart prior (nu_0 in
- Fig.1 of REF [1])
- clustersSigma: scale matrix of inverse-Wishart prior (S_0 in Fig.1
- of REF [1])
- hemMean: prior mean of hemodynamic parameters (mu_h in Fig.1
- of REF [1])
- hemSigma: prior covariance of hemodynamic parameters (Sigma_h
- in Fig.1 of REF [1])
- noiseInvScale: prior inverse scale of observation noise (b_0 in
- Fig.1 of REF [1])
- noiseShape: prior shape parameter of observation noise (a_0 in
- Fig.1 of REF [1])
- verbose - activates command line output (prints free energy
- difference, default: false)
- randomize - randomize starting values (default: false). WARNING:
- randomizing starting values can cause divergence of DCM.
- seed - seed for random number generator
-
- OUTPUT:
- DcmResults - struct used for storing the results from VB. Posterior
- parameters are stored in DcmResults.posterior, which is a
- struct containing the following fields:
- alpha: parameter of posterior over cluster weights
- (alpha_k in Eq.(15) of REF [1])
- softAssign: posterior assignment probability of subjects
- to clusters (q_nk in Eq.(18) in REF [1])
- clustersMean: posterior mean of clusters (m_k in Eq.(16) of
- REF [1])
- clustersTau: tau_k in Eq.(16) of REF [1]
- clustersDeg: posterior degrees of freedom (nu_k in Eq.(16)
- of REF [1])
- clustersSigma: posterior scale matrix (S_k in Eq.(16) of
- REF [1])
- logDetClustersSigma: log-determinant of S_k
- dcmMean: posterior mean of DCM parameters (mu_n in
- Eq.(19) of REF [1])
- dcmSigma: posterior covariance of hemodynamic
- parameters (Sigma_n in Eq.(19) of REF [1])
- logDetPostDcmSigma: log-determinant of Sigma_n
- noiseInvScale: posterior inverse scale of observation noise
- (b_n,r in Eq.(21) of REF [1])
- noiseShape: posterior shape parameter of observation noise
- (a_n,r in Eq.(21) of REF [1])
- meanNoisePrecision: posterior mean of precision of observation
- noise (lambda_n,r in Eq.(23) of REF [1])
- modifiedSumSqrErr: b'_n,r in Eq.(22) of REF [1]
-
- See also tapas_Huge, tapas_Huge.estimate, tapas_huge_demo
-
-
-\end{verbatim} \color{black}
-
-
-\subsection*{ \texttt{tapas\_huge\_build\_prior}}
-
- \begin{verbatim} WARNING: This function is deprecated and will be removed in a future
- version of this toolbox. Please use the new object-oriented interface
- provided by the tapas_Huge class.
-
- Generate values for prior parameters for HUGE. Prior mean of cluster
- centers and prior mean and covariance of hemodynamic parameters follow
- SPM convention (SPM8 r6313).
-
- INPUT:
- DcmInfo - cell array of DCM in SPM format
-
- OUTPUT:
- priors - struct containing priors
- DcmInfo - struct containing DCM model specification and BOLD time
- series in DcmInfo format
-
- See also tapas_Huge, tapas_Huge.estimate, tapas_huge_demo
-
-
\end{verbatim} \color{black}
@@ -1034,5 +964,6 @@ \section{Licence and Support}
+
\end{document}
diff --git a/huge/tapas_huge_property_names.m b/huge/tapas_huge_property_names.m
index 8cf9d7f4..50e9332a 100644
--- a/huge/tapas_huge_property_names.m
+++ b/huge/tapas_huge_property_names.m
@@ -1,5 +1,6 @@
%% List of name-value pair arguments accepted by tapas_Huge() and estimate()
%
+%
% NAME: Confounds
% VALUE: double array
% DESCRIPTION: Specify confounds for group-level analysis (e.g. age or sex)
@@ -28,11 +29,12 @@
% NAME: Method
% VALUE: 'VB'
% DESCRIPTION: Name of inversion method specified as character array. VB:
-% variational Bayes
+% variational Bayes.
%
% NAME: NumberOfIterations
-% VALUE: positive integer (default: 999)
-% DESCRIPTION: Maximum number of iterations of VB scheme.
+% VALUE: positive integer (default: 999 for VB, 2e5 for MH)
+% DESCRIPTION: For VB: maximum number of iterations. For Monte Carlo
+% methods: Length of Monte Carlo chain in samples.
%
% NAME: OmitFromClustering
% VALUE: array of logical | struct with fields a, b, c and d
@@ -59,7 +61,8 @@
% VALUE: 'default' | positive double
% DESCRIPTION: nu_0 determines the prior precision of the cluster
% covariance. For VB, this is the degrees of freedom of the
-% inverse-Wishart. Default: 100.
+% inverse-Wishart. For MH, this is the prior precision of the
+% cluster log-precision. Default: 100.
%
% NAME: PriorVarianceRatio
% VALUE: 'default' | positive double
@@ -104,6 +107,10 @@
% VALUE: character array
% DESCRIPTION: Model description
%
+% NAME: TransformInput
+% VALUE: bool (default: false)
+% DESCRIPTION: Transform input strength (C matrix) to log-domain.
+%
% NAME: Verbose
% VALUE: bool (default: false)
% DESCRIPTION: Activate/deactivate command line output.
diff --git a/misc/log_tapas.txt b/misc/log_tapas.txt
index 27131b43..b30e4be2 100644
--- a/misc/log_tapas.txt
+++ b/misc/log_tapas.txt
@@ -1,3 +1,4 @@
+4.0.0 https://www.tapas.tnu-zurich.com/examples_v4.0.0.zip 1c8f1b5f53f2ec5e7ab6d5b2d942c1d5
3.3.0 https://www.tapas.tnu-zurich.com/examples_v3.3.0.zip 95b885041126dfd81e689c95d7bb4aab
3.2.0 https://www.tapas.tnu-zurich.com/examples_v3.2.0.zip 00137f7a332be031fdb2a748a8b1592c
3.1.0 https://www.tapas.tnu-zurich.com/examples_v3.1.0.zip 05cbb1df4eaeab59f88d2c6ad7a87946
diff --git a/misc/tapas_check_for_new_release.m b/misc/tapas_check_for_new_release.m
new file mode 100644
index 00000000..ab81a2dc
--- /dev/null
+++ b/misc/tapas_check_for_new_release.m
@@ -0,0 +1,84 @@
+function haveNewerRelease = tapas_check_for_new_release(verbose)
+ %% Check if a new release is available.
+ %
+ % Input
+ % verbose -- Show information on command prompt:
+ % 0 no information
+ % 1 only if there is a new release (or not)
+ % 2 as 1, but if there is a new release also
+ % the release notes for the lase release
+ % 3 as 1, but if there is a new release also
+ % the release notes for all newer
+ % releases.
+ %
+ % Output
+ % haveNewerRelease -- True if there is a newer release on github
+
+ % muellmat@ethz.ch
+ % copyright (C) 2020
+ %
+
+ if nargin < 1
+ verbose = 3;
+ end
+
+ [online_version,data] = tapas_check_online_version();
+ if isempty(online_version) % Could not communicate with server
+ haveNewerRelease = false;
+ if verbose
+ fprintf(1, 'Could not reach github to get current TAPAS version!\n');
+ end
+ return;
+ end
+ offline_version = tapas_get_current_version();
+ % both versions are strings in the form '3.3.0'.
+ haveNewerRelease = tapas_compare_versions(online_version,offline_version);
+
+ if verbose % Show info
+ if ~haveNewerRelease
+ fprintf(1, '\nYour TAPAS version is up-to-date (version %s).\n',offline_version);
+ else
+ fprintf(1, ['\nThere is a new TAPAS release available (installed %s /'...
+ +'newest %s)!\n'],offline_version,online_version);
+ if verbose > 1 % Show release notes of the new releases
+ try % in case the api changed and the structure of the struct is
+ % different
+ n_data = numel(data);
+ fprintf(1, 'Release notes:\n')
+ if verbose == 2
+ n_data = 1; % Just iterate once through loop
+ end
+ for i_data = 1:n_data
+ str_version = data(i_data).tag_name;
+ str_version = strrep(str_version,'v','');
+ if tapas_compare_versions(str_version,offline_version)
+ fprintf(1, '===== TAPAS v%s =====\n',str_version)
+ body = data(i_data).body;
+ body = tapas_remove_problematic_escape_characters(body);
+ fprintf(1,body);
+ fprintf(1,'\n======================\n')
+ end
+ end
+ catch
+ fprintf(1, ['Cannot print release notes. Maybe the github API'...
+ ' has changed.\n']);
+ end
+ end
+ end
+ end
+
+end
+
+
+function str = tapas_remove_problematic_escape_characters(str)
+ %% Removing problematic escape characters
+ %
+ % Input
+ % str -- String with problematic escape characters
+ %
+ % Output
+ % str -- String without problematic escape characters
+
+ % matlab does not like some escape sequences from github
+ str = strrep(str,'\','');
+end
diff --git a/misc/tapas_check_online_version.m b/misc/tapas_check_online_version.m
new file mode 100644
index 00000000..4d1469a2
--- /dev/null
+++ b/misc/tapas_check_online_version.m
@@ -0,0 +1,28 @@
+function [version,data] = tapas_check_online_version()
+ %% Read online the current version of tapas there.
+ %
+ % Input
+ %
+ % Output
+ % version -- Current version of tapas on github (as string)
+ % If the service is not available, an empty string
+ % data -- The data form the github api
+ % If the service is not available, am empty struct
+
+ % muellmat@ethz.ch
+ % copyright (C) 2020
+ %
+
+ % acessing the github api. matlab is converting it to a struct (data)
+ try
+ data = webread('https://api.github.com/repos/translationalneuromodeling/tapas/releases');
+ % depending on verbose options, we use data(i).tag_name and data(i).body
+ % for all i (if api would change).
+ version = data(1).tag_name;
+ catch
+ data = struct();
+ version = '';
+ end
+ version = strrep(version,'v','');
+
+end
\ No newline at end of file
diff --git a/misc/tapas_compare_versions.m b/misc/tapas_compare_versions.m
new file mode 100644
index 00000000..fe228427
--- /dev/null
+++ b/misc/tapas_compare_versions.m
@@ -0,0 +1,41 @@
+function haveNewerRelease = tapas_compare_versions(online_version,offline_version)
+ %% Check if online_version is higher.
+ %
+ % Input
+ % online_version -- Online version as string of numbers separated
+ % by dots, i.e. '3.3.0'
+ % offline_version -- Online version as string of numbers separated
+ % by dots, i.e. '2.7.0.3'
+ %
+ % Output
+ % haveNewerRelease -- true if version number of online_version is
+ % higher than that of offline_version
+
+ % muellmat@ethz.ch
+ % copyright (C) 2020
+ %
+
+ haveNewerRelease = false; % If both releases are the same, return false
+ online_numbers = str2double(strsplit(online_version,'.'));
+ offline_numbers = str2double(strsplit(offline_version,'.'));
+ % Check whether they have the same lenght (oterwise fill with zeros)
+ n_online = numel(online_numbers);
+ n_offline = numel(offline_numbers);
+ if n_online > n_offline
+ offline_numbers(n_online) = 0; % matlab fills rest with zeros
+ elseif n_online < n_offline
+ online_numbers(n_offline) = 0; % matlab fills rest with zeros
+ end
+ % Now that they have the same length, compare them number by number.
+ % Return at the first difference.
+ for ind = 1:max(n_online,n_offline)
+ if online_numbers(ind) > offline_numbers(ind)
+ haveNewerRelease = true;
+ return;
+ elseif online_numbers(ind) < offline_numbers(ind)
+ haveNewerRelease = false;
+ return;
+ end
+ end
+
+end
\ No newline at end of file
diff --git a/misc/tapas_download_example_data.m b/misc/tapas_download_example_data.m
index c4c5d99b..f7b79501 100644
--- a/misc/tapas_download_example_data.m
+++ b/misc/tapas_download_example_data.m
@@ -1,10 +1,11 @@
-function [] = tapas_download_example_data(version)
+function [example_dir] = tapas_download_example_data(version)
%% Download example data and install it in tapas/examples/.
%
% Input
% version -- String with the desired release. If empty it defaults
% to the current version.
% Output
+% example_dir - folder containing example data
%
% Examples:
%
@@ -19,6 +20,7 @@
% copyright (C) 2018
%
+import JavaMD5.JavaMD5
% Default to the current version
if nargin < 1
version = tapas_get_current_version();
@@ -50,31 +52,37 @@
'Version is unknonwn')
fclose(fid);
-% Check the md5 hash, for security reasons
-zip_name = 'example.zip';
-websave(zip_name, line{2});
-hash = JavaMD5(zip_name);
-
-if ~strcmp(hash, line{3})
- error('tapas:example_data:invalid_hash', ...
- 'The downloaded file is invalid.');
-end
-
+% create folder
example_dir = fullfile(tapas_head, 'examples');
if ~exist(example_dir, 'dir')
mkdir(example_dir);
end
-new_example = fullfile(example_dir, line{1});
+example_dir = fullfile(example_dir, line{1});
+
+if exist(example_dir, 'dir')
+ error('tapas:example_data:target_exists', 'Directory %s already exists.',example_dir)
+end
+mkdir(example_dir);
+
+try
+ % download
+ zip_name = 'example.zip';
+ websave(zip_name, line{2});
+ % Check the md5 hash
+ hash = JavaMD5(zip_name);
-if ~exist(new_example, 'dir')
- mkdir(new_example);
-else
- error('tapas:example_data:target_exists', 'Target directory exists.')
+ if ~strcmp(hash, line{3})
+ error('tapas:example_data:invalid_hash', ...
+ 'The downloaded file is invalid.');
+ end
+catch matx
+ rmdir(example_dir);
+ rethrow(matx);
end
-unzip(zip_name, new_example);
+unzip(zip_name, example_dir);
delete(zip_name);
end
diff --git a/misc/tapas_init_toolboxes.m b/misc/tapas_init_toolboxes.m
new file mode 100644
index 00000000..e0e20298
--- /dev/null
+++ b/misc/tapas_init_toolboxes.m
@@ -0,0 +1,165 @@
+function tapas_init_toolboxes(toolboxes,tdir,doShowMessages)
+% Function initializing toolboxes
+%
+% IN
+% toolboxes
+% Names of toolboxes to add (including their dependencies).
+% If empty, all toolboxes are added. Use lower case letters.
+% tdir
+% TAPAS directory.
+% doShowMessages
+% Whether to show messages (which toolboxes are added).
+%
+
+% muellmat@ethz.ch
+% copyright (C) 2020
+
+% Init all toolboxes, if none are specified:
+doInitAll = false;
+
+if nargin < 1 || isempty(toolboxes)
+ doInitAll = true;
+ toolboxes = {};
+else
+ toolboxes = lower(toolboxes);
+ if ~iscell(toolboxes)
+ toolboxes = {toolboxes}; % We want to have it as a cell array afterwards.
+ end
+end
+% If TAPAS dir not specified, it should be the parent dir:
+if nargin < 2 || isempty(tdir)
+ f = mfilename('fullpath');
+ [tdir, ~, ~] = fileparts(f);
+ seps = strfind(tdir,filesep);
+ tdir = tdir(1:seps(end)-1);
+end
+% Show messages as default:
+if nargin < 3
+ doShowMessages = true;
+end
+
+% In the infos struct, we have all information about our toolboxes (which ones
+% we have, what other TAPAS toolboxes they depend on and whether they have a
+% init function):
+infos = tapas_init_get_toolbox_infos();
+
+% Strategy: Use fieldnames of struct for list of toolboxes. Have boolean array,
+% whether to add them.
+toolbox_names = fieldnames(infos);
+if doInitAll % That's easy: Just add all.
+ doInit = ones(size(toolbox_names),'logical');
+ toolboxes = toolbox_names;
+else
+ doInit = zeros(size(toolbox_names),'logical');
+ for iTool = 1:numel(toolboxes) % These are to add (input argument)
+ sTool = toolboxes{iTool};
+ if ~ismember(sTool,toolbox_names)
+ warning('I do not know the toolbox %s - skipping it.\n',sTool);
+ continue; % Don't add it, if we don't know how to do that.
+ end
+ doInit(ismember(toolbox_names,sTool)) = true;
+ dependencies = lower(infos.(sTool).dependencies);
+ if ~isempty(dependencies) % TODO: Include dependencies of dependencies etc.
+ doInit(ismember(toolbox_names,dependencies)) = true;
+ end
+ end
+end
+% Now that we know, which toolboxes (including dependencies) we want to add,
+% we can do that.
+for iTool = 1:numel(toolbox_names) % Now we are iterating over all toolboxes.
+ if doInit(iTool)
+ sTool = toolbox_names{iTool};
+ try
+ if doShowMessages
+ % If the name of the toolbox was in the previously specified,
+ % we can add it. Otherwise it was dependent.
+ if ismember(sTool,toolboxes)
+ fprintf(1,'===== Adding toolbox %s =====\n',sTool);
+ else
+ fprintf(1,'===== Adding dependent toolbox %s =====\n',sTool);
+ end
+ end
+ % If no init function is specified, we add the "genpath(init_dir)".
+ % Otherwise we call the init function.
+ if isempty(infos.(sTool).init_function)
+ addpath(genpath(fullfile(tdir,infos.(sTool).init_dir)));
+ else
+ % So that we can call the init function.
+ addpath(fullfile(tdir,infos.(sTool).init_dir));
+ % Call the init function.
+ feval(infos.(sTool).init_function);
+ end
+ catch matx
+ fprintf('Skipping toolbox %s. Initialization failed with error: "%s"\n',sTool,matx.message)
+ end
+ end
+end
+end
+
+
+function infos = tapas_init_get_toolbox_infos()
+ % Function returning with the dependencies and infos regarding the toolboxes
+ %
+ % Each toolbox is represented by a field with its lower-case-name.
+ % The field has three subfields:
+ % init_function [string]
+ % If specified, use that function to initialze the toolbox (and do
+ % not anything else apart from adding init_dir to the path).
+ % If not specified, add init_dir and all subfolders
+ % init_dir [string]
+ % If init function is specified; the directory, where it can be
+ % found (has to be added to MATLABPATH to call the function)
+ % If init function is not specified, the root dir of the toolbox,
+ % which (and all subdirs) will be added.
+ % dependencies. [string]
+ % Names of dependent toolboxes. Needs to be lower case (the field-
+ % name in the struct). At the moment, we cannot check for depen-
+ % dencies of dependencies, so they should be specified as depen-
+ % dencies as well.
+ %
+
+ infos = struct();
+
+ infos.physio.init_dir = strcat('PhysIO',filesep,'code');
+ infos.physio.init_function = 'tapas_physio_init';
+ infos.physio.dependencies = [];
+
+ infos.hgf.init_function = '';
+ infos.hgf.init_dir = 'HGF';
+ infos.hgf.dependencies = [];
+
+ infos.h2gf.init_function = '';
+ infos.h2gf.init_dir = 'h2gf';
+ infos.h2gf.dependencies = {'hgf','tools'};
+
+ infos.huge.init_function = 'tapas_huge_compile';
+ infos.huge.init_dir = 'huge';
+ infos.huge.dependencies = [];
+
+ infos.external.init_function = '';
+ infos.external.init_dir = 'external';
+ infos.external.dependencies = '';
+
+ % The following is just a shortcut for the defaults.
+ infos = tapas_init_default_toolbox_info(infos,'MICP');
+ infos = tapas_init_default_toolbox_info(infos,'mpdcm');
+ infos = tapas_init_default_toolbox_info(infos,'rDCM');
+ infos = tapas_init_default_toolbox_info(infos,'sem');
+ infos = tapas_init_default_toolbox_info(infos,'tools'); % Want to have that?
+ infos = tapas_init_default_toolbox_info(infos,'VBLM');
+ infos = tapas_init_default_toolbox_info(infos, 'ceode');
+
+end
+
+function infos = tapas_init_default_toolbox_info(infos,folderName)
+ % Setting default toolbox info (no init function, no dependencies).
+ fld_name = lower(folderName);
+ if ismember(fld_name,fieldnames(infos))
+ warning('Infos for toolbox %s already there!\n',fld_name);
+ end
+ infos.(fld_name).init_function = '';
+ infos.(fld_name).init_dir = folderName;
+ infos.(fld_name).dependencies = '';
+
+end
+
diff --git a/mpdcm/external/mcmcdiag/ChangeLog b/mpdcm/external/mcmcdiag/ChangeLog
deleted file mode 100644
index 0fd2f835..00000000
--- a/mpdcm/external/mcmcdiag/ChangeLog
+++ /dev/null
@@ -1,119 +0,0 @@
-2014-02-24 Aki Vehtari
-
- * psrf.m: Updated to follow changes in BDA3.
-
- * cpsrf.m: Ditto.
-
-
-2006-02-14 Aki Vehtari
-
- * join.m: Special handling for type and rstate fields.
-
-2005-12-09 Aki Vehtari
-
- * ksstat.m: Fixed a bug.
-
-2004-10-20 Aki Vehtari
-
- * ksstat.m: Rewrote of ks.
-
-2004-01-22 Aki Vehtari
-
- * ipsrf.m: New function: Interval PSRF.
-
- * cipsrf.m: New function: Cumulative interval PSRF.
-
- * psrf.m: Added neff, changed R^2->R, and some cleaning.
-
- * cpsrf.m: Ditto.
-
- * mpsrf.m: Ditto.
-
- * cmpsrf.m: Ditto.
-
-2003-11-05 Aki Vehtari
-
- * kernelp.m: Define normpdf because not everyone has Statistical
- toolbox.
-
-2003-11-04 Aki Vehtari
-
- * geyer_imse.m: Add this because not everyone has Optimization
- toolbox.
-
- * kernel1.m: Define normpdf because not everyone has Statistical
- toolbox.
-
- * kernelp.m: Define gminus so that genops need not be installed .
-
-2003-09-15 Aki Vehtari
-
- * thin.m: rmfield(x,'rstate');
-
-2003-05-14 Aki Vehtari
-
- * Release 1.0: Document updates, bug fixes.
-
-2002-10-15 Aki Vehtari
-
- * geyer_icse.m: New function, Geyer's intial convex sequence
- estimator for autocorrelation time.
-
-2002-08-09 Aki Vehtari
-
- * kernel1.m: Make sure P >= 0.
-
-2001-06-17 Aki Vehtari
-
- * acorrtime.m: maxlag was not passed...
-
-2001-01-25 Aki Vehtari
-
- * ks.m: New function, Kolmogorov-Smirnov test.
-
-2000-05-22 Aki Vehtari
-
- * ndhist.m: Use 'hist' option when calling bar.
-
-2000-04-26 Aki Vehtari
-
- * acorrtime.m: New function.
-
- * acorr.m: Use xcorr for estimating autocorrelations.
-
- * diagg.m: use acorr.m
-
-2000-04-25 Aki Vehtari
-
- * autodens.m: Use lags.
-
- * autog.m: Fixed same things as in diagg.m previosly.
-
-2000-04-19 Aki Vehtari
-
- * diagg.m: Another legend fix.
-
-2000-04-18 Aki Vehtari
-
- * thin.m: General thinnig function from fbmtools.
-
- * diagg.m: Now works with vector
- + check if T is horizontal vector
- + Removed thinning arguments. Use thin.m instead.
-
-2000-03-27 Aki Vehtari
-
- * kernel1.m: Get size of T only once
- and check if T is horizontal vector.
-
-
-1999-11-03 Simo Särkkä
-
- * psrf.m: Added argument nlast and fixed couple of bugs.
-
- * kernel1.m: Removed possiblity to give probabilities as
- an argument.
-
- * qtiles.m: Function now takes two alpha values
- and their meaning has changed.
-
diff --git a/mpdcm/external/mcmcdiag/Contents.m b/mpdcm/external/mcmcdiag/Contents.m
deleted file mode 100644
index 8108853b..00000000
--- a/mpdcm/external/mcmcdiag/Contents.m
+++ /dev/null
@@ -1,46 +0,0 @@
-% MCMC Diagnostics Toolbox for Matlab 6.x
-% Version 1.1 2004-01-23
-% Copyright (C) 1999 Simo Särkkä
-% Copyright (C) 2000-2004 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-%
-% Covergence diagnostics
-% PSRF - Potential Scale Reduction Factor
-% CPSRF - Cumulative Potential Scale Reduction Factor
-% MPSRF - Multivariate Potential Scale Reduction Factor
-% CMPSRF - Cumulative Multivariate Potential Scale Reduction Factor
-% IPSRF - Interval-based Potential Scale Reduction Factor
-% CIPSRF - Cumulative Interval-based Potential Scale Reduction Factor
-% KSSTAT - Kolmogorov-Smirnov goodness-of-fit hypothesis test
-% HAIR - Brooks' hairiness convergence diagnostic
-% CUSUM - Yu-Mykland convergence diagnostic for MCMC
-% SCORE - Calculate score-function convergence diagnostic
-% GBINIT - Initial iterations for Gibbs iteration diagnostic
-% GBITER - Estimate number of additional Gibbs iterations
-%
-% Time series analysis
-% ACORR - Estimate autocorrelation function of time series
-% ACORRTIME - Estimate autocorrelation evolution of time series (simple)
-% GEYER_ICSE - Compute autocorrelation time tau using Geyer's
-% initial convex sequence estimator
-% (requires Optimization toolbox)
-% GEYER_IMSE - Compute autocorrelation time tau using Geyer's
-% initial monotone sequence estimator
-%
-% Kernel density estimation etc.:
-% KERNEL1 - 1D Kernel density estimation of data
-% KERNELS - Kernel density estimation of independent components of data
-% KERNELP - 1D Kernel density estimation, with automatic kernel width
-% NDHIST - Normalized histogram of N-dimensional data
-% HPDI - Estimates the Bayesian HPD intervals
-%
-% Manipulation of MCMC chains
-% THIN - Delete burn-in and thin MCMC-chains
-% JOIN - Join similar structures of arrays to one structure of arrays
-%
-% Misc:
-% CUSTATS - Calculate cumulative statistics of data
-%
diff --git a/mpdcm/external/mcmcdiag/License.txt b/mpdcm/external/mcmcdiag/License.txt
deleted file mode 100644
index 60549be5..00000000
--- a/mpdcm/external/mcmcdiag/License.txt
+++ /dev/null
@@ -1,340 +0,0 @@
- GNU GENERAL PUBLIC LICENSE
- Version 2, June 1991
-
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.
- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-License is intended to guarantee your freedom to share and change free
-software--to make sure the software is free for all its users. This
-General Public License applies to most of the Free Software
-Foundation's software and to any other program whose authors commit to
-using it. (Some other Free Software Foundation software is covered by
-the GNU Library General Public License instead.) You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-this service if you wish), that you receive source code or can get it
-if you want it, that you can change the software or use pieces of it
-in new free programs; and that you know you can do these things.
-
- To protect your rights, we need to make restrictions that forbid
-anyone to deny you these rights or to ask you to surrender the rights.
-These restrictions translate to certain responsibilities for you if you
-distribute copies of the software, or if you modify it.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must give the recipients all the rights that
-you have. You must make sure that they, too, receive or can get the
-source code. And you must show them these terms so they know their
-rights.
-
- We protect your rights with two steps: (1) copyright the software, and
-(2) offer you this license which gives you legal permission to copy,
-distribute and/or modify the software.
-
- Also, for each author's protection and ours, we want to make certain
-that everyone understands that there is no warranty for this free
-software. If the software is modified by someone else and passed on, we
-want its recipients to know that what they have is not the original, so
-that any problems introduced by others will not reflect on the original
-authors' reputations.
-
- Finally, any free program is threatened constantly by software
-patents. We wish to avoid the danger that redistributors of a free
-program will individually obtain patent licenses, in effect making the
-program proprietary. To prevent this, we have made it clear that any
-patent must be licensed for everyone's free use or not licensed at all.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- GNU GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License applies to any program or other work which contains
-a notice placed by the copyright holder saying it may be distributed
-under the terms of this General Public License. The "Program", below,
-refers to any such program or work, and a "work based on the Program"
-means either the Program or any derivative work under copyright law:
-that is to say, a work containing the Program or a portion of it,
-either verbatim or with modifications and/or translated into another
-language. (Hereinafter, translation is included without limitation in
-the term "modification".) Each licensee is addressed as "you".
-
-Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running the Program is not restricted, and the output from the Program
-is covered only if its contents constitute a work based on the
-Program (independent of having been made by running the Program).
-Whether that is true depends on what the Program does.
-
- 1. You may copy and distribute verbatim copies of the Program's
-source code as you receive it, in any medium, provided that you
-conspicuously and appropriately publish on each copy an appropriate
-copyright notice and disclaimer of warranty; keep intact all the
-notices that refer to this License and to the absence of any warranty;
-and give any other recipients of the Program a copy of this License
-along with the Program.
-
-You may charge a fee for the physical act of transferring a copy, and
-you may at your option offer warranty protection in exchange for a fee.
-
- 2. You may modify your copy or copies of the Program or any portion
-of it, thus forming a work based on the Program, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) You must cause the modified files to carry prominent notices
- stating that you changed the files and the date of any change.
-
- b) You must cause any work that you distribute or publish, that in
- whole or in part contains or is derived from the Program or any
- part thereof, to be licensed as a whole at no charge to all third
- parties under the terms of this License.
-
- c) If the modified program normally reads commands interactively
- when run, you must cause it, when started running for such
- interactive use in the most ordinary way, to print or display an
- announcement including an appropriate copyright notice and a
- notice that there is no warranty (or else, saying that you provide
- a warranty) and that users may redistribute the program under
- these conditions, and telling the user how to view a copy of this
- License. (Exception: if the Program itself is interactive but
- does not normally print such an announcement, your work based on
- the Program is not required to print an announcement.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Program,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Program, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Program.
-
-In addition, mere aggregation of another work not based on the Program
-with the Program (or with a work based on the Program) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may copy and distribute the Program (or a work based on it,
-under Section 2) in object code or executable form under the terms of
-Sections 1 and 2 above provided that you also do one of the following:
-
- a) Accompany it with the complete corresponding machine-readable
- source code, which must be distributed under the terms of Sections
- 1 and 2 above on a medium customarily used for software interchange; or,
-
- b) Accompany it with a written offer, valid for at least three
- years, to give any third party, for a charge no more than your
- cost of physically performing source distribution, a complete
- machine-readable copy of the corresponding source code, to be
- distributed under the terms of Sections 1 and 2 above on a medium
- customarily used for software interchange; or,
-
- c) Accompany it with the information you received as to the offer
- to distribute corresponding source code. (This alternative is
- allowed only for noncommercial distribution and only if you
- received the program in object code or executable form with such
- an offer, in accord with Subsection b above.)
-
-The source code for a work means the preferred form of the work for
-making modifications to it. For an executable work, complete source
-code means all the source code for all modules it contains, plus any
-associated interface definition files, plus the scripts used to
-control compilation and installation of the executable. However, as a
-special exception, the source code distributed need not include
-anything that is normally distributed (in either source or binary
-form) with the major components (compiler, kernel, and so on) of the
-operating system on which the executable runs, unless that component
-itself accompanies the executable.
-
-If distribution of executable or object code is made by offering
-access to copy from a designated place, then offering equivalent
-access to copy the source code from the same place counts as
-distribution of the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 4. You may not copy, modify, sublicense, or distribute the Program
-except as expressly provided under this License. Any attempt
-otherwise to copy, modify, sublicense or distribute the Program is
-void, and will automatically terminate your rights under this License.
-However, parties who have received copies, or rights, from you under
-this License will not have their licenses terminated so long as such
-parties remain in full compliance.
-
- 5. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Program or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Program (or any work based on the
-Program), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Program or works based on it.
-
- 6. Each time you redistribute the Program (or any work based on the
-Program), the recipient automatically receives a license from the
-original licensor to copy, distribute or modify the Program subject to
-these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties to
-this License.
-
- 7. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Program at all. For example, if a patent
-license would not permit royalty-free redistribution of the Program by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Program.
-
-If any portion of this section is held invalid or unenforceable under
-any particular circumstance, the balance of the section is intended to
-apply and the section as a whole is intended to apply in other
-circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system, which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 8. If the distribution and/or use of the Program is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Program under this License
-may add an explicit geographical distribution limitation excluding
-those countries, so that distribution is permitted only in or among
-countries not thus excluded. In such case, this License incorporates
-the limitation as if written in the body of this License.
-
- 9. The Free Software Foundation may publish revised and/or new versions
-of the General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Program
-specifies a version number of this License which applies to it and "any
-later version", you have the option of following the terms and conditions
-either of that version or of any later version published by the Free
-Software Foundation. If the Program does not specify a version number of
-this License, you may choose any version ever published by the Free Software
-Foundation.
-
- 10. If you wish to incorporate parts of the Program into other free
-programs whose distribution conditions are different, write to the author
-to ask for permission. For software which is copyrighted by the Free
-Software Foundation, write to the Free Software Foundation; we sometimes
-make exceptions for this. Our decision will be guided by the two goals
-of preserving the free status of all derivatives of our free software and
-of promoting the sharing and reuse of software generally.
-
- NO WARRANTY
-
- 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
-REPAIR OR CORRECTION.
-
- 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-convey the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-
- Copyright (C) 19yy
-
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-
-Also add information on how to contact you by electronic and paper mail.
-
-If the program is interactive, make it output a short notice like this
-when it starts in an interactive mode:
-
- Gnomovision version 69, Copyright (C) 19yy name of author
- Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, the commands you use may
-be called something other than `show w' and `show c'; they could even be
-mouse-clicks or menu items--whatever suits your program.
-
-You should also get your employer (if you work as a programmer) or your
-school, if any, to sign a "copyright disclaimer" for the program, if
-necessary. Here is a sample; alter the names:
-
- Yoyodyne, Inc., hereby disclaims all copyright interest in the program
- `Gnomovision' (which makes passes at compilers) written by James Hacker.
-
- , 1 April 1989
- Ty Coon, President of Vice
-
-This General Public License does not permit incorporating your program into
-proprietary programs. If your program is a subroutine library, you may
-consider it more useful to permit linking proprietary applications with the
-library. If this is what you want to do, use the GNU Library General
-Public License instead of this License.
diff --git a/mpdcm/external/mcmcdiag/Readme.txt b/mpdcm/external/mcmcdiag/Readme.txt
deleted file mode 100644
index 7d4a6681..00000000
--- a/mpdcm/external/mcmcdiag/Readme.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-MCMC Diagnostics Toolbox for Matlab 6.x
-
-Copyright (C) 1999 Simo Särkkä
-Copyright (C) 2000-2004 Aki Vehtari
-Maintainer: Aki Vehtari
-
-In 1999 Simo Särkkä implemented several MCMC diagnostics in Matlab
-at Helsinki University of Technology, Laboratory of Computational
-Engineering . Later Aki Vehtari added a few
-additonal utilities, fixed bugs and improved the documentation.
-
-This software is distributed under the GNU General Public Licence
-(version 2 or later); please refer to the file Licence.txt,
-included with the software, for details.
diff --git a/mpdcm/external/mcmcdiag/acorr.m b/mpdcm/external/mcmcdiag/acorr.m
deleted file mode 100644
index fbec86d4..00000000
--- a/mpdcm/external/mcmcdiag/acorr.m
+++ /dev/null
@@ -1,30 +0,0 @@
-function c = acorr(x,maxlag)
-%ACORR Estimate autocorrelation function of time series
-%
-% C = ACORR(X,MAXLAG) returns normalized autocorrelation
-% sequences for each column of X using
-% C(:,i)=XCORR(X(:,i)-MEAN(X(:,i)),MAXLAG,'coeff'), but returns only
-% lags 1:MAXLAG. Default MAXLAG = M-1;
-%
-% See also
-% XCORR
-
-% Copyright (C) 2000 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-if nargin < 1
- error('Not enough input arguments.');
-end
-if nargin < 2
- maxlag=length(x)-1;
-end
-[m,n]=size(x);
-c=zeros(maxlag,n);
-for i1=1:n
- ct=xcorr(x(:,i1)-mean(x(:,i1)),maxlag,'coeff');
- ct=ct(maxlag+2:end);
- c(:,i1)=ct;
-end
diff --git a/mpdcm/external/mcmcdiag/acorrtime.m b/mpdcm/external/mcmcdiag/acorrtime.m
deleted file mode 100644
index 60692752..00000000
--- a/mpdcm/external/mcmcdiag/acorrtime.m
+++ /dev/null
@@ -1,42 +0,0 @@
-function t = acorrtime(x,maxlag)
-% ACORRTIME Estimate autocorrelation evolution of time series
-%
-% T = ACORRTIME(X,MAXLAG) returns estimate for autocorrelation
-% time defined as MAXLAG
-% t = 1 + 2 sum r(l),
-% l=1
-% where r(l) is the sample autocorrelation at the lag l.
-% Sum is cutted of at a finite value L beyond which the
-% autocorrelation estimate is close to zero, since adding
-% autocorrelations for higher lags will only add in excess noise.
-% Autocorrelation sequence is estimated using r=ACORR(X,MAXLAG).
-%
-% If MAXLAG is not given, maximum autocorrelation time over all possible
-% MAXLAG values is returned. This serves as a pessimistic estimate.
-%
-% See also
-% ACORR
-
-% References:
-% [1] R. Neal, "Probabilistic Inference Using Markov Chain
-% Monte Carlo Methods", Technical Report CRG-TR-93-1,
-% Dept. of Computer Science, University of Toronto, 1993. p.105.
-% [2] R. E. Kass et al., "Markov chain Monte Carlo in practice:
-% A roundtable discussion", American Statistician,
-% 52:93-100, 1998. p. 99.
-% [3] L. Zhu and B. P. Carlin, "Comparing hierarchical models
-% for spatio-temporally misaligned data using DIC
-% criterion. Technical report, Division of Biostatistics,
-% University of Minnesota, 1999. p. 9.
-
-% Copyright (C) 2000-2001 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-if nargin > 1
- t=1+2*sum(acorr(x,maxlag));
-else
- t=1+2*max(cumsum(acorr(x)));
-end
diff --git a/mpdcm/external/mcmcdiag/cipsrf.m b/mpdcm/external/mcmcdiag/cipsrf.m
deleted file mode 100644
index 433f808d..00000000
--- a/mpdcm/external/mcmcdiag/cipsrf.m
+++ /dev/null
@@ -1,52 +0,0 @@
-function R = cipsrf(varargin)
-%CIPSRF Cumulative Interval Potential Scale Reduction Factor
-%
-% [R] = CIPSRF(X,[n0]) or
-% [R] = CIPSRF(x1,x2,x3,...[,n0])
-% returns Cumulative Interval Potential Scale Reduction Factor
-% for collection of MCMC-simulations. Analysis is first based on
-% PSRF-analysis of samples 1 to n0. Then for samples 1 to n0+1
-% and so on.
-%
-% Default value for parameter n0 is |X|/2.
-%
-% See also
-% IPSRF
-
-% Copyright (C) 1999 Simo Särkkä
-% Copyright (C) 2004 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-
-% Handle the input arguments
-if prod(size(varargin{nargin}))==1
- count = nargin-1;
- n0 = varargin{nargin};
-else
- count = nargin;
- n0 = [];
-end
-
-if count<=1
- X = varargin{1};
-else
- X = zeros([size(varargin{1}) count]);
- for i=1:count
- X(:,:,i) = varargin{i};
- end
-end
-if isempty(n0)
- n0 = floor(size(X,1)/2) + 1;
-end
-if n0 < 2
- error('n0 should be at least 2');
-end
-
-[N,D,M]=size(X);
-R = zeros(N-n0+1,D);
-for i=n0:N
- R(i-n0+1,:)=ipsrf(X(1:i,:,:));
-end
diff --git a/mpdcm/external/mcmcdiag/cmpsrf.m b/mpdcm/external/mcmcdiag/cmpsrf.m
deleted file mode 100644
index 72abf894..00000000
--- a/mpdcm/external/mcmcdiag/cmpsrf.m
+++ /dev/null
@@ -1,54 +0,0 @@
-function [R,neff] = cmpsrf(varargin)
-%CMPSRF Cumulative Multivariate Potential Scale Reduction Factor
-%
-% [R,neff] = CMPSRF(X,[n0])
-% [R,neff] = CMPSRF(x1,x2,x3,...[,n0])
-% returns Cumulative Multivariate Potential Scale Reduction
-% Factor for collection of MCMC-simulations. Analysis is first
-% based on MPSRF-analysis of samples 1 to n0. Then for samples
-% 1 to n0+1 and so on.
-%
-% Default value for parameter n0 is |X|/2.
-%
-% See also
-% MPSRF, PSRF, CPSRF
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-% 2004-01-22 Aki.Vehtari@hut.fi Added neff, R^2->R, and cleaning
-
-% Handle the input arguments
-if prod(size(varargin{nargin}))==1
- count = nargin-1;
- n0 = varargin{nargin};
-else
- count = nargin;
- n0 = [];
-end
-
-if count<=1
- X = varargin{1};
-else
- X = zeros([size(varargin{1}) count]);
- for i=1:count
- X(:,:,i) = varargin{i};
- end
-end
-if isempty(n0)
- n0 = floor(size(X,1)/2) + 1;
-end
-if n0 < 2
- error('n0 should be at least 2');
-end
-
-% Calculate the reduction factors
-[m,n]=size(X);
-R = zeros(m-n0+1,n);
-neff = R;
-for i=n0:size(X,1)
- [R(i-n0+1,:),neff(i-n0+1,:)]=mpsrf(X(1:i,:,:));
-end
diff --git a/mpdcm/external/mcmcdiag/cpsrf.m b/mpdcm/external/mcmcdiag/cpsrf.m
deleted file mode 100644
index dce7f290..00000000
--- a/mpdcm/external/mcmcdiag/cpsrf.m
+++ /dev/null
@@ -1,47 +0,0 @@
-function [R,neff,V,W,B] = cpsrf(varargin)
-%CPSRF Cumulative Potential Scale Reduction Factor
-%
-% [R,neff,V,W,B] = CPSRF(X,[n0]) or
-% [R,neff,V,W,B] = CPSRF(x1,x2,x3,...[,n0])
-% returns Cumulative Potential Scale Reduction Factor for
-% collection of MCMC-simulations. Analysis is first based
-% on PSRF-analysis of samples 1 to n0. Then for samples
-% 1 to n0+1 and so on.
-%
-% Default value for parameter n0 is |X|/2.
-%
-% See also
-% PSRF, MPSRF, CMPSRF
-
-% Copyright (C) 1999 Simo Särkkä
-% Copyright (C) 2013 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 3 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-% 2004-01-22 Aki.Vehtari@hut.fi Added neff, R^2->R, and cleaning
-% 2013-10-20 Aki.Vehtari@aalto.fi Updated according to BDA3
-
-% Handle the input arguments
-if nargin>1 && isscalar(varargin{end})
- X=cat(3,varargin{1:end-1});
- n0 = varargin{end};
-else
- X=cat(3,varargin{:});
- n0 = floor(size(X,1)/2) + 1;
-end
-if n0 < 2
- error('n0 should be at least 2');
-end
-
-[N,D,M]=size(X);
-R = zeros(N-n0+1,D);
-neff = R;
-V = R;
-W = R;
-for i=n0:N
- [R(i-n0+1,:),neff(i-n0+1,:),V(i-n0+1,:),W(i-n0+1,:),B(i-n0+1,:)]=...
- psrf(X(1:i,:,:));
-end
-
diff --git a/mpdcm/external/mcmcdiag/custats.m b/mpdcm/external/mcmcdiag/custats.m
deleted file mode 100644
index 0a63badd..00000000
--- a/mpdcm/external/mcmcdiag/custats.m
+++ /dev/null
@@ -1,23 +0,0 @@
-function [CA,CS] = custats(X,n0)
-%CUSTATS Calculate cumulative statistics of data
-%
-% [CA,CS] = custats(X) or [CA,CS] = custats(X,n0)
-% returns cumulative statistics of X. CA is the
-% cumulative average and CS is the cumulative variance.
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-
-if nargin==1
- n0 = 0;
-end
-
-X = X((n0+1):end,:,:);
-X2 = X .* X;
-CA = cumsum(X)./ repmat((1:size(X,1))',[1 size(X,2) size(X,3)]);
-CS = cumsum(X2)./ repmat((1:size(X,1))',[1 size(X,2) size(X,3)]);
-CS = CS - CA.*CA;
diff --git a/mpdcm/external/mcmcdiag/cusum.m b/mpdcm/external/mcmcdiag/cusum.m
deleted file mode 100644
index d386e465..00000000
--- a/mpdcm/external/mcmcdiag/cusum.m
+++ /dev/null
@@ -1,38 +0,0 @@
-function C = cusum(W,n0)
-%CUSUM Yu-Mykland convergence diagnostic for MCMC
-%
-% C = cusum(W,n0) or C = cusum(W) returns
-% cumulative sum of each column of W as:
-%
-% n
-% ___
-% \
-% C(i) = /__( W(i) - S ),
-% i=n0+1
-%
-% where S is "empirical average":
-% n
-% ___
-% \
-% S = 1/T /__ W(i)
-% i=n0+1
-%
-% Default value for "burn-in" variable n0 is 0.
-%
-% See also
-% HAIR
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-if nargin==2
- W = W(n0+1:end,:);
-end
-T = size(W,1);
-S = sum(W) / T;
-C = cumsum(W-repmat(S,size(W,1),1));
-
-
diff --git a/mpdcm/external/mcmcdiag/gbinit.m b/mpdcm/external/mcmcdiag/gbinit.m
deleted file mode 100644
index 5dd848d0..00000000
--- a/mpdcm/external/mcmcdiag/gbinit.m
+++ /dev/null
@@ -1,28 +0,0 @@
-function nmin = gbinit(q,r,s)
-%GBINIT Initial iterations for Gibbs iteration diagnostic
-%
-% nmin = gbinit(q,r,s) returns number of
-% initial iterations needed for estimating how
-% many additional iterations are needed for
-% given precision.
-%
-% The definition of the precisions parameters:
-%
-% "Suppose that U is function of theta, which is the
-% parameter to be estimated. We want to estimate
-% P[U <= u | y] to within +-r with probability s.
-% We will find the approximate number of iterations
-% needed to do this when the correct answer is q."
-%
-% Use q=0.025, r=0.005, s=0.95 if you are unsure.
-%
-% See also
-% GBITER
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-nmin = round(norminv((s+1)/2)^2*q*(1-q)/r^2);
diff --git a/mpdcm/external/mcmcdiag/gbiter.m b/mpdcm/external/mcmcdiag/gbiter.m
deleted file mode 100644
index cb7812db..00000000
--- a/mpdcm/external/mcmcdiag/gbiter.m
+++ /dev/null
@@ -1,162 +0,0 @@
-function [M,N,k] = gbiter(X,q,r,s)
-%GBITER Estimate number of additional Gibbs iterations
-%
-% [M,N,k] = gbiter(X,[q,r,s]) or returns number of
-% additional iterations required for accurate result
-% and of what portion of the samples should be used.
-% The returned values are as follows:
-%
-% M defines how many of the first iterations should be
-% thrown away. N is the number of iterations should be done
-% (after the first M). Only every k'th sample should be used
-%
-% X has the initial >Nmin iterations which are
-% used for estimation. Parameters q, r and s
-% are defined as follows:
-%
-% "Suppose that U is function of theta, which is the
-% parameter to be estimated. We want to estimate
-% P[U <= u | y] to within +-r with probability s.
-% We will find the approximate number of iterations
-% needed to do this when the correct answer is q."
-%
-% Use q=0.025, r=0.005, s=0.95 (defaults) if you are unsure.
-% Thus, it could be reasonable to try different q-values
-% instead of selecting the default 0.025. See Brooks and
-% Roberts (1999) for more detailed discussion.
-%
-% References
-% Brooks, S.P. and Roberts, G.O. (1999) On Quantile Estimation
-% and MCMC Convergence. Biometrika.
-%
-% See also
-% GBINIT
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-
-if nargin < 4
- s = 0.95;
-end
-if nargin < 3
- r = 0.005;
-end
-if nargin < 2
- q = 0.025;
-end
-
-% Estimate q-quontiles u(:) for each variable and
-% create binary sequences Z(:,n).
-% (Method is from "gibbsit"-program.)
-e = 0.001;
-Z = zeros(size(X,1),size(X,2));
-for n=1:size(X,2)
- x = sort(X(:,n));
- order = q * (size(X,1)-1) + 1;
- fract = mod(order,1.0);
- low = max(floor(order),1);
- high = min(low+1, size(X,1));
- u = (1 - fract) * x(low) + fract * x(high);
- Z(:,n) = (X(:,n) <= u);
-end
-
-k1 = zeros(1,size(Z,2));
-alpha = zeros(1,size(Z,2));
-beta = zeros(1,size(Z,2));
-k2 = zeros(1,size(Z,2));
-
-for m=1:size(Z,2)
-
- % Find out when sequence turns from second
- % order Markov to first order
- bic = 1;
- kthin = 0;
- while bic >= 0
- kthin = kthin + 1;
- z = Z(1:kthin:end,m);
-
- % Estimate second order Markov chain
- M = zeros(2,2,2);
- for n=3:size(z,1)
- M(z(n-2)+1, z(n-1)+1, z(n)+1) = ...
- M(z(n-2)+1, z(n-1)+1, z(n)+1) + 1;
- end
-
- % Do g2 test
- count = size(z,1)-2;
- g2 = 0;
- for i=1:2
- for j=1:2
- for k=1:2
- if M(i,j,k) ~= 0
- fitted = sum(M(i,j,:)) * sum(M(:,j,k));
- fitted = fitted / sum(sum(M(:,j,:)));
- g2 = g2 + log( M(i,j,k) / fitted) * M(i,j,k);
- end
- end
- end
- end
- g2 = 2*g2;
- bic = g2 - 2*log(count);
- end
- k2(m) = kthin;
-
- % Estimate first order Markov chain
- M = zeros(2,2);
- for n=2:size(z,1)
- M(z(n-1)+1, z(n)+1) = ...
- M(z(n-1)+1, z(n)+1) + 1;
- end
- alpha(m) = M(1,2) / (M(1,1) + M(1,2));
- beta(m) = M(2,1) / (M(2,1) + M(2,2));
-
- % Find out when sequence turns from first
- % order Markov to independent sequence
- bic = 1;
- kthin = kthin-1;
-
- while bic >= 0
- kthin = kthin + 1;
- z = Z(1:kthin:end,m);
-
- % Estimate first order Markov chain
- M = zeros(2,2);
- for n=2:size(z,1)
- M(z(n-1)+1, z(n)+1) = ...
- M(z(n-1)+1, z(n)+1) + 1;
- end
-
- % Do g2 test
- count = size(z,1)-1;
- g2 = 0;
- for i=1:2
- for j=1:2
- if M(i,j) ~= 0
- fitted = sum(M(i,:)) * sum(M(:,j)) / count;
- g2 = g2 + log( M(i,j) / fitted) * M(i,j);
- end
- end
- end
- g2 = 2*g2;
- bic = g2 - log(count);
- end
-
- k1(m) = kthin;
-end
-
-% Calculate k, N and nburn
-tmp = log((alpha + beta) * e ./ ...
- max(alpha,beta)) ./ log(abs(1 - alpha - beta));
-nburn = round(tmp) .* k2;
-
-phi = norminv((s+1)/2);
-tmp = (2-alpha-beta) .* alpha .* beta ./ (alpha+beta).^3;
-tmp = tmp * (phi/r)^2;
-N = max(round(max(1,tmp)) .* k2);
-k = max(k2);
-M = max(nburn);
-
diff --git a/mpdcm/external/mcmcdiag/geyer_icse.m b/mpdcm/external/mcmcdiag/geyer_icse.m
deleted file mode 100644
index 64aaeff4..00000000
--- a/mpdcm/external/mcmcdiag/geyer_icse.m
+++ /dev/null
@@ -1,74 +0,0 @@
-function [t,t1] = geyer_icse(x,maxlag)
-% GEYER_ICSE - Compute autocorrelation time tau using Geyer's
-% initial convex sequence estimator
-%
-% C = GEYER_ICSE(X) returns autocorrelation time tau.
-% C = GEYER_ICSE(X,MAXLAG) returns autocorrelation time tau with
-% MAXLAG . Default MAXLAG = M-1.
-%
-% References:
-% [1] C. J. Geyer, (1992). "Practical Markov Chain Monte Carlo",
-% Statistical Science, 7(4):473-511
-
-% Copyright (C) 2002 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-% compute autocorrelation
-if nargin > 1
- cc=acorr(x,maxlag);
-else
- cc=acorr(x);
-end
-[n,m]=size(cc);
-
-% acorr returns values starting from lag 1, so add lag 0 here
-cc=[ones(1,m);cc];
-n=n+1;
-
-% now make n even
-if mod(n,2)
- n=n-1;
- cc(end,:)=[];
-end
-
-% loop through variables
-t=zeros(1,m);
-t1=zeros(1,m);
-opt=optimset('LargeScale','off','display','off');
-for i1=1:m
- c=cc(:,i1);
- c=sum(reshape(c,2,n/2),1);
- ci=find(c<0);
- if isempty(ci)
- warning(sprintf('Inital positive could not be found for variable %d, using maxlag value',i1));
- ci=n/2;
- else
- ci=ci(1)-1; % initial positive
- end
- c=[c(1:ci) 0]; % initial positive sequence
- t1(i1)=-1+2*sum(c); % initial positive sequence estimator
- if ci>2
- ca=fmincon(@se,c,[],[],[],[],0*c,c,@sc,opt,c); % monotone convex sequence
- else
- ca=c;
- end
- t(i1)=-1+2*sum(ca); % monotone convex sequence estimator
-end
-
-function e = se(x,xx)
-% SE - Error in monotone convex sequene estimator
-e=sum((xx-x).^2);
-
-function [c,ceq] = sc(x,xx)
-% SE - Constraint in monotone convex sequene estimator
-ceq=0*x;
-c=ceq;
-d=diff(x);
-dd=-diff(d);
-d(d<0)=0;d=d.^2;
-dd(dd<0)=0;dd=dd.^2;
-c(1:end-1)=d;c(2:end)=c(2:end)+d;
-c(1:end-2)=dd;c(2:end-1)=c(2:end-1)+dd;c(3:end)=c(3:end)+dd;
diff --git a/mpdcm/external/mcmcdiag/geyer_imse.m b/mpdcm/external/mcmcdiag/geyer_imse.m
deleted file mode 100644
index 938074e1..00000000
--- a/mpdcm/external/mcmcdiag/geyer_imse.m
+++ /dev/null
@@ -1,67 +0,0 @@
-function [t,t1] = geyer_imse(x,maxlag)
-% GEYER_IMSE - Compute autocorrelation time tau using Geyer's
-% initial monotone sequence estimator
-%
-% C = GEYER_IMSE(X) returns autocorrelation time tau.
-% C = GEYER_IMSE(X,MAXLAG) returns autocorrelation time tau with
-% MAXLAG . Default MAXLAG = M-1.
-%
-% References:
-% [1] C. J. Geyer, (1992). "Practical Markov Chain Monte Carlo",
-% Statistical Science, 7(4):473-511
-%
-% This function is replacment for GEYER_ICSE, when Optimization
-% toolbox is not available
-%
-% See also
-% GEYER_ICSE
-
-% Copyright (C) 2002-2003 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-
-% compute autocorrelation
-if nargin > 1
- cc=acorr(x,maxlag);
-else
- cc=acorr(x);
-end
-[n,m]=size(cc);
-
-% acorr returns values starting from lag 1, so add lag 0 here
-cc=[ones(1,m);cc];
-n=n+1;
-
-% now make n even
-if mod(n,2)
- n=n-1;
- cc(end,:)=[];
-end
-
-% loop through variables
-t=zeros(1,m);
-t1=zeros(1,m);
-for i1=1:m
- c=cc(:,i1);
- c=sum(reshape(c,2,n/2),1);
- ci=find(c<0);
- if isempty(ci)
- warning(sprintf('Inital positive could not be found for variable %d, using maxlag value',i1));
- ci=n/2;
- else
- ci=ci(1)-1; % initial positive
- end
- c=[c(1:ci) 0]; % initial positive sequence
- t1(i1)=-1+2*sum(c); % initial positive sequence estimator
- if ci>2
- for i2=length(c):-1:2
- if c(i2)>c(i2-1)
- c(i2-1)=c(i2); % monotone sequence
- end
- end
- end
- t(i1)=-1+2*sum(c); % monotone sequence estimator
-end
diff --git a/mpdcm/external/mcmcdiag/hair.m b/mpdcm/external/mcmcdiag/hair.m
deleted file mode 100644
index 9ffb75af..00000000
--- a/mpdcm/external/mcmcdiag/hair.m
+++ /dev/null
@@ -1,42 +0,0 @@
-function [DA,DS] = hair(W,n0)
-%HAIR Brooks' hairiness convergence diagnostic
-%
-% [DA,DS] = hair(W,n0) or [DA,DS] = hair(W)
-% returns a measurements of hairiness calculated
-% separately for every column of W
-% n
-% __
-% \
-% DA(t) = 1/t /__ d(i)
-% i=n0+1
-%
-% n
-% __
-% \
-% DS(t) = -DA(t)^2 + 1/t /__ d(i)^2
-% i=n0+1
-%
-% where d(i) is 1 if there is local maximum/
-% minimum in CUSUM C(i) of the column of W,
-% 0 otherwise. DA is the empirical average and
-% DS variance.
-%
-% Default value for "burn-in" variable n0 is 0.
-%
-% See also
-% CUSUM
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-if nargin==2
- C = cusum(W,n0);
-else
- C = cusum(W,0);
-end
-s = sign(C(1:end-1,:) - C(2:end,:));
-d = s(1:end-1,:) .* s(2:end,:) < 0;
-[DA,DS] = custats(d);
diff --git a/mpdcm/external/mcmcdiag/hpdi.m b/mpdcm/external/mcmcdiag/hpdi.m
deleted file mode 100644
index b3d8cfe8..00000000
--- a/mpdcm/external/mcmcdiag/hpdi.m
+++ /dev/null
@@ -1,33 +0,0 @@
-function hpdi = hpdi(x, p)
-% HPDI - Estimates the Bayesian HPD intervals
-%
-% Y = HPDI(X,P) returns a Highest Posterior Density (HPD) interval
-% for each column of X. P must be a scalar. Y is a 2 row matrix
-% where ith column is HPDI for ith column of X.
-
-% References:
-% [1] Chen, M.-H., Shao, Q.-M., and Ibrahim, J. Q., (2000).
-% Monte Carlo Methods in Bayesian Computation. Springer-Verlag.
-
-% Copyright (C) 2001 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-if nargin < 2
- error('Not enough arguments')
-end
-
-m=size(x,2);
-pts=linspace(0.1,99.9-p,20);
-pt1=prctile(x,pts);
-pt2=prctile(x,p+pts);
-cis=abs(pt2-pt1);
-[foo,hpdpi]=min(cis);
-if m==1
- hpdi=[pt1(hpdpi); pt2(hpdpi)];
-else
- hpdpi=sub2ind(size(pt1),hpdpi,1:m);
- hpdi=[pt1(hpdpi); pt2(hpdpi)];
-end
diff --git a/mpdcm/external/mcmcdiag/ipsrf.m b/mpdcm/external/mcmcdiag/ipsrf.m
deleted file mode 100644
index fed81f12..00000000
--- a/mpdcm/external/mcmcdiag/ipsrf.m
+++ /dev/null
@@ -1,74 +0,0 @@
-function [R] = ipsrf(varargin)
-%IPSRF Interavl Potential Scale Reduction Factor
-%
-% [R] = IPSRF(X) or
-% [R] = IPSRF(x1,x2,...,xs)
-% returns "Potential Scale Reduction Factor" (PSRF) for
-% collection of MCMC-simulations. X is a NxDxM matrix
-% which contains M MCMC simulations of length N, each with
-% dimension D. MCMC-simulations can be given as separate
-% arguments x1,x2,... which should have the same length.
-%
-% Returns
-% R PSRF in a row vector of length D
-%
-% The idea of the PSRF is that if R is not near 1 (below 1.1 for
-% example) one may conclude that the tested samples were not from
-% the same distribution (chain might not have been converged
-% yet). Instead of normality assumption, 80% empirical intervals
-% are used to compute R.
-%
-% If only one simulation is given, the factor is calculated
-% between first and last third of the chain. Note that use of
-% only one chain will produce over-optimistic result.
-%
-% Method is from:
-% Brooks, S.P. and Gelman, A. (1998) General methods for
-% monitoring convergence of iterative simulations. Journal of
-% Computational and Graphical Statistics. 7, 434-455.
-%
-% See also
-% CIPSRF, PSRF
-
-% Copyright (C) 1999 Simo Särkkä
-% Copyright (C) 2004 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-% In case of one argument split to two halves (first and last thirds)
-onechain=0;
-if nargin==1
- X = varargin{1};
- if size(X,3)==1
- n = floor(size(X,1)/3);
- x = zeros([n size(X,2) 2]);
- x(:,:,1) = X(1:n,:);
- x(:,:,2) = X((end-n+1):end,:);
- X = x;
- onechain=1;
- end
-elseif nargin==0
- error('Cannot calculate PSRF of scalar');
-else
- X = zeros([size(varargin{1}) nargin]);
- for i=1:nargin
- X(:,:,i) = varargin{i};
- end
-end
-
-[N,D,M]=size(X);
-
-if N<1
- error('Too few samples');
-end
-
-W = zeros(1,D);
-V = zeros(1,D);
-for d=1:D
- x=X(:,d,:);
- W(1,d)=mean(diff(prctile(x,[10 90])));
- V(1,d)=diff(prctile(x(:),[10 90]));
-end
-R = V./W;
diff --git a/mpdcm/external/mcmcdiag/join.m b/mpdcm/external/mcmcdiag/join.m
deleted file mode 100644
index 14cf2200..00000000
--- a/mpdcm/external/mcmcdiag/join.m
+++ /dev/null
@@ -1,63 +0,0 @@
-function r = join(rs, joinall)
-%JOIN Join similar structures of arrays to one structure of arrays
-%
-% JOIN can be used to combine statistics collected from several
-% independent simulations which collect samples to structure
-% of arrays.
-%
-% R = JOIN(RS) returns structure of arrays R, RS is array or
-% cell-array of similar structures of arrays. Arrays of R are
-% contanation of arrays in RS. Arrays having first dimension 1
-% are not concataned, but copied from the first element of RS.
-%
-% R = JOIN(RS, JOINALL) if JOINALL is 1, arrays having first
-% dimension 1 are concataned.
-%
-% See also
-% THIN
-
-% Copyright (C) 2000-2006 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-if nargin <2
- joinall=false;
-end
-
-[m,n]=size(rs);
-
-r=[];
-if (m==1 & n==1)
- r=rs;
-else
- if iscell(rs)
- rs=[rs{:}];
- end
- if isstruct(rs)
- r=rs(1);
- names = fieldnames(r);
- for i1=1:size(names,1)
- switch names{i1}
- case 'rstate'
- continue
- case 'type'
- r.type=rs(1).(names{1});
- continue
- end
- tmp1=getfield(r,names{i1});
- if iscell(tmp1)
- %tmp2=eval(['cat(1,rs(:).' names{i1} ')']);
- tmp2=cat(1,rs(:).(names{i1}));
- for i2=1:length(tmp1(:))
- %eval(['r.' names{i1} '{i2}=cat(1,tmp2{:,i2});']);
- r.(names{i1}){i2}=cat(1,tmp2{:,i2});
- end
- elseif length(tmp1) > 1 || joinall
- %eval(['r.' names{i1} '=cat(1,rs.' names{i1} ');']);
- r.(names{i1})=cat(1,rs.(names{i1}));
- end
- end
- end
-end
diff --git a/mpdcm/external/mcmcdiag/kernel1.m b/mpdcm/external/mcmcdiag/kernel1.m
deleted file mode 100644
index 38a43fe1..00000000
--- a/mpdcm/external/mcmcdiag/kernel1.m
+++ /dev/null
@@ -1,112 +0,0 @@
-function [P,X,sigma] = kernel1(T,sigma,bins,extra)
-%KERNEL1 1D Kernel density estimation of data
-%
-% [P,X,sigma] = kernel1(T,sigma,bins,extra) returns kernel based
-% marginal density estimate of each column of T. Default value
-% for the number of bins is min{50,sqrt(|T|)}. Default value
-% for the standard deviation sigma is max(STD(T)/2). Default
-% value for fraction of empty extra space is 0.2 (that is 20%).
-%
-% If no output arguments is given, functions plots the
-% graphs of each density component. Otherwise smoothed
-% and normalized densities are returned in P and the
-% corresponding coordinates in X.
-%
-% See also
-% NDHIST
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-% 2000-03-27 Aki Vehtari
-% Get size of T only once and check if T is horizontal vector.
-% 2002-08-09 Aki Vehtari
-% Make sure P >= 0
-% 2003-11-04 Aki Vehtari
-% Define normpdf because not everyone has Statistics toolbox
-
- [s1,s2]=size(T);
- if s1==1
- T=T(:);
- [s1,s2]=size(T);
- end
-
- if nargin < 2
- sigma = [];
- end
- if nargin < 3
- bins = [];
- end
- if nargin < 4
- extra = [];
- end
-
- if isempty(sigma)
- sigma = std(T)/2;
- else
- sigma = sigma(:)';
- end
- if isempty(bins)
- bins = max(50,floor(sqrt(s1))+1);
- end
- if isempty(extra)
- extra = 0.2;
- end
- if size(sigma,2)~=s2
- sigma = ones(1,s2)*sigma;
- end
-
- if s2 > 1
- P = zeros(bins,s2);
- X = zeros(bins,s2);
- for i=1:s2
- [P(:,i),X(:,i),sigma(i)] = kernel1(T(:,i),sigma(i),bins,extra);
- end
- else
- mx = max(T);
- mn = min(T);
- delta = extra * (mx - mn);
- mn = mn - delta/2;
- mx = mx + delta/2;
- dx = (mx - mn) / bins;
- [H,X] = ndhist(T,bins,mn,mx);
- H = H(:) / sum(H);
- x = 2*(max(X)-min(X))*(0:(2*size(H,1)-1))'/size(H,1);
- G = normpdf(x,mean(x),sigma);
- G = ifftshift(G(:));
- P = real(ifft(fft(G,size(G,1)) .* fft(H,size(G,1))));
- P = P(1:size(H,1));
- P = P / (sum(P) * dx);
- P(P<0)=0; % Make sure P >= 0
- end
-
- if nargout == 0
- m = 2;
- n = ceil(size(X,2)/m);
- while m*m < n
- m = m + 1;
- n = ceil(size(X,2)/m);
- end
- if s2 > 1
- for i=1:s2
- subplot(m,n,i);
- plot(X(:,i),P(:,i));
- set(gca,'XLim',minmax(X(:,i)'));
- ylim = get(gca,'YLim');
- set(gca,'YLim',[0 ylim(2)]);
- title(['T_' num2str(i)]);
- end
- else
- plot(X,P);
- end
- clear X;
- clear P;
- clear sigma;
- end
-
-function y = normpdf(x,mu,sigma)
-y = -0.5 * ((x-mu)./sigma).^2 -log(sigma) -log(2*pi)/2;
-y=exp(y);
diff --git a/mpdcm/external/mcmcdiag/kernelp.m b/mpdcm/external/mcmcdiag/kernelp.m
deleted file mode 100644
index 19c47dc6..00000000
--- a/mpdcm/external/mcmcdiag/kernelp.m
+++ /dev/null
@@ -1,91 +0,0 @@
-function [p,xx]=kernelp(x,xx)
-%KERNELP 1D Kernel density estimation of data, with automatic kernel width
-%
-% [P,XX]=KERNELP(X,XX) return density estimates P in points XX,
-% given data and optionally ecvaluation points XX. Density
-% estimate is based on simple Gaussian kernel density estimate
-% where all kernels have equal width and this width is selected by
-% optimising plug-in partial predictive density. Works well with
-% reasonable sized X.
-%
-
-% Copyright (C) 2001-2003 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-if nargin < 1
- error('Too few arguments');
-end
-[n,m]=size(x);
-if n>1 && m>1
- error('X must be a vector');
-end
-x=x(:);
-
-if nargin < 2
- n=200;
- xa=min(x);xb=max(x);xd=xb-xa;
- xa=xa-xd/20;xb=xb+xd/20;
- xx=linspace(xa,xb,n);
-else
- [n,m]=size(xx);
- if n>1 && m>1
- error('XX must be a vector');
- end
- xx=xx(:);
-end
-m=length(x)/2;
-stdx=std(x);
-xd=gminus(x(1:m),x(m+1:end)');
-sh=fminbnd(@err,stdx/5,stdx*20,[],xd);
-p=mean(normpdf(gminus(x(1:m),xx),0,sh));
-
-function e=err(s,xd)
-e=-sum(log(sum(normpdf(xd,0,s))));
-
-function y = normpdf(x,mu,sigma)
-y = -0.5 * ((x-mu)./sigma).^2 -log(sigma) -log(2*pi)/2;
-y=exp(y);
-
-function y=gminus(x1,x2)
-%GMINUS Generalized minus.
-y=genop(@minus,x1,x2);
-
-function y=genop(f,x1,x2)
-% GENOP - Generalized operation
-%
-% C = GENOP(F,A,B) Call function F with exapanded matrices Y and X.
-% The dimensions of the two operands are compared and singleton
-% dimensions in one are copied to match the size of the other.
-% Returns a matrix having dimension lengths equal to
-% MAX(SIZE(A),SIZE(B))
-%
-% See also GENOPS
-
-% Copyright (C) 2003 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-s1=size(x1);
-s2=size(x2);
-ls1=numel(s1);
-ls2=numel(s2);
-l=max(ls1,ls2);
-d=ls1-ls2;
-if d<0
- s1(ls1+1:ls1+d)=1;
-elseif d>0
- s2(ls2+1:ls2+d)=1;
-end
-if any(s1>1 & s2>1 & s1~=s2)
- error('Array dimensions are not appropriate.');
-end
-r1=ones(1,l);
-r2=r1;
-r1(s1==1)=s2(s1==1);
-r2(s2==1)=s1(s2==1);
-y=feval(f,repmat(x1,r1),repmat(x2,r2));
diff --git a/mpdcm/external/mcmcdiag/kernels.m b/mpdcm/external/mcmcdiag/kernels.m
deleted file mode 100644
index dd66a592..00000000
--- a/mpdcm/external/mcmcdiag/kernels.m
+++ /dev/null
@@ -1,49 +0,0 @@
-function [P,X,V,D] = kernels(T,varargin)
-%KERNELS Kernel density estimation of principal components of data
-%
-% [P,X,V,D] = kernels(T,[sigma,bins]) returns kernel based
-% marginal density estimate of each pricipal component of T.
-% Default value for the number of bins is min{50,sqrt(|T|)}.
-% Default value for the standard deviation sigma is the STD(T*)/2
-% where T* is the independent component of T.
-%
-% If no output arguments is given, functions plots the
-% graphs of each density component. Otherwise densities are
-% returned in P, the corresponding coordinates in X, directions
-% of principal components in V and variances of the principal
-% components in diagonal of D.
-%
-% Returned pricipal components are the uncorrelated (but not
-% independent) directions of the density. Relationship between
-% T and coordinates in X is X = T*V.
-%
-% See also
-% KERNEL1
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-
-m = mean(T);
-[V,D] = eig(cov(T));
-[C,A,W] = fastica((T-repmat(m,size(T,1),1))','verbose','off',...
- 'displayMode','off');
-V = A';
-V = V ./ repmat(sqrt(sum(V.*V)),size(V,1),1);
-[P,X] = kernel1(C'+repmat(m,size(T,1),1),varargin{:});
-if nargout == 0
- m = 2;
- n = ceil(size(X,2)/m);
- while m*m < n
- m = m + 1;
- n = ceil(size(X,2)/m);
- end
- for i=1:size(X,2)
- subplot(m,n,i);
- plot(X(:,i),P(:,i));
- title(['T^*_' num2str(i) ' = ' '[ ' num2str(V(:,i)',' %.2f') ' ]']);
- end
-end
diff --git a/mpdcm/external/mcmcdiag/ksstat.m b/mpdcm/external/mcmcdiag/ksstat.m
deleted file mode 100644
index 182c9d08..00000000
--- a/mpdcm/external/mcmcdiag/ksstat.m
+++ /dev/null
@@ -1,105 +0,0 @@
-function [snks, snkss] = ksstat(varargin)
-%KSSTAT Kolmogorov-Smirnov statistics
-%
-% ks = KSSTAT(X) or
-% ks = KSSTAT(X1,X2,...,XJ)
-% returns Kolmogorov-Smirnov statistics in form sqrt(N)*K
-% where M is number of samples. X is a NxMxJ matrix which
-% contains J MCMC simulations of length N, each with
-% dimension M. MCMC-simulations can be given as separate
-% arguments X1,X2,... which should have the same length.
-%
-% When comparing more than two simulations, maximum of all the
-% comparisons for each dimension is returned (Brooks et al,
-% 2003).
-%
-% Function returns ks-values in vector KS of length M.
-% An approximation of the 95% quantile for the limiting
-% distribution of sqrt(N)*K with M>=100 is 1.36. ks-values
-% can be compared against this value (Robert & Casella, 2004).
-% In case of comparing several chains, maximum of all the
-% comparisons can be compared to simulated distribution of
-% the maximum of all comparisons obtained using indpendent
-% random random numbers (e.g. using randn(size(X))).
-%
-% If only one simulation is given, the factor is calculated
-% between first and last third of the chain.
-%
-% Note that for this test samples have to be approximately
-% independent. Use thinning or batching for Markov chains.
-%
-% Example:
-% How to estimate the limiting value when comparing several
-% chains stored in (thinned) variable R. Simulate 100 times
-% independent samples. kss contains then 100 simulations of the
-% maximum of all the comparisons for independent samples.
-% Compare actual value for R to 95%-percentile of kss.
-%
-% kss=zeros(1,100);
-% for i1=1:100
-% kss(i1)=ksstat(randn(size(R)));
-% end
-% ks95=prctile(kss,95);
-%
-% References:
-% Robert, C. P, and Casella, G. (2004) Monte Carlo Statistical
-% Methods. Springer. p. 468-470.
-% Brooks, S. P., Giudici, P., and Philippe, A. (2003)
-% "Nonparametric Convergence Assessment for MCMC Model
-% Selection". Journal of Computational & Graphical Statistics,
-% 12(1):1-22.
-%
-% See also
-% PSRF, GEYER_IMSE, THIN
-
-% Copyright (C) 2001-2005 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-% In case of one argument split to two halves (first and last thirds)
-if nargin==1
- X = varargin{1};
- if size(X,3)==1
- n = floor(size(X,1)/3);
- x = zeros([n size(X,2) 2]);
- x(:,:,1) = X(1:n,:);
- x(:,:,2) = X((end-n+1):end,:);
- X = x;
- end
-else
- X = zeros([size(varargin{1}) nargin]);
- for i1=1:nargin
- X(:,:,i1) = varargin{i1};
- end
-end
-
-if (size(X,1)<1)
- error('X has zero rows');
-end
-
-[n1,n2,n3]=size(X);
-%if n1<=100
-% warning('Too few samples for reliable analysis');
-%end
-P = zeros(1,n2);
-snkss=zeros(sum(1:(n3-1)),1);
-for j1=1:size(X,2)
- ii=0;
- for i1=1:n3-1
- for i2=i1+1:n3
- ii=ii+1;
- snkss(ii,j1)=ksc(X(:,j1,i1),X(:,j1,i2));
- end
- end
- snks(j1)=max(snkss(:,j1));
-end
-
-function snks = ksc(x1,x2)
-n=numel(x1);
-edg=sort([x1; x2]);
-c1=histc(x1,edg);
-c2=histc(x2,edg);
-K=max(abs(cumsum(c1)-cumsum(c2))/n);
-snks=sqrt(n)*K;
diff --git a/mpdcm/external/mcmcdiag/mpsrf.m b/mpdcm/external/mcmcdiag/mpsrf.m
deleted file mode 100644
index dd3ad7f7..00000000
--- a/mpdcm/external/mcmcdiag/mpsrf.m
+++ /dev/null
@@ -1,92 +0,0 @@
-function [R,neff,V,W,B] = mpsrf(varargin)
-%MPSRF Multivariate Potential Scale Reduction Factor
-%
-% [R,neff,V,W,B] = MPSRF(X) or
-% [R,neff,V,W,B] = MPSRF(x1,x2,...,xs)
-% returns "Multivariate Potential Scale Reduction Factor"
-% (MPSRF) for collection of MCMC-simulations. X is a NxMxS
-% matrix which contains S MCMC simulations of length M with
-% dimension M. MCMC-simulations can be given as separate
-% arguments x1,x2,... which should have the same length.
-%
-% Returns
-% R PSRF (R=sqrt(V/W)) in row vector of length D
-% neff estimated effective number of samples mean(diag(M*N*V./B))
-% V estimated mixture-of-sequences cvariance
-% W estimated within sequence covariance
-% B estimated between sequence covariance
-%
-% If only one simulation is given, the factor is calculated
-% between first and last third of the chain. Note that use of
-% only one chain will produce over-optimistic result.
-%
-% Method is from:
-% Method is from:
-% Brooks, S.P. and Gelman, A. (1998) General methods for
-% monitoring convergence of iterative simulations. Journal of
-% Computational and Graphical Statistics. 7, 434-455. Note that
-% this function returns square-root definiton of R (see Gelman
-% et al (2003), Bayesian Data Analsyis p. 297).
-%
-% See also
-% CMPSRF, PSRF, CPSRF
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-% 2004-01-22 Aki.Vehtari@hut.fi Added neff, R^2->R, and cleaning
-
-
-% In case of one argument split to two halves
-onechain=0;
-if nargin==1
- X = varargin{1};
- if size(X,3)==1
- n = floor(size(X,1)/3);
- x = zeros([n size(X,2) 2]);
- x(:,:,1) = X(1:n,:);
- x(:,:,2) = X((end-n+1):end,:);
- X = x;
- onechain=1;
- end
-elseif nargin==0
- error('Cannot calculate PSRF of scalar');
-else
- X = zeros([size(varargin{1}) nargin]);
- for i=1:nargin
- X(:,:,i) = varargin{i};
- end
-end
-
-[N,D,M]=size(X);
-
-% Calculate mean W of the covariances
-W = zeros(D);
-for n=1:M
- x = X(:,:,n) - repmat(mean(X(:,:,n)),N,1);
- W = W + x'*x;
-end
-W = W / ((N-1) * M);
-
-% Calculate covariance B (in fact B/n) of the means.
-Bpn = zeros(D);
-m = mean(reshape(mean(X),D,M)');
-for n=1:M
- x = mean(X(:,:,n)) - m;
- Bpn = Bpn + x'*x;
-end
-Bpn = Bpn / (M-1);
-
-% Calculate reduction factor R
-E = sort(abs(eig(W \ Bpn)));
-R = (N-1)/N + E(end) * (M+1)/M;
-V = (N-1) / N * W + (1 + 1/M) * Bpn;
-R = sqrt(R);
-B = Bpn*N;
-neff = mean(min(diag(M*N*V./B),M*N));
-if onechain & (nargout>1)
- neff=neff*3/2;
-end
diff --git a/mpdcm/external/mcmcdiag/ndhist.m b/mpdcm/external/mcmcdiag/ndhist.m
deleted file mode 100644
index 776a4b67..00000000
--- a/mpdcm/external/mcmcdiag/ndhist.m
+++ /dev/null
@@ -1,176 +0,0 @@
-function [H,varargout] = ndhist(X,bins,mins,maxs,cdim)
-%NDHIST Normalized histogram of N-dimensional data
-%
-% [H,P] = ndhist(X,bins,[mins,maxs])
-% [H,x1,x2,...] = ndhist(X,bins,[mins,maxs])
-%
-% Returns normalized N-dimensional histogram H and the bin center
-% coordinates in P or variables x1,x2,... which all are of the
-% same size as H and contain the coordinates in same form as
-% output of ndgrid.
-%
-% Histogram is calculated for the points in argument X..
-% bins is a vector containing number of bins for each dimension.
-% Optional arguments mins and maxx specify the maximum allowed
-% values for each dimension.
-%
-% If no output arguments are given the function plots
-% graph of the histogram.
-%
-% Examples:
-% >> X = gamrnd(3,3,1000,1);
-% >> [H,x] = ndhist(X,50);
-% >> bar(x,H);
-%
-% >> X = mvnrnd([1 1],eye(2),1000) + round(rand(1000,1))*[-2 -2];
-% >> [H,x,y] = ndhist(X,[20 20]);
-% >> surf(x,y,H);
-%
-% See also
-% KERNEL1, HIST, NDGRID
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-
-% Check input and output arguments
-if nargin < 2
- bins = [];
-end
-if nargin < 3
- mins = [];
-end
-if nargin < 4
- maxs = [];
-end
-if nargin < 5
- cdim = 1;
- if size(X,1)==1
- X = X';
- end
-end
-
-if isempty(bins)
- bins = 10;
-end
-if isempty(mins)
- mins = min(X);
-end
-if isempty(maxs)
- maxs = max(X);
-end
-
-tmp = (maxs - mins) ./ bins;
-mins = mins - tmp/2;
-maxs = maxs + tmp/2;
-dx = (maxs - mins) ./ bins;
-
-if (nargout~=0) & (nargout~=1) & (nargout~=2) & (nargout~=size(X,2)+1)
- error('Illegal number of output arguments');
-end
-
-bins = reshape(bins,1,prod(size(bins)));
-if size(bins,2)~=size(X,2)
- if size(bins,2)==1
- bins = bins * ones(1,size(X,2));
- else
- error('Wrong number of bin sizes');
- end
-end
-
-% Create histogram for this dimension and
-% recursively for each sub-dimension.
-[tmpx,tmpi] = sort(X(:,cdim));
-X = X(tmpi,:);
-if cdim < size(X,2)
- H = zeros(bins(cdim),prod(bins(cdim+1:end)));
-else
- H = zeros(bins(cdim),1);
-end
-bnd = mins(cdim)+dx(cdim);
-beg = 1;
-ind = 1;
-k = 1;
-
-while (k <= size(X,1)) & (X(k,cdim) < mins(cdim))
- k = k + 1;
-end
-beg = k;
-while (k <= size(X,1)) & (X(k,cdim) <= maxs(cdim)) & (ind <= size(H,1))
- if X(k,cdim) <= bnd
- k = k + 1;
- else
- if k-beg > 0
- if cdim < size(X,2)
- H(ind,:) = ndhist(X(beg:k-1,:),bins,mins,maxs,cdim+1);
- else
- H(ind) = k-beg;
- end
- end
- bnd = bnd + dx(cdim);
- ind = ind + 1;
- beg = k;
- end
-end
-
-% Handle the last bin
-if (ind <= size(H,1))
- if cdim < size(X,2)
- H(ind,:) = ndhist(X(beg:k-1,:),bins,mins,maxs,cdim+1);
- else
- H(ind) = k-beg;
- end
-end
-
-% Reshape H to linear or multidimensional and
-% determine point positions and set output variables
-if cdim == 1
- if size(X,2)==1
- H = H(:);
- x = (0:(bins-1))'*(maxs-mins)/bins+mins+dx/2;
- varargout{1} = x;
- else
- H = reshape(H,bins);
- k = 0;
- tmp = cell(size(X,2),1);
- for i=1:size(X,2)
- x = (0:(bins(i)-1))'/bins(i)*(maxs(i)-mins(i))+mins(i)+dx(i)/2;
- args = cell(size(X,2),1);
- for j=1:size(X,2)
- args{j} = x;
- end
- tmp{i} = shiftdim(ndgrid(args{:}),k);
- k = mod(k + size(X,2)-1,size(X,2));
- end
- if nargout==2
- P = zeros(size(X,2),prod(bins));
- for i=1:size(X,2)
- P(i,:) = reshape(tmp{i},1,prod(bins));
- end
- varargout{1} = reshape(P,[size(X,2) bins]);
- else
- varargout = tmp;
- end
- end
- c = sum(reshape(H,1,prod(bins)));
- H = H/c;
-else
- H = reshape(H,1,prod(bins(cdim:end)));
-end
-
-% If there were no output arguments, draw a graph
-if nargout==0
- if size(X,2)==1
- bar(varargout{1},H,'hist');
- elseif size(X,2)==2
- surf(varargout{1},varargout{2},H);
- else
- error('Unable to draw >2 dimensional densities');
- end
- clear H;
- clear varargout;
-end
-
diff --git a/mpdcm/external/mcmcdiag/psrf.m b/mpdcm/external/mcmcdiag/psrf.m
deleted file mode 100644
index 2da70417..00000000
--- a/mpdcm/external/mcmcdiag/psrf.m
+++ /dev/null
@@ -1,107 +0,0 @@
-function [R,neff,Vh,W,B,tau,thin] = psrf(varargin)
-%PSRF Potential Scale Reduction Factor
-%
-% [R,NEFF,V,W,B,TAU,THIN] = PSRF(X) or
-% [R,NEFF,V,W,B,TAU,THIN] = PSRF(x1,x2,...,xs)
-% returns "Potential Scale Reduction Factor" (PSRF) for collection
-% of MCMC-simulations. X is a NxDxM matrix which contains M MCMC
-% simulations of length N, each with dimension D. MCMC-simulations
-% can be given as separate arguments x1,x2,... which should have the
-% same length.
-%
-% Returns
-% R PSRF (R=sqrt(V/W)) in row vector of length D
-% neff estimated effective number of samples M*N/(1+2*sum(rhohat))
-% V estimated mixture-of-sequences variances
-% W estimated within sequence variances
-% B estimated between sequence variances
-% TAU estimated autocorrelation time
-% THIN Geyer's initial positive sequence lag (useful for thinning)
-%
-% The idea of the PSRF is that if R is not close to 1 (below 1.1 for
-% example) one may conclude that the tested samples were not from
-% the same distribution (chain might not have been converged yet).
-%
-% Original method:
-% Brooks, S.P. and Gelman, A. (1998) General methods for
-% monitoring convergence of iterative simulations. Journal of
-% Computational and Graphical Statistics. 7, 434-455.
-% Current version:
-% Split chains, return square-root definiton of R, and compute
-% n_eff using variogram estimate and Geyer's initial positive
-% sequence as described in Gelman et al (2013), Bayesian Data
-% Analsyis, 3rd ed, sections 11.4-11.5.
-%
-% See also
-% CPSRF, MPSRF, IPSRF
-
-% Copyright (C) 1999 Simo Särkkä
-% Copyright (C) 2003-2004,2013 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% Licence (version 3 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-% 2004-01-22 Aki.Vehtari@hut.fi Added neff, R^2->R, and cleaning
-% 2013-10-20 Aki.Vehtari@aalto.fi Updated according to BDA3
-
-X=cat(3,varargin{:});
-mid=floor(size(X,1)/2);
-X=cat(3,X(1:mid,:,:),X((end-mid+1):end,:,:));
-
-[N,D,M]=size(X);
-
-if N<=2
- error('Too few samples');
-end
-
-% Calculate means W of the variances
-W = zeros(1,D);
-for mi=1:M
- x = bsxfun(@minus,X(:,:,mi),mean(X(:,:,mi)));
- W = W + sum(x.*x);
-end
-W = W / ((N-1) * M);
-
-% Calculate variances B (in fact B/n) of the means.
-Bpn = zeros(1,D);
-m = mean(reshape(mean(X),D,M)');
-for mi=1:M
- x = mean(X(:,:,mi)) - m;
- Bpn = Bpn + x.*x;
-end
-Bpn = Bpn / (M-1);
-
-% Calculate reduction factors
-B = Bpn*N;
-Vh = (N-1)/N*W + Bpn;
-R = sqrt(Vh./W);
-
-if nargout>1
- % compute autocorrelation
- for t=1:N-1
- % variogram
- Vt(t,:)=sum(sum((X(1:end-t,:,:)-X(1+t:end,:,:)).^2,1),3)/M/(N-t);
- end
- % autocorrelation
- rho=1-bsxfun(@rdivide,Vt./2,Vh);
- % add zero lag autocorrelation
- rho=[ones(1,D);rho];
-
- mid=floor(N/2);
- neff=zeros(1,D);
- for di=1:D
- cp=sum(reshape(rho(1:2*mid,di),2,mid),1);
- ci=find(cp<0,1);
- if isempty(ci)
- warning(sprintf('Inital positive could not be found for variable %d, using maxlag value',di));
- ci=mid;
- else
- ci=ci-1; % last positive
- end
- cp=[cp(1:ci) 0]; % initial positive sequence
- tau(di)=-1+2*sum(cp); % initial positive sequence estimator
- neff(di)=M*N/tau(di); % initial positive sequence estimator for neff
- thin(di)=ci*2;
- end
-end
diff --git a/mpdcm/external/mcmcdiag/score.m b/mpdcm/external/mcmcdiag/score.m
deleted file mode 100644
index e5d38757..00000000
--- a/mpdcm/external/mcmcdiag/score.m
+++ /dev/null
@@ -1,34 +0,0 @@
-function [CA,CS] = score(X,gradF,n0,varargin)
-%SCORE Calculate score-function convergence diagnostic
-%
-% [CA,CS] = score(X,gradF,n0,P1,P2,...)
-% returns convergence diagnostic based on score-functions
-% d ln(p(x))/dx_k that should should approach 0 as n increases.
-%
-% gradF is name of the gradient logarithm function (or
-% its opposite) and X's are the sampled values. n0 is length
-% of "burn-in" and defaults to 0.
-%
-% The idea is from:
-% Anne Philippe and Christian P. Robert (Oct, 1998)
-% Riemann Sums for MCMC Estimation and
-% Convergence Monitoring. EP CNRS
-
-% Copyright (C) 1999 Simo Särkkä
-%
-% This software is distributed under the GNU General Public
-% Licence (version 2 or later); please refer to the file
-% Licence.txt, included with the software, for details.
-
-if (nargin < 3) | isempty(n0)
- n0 = 0;
-end
-X = X((n0+1):end,:,:);
-G = zeros(size(X));
-for i=1:size(X,1)
- for j=1:size(X,3)
- G(i,:,j) = feval(gradF,X(i,:,j),varargin{:});
- end
-end
-
-[CA,CS] = custats(G);
diff --git a/mpdcm/external/mcmcdiag/thin.m b/mpdcm/external/mcmcdiag/thin.m
deleted file mode 100644
index c2eb1374..00000000
--- a/mpdcm/external/mcmcdiag/thin.m
+++ /dev/null
@@ -1,74 +0,0 @@
-function x = thin(x,nburn,nthin,nlast)
-%THIN Delete burn-in and thin in MCMC-chains
-%
-% x = thin(x,nburn,nthin,nlast) returns chain containing only
-% every nthin:th simulation sample starting from sample number
-% nburn+1 and continuing to sample number nlast.
-%
-% See also
-% JOIN
-
-% Copyright (c) 1999 Simo Särkkä
-% Copyright (c) 2000 Aki Vehtari
-%
-% This software is distributed under the GNU General Public
-% License (version 2 or later); please refer to the file
-% License.txt, included with the software, for details.
-
-if nargin < 4
- nlast = [];
-end
-if nargin < 3
- nthin = [];
-end
-if nargin < 2
- nburn = [];
-end
-
-[m,n]=size(x);
-if isfield(x,'rstate')
- x=rmfield(x,'rstate');
-end
-
-if isstruct(x)
- if (m>1 | n>1)
- % array of structures
- for i=1:(m*n)
- x(i) = thin(x(i),nburn,nthin,nlast);
- end
- else
- % single structure
- names = fieldnames(x);
- for i=1:size(names,1)
- value = getfield(x,names{i});
- if length(value) > 1
- x = setfield(x,names{i},thin(value,nburn,nthin,nlast));
- elseif iscell(value)
- x = setfield(x,names{i},{thin(value{1},nburn,nthin,nlast)});
- end
- end
- end
-elseif iscell(x)
- % cell array
- for i=1:(m*n)
- x{i} = thin(x{i},nburn,nthin,nlast);
- end
-elseif m > 1
- % field array
- if isempty(nburn)
- nburn = 0;
- elseif (nburn < 0) | (nburn >= m)
- error('Illegal burn-in value');
- end
- if isempty(nthin)
- nthin = 1;
- elseif (nthin < 1) | (nthin > m)
- error('Illegal thinning value');
- end
- if isempty(nlast)
- nlast = m;
- elseif (nlast < 1) | (nlast > m)
- error('Illegal last index');
- end
- x = x((nburn+1):nthin:nlast,:);
-end
diff --git a/rDCM/CHANGELOG.md b/rDCM/CHANGELOG.md
index 2ee5ac13..7f60d594 100755
--- a/rDCM/CHANGELOG.md
+++ b/rDCM/CHANGELOG.md
@@ -2,6 +2,20 @@
Regression Dynamic Causal Modeling (rDCM) toolbox
+## [1.2] 2020-09-01
+
+### Added
+- Facilitation of using rDCM for resting-state fMRI data. This includes changes to the MATLAB functions as well as information added to the [Manual](docs/Manual.pdf) of the toolbox.
+- Possibility to include multiple confounds rather than a simple constant for baseline shifts.
+- Helper function for specification of whole-brain dynamic causal models (i.e., DCM structure).
+
+### Changed
+- Corrected small bug in the specification of regressors
+
+### Removed
+- none
+
+
## [1.1] 2019-03-03
### Added
diff --git a/rDCM/README.md b/rDCM/README.md
index 0aaa0230..161441cd 100755
--- a/rDCM/README.md
+++ b/rDCM/README.md
@@ -1,31 +1,39 @@
-Regression dynamic causal modeling (rDCM)
-=========================================
+![rDCM Logo](misc/rDCM_Logo.png?raw=true "rDCM Logo")
-> Authors: Stefan Frässle (), Ekaterina I. Lomakina
+rDCM - regression Dynamic Causal Modeling.
+========================================================================
-> Copyright (C) 2016-2018
+This ReadMe file provides the relevant information on the regression dynamic causal modeling (rDCM)
+toolbox.
-> Translational Neuromodeling Unit (TNU)
-> Institute for Biomedical Engineering
+-------------------
+General information
+-------------------
-> University of Zurich & ETH Zurich
+- Authors: Stefan Frässle (), Ekaterina I. Lomakina
+- Copyright (C) 2016-2020
+- Translational Neuromodeling Unit (TNU)
+- Institute for Biomedical Engineering
+- University of Zurich & ETH Zurich
+
+--------
Download
--------
+--------
- Please download the latest stable versions of the rDCM Toolbox on GitHub as part of the
[TAPAS software releases of the TNU](https://github.com/translationalneuromodeling/tapas/releases).
- The latest bugfixes can be found in the [GitHub Issue Forum](https://github.com/translationalneuromodeling/tapas/issues) or by request to the authors.
- Changes between all versions will be documented in the
- [CHANGELOG](https://tnurepository.ethz.ch/sfraessle/rDCM/blob/master/CHANGELOG.md).
-
+ [CHANGELOG](CHANGELOG.md).
+-------
Purpose
-------
@@ -34,12 +42,13 @@ of DCM for fMRI that enables extremely efficient inference on effective (i.e.,
directed) connectivity among brain regions. Due to its
computational efficiency, inversion of large network models becomes feasible.
-The accompanying technical papers about the toolbox concept and methodology
-can be found in [Frässle et al., 2017](https://www.sciencedirect.com/science/article/pii/S105381191730201X?via%3Dihub)
+For the accompanying technical papers, detailing the methodology presented in this toolbox,
+please see [Frässle et al., 2017](https://www.sciencedirect.com/science/article/pii/S105381191730201X?via%3Dihub)
and [Frässle et al., 2018](https://www.sciencedirect.com/science/article/pii/S1053811918304762?via%3Dihub).
+------------
Installation
------------
@@ -51,6 +60,7 @@ Installation
+---------------
Important Notes
---------------
@@ -64,6 +74,7 @@ detailed explanations.
+---------------
Contact/Support
---------------
@@ -78,15 +89,18 @@ but just some general pointers and templates. Before you contact us, please try
+----------
References
----------
### Main Toolbox References ###
1. Frässle, S., Lomakina, E.I., Razi, A., Friston, K.J., Buhmann, J.M., Stephan, K.E., 2017. Regression DCM for fMRI. NeuroImage 155, 406–421. doi:10.1016/j.neuroimage.2017.02.090
2. Frässle, S., Lomakina, E.I., Kasper, L., Manjaly Z.M., Leff, A., Pruessmann, K.P., Buhmann, J.M., Stephan, K.E., 2018. A generative model of whole-brain effective connectivity. NeuroImage 179, 505-529. doi:10.1016/j.neuroimage.2018.05.058
+3. Frässle, S., Harrison, S.J., Heinzle, J., Clementz, B.A., Tamminga, C.A., Sweeney, J.A., Gershon, E.S., Keshavan, M.S., Pearlson, G.D., Powers, A., Stephan, K.E., 2020. Regression dynamic causal modeling for resting-state fMRI. bioRxiv. doi:10.1101/2020.08.12.247536
+---------------
Copying/License
---------------
@@ -106,8 +120,9 @@ along with this program (see the file [LICENSE](LICENSE)). If not, see
+--------------
Acknowledgment
----------------
+--------------
We would like to highlight and acknowledge that the rDCM toolbox uses some
functions that were publised as part of the Statistical Parameteric Mapping
diff --git a/rDCM/code/tapas_rdcm_compute_signals.m b/rDCM/code/tapas_rdcm_compute_signals.m
index 4acc3739..d663e728 100755
--- a/rDCM/code/tapas_rdcm_compute_signals.m
+++ b/rDCM/code/tapas_rdcm_compute_signals.m
@@ -16,7 +16,7 @@
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
@@ -58,13 +58,10 @@
% store true or measured temporal derivative (in frequency domain)
yd_source_fft = output.temp.yd_source_fft;
-yd_source_fft(~isfinite(yd_source_fft)) = 0;
+yd_source_fft(~isfinite(yd_source_fft)) = 0;
output.signal.yd_source_fft = yd_source_fft(:);
-% adding the constant baseline
-DCM.U.u(:,end+1) = ones(size(DCM.U.u,1),1);
-
% get rDCM parameters
DCM.Tp = output.Ep;
@@ -73,21 +70,30 @@
DCM.Tp.baseline = zeros(size(DCM.Tp.C,1),1);
end
-% include the baseline
-DCM.Tp.C = [DCM.Tp.C, DCM.Tp.baseline];
-DCM.Tp.B(:,:,end+1) = DCM.Tp.B(:,:,1);
-DCM.Y.dt = DCM.U.dt;
+% increase sampling rate
+r_dt = DCM.Y.dt/DCM.U.dt;
+DCM.Y.dt = DCM.U.dt;
% posterior probability (for sparse rDCM)
if ( isfield(output,'Ip') )
DCM.Tp.A = DCM.Tp.A .* output.Ip.A;
- DCM.Tp.C = DCM.Tp.C .* [output.Ip.C, ones(size(DCM.Tp.baseline))];
+ DCM.Tp.C = DCM.Tp.C .* output.Ip.C;
end
% generate predicted signal (tapas_rdcm_generate)
DCM_rDCM = tapas_rdcm_generate(DCM, options, Inf);
-output.signal.y_pred_rdcm = DCM_rDCM.Y.y(:);
+
+% add the confounds to predicted time series
+for t = 1:size(DCM.Y.y,1)
+ for r = 1:size(DCM.Y.y,2)
+ DCM_rDCM.Y.y(t,r) = DCM_rDCM.Y.y(t,r) + DCM_rDCM.Tp.baseline(r,:) * DCM_rDCM.U.X0((1+r_dt*(t-1)),:)';
+ end
+end
+
+% turn into vector
+output.signal.y_pred_rdcm = DCM_rDCM.Y.y(:) ;
+
% store predicted temporal derivative (in frequency domain)
yd_pred_rdcm_fft = output.temp.yd_pred_rdcm_fft;
diff --git a/rDCM/code/tapas_rdcm_compute_statistics.m b/rDCM/code/tapas_rdcm_compute_statistics.m
index ea39bef3..70096db5 100755
--- a/rDCM/code/tapas_rdcm_compute_statistics.m
+++ b/rDCM/code/tapas_rdcm_compute_statistics.m
@@ -16,7 +16,7 @@
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
diff --git a/rDCM/code/tapas_rdcm_create_regressors.m b/rDCM/code/tapas_rdcm_create_regressors.m
index 40fb7af9..97e541c9 100755
--- a/rDCM/code/tapas_rdcm_create_regressors.m
+++ b/rDCM/code/tapas_rdcm_create_regressors.m
@@ -19,7 +19,7 @@
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
@@ -36,9 +36,6 @@
%% preparations
-% adding a constant baseline
-DCM.U.u(:,end+1) = ones(size(DCM.U.u,1),1);
-
% circular shift of the stimulus input function
temp = circshift(DCM.U.u, options.u_shift);
DCM.U.u = temp;
@@ -68,6 +65,25 @@
% convolution of stimulus input and hemodynamic response function
u = ifft(fft(u).* repmat(h_fft, 1, nu));
+
+% if empty, set constant confound (task) or no confound (rest)
+if ( ~isfield(DCM.U,'X0') )
+
+ % no inputs to filter for resting-state state
+ if ( ~strcmp(DCM.U.name{1},'null') )
+ DCM.U.X0 = ones(size(DCM.U.u,1),1);
+ options.filtu = 1;
+ else
+ DCM.U.X0 = zeros(size(DCM.U.u,1),0);
+ options.filtu = 0;
+ end
+
+end
+
+% add confounds (e.g, constant, linear trend, sinusoids)
+u = [u, DCM.U.X0];
+
+
% interpolation (upsampling) of BOLD data (or not)
if options.padding
y_fft(round(Ny / 2) + 1, : ) = y_fft(round(Ny / 2) + 1, : ) / 2;
@@ -77,7 +93,7 @@
else
if r_dt > 1
u = u(1 : r_dt : end, : );
- h_fft = h_fft(1 : r_dt : end, : );
+ h_fft = fft(options.h(1 : r_dt : end, : ));
end
u_fft = fft(u);
end
@@ -99,11 +115,11 @@
yd_fft(~idx) = NaN;
% bilinear term (not supported in present version)
-yu_fft = zeros(Ny, nr * nu);
+yu_fft = zeros(Ny, nr * (nu+size(DCM.U.X0,2)));
if isfield(options, 'bilinear') && options.bilinear
y_unconv = ifft(y_fft./ repmat(h_fft_tr, 1, nr));
for i = 1 : nr
- for j = 1 : nu
+ for j = 1 : (nu+size(DCM.U.X0,2))
yu_fft( : , (j - 1) * nr + i) = fft(y_unconv( : , i).* u( : , j)).* h_fft;
end
end
@@ -132,9 +148,6 @@
P = [];
-% remove the additional regressor
-DCM.U.u = DCM.U.u(:,1:end-1);
-
% define output arguments
args.P = P;
args.r_dt = r_dt;
diff --git a/rDCM/code/tapas_rdcm_empty_par.m b/rDCM/code/tapas_rdcm_empty_par.m
index 3720d382..cc927d79 100755
--- a/rDCM/code/tapas_rdcm_empty_par.m
+++ b/rDCM/code/tapas_rdcm_empty_par.m
@@ -14,7 +14,7 @@
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
diff --git a/rDCM/code/tapas_rdcm_ep2par.m b/rDCM/code/tapas_rdcm_ep2par.m
index 6233f060..6c8e79ea 100755
--- a/rDCM/code/tapas_rdcm_ep2par.m
+++ b/rDCM/code/tapas_rdcm_ep2par.m
@@ -14,7 +14,7 @@
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
diff --git a/rDCM/code/tapas_rdcm_estimate.m b/rDCM/code/tapas_rdcm_estimate.m
index 0893767c..512d2023 100755
--- a/rDCM/code/tapas_rdcm_estimate.m
+++ b/rDCM/code/tapas_rdcm_estimate.m
@@ -30,7 +30,7 @@
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
@@ -68,7 +68,7 @@
% check for endogenous DCMs, with no exogenous driving effects
-if ( ~isfield(DCM,'c') || isempty(DCM.c) || ~isfield(DCM,'U') || isempty(DCM.U.u) )
+if ( ~isfield(DCM,'c') || isempty(DCM.c) || ~isfield(DCM,'U') || isempty(DCM.U.u) || strcmp(DCM.U.name{1},'null') )
% specify empty driving input
DCM.U.u = zeros(size(DCM.Y.y,1)*16, 1);
@@ -80,9 +80,6 @@
DCM.c = zeros(DCM.n, size(DCM.U.u,2));
DCM.d = zeros(DCM.n, DCM.n, 0);
- % no inputs - don't filter frequencies
- options.filter_str = 0;
-
end
@@ -182,6 +179,6 @@
% store the random number seed and the version number
output.rngSeed = rngSeed;
-output.ver = '2018_v01';
+output.ver = '2020_v01.2';
end
diff --git a/rDCM/code/tapas_rdcm_filter.m b/rDCM/code/tapas_rdcm_filter.m
index 936800b2..1dd45142 100755
--- a/rDCM/code/tapas_rdcm_filter.m
+++ b/rDCM/code/tapas_rdcm_filter.m
@@ -20,7 +20,7 @@
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
@@ -46,7 +46,11 @@
h_idx = abs(h_fft) > prec;
% freq which are non-zero due to the input structure
-u_idx = sum(abs(u_fft),2) > prec;
+if ( options.filtu == 1 )
+ u_idx = sum(abs(u_fft),2) > prec;
+else
+ u_idx = ones(size(u_fft,1),1);
+end
% padding detection
if ( N ~= Ny )
@@ -84,7 +88,13 @@
%% high-pass filter
% specify the frequency
-freq = round(7*N/16);
+if ( options.filtu == 1 )
+ hpf = 16;
+ freq = round(7*N/(hpf));
+else
+ hpf = max(16 + (thr-1)*4,16);
+ freq = round(7*N/(hpf));
+end
% high-pass filtering
idx_freq = [ones(1+freq, nr); zeros(N - 2*freq - 1, nr); ones(freq, nr)];
diff --git a/rDCM/code/tapas_rdcm_generate.m b/rDCM/code/tapas_rdcm_generate.m
index 1fbc83c2..ded09642 100755
--- a/rDCM/code/tapas_rdcm_generate.m
+++ b/rDCM/code/tapas_rdcm_generate.m
@@ -17,7 +17,7 @@
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
diff --git a/rDCM/code/tapas_rdcm_get_convolution_bm.m b/rDCM/code/tapas_rdcm_get_convolution_bm.m
index c64606d7..46641694 100755
--- a/rDCM/code/tapas_rdcm_get_convolution_bm.m
+++ b/rDCM/code/tapas_rdcm_get_convolution_bm.m
@@ -15,7 +15,7 @@
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
diff --git a/rDCM/code/tapas_rdcm_get_prior.m b/rDCM/code/tapas_rdcm_get_prior.m
index ff1147a7..0e6c2fc5 100755
--- a/rDCM/code/tapas_rdcm_get_prior.m
+++ b/rDCM/code/tapas_rdcm_get_prior.m
@@ -18,7 +18,7 @@
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
diff --git a/rDCM/code/tapas_rdcm_get_prior_all.m b/rDCM/code/tapas_rdcm_get_prior_all.m
index 57b9dd20..781998b2 100755
--- a/rDCM/code/tapas_rdcm_get_prior_all.m
+++ b/rDCM/code/tapas_rdcm_get_prior_all.m
@@ -19,7 +19,7 @@
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
diff --git a/rDCM/code/tapas_rdcm_model_specification.m b/rDCM/code/tapas_rdcm_model_specification.m
new file mode 100644
index 00000000..5dd71ffd
--- /dev/null
+++ b/rDCM/code/tapas_rdcm_model_specification.m
@@ -0,0 +1,190 @@
+function [ DCM ] = tapas_rdcm_model_specification(Y, U, args)
+% [ DCM ] = tapas_rdcm_model_specification(Y, U, args)
+%
+% Utilizes data and driving inputs to specify a whole-brain dynamic causal
+% modeling (DCM) structure that can be utilized for inference with the
+% regression DCM (rDCM) toolbox.
+%
+% Input:
+% Y - data structure
+% Y.y - data [NxR]
+% N = number of datapoints
+% R = number of regions
+% Y.dt - repetition time [s]
+% Y.name - region names (optional)
+% default: region_1, ..., region_R
+%
+% U - input structure
+% U.u - inputs [(16*N)xU] (if inputs are specified with dimension NxU, the function
+% will adapt inputs to match the correct microtime resolution)
+% U.name - input names (optional)
+% default: input_1, ..., input_U
+%
+% args - arguments
+%
+% Output:
+% DCM - DCM structure
+%
+% Note: Some fields are not (yet) used by the rDCM toolbox but are there
+% for consistency with the original DCM framework (SPM) and/or because they
+% might represent features that will be added in future releases.
+%
+
+% ----------------------------------------------------------------------
+%
+% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
+%
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
+% Institute for Biomedical Engineering
+% University of Zurich & ETH Zurich
+%
+% This file is part of the TAPAS rDCM Toolbox, which is released under the
+% terms of the GNU General Public License (GPL), version 3.0 or later. You
+% can redistribute and/or modify the code under the terms of the GPL. For
+% further see COPYING or .
+%
+% Please note that this toolbox is in an early stage of development. Changes
+% are likely to occur in future releases.
+%
+% ----------------------------------------------------------------------
+
+
+% check if data and inputs are defined correctly
+if ( ~isfield(Y,'y') || (~isempty(U) && ~isfield(U,'u')) )
+ fprintf('\nERROR: Data (y) and/or inputs (u) not correctly specified! \n')
+ fprintf('Please double-check... \n')
+ DCM = [];
+ return;
+end
+
+
+% specify connectivity matrices (just for order in structure)
+DCM.a = [];
+DCM.b = [];
+DCM.c = [];
+DCM.d = [];
+
+
+% specify data
+DCM.Y.y = Y.y;
+DCM.Y.dt = Y.dt;
+
+% specify region names
+if ( isfield(Y,'name') && iscell(Y.name) )
+ DCM.Y.name = Y.name;
+else
+ for Nr_region = 1:size(Y.y,2)
+ DCM.Y.name{Nr_region} = ['region_' num2str(Nr_region)];
+ end
+end
+
+
+% specification of inputs
+if ( ~isempty(U) )
+
+ % check for dimensionality of inputs
+ if ( size(U.u,1) == size(DCM.Y.y,1)*16 )
+ u_temp = U.u;
+ elseif ( size(U.u,1) == size(DCM.Y.y,1) )
+ u_temp = zeros(size(U.u,1)*16,size(U.u,2));
+ for Nr_input = 1:size(U.u,2)
+ uu = U.u(:,Nr_input)';
+ uu = repmat(uu,16,1);
+ u_temp(:,Nr_input) = uu(:);
+ end
+ else
+ fprintf('\nERROR: Dimensionality of data (y) and inputs (u) does not match! \n')
+ fprintf('Please double-check... \n')
+ DCM = [];
+ return;
+ end
+
+ % specify inputs
+ DCM.U.u = u_temp;
+
+ % sampling rate of inputs
+ DCM.U.dt = DCM.Y.dt/16;
+
+ % specify input names
+ if ( isfield(U,'name') && iscell(U.name) )
+ DCM.U.name = U.name;
+ else
+ for Nr_input = 1:size(U.u,2)
+ DCM.U.name{Nr_input} = ['input_' num2str(Nr_input)];
+ end
+ end
+
+else
+
+ % make user aware that empty input argument is interpreted as
+ % resting-state fMRI data. For this case, no field U is defined as
+ % this will be handled automatically by "tapas_rdcm_estimate.m"
+ fprintf('\nNOTE: No inputs specified! Assuming resting-state model... \n')
+
+end
+
+
+% specify number of datapoints (per regions)
+DCM.v = size(DCM.Y.y,1);
+
+% specify number of regions
+DCM.n = size(DCM.Y.y,2);
+
+
+% task based or resting state
+if ( ~isempty(U) )
+
+ % specify connectivity matrices (default: full connectivity and input)
+ DCM.a = ones(size(Y.y,2));
+ DCM.b = zeros(size(Y.y,2),size(Y.y,2),size(U.u,2));
+ DCM.c = ones(size(Y.y,2),size(U.u,2));
+ DCM.d = zeros(size(Y.y,2),size(Y.y,2),0);
+
+
+ % overwrite default connectivity matrices
+ if ( ~isempty(args) )
+
+ % overwrite A-matrix
+ if ( isfield(args,'a') )
+ DCM.a = args.a;
+ end
+
+ % overwrite C-matrix
+ if ( isfield(args,'c') )
+ DCM.c = args.c;
+ end
+ end
+
+else
+
+ % specify connectivity matrices; sets dummy B, C, and D matrices as
+ % these will be handled automatically by "tapas_rdcm_estimate.m"
+ DCM.a = ones(size(Y.y,2));
+ DCM.b = zeros(size(Y.y,2),size(Y.y,2),0);
+ DCM.c = zeros(size(Y.y,2),0);
+ DCM.d = zeros(size(Y.y,2),size(Y.y,2),0);
+
+
+ % overwrite default connectivity matrices
+ if ( ~isempty(args) )
+
+ % overwrite A-matrix
+ if ( isfield(args,'a') )
+ DCM.a = args.a;
+ end
+ end
+
+end
+
+
+% specify delays (not used so far | might be added later)
+DCM.delays = (DCM.Y.dt/2) * ones(DCM.v,1);
+
+% specify options (not used so far | might be added later)
+DCM.options.nonlinear = 0;
+DCM.options.two_state = 0;
+DCM.options.stochastic = 0;
+DCM.options.centre = 0;
+DCM.options.endogenous = 0;
+
+end
diff --git a/rDCM/code/tapas_rdcm_plot_fft.m b/rDCM/code/tapas_rdcm_plot_fft.m
index bc538759..e4848363 100755
--- a/rDCM/code/tapas_rdcm_plot_fft.m
+++ b/rDCM/code/tapas_rdcm_plot_fft.m
@@ -14,7 +14,7 @@ function tapas_rdcm_plot_fft(y, region_id)
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
diff --git a/rDCM/code/tapas_rdcm_plot_pred.m b/rDCM/code/tapas_rdcm_plot_pred.m
index 0de60591..7ad9fdcc 100755
--- a/rDCM/code/tapas_rdcm_plot_pred.m
+++ b/rDCM/code/tapas_rdcm_plot_pred.m
@@ -19,7 +19,7 @@ function tapas_rdcm_plot_pred(Ep, Y, X, region_id)
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
diff --git a/rDCM/code/tapas_rdcm_reduce_zeros.m b/rDCM/code/tapas_rdcm_reduce_zeros.m
index 963fa967..21db5ea0 100755
--- a/rDCM/code/tapas_rdcm_reduce_zeros.m
+++ b/rDCM/code/tapas_rdcm_reduce_zeros.m
@@ -16,7 +16,7 @@
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
diff --git a/rDCM/code/tapas_rdcm_ridge.m b/rDCM/code/tapas_rdcm_ridge.m
index fb849467..c82ef93c 100755
--- a/rDCM/code/tapas_rdcm_ridge.m
+++ b/rDCM/code/tapas_rdcm_ridge.m
@@ -24,7 +24,7 @@
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
@@ -42,9 +42,12 @@
% precision limit
pr = 10^(-5);
-% add a constant baseline regressor
-DCM.b(:,:,end+1) = DCM.b(:,:,1);
-DCM.c(:,end+1) = ones(1,size(DCM.c,1));
+% add confound regressor dimensions
+Nc = size(DCM.U.X0,2);
+for nc = 1:Nc
+ DCM.b(:,:,end+1) = DCM.b(:,:,1);
+ DCM.c(:,end+1) = ones(1,size(DCM.c,1));
+end
% get the number of regions and inputs
[nr, nu] = size(DCM.c);
diff --git a/rDCM/code/tapas_rdcm_set_options.m b/rDCM/code/tapas_rdcm_set_options.m
index d91a3ce5..c15cd0ae 100755
--- a/rDCM/code/tapas_rdcm_set_options.m
+++ b/rDCM/code/tapas_rdcm_set_options.m
@@ -18,7 +18,7 @@
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
diff --git a/rDCM/code/tapas_rdcm_sparse.m b/rDCM/code/tapas_rdcm_sparse.m
index cf0cc592..477c973d 100755
--- a/rDCM/code/tapas_rdcm_sparse.m
+++ b/rDCM/code/tapas_rdcm_sparse.m
@@ -26,7 +26,7 @@
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
@@ -47,13 +47,16 @@
% precision limit
pr = 10^(-5);
-% add a constant baseline regressor
-DCM.b(:,:,end+1) = DCM.b(:,:,1);
-DCM.c(:,end+1) = ones(size(DCM.c,1),1);
+% add confound regressor dimensions
+Nc = size(DCM.U.X0,2);
+for nc = 1:Nc
+ DCM.b(:,:,end+1) = DCM.b(:,:,1);
+ DCM.c(:,end+1) = ones(1,size(DCM.c,1));
+end
-% no baseline regressor for simulations
+% no confound regressors for simulations
if ( strcmp(args.type,'s') )
- DCM.c(:,end) = 0;
+ DCM.c(:,end-Nc+1:end) = 0;
end
% get the priors
diff --git a/rDCM/code/tapas_rdcm_store_parameters.m b/rDCM/code/tapas_rdcm_store_parameters.m
index 239b98c3..e43df5db 100755
--- a/rDCM/code/tapas_rdcm_store_parameters.m
+++ b/rDCM/code/tapas_rdcm_store_parameters.m
@@ -23,7 +23,7 @@
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
@@ -38,9 +38,10 @@
% ----------------------------------------------------------------------
-% remove baseline regressor
-DCM.b = DCM.b(:,:,1:end-1);
-DCM.c = DCM.c(:,1:end-1);
+% remove confound regressors
+Nc = size(DCM.U.X0,2);
+DCM.b = DCM.b(:,:,1:end-Nc);
+DCM.c = DCM.c(:,1:end-Nc);
% get number of regions and inputs
[nr, nu] = size(DCM.c);
@@ -60,13 +61,12 @@
output.Ep = tapas_rdcm_empty_par(DCM);
output.Ep.A = mN(1:nr,1:nr);
output.Ep.B = reshape(mN(1:nr,nr+1:nr+nr*nu),[nr nr nu]);
-output.Ep.C = mN(1:nr,end-nu:end-1);
-output.Ep.baseline = mN(1:nr,end);
+output.Ep.C = mN(1:nr,end-Nc-nu+1:end-Nc);
+output.Ep.baseline = mN(1:nr,end-Nc+1:end);
% modify driving inputs
if ( strcmp(args.type,'r') )
output.Ep.C = output.Ep.C*16;
- output.Ep.baseline = output.Ep.baseline*16;
end
@@ -156,4 +156,4 @@
output.logF_term.log_q_z = sum(logF_term.log_q_z);
end
-end
+end
\ No newline at end of file
diff --git a/rDCM/code/tapas_rdcm_subsample.m b/rDCM/code/tapas_rdcm_subsample.m
index e96c5088..c4954363 100755
--- a/rDCM/code/tapas_rdcm_subsample.m
+++ b/rDCM/code/tapas_rdcm_subsample.m
@@ -15,7 +15,7 @@
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
diff --git a/rDCM/code/tapas_rdcm_tutorial.m b/rDCM/code/tapas_rdcm_tutorial.m
index b2c25ea4..b4763aa0 100755
--- a/rDCM/code/tapas_rdcm_tutorial.m
+++ b/rDCM/code/tapas_rdcm_tutorial.m
@@ -16,7 +16,7 @@ function tapas_rdcm_tutorial()
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
diff --git a/rDCM/code/tapas_rdcm_visualize.m b/rDCM/code/tapas_rdcm_visualize.m
index a0f8be1b..ca37dac9 100755
--- a/rDCM/code/tapas_rdcm_visualize.m
+++ b/rDCM/code/tapas_rdcm_visualize.m
@@ -18,7 +18,7 @@ function tapas_rdcm_visualize(output, DCM, options, plot_regions, plot_mode)
%
% Authors: Stefan Fraessle (stefanf@biomed.ee.ethz.ch), Ekaterina I. Lomakina
%
-% Copyright (C) 2016-2018 Translational Neuromodeling Unit
+% Copyright (C) 2016-2020 Translational Neuromodeling Unit
% Institute for Biomedical Engineering
% University of Zurich & ETH Zurich
%
diff --git a/rDCM/docs/Manual.pdf b/rDCM/docs/Manual.pdf
index b802c659..21ee2ab3 100644
Binary files a/rDCM/docs/Manual.pdf and b/rDCM/docs/Manual.pdf differ
diff --git a/rDCM/misc/rDCM_Avatar.jpg b/rDCM/misc/rDCM_Avatar.jpg
new file mode 100644
index 00000000..a1ce1c5e
Binary files /dev/null and b/rDCM/misc/rDCM_Avatar.jpg differ
diff --git a/rDCM/misc/rDCM_Logo.png b/rDCM/misc/rDCM_Logo.png
new file mode 100644
index 00000000..8984e3d3
Binary files /dev/null and b/rDCM/misc/rDCM_Logo.png differ
diff --git a/tapas_init.m b/tapas_init.m
index a0140a04..4f1794c0 100644
--- a/tapas_init.m
+++ b/tapas_init.m
@@ -1,28 +1,85 @@
-function tapas_init()
-%% Initilizes the toolbox and prints a message in the console.
+function tapas_init(varargin)
+% Initialize TAPAS and print a message in the console
%
-
-% aponteeduardo@gmail.com
-% copyright (C) 2017
+% If no argument is given, all toolboxes are initialized.
+% If you want to initialize only certain toolboxes, use their
+% names as arguments, i.e. tapas_init('hgf') for the HGF-toolbox.
+% Dependent TAPAS toolboxes will be initialised as well.
%
+% To suppress startup messages, use '-noMessages'.
+% To suppress the online-checks for new revisions, use '-noUpdates'
+% If startups messages are suppressed, there will be no check for updates.
+%
+
+% muellmat@ethz.ch
+% copyright (C) 2020
+
f = mfilename('fullpath');
[tdir, ~, ~] = fileparts(f);
+addpath(tdir) % Add tapas dir to path.
+addpath(fullfile(tdir,'misc')) % Add misc for core tapas functionality.
-addpath(genpath(tdir));
+% Separate options (start with '-' as in '-noUpdate') from toolbox names:
+[init_options,toolboxes] = tapas_init_process_varargin(varargin); %
-[version, hash] = tapas_version();
-disp(strcat('Initializing TAPAS ...'));
-fprintf(1, 'Version %s.%s.%s\n', version{:});
+% If not suppressed, print TAPAS logo and version:
+if init_options.doShowStartupMessage
+ [version, hash] = tapas_version();
+ disp(strcat('Initializing TAPAS ...'));
+ fprintf(1, 'Version %s.%s.%s\n', version{:});
-tapas_print_logo();
+ tapas_print_logo();
+end
+% Check for updates if not suppressed:
+if init_options.doCheckUpdates && init_options.doShowStartupMessage
+ % The level 3 shows now the infos for all newer versions. If that is
+ % too much, one might change that to 2 (only notes of newest release).
+ tapas_check_for_new_release(3);
+end
-% Check if the examples directory exist and print a message is required.
+% This function is adding the toolboxes. If toolboxes is empty, all are added.
+tapas_init_toolboxes(toolboxes,tdir,init_options.doShowStartupMessage)
-if ~exist(fullfile(tdir, 'examples'), 'dir')
- fprintf(1, ...
- ['Example data can be downloaded with ' ...
- '\''tapas_download_example_data()\''\n']);
+% Look, if the example data folder exists. If not, give message.
+if init_options.doShowStartupMessage
+ if ~exist(fullfile(tdir, 'examples'), 'dir')
+ fprintf(1, ...
+ ['Example data can be downloaded with ' ...
+ '\''tapas_download_example_data()\''\n']);
+ end
end
+
end
+
+
+function [init_options,toolboxes] = tapas_init_process_varargin(in)
+% Function to separate the varargins into options (start with '-') and
+% function names. Options also have defaults.
+
+% Separation of varagin in messages and options:
+getOpts = @(x) startsWith(x,'-');
+isOpt = cellfun(getOpts,in);
+opts = in(isOpt);
+toolboxes = in(~isOpt);
+toolboxes = lower(toolboxes);
+
+% Create struct for init options and set defaults:
+init_options = struct('doShowStartupMessage',true,'doCheckUpdates',true);
+
+% Integrate options from varargin. If unknown options are used, a warning is issued.
+if ismember('-noUpdates',opts)
+ init_options.doCheckUpdates = false;
+ opts(ismember(opts,'-noUpdates')) = []; % delete to find wrong options
+end
+if ismember('-noMessages',opts)
+ init_options.doShowStartupMessage = false;
+ opts(ismember(opts,'-noMessages')) = []; % delete to find wrong options
+end
+if ~isempty(opts)
+ str = sprintf('\n\t%s',opts{:});
+ warning('Received unused options %s\n I am irgnoring them!\n',str)
+end
+
+end
\ No newline at end of file
diff --git a/task/FDT/LICENSE b/task/FDT/LICENSE
new file mode 100644
index 00000000..f288702d
--- /dev/null
+++ b/task/FDT/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/task/FDT/README.md b/task/FDT/README.md
new file mode 100644
index 00000000..4e363f91
--- /dev/null
+++ b/task/FDT/README.md
@@ -0,0 +1,209 @@
+# FILTER DETECTION TASK
+
+
+VERSION: 0.2.2
+
+Author: Olivia Harrison
+
+Created: 14/08/2018
+
+This software is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+
+See the GNU General Public License for more details:
+
+-----
+
+Updated to 0.2.2: 27/07/2020
+
+- Paired session difference analysis option added to the toolbox
+
+Updated to 0.2.1: 22/06/2020
+
+- Added error to avoid over-writing files with the same PPID specified
+
+- Information regarding download or location of freely-available high quality pink noise files added
+
+Updated to 0.2.0: 02/09/2019
+
+- Regression analysis option added to the toolbox
+
+- More highly regularised roving staircase with a tighter accuracy band (70-75% range) and less tolerant error risk (0.3 from 0.2)
+
+- Criterion representation fixed (c < 0 indicates bias towards yes)
+
+Updated to 0.1.3: 05/07/2019
+
+- Added option to run with a fixed or roving staircase
+
+Updated to 0.1.2: 17/05/2019
+
+- Bug fixed in `filter_detection_task_fix` script (typo) that caught script
+
+Updated to 0.1.1: 25/11/2018
+
+- 2IFC Task option included as an alternative
+
+- Option to specify upper and lower confidence bounds
+
+- Automatic avoidance of zero filters during main task
+
+-----
+
+
+### GENERAL OVERVIEW
+
+This task is a breathing detection task that aims to understand how sensitive an individual is to very small resistances to their inspiration, and any biases they may have towards over- or under- reporting these changes (if run as a yes/no task - default setting). Alternatively, this task can be run as a two-interval forced choice task, to create more compatibility if needing to compare the results with other forced-choice tasks.
+
+Furthermore, this task aims to quantify how 'metacognitively aware' and efficient a participant is, or how much their confidence in their decisions relates to the accuracy of their performance. For example, an individual with better metacognitive scores will report higher confidence when they are correct in their perceptual decision, and lower confidence when they are incorrect.
+
+**THIS TASK AIMS TO DETERMINE:**
+ 1) The number of breathing filters a participant is able to discriminate from a dummy filter with ~60-85% accuracy.
+ 2) The participant's discrimination metric (d') and bias criterion (c) for reporting breathing resistance, using signal detection theory.
+ 3) The participant's metacognitive awareness and efficiency about their performance, in the form of both average confidence over trials and the metacognitive efficiency metric of meta-d'/d'.
+
+-----
+
+### EXPERIMENTER INSTRUCTIONS
+
+**TO RUN THIS TASK:**
+ 1) Copy the entire set of files to a location on your computer and add all folders and subfolders to your matlab path. Open the `filter_detection_task.m` script and set the following properties:
+
+ - Task type: results.setup.taskType = 1 or 2
+
+ 1 = Yes/No task (default)
+
+ 2 = 2IFC task
+
+ - Staircase type: results.setup.staircaseType = 1 or 2
+
+ 1 = Constant (default: collects all threshold trials at a constant filter intensity, and may result in additional trials to find the perceptual threshold filter intensity)
+
+ 2 = Roving (if set, the filter number can change across the threshold trials to maintain performance at the approximate perceptual threshold, and only the specified number of trials will be collected)
+
+ - Confidence scale: (default example)
+
+ results.setup.confidenceLower = 1
+
+ results.setup.confidenceUpper = 10
+ 2) Navigate to the main folder (`filter_detection_task`) in matlab, and type `filter_detection_task` into the matlab terminal.
+ 3) Use the supplied instructions file to explain the task requirements to the participant (see `filter_detection_task/participant_instructions/breathing_task_instructions_{english/german}.doc`).
+ 4) Follow the matlab prompts to specify whether practice and calibration trials should be run, and the number of trials you aim to complete at threshold (minimum recommendation = 60 trials).
+ 5) Turn on a low level of pink noise (see *IMPORTANT NOTES* section below) to reduce the influence of any noise cues.
+ 6) Follow the prompt instructions to complete the task. Only for the very first practice trial (a dummy) is it explicitly explained to the participant whether or not they will receive the load, and then all following practice/calibration/main trials will continue on from each other with no changes in instruction, nor with any feedback given.
+ 7) Once the task is complete, ask the participant to fill in the provided de-briefing questionnaire (see `filter_detection_task/participant_debriefing/debriefing_detection_{english/german}.doc`). This should help you to determine if any significant strategy switch or learning occurred that would warrant post-hoc subject exclusion.
+
+**IMPORTANT NOTES:**
+
+ 1) If at any point you should need to terminate the task, use 'control' + 'c' to exit the loop. All data up to that point will be saved in the specified output file.
+ 2) If any trials were incorrectly entered by the experimenter, a script is provided that will allow you to overwrite specific trials (see `filter_detection_task_fix.m` using the option 'fix').
+ 3) If the task is exited early for any reason, a new session can be started (without practice and calibration trials), with the filter number and remaining trials specified by the experimenter. Once the task is complete, the two sets of results can be combined (if the filter number stays the same) using the provided script (`filter_detection_task_fix.m` using the option 'combine'). The original data files will be moved to a new folder and a combined file will be produced in the results directory.
+ 4) If you would like to run any group analyses using the scripts provided by this toolbox, additional software and code is required (see **IMPORTANT ANALYSIS NOTES** below). This additional software is **NOT** required to run the task itself.
+
+-----
+
+### TRIAL STRUCTURE
+
+**BASIC STRUCTURE FOR YES/NO TASK (practice, calibration and main trials):**
+ 1) The participant takes three or more breaths on the baseline breathing system (dummy filter), and then indicates when they are ready by raising their hand. The experimenter (out of view) then removes the dummy and replaces it either with the stacked filters or the dummy again. The participant takes up to three more breaths against the resistance, and then removes the mouthpiece and responds to the question: 'Did you feel any increase in resistance to your breathing?'. The experimenter enters the answer into the command line at the prompt.
+ 2) The participant then rates on a scale (e.g. 1-10) how confident they are **in their decision** (i.e. not how confident they are that there was a resistance present). On this example scale, 1 = not at all confident, and 10 = extremely confident. The experimenter enters the confidence score at the prompt, and then the script requires a confirmation of all answers to continue to the next trial (any input mistakes can be corrected here). If any mistakes were made, answer the confirmation with 0 (or any other valid key) to repeat the trial prompt. Any mistypings will also trigger a repeat trial presentation on screen for re-input.
+ 3) Note (repeated): Only for the very first practice trial (a dummy) it is explicitly explained to the participant whether or not they will receive the load, and then all following practice/calibration/main trials will continue on from each other with no changes in instruction, nor with any feedback given.
+
+-----
+
+### TASK OVERVIEW (YES/NO)
+
+**TRIAL ORDER:**
+
+Practice trials, calibration trials and then the main task trials are automatically run (in order) if any/all are specified by the experimenter when prompted.
+
+**PRACTICE TRIALS:**
+ 1) For the first practice trial, the dummy filter is presented and explicitly explained to the participant. If the participant does not understand or reports an increase in resistance to their breathing, the dummy trial can be repeated (enter 1 for response at the prompt)
+ 2) It is then explained to the participant that they will not be told whether or not any change in breathing occurs from here onwards. For the second practice trial, 7 filters are presented (large load). If the participant does not report any change in their breathing perception, the practice trial is repeated with an additional filter until perception is reported.
+
+**CALIBRATION TRIALS:**
+ 1) The number of filters to be presented at each trial during the calibration phase is automatically calculated and prompted at the command line. The aim of the calibration phase is to find approximately the right filter to start the main trials on, although this will be adjusted later if needed. Calibration trials can be chosen to be omitted at the beginning of the task, and manual input of the filter number will be prompted instead.
+ 2) For the calibration trials, the first trial is always a presentation of the dummy filter. One filter is then added each trial until the participant reports the perception of the filters.
+ 3) Once a first filter perception has been reported (n), another filter is added for the next trial (n+1). If the participant also reports perception of this additional filter, one filter is taken away (back to n) for a final confirmation trial. If the answer is 'yes' on this confirmation trial, the starting filter number will be n, and if it is 'no', the starting filter number will be n+1. Calibration will finish automatically here.
+ 4) If the first 'yes' report is followed by a 'no' at n+1, filters will continue to be added until there are two 'yes' responses at ascending filter numbers, before a confirmation trial is conducted and the calibration phase terminates.
+
+**MAIN TASK TRIALS:**
+ 1) The aim of the main task is to complete a specified number of trials (recommendation >= 60 trials) of a random presentation of either the specified number of filters (via calibration or manual input) and the dummy filter. The target is for participants to be ideally within 65-80% accuracy across the task, with their probable actual accuracy calculated from all trials completed at the current filter level. If participants move outside of this range within the first 30 trials, the script will suggest a filter change, and the trial count will begin again (or continue from the last trial number at the same filter level). Further details as follows:
+ 2) For each trial, participants will respond whether they perceived it to become harder to breathe or stayed the same (see `breathing_task_instructions` file for detailed instructions), as well as their confidence **IN THEIR DECISION** (i.e. not confidence in the presence of the filters --> this distinction is imperative for metacognition).
+ 3) After 5 trials, the script will begin to calculate both the observed accuracy (e.g. 7/8 trials correct), as well as the likelihood that the true accuracy lies between 65-80% (if using a constant staircase, or if using a roving staircase then a narrower band of 70-75% is employed as greater regularisation does not come at the cost of additional trials). If the probability that the true accuracy lies within this band falls below 20%, an addition or removal of a filter is automatically suggested. The experimenter is asked for confirmation, or can override the suggestion if necessary.
+ 4) If the new filter number has not yet been tested in the main trials, the trial count will begin again from 1. If the filter change moves the testing filter number back to that of previous trials, the trial count will pick up again from the last trial at this level.
+ 5) Once the trial count has reached 30 trials (if using a constant staircase), the script will change to only reporting the performance accuracy every 10 trials. If using a roving staircase, the accuracy will continue to be evaluated at every trial. For the constant staircase >= 30 trials, if the accuracy is within 60-85% a simple confirmation to continue at the current filter number will be asked for. If the accuracy is outside 60-85%, the accuracy of any trials completed at the number of filters directly above and below the current filter number will also be reported. In both instances, the experimenter can choose to continue at the current number of trials or change filter number. If considering changing filters, the experimenter must consider the time required to complete the experiment, and the attention, comfort and motivation of the participant. While completing the full set of trials both at one filter number and within the 60-85% accuracy band is the goal, it must be decided whether the number of completed trials OR the accuracy band is most appropriate to be relaxed when necessary in each experimental setting.
+ 6) Once trials continue past 10 on the same filter, a graph of both running 10-trial accuracy (if using a constant staircase) and the total cumulative accuracy are plotted for the experimenter to monitor online performance of the participant.
+ 7) The task will continue until the specified number of trials are reached, either all at one filter level if using a constant staircase, or the total specified trials (regardless of filter number) if using a roving staircase. All results are saved continuously in case of an early termination of the task, and the task can be exited at any time by using 'control' + 'c'.
+ 8) The task can be restarted (without practice and calibration trials) for any remaining trials if necessary. In this case, name the PPID with a new name (e.g. P003b) otherwise it will throw an error to stop it overriding the original results file. These files can be combined using the provided fixing script (see `filter_detection_task_fix.m`, using the option 'combine'). The original data files will be moved by this script, and a combined file will be produced in the results directory.
+
+-----
+
+### ALTERNATIVE OPTIONS
+
+**YES/NO TASK vs 2IFC TASK CONFIGURATION:**
+
+To run the task as a two-interval forced choice task, first specify this in the 'SET UP THE TASK' section of the main task function (found in `filter_detection_task.m`). The main algorithm and default analysis options will stay the same, but the task instructions will change to presenting the resistance in either the first three-breath interval or the second three breath-interval. Participants will need to choose which interval they thought the resistance was present, and rate their confidence as before.
+
+**STAIRCASE OPTIONS:**
+
+You can decide if you would like to run the task with a 'constant staircase', where all threshold trials are collected at a constant number of filters, or a 'roving staircase', where the filter number can change across the threshold trials. The former option will likely require the collection of additional trials at other filter numbers, but will result in a final set of threshold trials at a constant external load. The roving staircase option will only complete the number of trials set out by the experimenter, but runs the potential risk of not stabilising around the perceptual threshold. To help with this, the accuracy band has been more highly regularised to between 70-75% for this staircase option.
+
+**CONFIDENCE RATING SCALE:**
+
+The default is set between 1 and 10 for the confidence rating scale. In principle you can choose whichever scale you like, however, the larger the rating scale (e.g. 1-100), the more computationally expensive the analysis will become, with large scales requiring exceptionally long fit times. If data has been collected on larger scales, one option would be to 'bin' the confidence data onto a smaller rating scale for feasible metacognition model fit times. This option is not automatically included in this toolbox and would require additional testing.
+
+-----
+
+### ANALYSIS OVERVIEW
+
+This analysis script uses either Brian Maniscalco's single subject analysis or Steve Fleming's Hierarchical Bayesian toolbox (for group analysis) to calculate perceptual decision and metacognitive metrics, specific to data produced by running the `filter_detection_analysis` task.
+
+**IMPORTANT ANALYSIS NOTES:**
+ 1) The code requires JAGS software to run, which can be found here: . The code has been tested on JAGS 3.4.0; there are compatibility issues between matjags and JAGS 4.X.
+ 2) The code requires the [HMeta-d toolbox](https://github.com/metacoglab/HMeta-d). This needs to be downloaded and placed within the `scripts/` folder.
+ 3) This script is looking for specific results files that were output from the `filter_detection_task`, which are located in the `results/` folder. The results are expected to contain a results.filterThreshold.xx structure, where values for xx:
+ - results.filterThreshold.filterNum: a value to determine the number of filters where trials were performed
+ - results.filterThreshold.filters: a vector with 1 meaning filters were presented, 0 when filters were absent (dummy)
+ - results.filterThreshold.response: a vector with 1 meaning response was 'yes', 0 when response was 'no'
+ - results.filterThreshold.confidence: a vector containing confidence score (1-10) on each trial
+ - If your results are formatted differently, refer directly to the original scripts from the [HMeta-d toolbox](https://github.com/metacoglab/HMeta-d).
+
+**TO RUN THIS SCRIPT:**
+
+Type `filter_detection_analysis` into the MATLAB terminal from the main `filter_detection_task` folder, and follow the prompts. For full information on the analysis of this task please see the `filter_detection_analysis.m` file in the `scripts/` folder.
+
+**ANALYSIS OPTIONS OVERVIEW:**
+
+This script allows you to run either:
+
+ - A single subject analysis: A non-Bayesian estimation of meta-d', fitting one subject at a time using a single point maximum likelihood estimation (from the original Maniscalco & Lau 2012 paper, more info can be found here: . HOWEVER: Simulations have shown this analysis to be VERY unstable when estimating meta-d' using 60 trials. It is STRONGLY encouraged to utilise the hierarchical models, or collect many more trials (200+ trials) for each subject to have a more reliable measure of meta-d'.
+ - A group mean analysis: A hierarchical Bayesian analysis, whereby all subjects are fit together and information from the group mean is used as prior information for each subject. This hierarchical model helps with much more accurate estimations of meta-d' with small trial numbers, such as using 60 trials per subject.
+ - A group difference analysis: A hierarchical Bayesian analysis for independent groups, where each group is fitted separately and then the results are compared. Frequentist statistics (i.e. parametric unpaired T-tests, or non-parametric Wilcoxon signed-rank tests) can be used for all values that are not fitted using hierarchical information, such as d', c, filter number, accuracy and average confidence. As the group values for log(meta-d'/d') are calculated using two separate hierarchical models, group differences are then inferred via comparison of the resulting log(meta-d'/d') distributions, and whether the 95% highest-density interval (HDI) of the difference between the distributions spans zero. The HDI is the shortest possible interval containing 95% of the MCMC samples, and may not be symmetric.
+NOTE: If single subject values for log(meta-d'/d') (or any related meta-d' metric) are required for further analyses that span both groups (such as entry into general linear models), it is recommended to fit all subjects together in one regression model with a regressor denoting group identity.
+ - A group regression analysis: A hierarchical Bayesian analysis for one group of subjects, where both the group logMratio and a regression parameter (beta) are simultaneously fit. This model formulation helps with much more accurate estimations of a group beta parameter with small trial numbers (e.g. 60 trials/subject), as individual logMratio values are subject to heavy regularisation towards the group mean. **IMPORTANT NOTE:** This regression parameter beta is fit against logMratio, not Mratio.
+ - A session difference analysis (paired group difference): A hierarchical Bayesian analysis, whereby two sessions / measures from the same participants are fitted in a single model using a multivariate normal distribution. This distribution allows for the non-independence between sessions for each participant. NOTE: Participants must be listed in the same order for analysis, and must have data for both sessions / each measure.
+
+**IMPORTANT ANALYSIS NOTES:**
+
+ - The code requires JAGS software to run, which can be found here: . The code has been tested on JAGS 3.4.0; there are compatibility issues between matjags and JAGS 4.X.
+ - This script is looking for specific results files that were output from the `filter_detection_task`, which are located in the `results/` folder. For full information on the requirements of this analysis please see the `filter_detection_analysis.m` file in the `scripts/` folder.
+
+**KEY ANALYSIS OUTPUT MEASURES:**
+
+ - filterNum: Number of filters. Less filters means more sensitive to changes in breathing.
+ - d1: d prime, the discriminability between filter and dummy trials. Larger d' means more discriminability at specific filter number
+ - c1: Decision criterion, or where the decision boundary exists. Negative criterion values indicate bias towards 'yes', positive values indicate a bias towards a 'no' response.
+ - meta_d: A measure of metacognition, or 'type 2' sensitivity. This reflects how much information, in signal-to-noise units, is available for metacognition (see Maniscalco & Lau, 2012). **NB: ISSUES WITH THIS ESTIMATION (AND ALL RELATED ESTIMATIONS) IF USING SINGLE SUBJECT ANALYSES, AS DESCRIBED ABOVE**.
+ - Mratio: Meta-d' to d' ratio, as a measure of metacognitive 'efficiency' (see Rouault et al., 2018) --> how much information is lost from discriminability to meta-cognition)
+ - log_Mratio: log(meta_d/d1), reported in papers to help with normalisation of data (see Rouault et al., 2018).
+ - avgConfidence: A second measure of metacognition, thought to be independent from meta-d'. NB: Average confidence should only be compared between two groups if there is no difference in d' between the groups (i.e. task difficulty was comparable --> if it is not, this measure will need to be corrected for differences in d')
+
+**ADDITIONAL GROUP / SESSION DIFFERENCE OUTPUT VALUES:**
+
+If the analysis is a two-group or two-session (paired) difference, the following will also be calculated for the non-hierarchical measures (xx = filterNum, d1, c1 and avgConfidence): (test = groupDiff or sessionDiff)
+ 1) analysis.test.xx.h = Results of null hypothesis test, where h = 1 for rejection of the null, and h = 0 for no rejection.
+ 2) analysis.test.xx.p = The p-value for the statistical test.
+ 3) analysis.test.xx.stats = Further statistics (such as tstats, number of samples, degrees of freedom) associated with the test.
+ 4) analysis.test.xx.ci = Confidence interval of the difference, calculated only when T-test is specified.
+
+The highest density interval (HDI) for the difference in log(meta-d'/d') between the groups / sessions will be calculated and recorded, as frequentist statistics cannot be used here. A summary Figure for each of these metrics will be created and saved in the `analysis/` folder.
\ No newline at end of file
diff --git a/task/FDT/analysis/.gitignore b/task/FDT/analysis/.gitignore
new file mode 100644
index 00000000..8b137891
--- /dev/null
+++ b/task/FDT/analysis/.gitignore
@@ -0,0 +1 @@
+
diff --git a/task/FDT/equipment/equipment_details.xlsx b/task/FDT/equipment/equipment_details.xlsx
new file mode 100644
index 00000000..6cc6e465
Binary files /dev/null and b/task/FDT/equipment/equipment_details.xlsx differ
diff --git a/task/FDT/equipment/interoception_diagram.pdf b/task/FDT/equipment/interoception_diagram.pdf
new file mode 100644
index 00000000..df12a81d
Binary files /dev/null and b/task/FDT/equipment/interoception_diagram.pdf differ
diff --git a/task/FDT/equipment/photo_experimenter_end.JPG b/task/FDT/equipment/photo_experimenter_end.JPG
new file mode 100644
index 00000000..951fcd1c
Binary files /dev/null and b/task/FDT/equipment/photo_experimenter_end.JPG differ
diff --git a/task/FDT/equipment/photo_experimenter_end2.JPG b/task/FDT/equipment/photo_experimenter_end2.JPG
new file mode 100644
index 00000000..32c16a45
Binary files /dev/null and b/task/FDT/equipment/photo_experimenter_end2.JPG differ
diff --git a/task/FDT/equipment/photo_participant_end.JPG b/task/FDT/equipment/photo_participant_end.JPG
new file mode 100644
index 00000000..5d80b900
Binary files /dev/null and b/task/FDT/equipment/photo_participant_end.JPG differ
diff --git a/task/FDT/figures/.gitignore b/task/FDT/figures/.gitignore
new file mode 100644
index 00000000..8b137891
--- /dev/null
+++ b/task/FDT/figures/.gitignore
@@ -0,0 +1 @@
+
diff --git a/task/FDT/participant_debriefing/debriefing_detection_english.docx b/task/FDT/participant_debriefing/debriefing_detection_english.docx
new file mode 100644
index 00000000..5e404bee
Binary files /dev/null and b/task/FDT/participant_debriefing/debriefing_detection_english.docx differ
diff --git a/task/FDT/participant_debriefing/debriefing_detection_german.docx b/task/FDT/participant_debriefing/debriefing_detection_german.docx
new file mode 100644
index 00000000..2dd80a1f
Binary files /dev/null and b/task/FDT/participant_debriefing/debriefing_detection_german.docx differ
diff --git a/task/FDT/participant_instructions/breathing_task_instructions_english.docx b/task/FDT/participant_instructions/breathing_task_instructions_english.docx
new file mode 100755
index 00000000..d41b147b
Binary files /dev/null and b/task/FDT/participant_instructions/breathing_task_instructions_english.docx differ
diff --git a/task/FDT/participant_instructions/breathing_task_instructions_german.docx b/task/FDT/participant_instructions/breathing_task_instructions_german.docx
new file mode 100755
index 00000000..9ade16d2
Binary files /dev/null and b/task/FDT/participant_instructions/breathing_task_instructions_german.docx differ
diff --git a/task/FDT/results/covariate_example.txt b/task/FDT/results/covariate_example.txt
new file mode 100644
index 00000000..a0600bf5
--- /dev/null
+++ b/task/FDT/results/covariate_example.txt
@@ -0,0 +1,6 @@
+5
+7
+3
+2
+8
+6
diff --git a/task/FDT/results/filter_task_results_T001.mat b/task/FDT/results/filter_task_results_T001.mat
new file mode 100644
index 00000000..0e89e15a
Binary files /dev/null and b/task/FDT/results/filter_task_results_T001.mat differ
diff --git a/task/FDT/results/filter_task_results_T002.mat b/task/FDT/results/filter_task_results_T002.mat
new file mode 100755
index 00000000..9d894015
Binary files /dev/null and b/task/FDT/results/filter_task_results_T002.mat differ
diff --git a/task/FDT/results/filter_task_results_T003.mat b/task/FDT/results/filter_task_results_T003.mat
new file mode 100755
index 00000000..66b84252
Binary files /dev/null and b/task/FDT/results/filter_task_results_T003.mat differ
diff --git a/task/FDT/results/filter_task_results_T004.mat b/task/FDT/results/filter_task_results_T004.mat
new file mode 100755
index 00000000..51b1dbed
Binary files /dev/null and b/task/FDT/results/filter_task_results_T004.mat differ
diff --git a/task/FDT/results/filter_task_results_T005.mat b/task/FDT/results/filter_task_results_T005.mat
new file mode 100755
index 00000000..7cd6e750
Binary files /dev/null and b/task/FDT/results/filter_task_results_T005.mat differ
diff --git a/task/FDT/results/filter_task_results_T006.mat b/task/FDT/results/filter_task_results_T006.mat
new file mode 100755
index 00000000..ace056f4
Binary files /dev/null and b/task/FDT/results/filter_task_results_T006.mat differ
diff --git a/task/FDT/scripts/tapas_filter_detection_analysis.m b/task/FDT/scripts/tapas_filter_detection_analysis.m
new file mode 100644
index 00000000..de199d67
--- /dev/null
+++ b/task/FDT/scripts/tapas_filter_detection_analysis.m
@@ -0,0 +1,975 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%% BREATHING FILTER DETECTION TASK ANALYSIS %%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% -------------------------------------------------------------------------
+% Author: Olivia Harrison
+% Created: 14/08/2018
+%
+% This software is free software: you can redistribute it and/or modify it
+% under the terms of the GNU General Public License as published by the
+% Free Software Foundation, either version 3 of the License, or (at your
+% option) any later version. This software is distributed in the hope that
+% it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+% warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+% GNU General Public License for more details: http://www.gnu.org/licenses/
+% -------------------------------------------------------------------------
+
+% This analysis script uses either Brian Maniscalco's single subect
+% analysis or Steve Fleming's Hierarchical Bayesian toolbox (for group
+% analysis) to calculate perceptual decision and metacognitive metrics,
+% specific to data produced by running the tapas_filter_detection_task.
+
+% IMPORTANT ANALYSIS NOTES:
+% 1) The code requires JAGS software to run, which can be found here:
+% http://mcmc-jags.sourceforge.net/
+% The code has been tested on JAGS 3.4.0; there are compatibility
+% issues between matjags and JAGS 4.X.
+% 2) The code requires the HMeta-d toolbox (provided as a submodule
+% from https://github.com/metacoglab/HMeta-d) to be on your path.
+% 3) This script is looking for specific results files that were output
+% from the tapas_filter_detection_task, which are located in the
+% FDT/results/ folder. The results are expected to contain a
+% results.filterThreshold.xx structure, where values for xx:
+% - results.filterThreshold.filterNum: a value to determine the
+% number of filters where trials were performed
+% - results.filterThreshold.filters: a vector with 1 meaning
+% filters were presented, 0 when filters were absent (dummy)
+% - results.filterThreshold.response: a vector with 1 meaning
+% response was 'yes', 0 when response was 'no'
+% - results.filterThreshold.confidence: a vector containing
+% confidence score (1-10) on each trial
+% If your results are formatted differently, refer directly to the
+% original scripts from the HMeta-d toolbox
+% (https://github.com/metacoglab/HMeta-d).
+
+% TO RUN THIS SCRIPT:
+% type tapas_filter_detection_analysis into the MATLAB terminal from the
+% main FDT folder, and follow the prompts.
+
+% ANALYSIS OPTIONS:
+% This script allows you to run either:
+% - A single subject analysis: A non-Bayesian estimation of meta-d',
+% fitting one subject at a time using a single point maximum
+% likelihood estimation (from the original Maniscalco & Lau 2012
+% paper, more info can be found here:
+% http://www.columbia.edu/~bsm2105/type2sdt/archive/index.html).
+% HOWEVER: Simulations have shown this analysis to be VERY unstable
+% when estimating meta-d' using 60 trials. It is STRONGLY encouraged
+% to utilise the hierarchical models, or collect many more trials
+% (200+ trials) for each subject to have a more reliable measure of
+% meta-d'.
+% - A group mean analysis: A hierarchical Bayesian analysis, whereby all
+% subjects are fit together and information from the group mean is
+% used as prior information for each subject. This hierarchical model
+% helps with much more accurate estimations of meta-d' with small
+% trial numbers, such as using 60 trials per subject.
+% - A group regression analysis: A hierarchical Bayesian regression
+% analysis that is an extension on the group mean analysis, whereby
+% subjects are fit together in one model, and the relationship between
+% single subject log(meta-d'/d') values and the covariate(s) is
+% estimated within the hierarchical model structure.
+% - A group difference analysis: A hierarchical Bayesian analysis,
+% whereby each group of subjects is fitted separately, and the groups
+% are then compared. Frequentist statistics (such as parametric
+% unpaired T-tests, or non-parametric Wilcoxon signed-rank tests) can
+% be used for all values that are not fitted using hierarchical
+% information, such as d', c, filter number, accuracy and average
+% confidence. As the group values for log(meta-d'/d') are calculated
+% using two separate hierarchical models, group differences are then
+% inferred via comparison of the resulting log(meta-d'/d')
+% distributions, and whether the 95% highest-density interval (HDI) of
+% the difference between the distributions spans zero. The HDI is the
+% shortest possible interval containing 95% of the MCMC samples, and
+% may not be symmetric. NOTE: If single subject values for
+% log(meta-d'/d') (or any related meta-d' metric) are required for
+% further analyses that span both groups (such as entry into general
+% linear models), it is recommended to fit all subjects together in
+% one regression model with a regressor denoting group identity.
+% - A session difference analysis (paired group difference): A
+% hierarchical Bayesian analysis, whereby two sessions / measures from
+% the same participants are fitted in a single model using a
+% multivariate normal distribution. This distribution allows for the
+% non-independence between sessions for each participant. NOTE:
+% Participants must be listed in the same order for analysis, and must
+% have data for both sessions / each measure.
+
+% NOTES ON NON-BAYESIAN SINGLE SUBJECT ANALYSIS FROM AUTHORS' WEBSITE
+% (columbia.edu/~bsm2105/type2sdt/archive/index.html):
+% This analysis is intended to quantify metacognitive sensitivity (i.e. the
+% efficacy with which confidence ratings discriminate between correct and
+% incorrect judgments) in a signal detection theory framework. A central
+% idea is that primary task performance can influence metacognitive
+% sensitivity, and it is informative to take this influence into account.
+% Description of the methodology can be found here: Maniscalco, B., & Lau,
+% H. (2012). A signal detection theoretic approach for estimating
+% metacognitive sensitivity from confidence ratings. Consciousness and
+% Cognition, 21(1), 422–430. doi:10.1016/j.concog.2011.09.021
+% If you use these analysis files, please reference the Consciousness &
+% Cognition paper and website. Brian Maniscalco: brian@psych.columbia.edu
+
+% NOTES ON HIERARCHICAL TOOLBOX FROM ORIGINAL SCRIPTS (FOR GROUP ANALYSES):
+% This MATLAB toolbox implements the meta-d’ model (Maniscalco & Lau, 2012)
+% in a hierarchical Bayesian framework using Matlab and JAGS, a program for
+% conducting MCMC inference on arbitrary Bayesian models. A paper with more
+% details on the method and the advantages of estimating meta-d’ in a
+% hierarchal Bayesian framework is available here https://academic.oup.com/
+% nc/article/doi/10.1093/nc/nix007/3748261/HMeta-d-hierarchical-Bayesian-
+% estimation-of. For a more general introduction to Bayesian models of
+% cognition see Lee & Wagenmakers, Bayesian Cognitive Modeling: A Practical
+% Course http://bayesmodels.com/. This code is being released with a
+% permissive open-source license. You should feel free to use or adapt the
+% utility code as long as you follow the terms of the license provided. If
+% you use the toolbox in a publication we ask that you cite the following
+% paper: Fleming, S.M. (2017) HMeta-d: hierarchical Bayesian estimation of
+% metacognitive efficiency from confidence ratings, Neuroscience of
+% Consciousness, 3(1) nix007, https://doi.org/10.1093/nc/nix007. Copyright
+% (c) 2017, Stephen Fleming. For more information and/or licences, please
+% see the original code: https://github.com/metacoglab/HMeta-d.
+
+% KEY ANALYSIS OUTPUT VALUES:
+% The primary measures to come out of this analysis can be found in
+% analysis.{single/groupMean/groupDiff}.xx, and they are:
+% 1) xx = filterNum: Number of filters. Less filters means more sensitive
+% to changes in breathing.
+% 2) xx = d1: d prime, discriminability between filter and dummy trials.
+% Larger d' means more discriminability at specific filter number
+% 3) xx = c1: Decision criterion, or where the decision boundary exists.
+% Negative criterion values mean bias towards 'yes' (lower, more
+% liberal criterion), while positive values mean bias towards
+% 'no' response (higher, more strngent criterion).
+% 4) xx = meta_d: A measure of metacognition, or 'type 2' sensitivity.
+% This reflects how much information, in signal-to-noise units,
+% is available for metacognition (see Maniscalco & Lau, 2012).
+% NB: ISSUES WITH THIS ESTIMATION (AND ALL RELATED ESTIMATIONS)
+% IF USING SINGLE SUBJECT ANALYSES, AS DESCRIBED ABOVE.
+% 5) xx = Mratio: Meta-d' to d' ratio, as a measure of metacognitive
+% 'efficiency' (see Rouault et al., 2018).
+% 6) xx = log_Mratio: log(meta_d/d1), reported in papers to help with
+% normalisation of data (see Rouault et al., 2018).
+% 7) xx = avgConfidence: A second measure of metacognition, thought to be
+% independent from meta-d'. NB: Average confidence should only be
+% compared between two groups if there is no difference in d'
+% between the groups (i.e. task difficulty was comparable).
+
+% ADDITIONAL GROUP DIFFERENCE OUTPUT VALUES:
+% If the analysis is a two-group or two-session (paired) difference, the
+% following will also be calculated for the non-hierarchical measures
+% (test = groupDiff or sessionDiff; xx = filterNum, d1, c1 and
+% avgConfidence):
+% 1) analysis.test.xx.h = Results of null hypothesis test, where h =
+% 1 for rejection of the null, and h = 0 for no rejection.
+% 2) analysis.test.xx.p = The p-value for the statistical test.
+% 3) analysis.test.xx.stats = Further statistics (such as tstats,
+% number of samples, degrees of freedom) associated with the test.
+% 4) analysis.test.xx.ci = Confidence interval of the difference,
+% calculated only when T-test is specified.
+% The highest density interval (HDI) for the difference in log(meta-d'/d')
+% between the groups / sessions will be calculated and recorded, as
+% frequentist statistics cannot be used here. A summary Figure for each of
+% these metrics will be created and saved in the FDT/analysis/ folder.
+
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SET UP THE ANALYSIS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function tapas_filter_detection_analysis()
+
+% Check folder location is main FDT folder
+[~,dir_name] = fileparts(pwd);
+if ~strcmp(dir_name,'FDT')
+ error('Not currently in main FDT folder. Please move to FDT folder and try again.');
+end
+
+% Add relevant paths
+addpath('analysis');
+
+% Display setup on screen
+fprintf('\n________________________________________\n\n SET UP ANALYSIS FOR FILTER TASK\n________________________________________\n');
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CHOOSE THE TYPE OF ANALYSIS TO RUN AND SPECIFY FILES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+try
+ analysis.type = input('Type of analysis (single or group) = ', 's'); % Ask for type of analysis to be run
+catch
+ fprintf('\nOption does not exist, please try again.\n');
+ return
+end
+
+try
+ if strcmp(analysis.type,'single') == 1 % If single subject analysis specified
+ analysis.PPIDs = input('PPID = ', 's'); % Ask for PPID
+ try
+ analysis.data = load(fullfile('results', ['filter_task_results_', analysis.PPIDs, '.mat'])); % Load data
+ analysis.ratings = analysis.data.results.setup.confidenceUpper - analysis.data.results.setup.confidenceLower + 1; % Calculate number of confidence rating bins
+ catch
+ fprintf('\nInvalid PPID.\n');
+ return
+ end
+ elseif strcmp(analysis.type,'group') == 1 % If group analysis specified
+ analysis.type = input('Type of analysis (mean, diff, paired or regress) = ', 's'); % Ask for type of group analysis to be run
+ if strcmp(analysis.type,'mean') == 1 % If group mean analysis specified
+ analysis.PPIDs = input('Input group PPIDs (e.g. {''001'', ''002'', ''003'',...}) = '); % Ask for PPIDs
+ analysis.groupsize(1) = length(analysis.PPIDs);
+ for n = 1:length(analysis.PPIDs)
+ PPID = char(analysis.PPIDs(n));
+ try
+ analysis.data(n) = load(fullfile('results', ['filter_task_results_', PPID, '.mat'])); % Load data
+ catch
+ fprintf('\nInvalid PPIDs.\n');
+ return
+ end
+ end
+ analysis.ratings = analysis.data(1).results.setup.confidenceUpper - analysis.data(1).results.setup.confidenceLower + 1; % Calculate number of confidence rating bins
+ elseif strcmp(analysis.type,'diff') == 1 % If two group difference analysis specified
+ analysis.PPIDs.group1 = input('Input group 1 PPIDs (e.g. {''001'', ''002'', ''003'',...}) = '); % Ask for PPIDs
+ analysis.PPIDs.group2 = input('Input group 2 PPIDs (e.g. {''004'', ''005'', ''006'',...}) = '); % Ask for PPIDs
+ analysis.groupDiff.test = input('Type 1 variable tests (ttest or wilcoxon) = ', 's'); % Ask for parametric or non-parmetric test options for type 1 variables (d', c etc.)
+ analysis.groupsize(1) = length(analysis.PPIDs.group1);
+ analysis.groupsize(2) = length(analysis.PPIDs.group2);
+ for n = 1:analysis.groupsize(1)
+ PPID = char(analysis.PPIDs.group1(n));
+ try
+ analysis.group1.data(n) = load(fullfile('results', ['filter_task_results_', PPID, '.mat'])); % Load data
+ catch
+ fprintf('\nInvalid PPIDs for group 1.\n');
+ return
+ end
+ end
+ for n = 1:analysis.groupsize(2)
+ PPID = char(analysis.PPIDs.group2(n));
+ try
+ analysis.group2.data(n) = load(fullfile('results', ['filter_task_results_', PPID, '.mat'])); % Load data
+ catch
+ fprintf('\nInvalid PPIDs for group 2.\n');
+ return
+ end
+ end
+ analysis.ratings = analysis.group1.data(1).results.setup.confidenceUpper - analysis.group1.data(1).results.setup.confidenceLower + 1; % Calculate number of confidence rating bins
+ elseif strcmp(analysis.type,'paired') == 1 % If paired difference analysis specified
+ fprintf('\nNOTE: PPIDs from each session need to be paired and in the same order\n');
+ analysis.PPIDs.session1 = input('Input session 1 PPIDs (e.g. {''001a'', ''002a'', ''003a'',...}) = '); % Ask for PPIDs
+ analysis.PPIDs.session2 = input('Input session 2 PPIDs (e.g. {''001b'', ''002b'', ''003b'',...}) = '); % Ask for PPIDs
+ analysis.sessionDiff.test = input('Type 1 variable tests (ttest or wilcoxon) = ', 's'); % Ask for parametric or non-parmetric test options for type 1 variables (d', c etc.)
+ analysis.sessionSize(1) = length(analysis.PPIDs.session1);
+ analysis.sessionSize(2) = length(analysis.PPIDs.session2);
+ if analysis.sessionSize(1) ~= analysis.sessionSize(2)
+ error('Number of PPIDs in each session does not match!');
+ end
+ for n = 1:analysis.sessionSize(1)
+ PPID = char(analysis.PPIDs.session1(n));
+ try
+ analysis.session1.data(n) = load(fullfile('results', ['filter_task_results_', PPID, '.mat'])); % Load data
+ catch
+ fprintf('\nInvalid PPIDs for session 1.\n');
+ return
+ end
+ end
+ for n = 1:analysis.sessionSize(2)
+ PPID = char(analysis.PPIDs.session2(n));
+ try
+ analysis.session2.data(n) = load(fullfile('results', ['filter_task_results_', PPID, '.mat'])); % Load data
+ catch
+ fprintf('\nInvalid PPIDs for session 2.\n');
+ return
+ end
+ end
+ analysis.ratings = analysis.session1.data(1).results.setup.confidenceUpper - analysis.session1.data(1).results.setup.confidenceLower + 1; % Calculate number of confidence rating bins
+ elseif strcmp(analysis.type,'regress') == 1 % If regression analysis specified
+ analysis.PPIDs = input('Input group PPIDs (e.g. {''001'', ''002'', ''003'',...}) = '); % Ask for PPIDs
+ analysis.groupsize(1) = length(analysis.PPIDs);
+ for n = 1:length(analysis.PPIDs)
+ PPID = char(analysis.PPIDs(n));
+ try
+ analysis.data(n) = load(fullfile('results', ['filter_task_results_', PPID, '.mat'])); % Load data
+ catch
+ fprintf('\nInvalid PPIDs.\n');
+ return
+ end
+ end
+ analysis.ratings = analysis.data(1).results.setup.confidenceUpper - analysis.data(1).results.setup.confidenceLower + 1; % Calculate number of confidence rating bins
+ fprintf('\nNote: Covariate text file required to be placed in results folder\n--> Scores need to be in the SAME ORDER as PPID input order.\n');
+ analysis.covariate.fileName = input('Input covariate file name (e.g. covariate_example.txt) = ', 's'); % Ask for covariate file name
+ try
+ analysis.covariate.data = load(fullfile('results', analysis.covariate.fileName)); % Load data
+ catch
+ fprintf('\nCovariate file cannot be found in results folder.\n');
+ return
+ end
+ [a,b] = size(analysis.covariate.data);
+ if a > b % Re-shape vector if needed
+ analysis.covariate.data = analysis.covariate.data';
+ end
+ end
+ end
+catch
+ fprintf('\nInvalid.\n');
+ return
+end
+
+% Save results
+if strcmp(analysis.type,'single') == 1
+ resultsFile = fullfile('analysis', ['filter_task_analysis_', analysis.type, analysis.PPIDs]); % Create figure file name
+else
+ resultsFile = fullfile('analysis', ['filter_task_analysis_', analysis.type]); % Create figure file name
+end
+save(resultsFile, 'analysis'); % Save results
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RUN TRIALS2COUNTS SCRIPT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+if strcmp(analysis.type,'single') == 1 || strcmp(analysis.type,'mean') == 1 || strcmp(analysis.type,'regress') == 1
+
+ % Run trials2counts script for single subject or whole group
+ for n = 1:length(analysis.data)
+ stimID = analysis.data(n).results.thresholdTrials.filters;
+ response = analysis.data(n).results.thresholdTrials.response;
+ rating = analysis.data(n).results.thresholdTrials.confidence;
+ [analysis.trials2counts.nR_S1{n}, analysis.trials2counts.nR_S2{n}] = trials2counts(stimID,response,rating,analysis.ratings,0); % Run for number of ratings and no cell padding
+ end
+
+elseif strcmp(analysis.type,'diff') == 1
+
+ % Run trials2counts script for group 1
+ for n = 1:length(analysis.group1.data)
+ stimID = analysis.group1.data(n).results.thresholdTrials.filters;
+ response = analysis.group1.data(n).results.thresholdTrials.response;
+ rating = analysis.group1.data(n).results.thresholdTrials.confidence;
+ [analysis.group1.trials2counts.nR_S1{n}, analysis.group1.trials2counts.nR_S2{n}] = trials2counts(stimID,response,rating,analysis.ratings,0); % Run for number of ratings and no cell padding
+ end
+ % Run trials2counts script for group 2
+ for n = 1:length(analysis.group2.data)
+ stimID = analysis.group2.data(n).results.thresholdTrials.filters;
+ response = analysis.group2.data(n).results.thresholdTrials.response;
+ rating = analysis.group2.data(n).results.thresholdTrials.confidence;
+ [analysis.group2.trials2counts.nR_S1{n}, analysis.group2.trials2counts.nR_S2{n}] = trials2counts(stimID,response,rating,analysis.ratings,0); % Run for number of ratings and no cell padding
+ end
+
+elseif strcmp(analysis.type,'paired') == 1
+
+ % Run trials2counts script for session 1
+ for n = 1:length(analysis.session1.data)
+ stimID = analysis.session1.data(n).results.thresholdTrials.filters;
+ response = analysis.session1.data(n).results.thresholdTrials.response;
+ rating = analysis.session1.data(n).results.thresholdTrials.confidence;
+ [analysis.trials2counts.nR_S1(1).counts{n}, analysis.trials2counts.nR_S2(1).counts{n}] = trials2counts(stimID,response,rating,analysis.ratings,0); % Run for number of ratings and no cell padding
+ end
+ % Run trials2counts script for session 2
+ for n = 1:length(analysis.session2.data)
+ stimID = analysis.session2.data(n).results.thresholdTrials.filters;
+ response = analysis.session2.data(n).results.thresholdTrials.response;
+ rating = analysis.session2.data(n).results.thresholdTrials.confidence;
+ [analysis.trials2counts.nR_S1(2).counts{n}, analysis.trials2counts.nR_S2(2).counts{n}] = trials2counts(stimID,response,rating,analysis.ratings,0); % Run for number of ratings and no cell padding
+ end
+
+end
+
+% Save results
+save(resultsFile, 'analysis');
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RUN SINGLE SUBJECT ANALYSIS IF SPECIFIED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+if strcmp(analysis.type,'single') == 1 % If single subject analysis specified
+
+ % Pad ratings so that zero counts do not interfere with fit
+ analysis.trials2counts.nR_S1_padded = analysis.trials2counts.nR_S1{1} + 1/(2*10);
+ analysis.trials2counts.nR_S2_padded = analysis.trials2counts.nR_S2{1} + 1/(2*10);
+
+ % Fit data
+ analysis.single.fit = fit_meta_d_MLE(analysis.trials2counts.nR_S1_padded, analysis.trials2counts.nR_S2_padded);
+
+ % Pull out key variables
+ analysis.single.filterNum = mean(analysis.data.results.thresholdTrials.filterNum);
+ analysis.single.accuracy = analysis.data.results.thresholdTrials.accuracyTotal;
+ analysis.single.d1 = analysis.single.fit.d1;
+ analysis.single.c1 = analysis.single.fit.c1;
+ analysis.single.meta_d = analysis.single.fit.meta_d;
+ analysis.single.Mratio = analysis.single.fit.M_ratio;
+ analysis.single.fit.log_Mratio = log(analysis.single.fit.M_ratio);
+ analysis.single.avgConfidence = mean(analysis.data(1).results.thresholdTrials.confidence);
+
+ % Save results
+ save(resultsFile, 'analysis'); % Save results
+
+ % Display completion message on screen
+ fprintf('\n________________________________________\n\n COMPLETED SINGLE SUBJECT ANALYSIS\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n');
+ fprintf('\n MRATIO = %.2f\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n', analysis.single.Mratio);
+ fprintf('\n RESULTS CAN BE FOUND IN: \n FDT/analysis/\n________________________________________\n');
+
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RUN GROUP MEAN ANALYSIS IF SPECIFIED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+if strcmp(analysis.type,'mean') == 1 % If group mean analysis specified
+
+ % Specify parameters
+ analysis.groupMean.mcmc_params = fit_meta_d_params;
+
+ % Fit group data all at once
+ analysis.groupMean.fit = fit_meta_d_mcmc_group(analysis.trials2counts.nR_S1, analysis.trials2counts.nR_S2, analysis.groupMean.mcmc_params);
+
+ % Calculate log of Mratio for single subjects values
+ for n = 1:length(analysis.groupMean.fit.Mratio)
+ analysis.groupMean.log_Mratio.singleSubject(n) = log(analysis.groupMean.fit.Mratio(n));
+ end
+
+ % Pull out group mean values
+ analysis.groupMean.d1.groupMean = mean(analysis.groupMean.fit.d1);
+ analysis.groupMean.d1.singleSubject = analysis.groupMean.fit.d1;
+ analysis.groupMean.c1.groupMean = mean(analysis.groupMean.fit.c1);
+ analysis.groupMean.c1.singleSubject = analysis.groupMean.fit.c1;
+ analysis.groupMean.meta_d.groupMean = mean(analysis.groupMean.fit.meta_d);
+ analysis.groupMean.meta_d.singleSubject = analysis.groupMean.fit.meta_d;
+ analysis.groupMean.Mratio.groupMean = exp(analysis.groupMean.fit.mu_logMratio);
+ analysis.groupMean.Mratio.singleSubject = analysis.groupMean.fit.Mratio;
+ analysis.groupMean.Mratio.hdi = calc_HDI(exp(analysis.groupMean.fit.mcmc.samples.mu_logMratio(:)));
+ analysis.groupMean.log_Mratio.groupMean = analysis.groupMean.fit.mu_logMratio;
+ analysis.groupMean.log_Mratio.hdi = calc_HDI(analysis.groupMean.fit.mcmc.samples.mu_logMratio(:));
+
+ % Calculate average confidence, add filter number and accuracy to analysis results
+ for n = 1:length(analysis.data)
+ analysis.groupMean.avgConfidence.singleSubject(n) = mean(analysis.data(n).results.thresholdTrials.confidence);
+ analysis.groupMean.filterNum.singleSubject(n) = mean(analysis.data(n).results.thresholdTrials.filterNum);
+ analysis.groupMean.accuracy.singleSubject(n) = analysis.data(n).results.thresholdTrials.accuracyTotal;
+ end
+ analysis.groupMean.avgConfidence.groupMean = mean(analysis.groupMean.avgConfidence.singleSubject);
+ analysis.groupMean.filterNum.groupMean = mean(analysis.groupMean.filterNum.singleSubject);
+ analysis.groupMean.accuracy.groupMean = mean(analysis.groupMean.accuracy.singleSubject);
+
+ % Save results
+ save(resultsFile, 'analysis'); % Save results
+
+ % Display completion message on screen
+ fprintf('\n________________________________________\n\n COMPLETED GROUP MEAN ANALYSIS\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n');
+ fprintf('\n GROUP MRATIO = %.2f (HDI: %.2f to %.2f)\n', analysis.groupMean.Mratio.groupMean, analysis.groupMean.Mratio.hdi(1), analysis.groupMean.Mratio.hdi(2));
+ if (analysis.groupMean.Mratio.hdi(1) > 0 && analysis.groupMean.Mratio.hdi(2) > 0) || (analysis.groupMean.Mratio.hdi(1) < 0 && analysis.groupMean.Mratio.hdi(2) < 0)
+ fprintf(' HDI DOES NOT SPAN ZERO: MRATIO SIG.\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n');
+ else
+ fprintf(' HDI SPANS ZERO: MRATIO NOT SIG.\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n');
+ end
+ fprintf('\n RESULTS CAN BE FOUND IN: \n FDT/analysis/\n________________________________________\n');
+
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RUN GROUP DIFFERENCE ANALYSIS (UNPAIRED) IF SPECIFIED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+if strcmp(analysis.type,'diff') == 1 % If group difference analysis specified
+
+ % For two-group difference analysis: Print message about groups being fit separately --> no t-tests possible on meta-d' metrics
+ fprintf('\nNOTE: Groups are fit using separate hierarchical models.\nFrequentist statistics (such as t-tests) are not possible on any metrics involving meta-d''.\nFrequentist statistics will still be applied to all type 1 metrics and average confidence values.\n');
+
+ % Specify parameters
+ analysis.groupDiff.mcmc_params = fit_meta_d_params;
+
+ % Fit each group using a separate hierarchical Bayesian model
+ analysis.group1.fit = fit_meta_d_mcmc_group(analysis.group1.trials2counts.nR_S1, analysis.group1.trials2counts.nR_S2, analysis.groupDiff.mcmc_params);
+ analysis.group2.fit = fit_meta_d_mcmc_group(analysis.group2.trials2counts.nR_S1, analysis.group2.trials2counts.nR_S2, analysis.groupDiff.mcmc_params);
+
+ % Compute HDI of difference for log(meta-d'/d')
+ analysis.group1.logMratio.groupMean = analysis.group1.fit.mu_logMratio;
+ analysis.group1.logMratio.singleSubject = log(analysis.group1.fit.Mratio);
+ analysis.group1.Mratio.groupMean = exp(analysis.group1.fit.mu_logMratio);
+ analysis.group1.Mratio.singleSubject = analysis.group1.fit.Mratio;
+ analysis.group2.logMratio.groupMean = analysis.group2.fit.mu_logMratio;
+ analysis.group2.logMratio.singleSubject = log(analysis.group2.fit.Mratio);
+ analysis.group2.Mratio.groupMean = exp(analysis.group2.fit.mu_logMratio);
+ analysis.group2.Mratio.singleSubject = analysis.group2.fit.Mratio;
+ analysis.groupDiff.log_Mratio.sampleDiff = analysis.group1.fit.mcmc.samples.mu_logMratio - analysis.group2.fit.mcmc.samples.mu_logMratio;
+ analysis.groupDiff.log_Mratio.mean = analysis.group1.fit.mu_logMratio - analysis.group2.fit.mu_logMratio;
+ analysis.groupDiff.log_Mratio.hdi = calc_HDI(analysis.groupDiff.log_Mratio.sampleDiff(:));
+ analysis.groupDiff.Mratio.mean = exp(analysis.group1.fit.mu_logMratio) - exp(analysis.group2.fit.mu_logMratio);
+ analysis.groupDiff.Mratio.hdi = calc_HDI((exp(analysis.group1.fit.mcmc.samples.mu_logMratio(:)) - exp(analysis.group2.fit.mcmc.samples.mu_logMratio(:))));
+
+ % Pull out group mean values for all non-hierarchical metrics
+ analysis.group1.d1.groupMean = mean(analysis.group1.fit.d1);
+ analysis.group1.d1.singleSubject = analysis.group1.fit.d1;
+ analysis.group1.c1.groupMean = mean(analysis.group1.fit.c1);
+ analysis.group1.c1.singleSubject = analysis.group1.fit.c1;
+ analysis.group2.d1.groupMean = mean(analysis.group2.fit.d1);
+ analysis.group2.d1.singleSubject = analysis.group2.fit.d1;
+ analysis.group2.c1.groupMean = mean(analysis.group2.fit.c1);
+ analysis.group2.c1.singleSubject = analysis.group2.fit.c1;
+
+ % Calculate average confidence, add filter number and accuracy to results for group 1
+ for n = 1:length(analysis.group1.data)
+ analysis.group1.avgConfidence.singleSubject(n) = mean(analysis.group1.data(n).results.thresholdTrials.confidence);
+ analysis.group1.filterNum.singleSubject(n) = mean(analysis.group1.data(n).results.thresholdTrials.filterNum);
+ analysis.group1.accuracy.singleSubject(n) = analysis.group1.data(n).results.thresholdTrials.accuracyTotal;
+ end
+ analysis.group1.avgConfidence.groupMean = mean(analysis.group1.avgConfidence.singleSubject);
+ analysis.group1.filterNum.groupMean = mean(analysis.group1.filterNum.singleSubject);
+ analysis.group1.accuracy.groupMean = mean(analysis.group1.accuracy.singleSubject);
+
+ % Calculate average confidence, add filter number and accuracy to results for group 2
+ for n = 1:length(analysis.group2.data)
+ analysis.group2.avgConfidence.singleSubject(n) = mean(analysis.group2.data(n).results.thresholdTrials.confidence);
+ analysis.group2.filterNum.singleSubject(n) = mean(analysis.group2.data(n).results.thresholdTrials.filterNum);
+ analysis.group2.accuracy.singleSubject(n) = analysis.group2.data(n).results.thresholdTrials.accuracyTotal;
+ end
+ analysis.group2.avgConfidence.groupMean = mean(analysis.group2.avgConfidence.singleSubject);
+ analysis.group2.filterNum.groupMean = mean(analysis.group2.filterNum.singleSubject);
+ analysis.group2.accuracy.groupMean = mean(analysis.group2.accuracy.singleSubject);
+
+ % Calculate group difference values for all non-hierarchical metrics
+ analysis.groupDiff.filterNum.meanDiff = analysis.group1.filterNum.groupMean - analysis.group2.filterNum.groupMean;
+ analysis.groupDiff.accuracy.meanDiff = analysis.group1.accuracy.groupMean - analysis.group2.accuracy.groupMean;
+ analysis.groupDiff.d1.meanDiff = analysis.group1.d1.groupMean - analysis.group2.d1.groupMean;
+ analysis.groupDiff.c1.meanDiff = analysis.group1.c1.groupMean - analysis.group2.c1.groupMean;
+ analysis.groupDiff.avgConfidence.meanDiff = analysis.group1.avgConfidence.groupMean - analysis.group2.avgConfidence.groupMean;
+
+ % Run specified statistical test on all non-hierarchical metrics
+ if strcmp(analysis.groupDiff.test,'wilcoxon') == 1
+ analysis.groupDiff.testType = 'Wilcoxon rank sum test';
+ [analysis.groupDiff.filterNum.p,analysis.groupDiff.filterNum.h,analysis.groupDiff.filterNum.stats] = ranksum(analysis.group1.filterNum.singleSubject,analysis.group2.filterNum.singleSubject);
+ [analysis.groupDiff.accuracy.p,analysis.groupDiff.accuracy.h,analysis.groupDiff.accuracy.stats] = ranksum(analysis.group1.accuracy.singleSubject,analysis.group2.accuracy.singleSubject);
+ [analysis.groupDiff.d1.p,analysis.groupDiff.d1.h,analysis.groupDiff.d1.stats] = ranksum(analysis.group1.d1.singleSubject,analysis.group2.d1.singleSubject);
+ [analysis.groupDiff.c1.p,analysis.groupDiff.c1.h,analysis.groupDiff.c1.stats] = ranksum(analysis.group1.c1.singleSubject,analysis.group2.c1.singleSubject);
+ [analysis.groupDiff.avgConfidence.p,analysis.groupDiff.avgConfidence.h,analysis.groupDiff.avgConfidence.stats] = ranksum(analysis.group1.avgConfidence.singleSubject,analysis.group2.avgConfidence.singleSubject);
+ elseif strcmp(analysis.groupDiff.test,'ttest') == 1
+ analysis.groupDiff.testType = 'Unpaired T-test';
+ [analysis.groupDiff.filterNum.h,analysis.groupDiff.filterNum.p,analysis.groupDiff.filterNum.ci,analysis.groupDiff.filterNum.stats] = ttest2(analysis.group1.filterNum.singleSubject,analysis.group2.filterNum.singleSubject);
+ [analysis.groupDiff.accuracy.h,analysis.groupDiff.accuracy.p,analysis.groupDiff.accuracy.ci,analysis.groupDiff.accuracy.stats] = ttest2(analysis.group1.accuracy.singleSubject,analysis.group2.accuracy.singleSubject);
+ [analysis.groupDiff.d1.h,analysis.groupDiff.d1.p,analysis.groupDiff.d1.ci,analysis.groupDiff.d1.stats] = ttest2(analysis.group1.d1.singleSubject,analysis.group2.d1.singleSubject);
+ [analysis.groupDiff.c1.h,analysis.groupDiff.c1.p,analysis.groupDiff.c1.ci,analysis.groupDiff.c1.stats] = ttest2(analysis.group1.c1.singleSubject,analysis.group2.c1.singleSubject);
+ [analysis.groupDiff.avgConfidence.h,analysis.groupDiff.avgConfidence.p,analysis.groupDiff.avgConfidence.ci,analysis.groupDiff.avgConfidence.stats] = ttest2(analysis.group1.avgConfidence.singleSubject,analysis.group2.avgConfidence.singleSubject);
+ end
+
+ % Save results
+ save(resultsFile, 'analysis'); % Save results
+
+ % Create Figure to display results
+ figure
+ set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 0.6 0.6]);
+ labels = ['Group 1'; 'Group 2'];
+ % Plot Type 1 metrics on top line
+ ax1 = subplot(2,4,1);
+ bar(ax1, [analysis.group1.filterNum.groupMean; analysis.group2.filterNum.groupMean]);
+ hold on
+ errorbar(ax1, [analysis.group1.filterNum.groupMean; analysis.group2.filterNum.groupMean], [std(analysis.group1.filterNum.singleSubject), std(analysis.group2.filterNum.singleSubject)], 'o', 'marker', 'none', 'linewidth', 1, 'Color','k');
+ set(gca,'XTickLabel',labels);
+ set(gca,'XTickLabelRotation',90)
+ if analysis.groupDiff.filterNum.h == 0
+ title('FILTER NUMBER: NON-SIG DIFF')
+ elseif analysis.groupDiff.filterNum.h > 0
+ title('FILTER NUMBER: SIG DIFF')
+ end
+ hold off
+ ax2 = subplot(2,4,2);
+ bar(ax2, [analysis.group1.accuracy.groupMean; analysis.group2.accuracy.groupMean]);
+ hold on
+ errorbar(ax2, [analysis.group1.accuracy.groupMean; analysis.group2.accuracy.groupMean], [std(analysis.group1.accuracy.singleSubject), std(analysis.group2.accuracy.singleSubject)], 'o', 'marker', 'none', 'linewidth', 1, 'Color','k');
+ set(gca,'XTickLabel',labels);
+ set(gca,'XTickLabelRotation',90)
+ if analysis.groupDiff.accuracy.h == 0
+ title('ACCURACY: NON-SIG DIFF')
+ elseif analysis.groupDiff.accuracy.h > 0
+ title('ACCURACY: SIG DIFF')
+ end
+ ax3 = subplot(2,4,3);
+ bar(ax3, [analysis.group1.d1.groupMean; analysis.group2.d1.groupMean]);
+ hold on
+ errorbar(ax3, [analysis.group1.d1.groupMean; analysis.group2.d1.groupMean], [std(analysis.group1.d1.singleSubject), std(analysis.group2.d1.singleSubject)], 'o', 'marker', 'none', 'linewidth', 1, 'Color','k');
+ set(gca,'XTickLabel',labels);
+ set(gca,'XTickLabelRotation',90)
+ if analysis.groupDiff.d1.h == 0
+ title('d'': NON-SIG DIFF')
+ elseif analysis.groupDiff.d1.h > 0
+ title('d'': SIG DIFF')
+ end
+ hold off
+ ax4 = subplot(2,4,4);
+ bar(ax4, [analysis.group1.c1.groupMean; analysis.group2.c1.groupMean]);
+ hold on
+ errorbar(ax4, [analysis.group1.c1.groupMean; analysis.group2.c1.groupMean], [std(analysis.group1.c1.singleSubject), std(analysis.group2.c1.singleSubject)], 'o', 'marker', 'none', 'linewidth', 1, 'Color','k');
+ set(gca,'XTickLabel',labels);
+ set(gca,'XTickLabelRotation',90)
+ if analysis.groupDiff.c1.h == 0
+ title('CRITERION: NON-SIG DIFF')
+ elseif analysis.groupDiff.c1.h > 0
+ title('CRITERION: SIG DIFF')
+ end
+ hold off
+ % Plot group Mratio and the difference
+ ax5 = subplot(2,4,5);
+ histogram(ax5, exp(analysis.group1.fit.mcmc.samples.mu_logMratio))
+ xlim([0 2])
+ xlabel('MRatio');
+ ylabel('Sample count');
+ hold on
+ histogram(ax5, exp(analysis.group2.fit.mcmc.samples.mu_logMratio))
+ hold off
+ lgd = legend('Group 1', 'Group 2', 'Location', 'northeast');
+ lgd.FontSize = 10;
+ if (analysis.groupDiff.Mratio.hdi(1) > 0 && analysis.groupDiff.Mratio.hdi(2) > 0) || (analysis.groupDiff.Mratio.hdi(1) < 0 && analysis.groupDiff.Mratio.hdi(2) < 0)
+ title('MRATIO: SIG DIFF')
+ else
+ title('MRATIO: NON-SIG DIFF')
+ end
+ ax6 = subplot(2,4,6);
+ histogram(ax6, analysis.group1.fit.mcmc.samples.mu_logMratio)
+ xlabel('log(MRatio)');
+ ylabel('Sample count');
+ hold on
+ histogram(ax6, analysis.group2.fit.mcmc.samples.mu_logMratio)
+ hold off
+ lgd = legend('Group 1', 'Group 2', 'Location', 'northwest');
+ lgd.FontSize = 10;
+ if (analysis.groupDiff.log_Mratio.hdi(1) > 0 && analysis.groupDiff.log_Mratio.hdi(2) > 0) || (analysis.groupDiff.log_Mratio.hdi(1) < 0 && analysis.groupDiff.log_Mratio.hdi(2) < 0)
+ title('LOG(MRATIO): SIG DIFF')
+ else
+ title('LOG(MRATIO): NON-SIG DIFF')
+ end
+ ax7 = subplot(2,4,7);
+ histogram(ax7, analysis.groupDiff.log_Mratio.sampleDiff)
+ xlabel('log(MRatio)');
+ ylabel('Sample count');
+ if (analysis.groupDiff.log_Mratio.hdi(1) > 0 && analysis.groupDiff.log_Mratio.hdi(2) > 0) || (analysis.groupDiff.log_Mratio.hdi(1) < 0 && analysis.groupDiff.log_Mratio.hdi(2) < 0)
+ title('LOG(MRATIO) DIFF: SIG DIFF')
+ else
+ title('LOG(MRATIO) DIFF: NON-SIG DIFF')
+ end
+ hold on
+ ln2 = line([analysis.groupDiff.log_Mratio.hdi(1) analysis.groupDiff.log_Mratio.hdi(1)], [0 1800]);
+ ln2.Color = 'r';
+ ln2.LineWidth = 1.5;
+ ln2.LineStyle = '--';
+ ln2 = line([analysis.groupDiff.log_Mratio.hdi(2) analysis.groupDiff.log_Mratio.hdi(2)], [0 1800]);
+ ln2.Color = 'r';
+ ln2.LineWidth = 1.5;
+ ln2.LineStyle = '--';
+ hold off
+ % Plot average confidence
+ ax8 = subplot(2,4,8);
+ bar(ax8, [analysis.group1.avgConfidence.groupMean; analysis.group2.avgConfidence.groupMean]);
+ hold on
+ errorbar(ax8, [analysis.group1.avgConfidence.groupMean; analysis.group2.avgConfidence.groupMean], [std(analysis.group1.avgConfidence.singleSubject), std(analysis.group2.avgConfidence.singleSubject)], 'o', 'marker', 'none', 'linewidth', 1, 'Color','k');
+ set(gca,'XTickLabel',labels);
+ set(gca,'XTickLabelRotation',90)
+ if analysis.groupDiff.avgConfidence.h == 0
+ title('CONFIDENCE: NON-SIG DIFF')
+ elseif analysis.groupDiff.avgConfidence.h > 0
+ title('CONFIDENCE: SIG DIFF')
+ end
+ hold off
+
+ % Print figure
+ figureFile = fullfile('analysis', ['filter_task_analysis_', analysis.type]); % Create figure file name
+ print(figureFile, '-dtiff');
+
+ % Display completion message on screen
+ fprintf('\n________________________________________\n\n COMPLETED GROUP DIFFERENCE ANALYSIS\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n');
+ fprintf('\n DIFF MRATIO = %.2f (HDI: %.2f to %.2f)\n', analysis.groupDiff.Mratio.mean, analysis.groupDiff.Mratio.hdi(1), analysis.groupDiff.Mratio.hdi(2));
+ if (analysis.groupDiff.Mratio.hdi(1) > 0 && analysis.groupDiff.Mratio.hdi(2) > 0) || (analysis.groupDiff.Mratio.hdi(1) < 0 && analysis.groupDiff.Mratio.hdi(2) < 0)
+ fprintf('HDI DOES NOT SPAN ZERO: MRATIO DIFF SIG.\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n');
+ else
+ fprintf(' HDI SPANS ZERO: MRATIO DIFF NOT SIG.\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n');
+ end
+ fprintf('\n RESULTS CAN BE FOUND IN: \n FDT/analysis/\n________________________________________\n');
+
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RUN SESSION DIFFERENCE ANALYSIS (PAIRED) IF SPECIFIED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+if strcmp(analysis.type,'paired') == 1 % If session difference analysis specified
+
+ % For two-session difference analysis: Print message about groups being fit together --> t-tests possible on meta-d' metrics
+ fprintf('\nNOTE: Groups are fit using one hierarchical model.\nFrequentist statistics (such as t-tests) are possible on any metrics involving meta-d''.\nFrequentist statistics are applied to all type 1 metrics and average confidence values.\n');
+
+ % Specify parameters
+ analysis.sessionDiff.mcmc_params = fit_meta_d_params;
+
+ % Fit each group using a separate hierarchical Bayesian model
+ analysis.sessionDiff.fit = fit_meta_d_mcmc_groupCorr(analysis.trials2counts.nR_S1, analysis.trials2counts.nR_S2, analysis.sessionDiff.mcmc_params);
+
+ % Compute HDI of difference for log(meta-d'/d')
+ analysis.session1.logMratio.sessionMean = analysis.sessionDiff.fit.mu_logMratio(1);
+ analysis.session1.logMratio.singleSubject = log(analysis.sessionDiff.fit.Mratio(:,1));
+ analysis.session1.Mratio.sessionMean = exp(analysis.sessionDiff.fit.mu_logMratio(1));
+ analysis.session1.Mratio.singleSubject = analysis.sessionDiff.fit.Mratio(:,1);
+ analysis.session2.logMratio.sessionMean = analysis.sessionDiff.fit.mu_logMratio(2);
+ analysis.session2.logMratio.singleSubject = log(analysis.sessionDiff.fit.Mratio(:,2));
+ analysis.session2.Mratio.sessionMean = exp(analysis.sessionDiff.fit.mu_logMratio(2));
+ analysis.session2.Mratio.singleSubject = analysis.sessionDiff.fit.Mratio(:,2);
+ analysis.sessionDiff.log_Mratio.sampleDiff = analysis.sessionDiff.fit.mcmc.samples.mu_logMratio(:,:,1) - analysis.sessionDiff.fit.mcmc.samples.mu_logMratio(:,:,2);
+ analysis.sessionDiff.log_Mratio.mean = analysis.session1.logMratio.sessionMean - analysis.session2.logMratio.sessionMean;
+ analysis.sessionDiff.log_Mratio.hdi = calc_HDI(analysis.sessionDiff.log_Mratio.sampleDiff(:));
+ analysis.sessionDiff.Mratio.mean = exp(analysis.session1.logMratio.sessionMean) - exp(analysis.session2.logMratio.sessionMean);
+ analysis.sessionDiff.Mratio.hdi = calc_HDI((exp(analysis.sessionDiff.fit.mcmc.samples.mu_logMratio(:,:,1)) - exp(analysis.sessionDiff.fit.mcmc.samples.mu_logMratio(:,:,2))));
+
+ % Pull out session mean values for all non-hierarchical metrics
+ analysis.session1.d1.sessionMean = mean(analysis.sessionDiff.fit.d1(:,1));
+ analysis.session1.d1.singleSubject = analysis.sessionDiff.fit.d1(:,1);
+ analysis.session1.c1.sessionMean = mean(analysis.sessionDiff.fit.c1(:,1));
+ analysis.session1.c1.singleSubject = analysis.sessionDiff.fit.c1(:,1);
+ analysis.session2.d1.sessionMean = mean(analysis.sessionDiff.fit.d1(:,2));
+ analysis.session2.d1.singleSubject = analysis.sessionDiff.fit.d1(:,2);
+ analysis.session2.c1.sessionMean = mean(analysis.sessionDiff.fit.c1(:,2));
+ analysis.session2.c1.singleSubject = analysis.sessionDiff.fit.c1(:,2);
+
+ % Calculate average confidence, add filter number and accuracy to results for session 1
+ for n = 1:length(analysis.session1.data)
+ analysis.session1.avgConfidence.singleSubject(n) = mean(analysis.session1.data(n).results.thresholdTrials.confidence);
+ analysis.session1.filterNum.singleSubject(n) = mean(analysis.session1.data(n).results.thresholdTrials.filterNum);
+ analysis.session1.accuracy.singleSubject(n) = analysis.session1.data(n).results.thresholdTrials.accuracyTotal;
+ end
+ analysis.session1.avgConfidence.sessionMean = mean(analysis.session1.avgConfidence.singleSubject);
+ analysis.session1.filterNum.sessionMean = mean(analysis.session1.filterNum.singleSubject);
+ analysis.session1.accuracy.sessionMean = mean(analysis.session1.accuracy.singleSubject);
+
+ % Calculate average confidence, add filter number and accuracy to results for session 2
+ for n = 1:length(analysis.session2.data)
+ analysis.session2.avgConfidence.singleSubject(n) = mean(analysis.session2.data(n).results.thresholdTrials.confidence);
+ analysis.session2.filterNum.singleSubject(n) = mean(analysis.session2.data(n).results.thresholdTrials.filterNum);
+ analysis.session2.accuracy.singleSubject(n) = analysis.session2.data(n).results.thresholdTrials.accuracyTotal;
+ end
+ analysis.session2.avgConfidence.sessionMean = mean(analysis.session2.avgConfidence.singleSubject);
+ analysis.session2.filterNum.sessionMean = mean(analysis.session2.filterNum.singleSubject);
+ analysis.session2.accuracy.sessionMean = mean(analysis.session2.accuracy.singleSubject);
+
+ % Calculate session difference values for all non-hierarchical metrics
+ analysis.sessionDiff.filterNum.meanDiff = analysis.session1.filterNum.sessionMean - analysis.session2.filterNum.sessionMean;
+ analysis.sessionDiff.accuracy.meanDiff = analysis.session1.accuracy.sessionMean - analysis.session2.accuracy.sessionMean;
+ analysis.sessionDiff.d1.meanDiff = analysis.session1.d1.sessionMean - analysis.session2.d1.sessionMean;
+ analysis.sessionDiff.c1.meanDiff = analysis.session1.c1.sessionMean - analysis.session2.c1.sessionMean;
+ analysis.sessionDiff.avgConfidence.meanDiff = analysis.session1.avgConfidence.sessionMean - analysis.session2.avgConfidence.sessionMean;
+
+ % Run specified statistical test on all non-hierarchical metrics
+ if strcmp(analysis.sessionDiff.test,'wilcoxon') == 1
+ analysis.sessionDiff.testType = 'Wilcoxon signed rank test';
+ [analysis.sessionDiff.filterNum.p,analysis.sessionDiff.filterNum.h,analysis.sessionDiff.filterNum.stats] = signrank(analysis.session1.filterNum.singleSubject,analysis.session2.filterNum.singleSubject);
+ [analysis.sessionDiff.accuracy.p,analysis.sessionDiff.accuracy.h,analysis.sessionDiff.accuracy.stats] = signrank(analysis.session1.accuracy.singleSubject,analysis.session2.accuracy.singleSubject);
+ [analysis.sessionDiff.d1.p,analysis.sessionDiff.d1.h,analysis.sessionDiff.d1.stats] = signrank(analysis.session1.d1.singleSubject,analysis.session2.d1.singleSubject);
+ [analysis.sessionDiff.c1.p,analysis.sessionDiff.c1.h,analysis.sessionDiff.c1.stats] = signrank(analysis.session1.c1.singleSubject,analysis.session2.c1.singleSubject);
+ [analysis.sessionDiff.avgConfidence.p,analysis.sessionDiff.avgConfidence.h,analysis.sessionDiff.avgConfidence.stats] = signrank(analysis.session1.avgConfidence.singleSubject,analysis.session2.avgConfidence.singleSubject);
+ elseif strcmp(analysis.sessionDiff.test,'ttest') == 1
+ analysis.sessionDiff.testType = 'Paired T-test';
+ [analysis.sessionDiff.filterNum.h,analysis.sessionDiff.filterNum.p,analysis.sessionDiff.filterNum.ci,analysis.sessionDiff.filterNum.stats] = ttest(analysis.session1.filterNum.singleSubject,analysis.session2.filterNum.singleSubject);
+ [analysis.sessionDiff.accuracy.h,analysis.sessionDiff.accuracy.p,analysis.sessionDiff.accuracy.ci,analysis.sessionDiff.accuracy.stats] = ttest(analysis.session1.accuracy.singleSubject,analysis.session2.accuracy.singleSubject);
+ [analysis.sessionDiff.d1.h,analysis.sessionDiff.d1.p,analysis.sessionDiff.d1.ci,analysis.sessionDiff.d1.stats] = ttest(analysis.session1.d1.singleSubject,analysis.session2.d1.singleSubject);
+ [analysis.sessionDiff.c1.h,analysis.sessionDiff.c1.p,analysis.sessionDiff.c1.ci,analysis.sessionDiff.c1.stats] = ttest(analysis.session1.c1.singleSubject,analysis.session2.c1.singleSubject);
+ [analysis.sessionDiff.avgConfidence.h,analysis.sessionDiff.avgConfidence.p,analysis.sessionDiff.avgConfidence.ci,analysis.sessionDiff.avgConfidence.stats] = ttest(analysis.session1.avgConfidence.singleSubject,analysis.session2.avgConfidence.singleSubject);
+ end
+
+ % Save results
+ save(resultsFile, 'analysis'); % Save results
+
+ % Create Figure to display results
+ figure
+ set(gcf, 'Units', 'Normalized', 'OuterPosition', [0 0 0.6 0.6]);
+ labels = ['Session 1'; 'Session 2'];
+ % Plot Type 1 metrics on top line
+ ax1 = subplot(2,4,1);
+ bar(ax1, [analysis.session1.filterNum.sessionMean; analysis.session2.filterNum.sessionMean]);
+ hold on
+ errorbar(ax1, [analysis.session1.filterNum.sessionMean; analysis.session2.filterNum.sessionMean], [std(analysis.session1.filterNum.singleSubject), std(analysis.session2.filterNum.singleSubject)], 'o', 'marker', 'none', 'linewidth', 1, 'Color','k');
+ set(gca,'XTickLabel',labels);
+ set(gca,'XTickLabelRotation',90)
+ if analysis.sessionDiff.filterNum.h == 0
+ title('FILTER NUMBER: NON-SIG DIFF')
+ elseif analysis.sessionDiff.filterNum.h > 0
+ title('FILTER NUMBER: SIG DIFF')
+ end
+ hold off
+ ax2 = subplot(2,4,2);
+ bar(ax2, [analysis.session1.accuracy.sessionMean; analysis.session2.accuracy.sessionMean]);
+ hold on
+ errorbar(ax2, [analysis.session1.accuracy.sessionMean; analysis.session2.accuracy.sessionMean], [std(analysis.session1.accuracy.singleSubject), std(analysis.session2.accuracy.singleSubject)], 'o', 'marker', 'none', 'linewidth', 1, 'Color','k');
+ set(gca,'XTickLabel',labels);
+ set(gca,'XTickLabelRotation',90)
+ if analysis.sessionDiff.accuracy.h == 0
+ title('ACCURACY: NON-SIG DIFF')
+ elseif analysis.sessionDiff.accuracy.h > 0
+ title('ACCURACY: SIG DIFF')
+ end
+ ax3 = subplot(2,4,3);
+ bar(ax3, [analysis.session1.d1.sessionMean; analysis.session2.d1.sessionMean]);
+ hold on
+ errorbar(ax3, [analysis.session1.d1.sessionMean; analysis.session2.d1.sessionMean], [std(analysis.session1.d1.singleSubject), std(analysis.session2.d1.singleSubject)], 'o', 'marker', 'none', 'linewidth', 1, 'Color','k');
+ set(gca,'XTickLabel',labels);
+ set(gca,'XTickLabelRotation',90)
+ if analysis.sessionDiff.d1.h == 0
+ title('d'': NON-SIG DIFF')
+ elseif analysis.sessionDiff.d1.h > 0
+ title('d'': SIG DIFF')
+ end
+ hold off
+ ax4 = subplot(2,4,4);
+ bar(ax4, [analysis.session1.c1.sessionMean; analysis.session2.c1.sessionMean]);
+ hold on
+ errorbar(ax4, [analysis.session1.c1.sessionMean; analysis.session2.c1.sessionMean], [std(analysis.session1.c1.singleSubject), std(analysis.session2.c1.singleSubject)], 'o', 'marker', 'none', 'linewidth', 1, 'Color','k');
+ set(gca,'XTickLabel',labels);
+ set(gca,'XTickLabelRotation',90)
+ if analysis.sessionDiff.c1.h == 0
+ title('CRITERION: NON-SIG DIFF')
+ elseif analysis.sessionDiff.c1.h > 0
+ title('CRITERION: SIG DIFF')
+ end
+ hold off
+ % Plot session Mratio and the difference
+ ax5 = subplot(2,4,5);
+ histogram(ax5, exp(analysis.sessionDiff.fit.mcmc.samples.mu_logMratio(:,:,1)))
+ xlim([0 2])
+ xlabel('MRatio');
+ ylabel('Sample count');
+ hold on
+ histogram(ax5, exp(analysis.sessionDiff.fit.mcmc.samples.mu_logMratio(:,:,2)))
+ hold off
+ lgd = legend('Session 1', 'Session 2', 'Location', 'northeast');
+ lgd.FontSize = 10;
+ if (analysis.sessionDiff.Mratio.hdi(1) > 0 && analysis.sessionDiff.Mratio.hdi(2) > 0) || (analysis.sessionDiff.Mratio.hdi(1) < 0 && analysis.sessionDiff.Mratio.hdi(2) < 0)
+ title('MRATIO: SIG DIFF')
+ else
+ title('MRATIO: NON-SIG DIFF')
+ end
+ ax6 = subplot(2,4,6);
+ histogram(ax6, analysis.sessionDiff.fit.mcmc.samples.mu_logMratio(:,:,1))
+ xlabel('log(MRatio)');
+ ylabel('Sample count');
+ hold on
+ histogram(ax6, analysis.sessionDiff.fit.mcmc.samples.mu_logMratio(:,:,2))
+ hold off
+ lgd = legend('Session 1', 'Session 2', 'Location', 'northwest');
+ lgd.FontSize = 10;
+ if (analysis.sessionDiff.log_Mratio.hdi(1) > 0 && analysis.sessionDiff.log_Mratio.hdi(2) > 0) || (analysis.sessionDiff.log_Mratio.hdi(1) < 0 && analysis.sessionDiff.log_Mratio.hdi(2) < 0)
+ title('LOG(MRATIO): SIG DIFF')
+ else
+ title('LOG(MRATIO): NON-SIG DIFF')
+ end
+ ax7 = subplot(2,4,7);
+ histogram(ax7, analysis.sessionDiff.log_Mratio.sampleDiff)
+ xlabel('log(MRatio)');
+ ylabel('Sample count');
+ if (analysis.sessionDiff.log_Mratio.hdi(1) > 0 && analysis.sessionDiff.log_Mratio.hdi(2) > 0) || (analysis.sessionDiff.log_Mratio.hdi(1) < 0 && analysis.sessionDiff.log_Mratio.hdi(2) < 0)
+ title('LOG(MRATIO) DIFF: SIG DIFF')
+ else
+ title('LOG(MRATIO) DIFF: NON-SIG DIFF')
+ end
+ hold on
+ ln2 = line([analysis.sessionDiff.log_Mratio.hdi(1) analysis.sessionDiff.log_Mratio.hdi(1)], [0 1800]);
+ ln2.Color = 'r';
+ ln2.LineWidth = 1.5;
+ ln2.LineStyle = '--';
+ ln2 = line([analysis.sessionDiff.log_Mratio.hdi(2) analysis.sessionDiff.log_Mratio.hdi(2)], [0 1800]);
+ ln2.Color = 'r';
+ ln2.LineWidth = 1.5;
+ ln2.LineStyle = '--';
+ hold off
+ % Plot average confidence
+ ax8 = subplot(2,4,8);
+ bar(ax8, [analysis.session1.avgConfidence.sessionMean; analysis.session2.avgConfidence.sessionMean]);
+ hold on
+ errorbar(ax8, [analysis.session1.avgConfidence.sessionMean; analysis.session2.avgConfidence.sessionMean], [std(analysis.session1.avgConfidence.singleSubject), std(analysis.session2.avgConfidence.singleSubject)], 'o', 'marker', 'none', 'linewidth', 1, 'Color','k');
+ set(gca,'XTickLabel',labels);
+ set(gca,'XTickLabelRotation',90)
+ if analysis.sessionDiff.avgConfidence.h == 0
+ title('CONFIDENCE: NON-SIG DIFF')
+ elseif analysis.sessionDiff.avgConfidence.h > 0
+ title('CONFIDENCE: SIG DIFF')
+ end
+ hold off
+
+ % Print figure
+ figureFile = fullfile('analysis', ['filter_task_analysis_', analysis.type]); % Create figure file name
+ print(figureFile, '-dtiff');
+
+ % Display completion message on screen
+ fprintf('\n________________________________________\n\n COMPLETED SESSION DIFFERENCE ANALYSIS\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n');
+ fprintf('\n DIFF MRATIO = %.2f (HDI: %.2f to %.2f)\n', analysis.sessionDiff.Mratio.mean, analysis.sessionDiff.Mratio.hdi(1), analysis.sessionDiff.Mratio.hdi(2));
+ if (analysis.sessionDiff.Mratio.hdi(1) > 0 && analysis.sessionDiff.Mratio.hdi(2) > 0) || (analysis.sessionDiff.Mratio.hdi(1) < 0 && analysis.sessionDiff.Mratio.hdi(2) < 0)
+ fprintf('HDI DOES NOT SPAN ZERO: MRATIO DIFF SIG.\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n');
+ else
+ fprintf(' HDI SPANS ZERO: MRATIO DIFF NOT SIG.\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n');
+ end
+ fprintf('\n RESULTS CAN BE FOUND IN: \n FDT/analysis/\n________________________________________\n');
+
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RUN GROUP REGRESSION ANALYSIS IF SPECIFIED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+if strcmp(analysis.type,'regress') == 1 % If group regression analysis specified
+
+ % Specify parameters
+ analysis.groupRegression.mcmc_params = fit_meta_d_params;
+
+ % Standardise covariate
+ analysis.groupRegression.cov = zscore(analysis.covariate.data);
+
+ % Fit group data all at once
+ analysis.groupRegression.fit = fit_meta_d_mcmc_regression(analysis.trials2counts.nR_S1, analysis.trials2counts.nR_S2, analysis.groupRegression.cov, analysis.groupRegression.mcmc_params);
+
+ % Calculate log of Mratio for single subjects values
+ for n = 1:length(analysis.groupRegression.fit.Mratio)
+ analysis.groupRegression.log_Mratio.singleSubject(n) = log(analysis.groupRegression.fit.Mratio(n));
+ end
+
+ % Pull out group and single subject values
+ analysis.groupRegression.d1.groupMean = mean(analysis.groupRegression.fit.d1);
+ analysis.groupRegression.d1.singleSubject = analysis.groupRegression.fit.d1;
+ analysis.groupRegression.c1.groupMean = mean(analysis.groupRegression.fit.c1);
+ analysis.groupRegression.c1.singleSubject = analysis.groupRegression.fit.c1;
+ analysis.groupRegression.meta_d.groupMean = mean(analysis.groupRegression.fit.meta_d);
+ analysis.groupRegression.meta_d.singleSubject = analysis.groupRegression.fit.meta_d;
+ analysis.groupRegression.Mratio.groupMean = exp(analysis.groupRegression.fit.mu_logMratio);
+ analysis.groupRegression.Mratio.singleSubject = analysis.groupRegression.fit.Mratio;
+ analysis.groupRegression.Mratio.hdi = calc_HDI(exp(analysis.groupRegression.fit.mcmc.samples.mu_logMratio(:)));
+ analysis.groupRegression.log_Mratio.groupMean = analysis.groupRegression.fit.mu_logMratio;
+ analysis.groupRegression.log_Mratio.hdi = calc_HDI(analysis.groupRegression.fit.mcmc.samples.mu_logMratio(:));
+ analysis.groupRegression.beta1.groupMean = analysis.groupRegression.fit.mu_beta1;
+ analysis.groupRegression.beta1.hdi = calc_HDI(analysis.groupRegression.fit.mcmc.samples.mu_beta1(:));
+
+ % Calculate average confidence, add filter number and accuracy to analysis results
+ for n = 1:length(analysis.data)
+ analysis.groupRegression.avgConfidence.singleSubject(n) = mean(analysis.data(n).results.thresholdTrials.confidence);
+ analysis.groupRegression.filterNum.singleSubject(n) = mean(analysis.data(n).results.thresholdTrials.filterNum);
+ analysis.groupRegression.accuracy.singleSubject(n) = analysis.data(n).results.thresholdTrials.accuracyTotal;
+ end
+ analysis.groupRegression.avgConfidence.groupMean = mean(analysis.groupRegression.avgConfidence.singleSubject);
+ analysis.groupRegression.filterNum.groupMean = mean(analysis.groupRegression.filterNum.singleSubject);
+ analysis.groupRegression.accuracy.groupMean = mean(analysis.groupRegression.accuracy.singleSubject);
+
+ % Save results
+ save(resultsFile, 'analysis'); % Save results
+
+ % Display completion message on screen plus results
+ fprintf('\n________________________________________\n\n COMPLETED GROUP REGRESSION ANALYSIS\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n');
+ fprintf('\n GROUP MRATIO = %.2f (HDI: %.2f to %.2f)\n', analysis.groupRegression.Mratio.groupMean, analysis.groupRegression.Mratio.hdi(1), analysis.groupRegression.Mratio.hdi(2));
+ if analysis.groupRegression.Mratio.hdi(1) > 0
+ fprintf(' HDI DOES NOT SPAN ZERO: MRATIO SIG.\n');
+ else
+ fprintf(' HDI SPANS ZERO: MRATIO NOT SIG.\n');
+ end
+ fprintf('\n GROUP BETA = %.2f (HDI: %.2f to %.2f)\n', analysis.groupRegression.beta1.groupMean, analysis.groupRegression.beta1.hdi(1), analysis.groupRegression.beta1.hdi(2));
+ if analysis.groupRegression.beta1.hdi(1) > 0
+ fprintf(' HDI DOES NOT SPAN ZERO: BETA SIG.\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n');
+ else
+ fprintf(' HDI SPANS ZERO: BETA NOT SIG.\n _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _\n');
+ end
+ fprintf('\n RESULTS CAN BE FOUND IN: \n FDT/analysis/\n________________________________________\n');
+
+end
+
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
diff --git a/task/FDT/scripts/tapas_filter_detection_task.m b/task/FDT/scripts/tapas_filter_detection_task.m
new file mode 100644
index 00000000..69da2d4a
--- /dev/null
+++ b/task/FDT/scripts/tapas_filter_detection_task.m
@@ -0,0 +1,716 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%% BREATHING FILTER DETECTION TASK %%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% -------------------------------------------------------------------------
+% Author: Olivia Harrison
+% Created: 14/08/2018
+%
+% This software is free software: you can redistribute it and/or modify it
+% under the terms of the GNU General Public License as published by the
+% Free Software Foundation, either version 3 of the License, or (at your
+% option) any later version. This software is distributed in the hope that
+% it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+% warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+% GNU General Public License for more details: http://www.gnu.org/licenses/
+% -------------------------------------------------------------------------
+
+% THIS TASK AIMS TO DETERMINE:
+% 1) The number of breathing filters a participant is able to
+% discriminate from a dummy filter with 60 - 85% accuracy.
+% 2) The participant's discrimination metric (d') and bias criterion (c)
+% for reporting breathing resistance, using signal detection theory.
+% 3) The participant's metacognitive awareness and efficiency about their
+% performance, in the form of both average confidence over trials as
+% well as the metacognitive metric of meta-d'.
+
+% For full information on the set up of this task please see the
+% README.md file in the main task folder.
+
+% TO RUN THIS TASK:
+% 1) Copy the entire set of files to a location on your computer and add
+% folders and subfolders to your matlab path. Open the
+% tapas_filter_detection_task.m script and set the following
+% properties:
+% - Task type: results.setup.taskType = 1 or 2
+% 1 = Yes/No task (default)
+% 2 = 2IFC task
+% - Staircase type: results.setup.staircaseType = 1 or 2
+% 1 = Constant (default - threshold trials at constant filter)
+% 2 = Roving (filter number can change across threshold trials)
+% - Confidence scale: example (default)
+% results.setup.confidenceLower = 1
+% results.setup.confidenceUpper = 10
+% 2) Navigate to the main folder (FDT) in matlab, and type
+% tapas_filter_detection_task into the matlab terminal.
+% 3) Use the supplied instructions files to explain the task requirements
+% to the participant (see FDT/participant_instructions/
+% breathing_task_instructions_{english/german}.doc).
+% 4) Follow the matlab prompts to specify whether practice and
+% calibration trials should be run, and the number of trials you aim
+% to complete at threshold (minimum recommendation = 60 trials).
+% 5) Turn on a low level of pink noise (required) to reduce the influence
+% of any noise cues (see README.md).
+% 6) Follow the prompt instructions to complete the task. Only for the
+% very first practice trial (a dummy) is it explicitly explained to
+% the participant whether or not they will receive the load, and then
+% all following practice/calibration/main trials will continue on from
+% each other with no changes in instruction, nor with any feedback
+% given.
+% 7) Once the task is complete, ask the participant to fill in the
+% provided de-briefing questionnaire (see FDT/participant_debriefing/
+% debriefing_detection_{english/german}.doc).
+% This should help you to determine if any significant strategy switch
+% or learning occurred that would warrant post-hoc subject exclusion.
+%
+% Scripts are provided to both correct any input errors that may occur
+% (see scripts/tapas_filter_detection_task_fix.m) and to run the analysis
+% (see scripts/tapas_filter_detection_analysis.m) for all subjects.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SET UP OPTIONS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function tapas_filter_detection_task()
+
+% Specify the task type: 1 = Yes/No task, 2 = 2IFC task
+results.setup.taskType = 1; % Change this to change the task type
+if results.setup.taskType == 1
+ results.setup.taskDescription = 'YesNo';
+elseif results.setup.taskType == 2
+ results.setup.taskDescription = '2IFC';
+end
+
+% Specify the type of staircase:
+% 1 = Fixed staircase, where threshold trials remain at one filter level
+% 2 = Roving staircase, where threshold trials can cross filter levels
+results.setup.staircaseType = 1; % Change this to change the staircase type
+if results.setup.staircaseType == 1
+ results.setup.staircaseDescription = 'Constant';
+elseif results.setup.staircaseType == 2
+ results.setup.staircaseDescription = 'Roving';
+end
+
+% Specify confidence range =
+results.setup.confidenceLower = 1;
+results.setup.confidenceUpper = 10;
+
+% Set ideal accuracy band (inclusive) and error risk
+if results.setup.staircaseType == 1
+ results.setup.lowerBand = 0.65;
+ results.setup.upperBand = 0.80;
+ results.setup.errorRisk = 0.2;
+elseif results.setup.staircaseType == 2
+ results.setup.lowerBand = 0.70;
+ results.setup.upperBand = 0.75;
+ results.setup.errorRisk = 0.3;
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SET UP THE TASK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Close any open figures etc.
+close all
+
+% Check folder location is main FDT folder
+[~,dir_name] = fileparts(pwd);
+if ~strcmp(dir_name,'FDT')
+ error('Not currently in main FDT folder. Please move to FDT folder and try again.');
+end
+
+% Add relevant paths
+addpath('results');
+addpath('figures');
+
+% Display setup on screen
+fprintf('\n_______________________________________\n\n SET UP FILTER TASK\n_______________________________________\n');
+
+% Prompt for PPID
+results.PPID = input('PPID: ','s'); % Get subject ID
+resultsFile = fullfile('results', ['filter_task_results_', results.PPID]); % Create results file name
+% Check if PPID file already exists
+if isfile([resultsFile, '.mat']) == 1
+ error('PPID file already exists. Please choose a different PPID');
+end
+figureFile = fullfile('figures', ['filter_task_results_', results.PPID]); % Create figure file name
+
+% Specify number of trials, and whether practice and calibration should be run
+results.trials = input('NUMBER OF TRIALS = '); % Specify number of trials
+practice = input('RUN PRACTICE: (Yes = 1 No = 0)? '); % Specify whether practice trial(s) should be run
+calibration = input('RUN CALIBRATION: (Yes = 1 No = 0)? '); % Specify whether calibration trials should be run
+if calibration == 0
+ start_filters = input('STARTING FILTER NUMBER = '); % Specify which filter number to use if no calibration trials will be run
+end
+
+% Specify starting filter numbers for practice trials and calibration trials
+% --> Change these if required
+if results.setup.taskType == 1
+ results.practice.intensity = [0 7]; % Start practice at no filters and explicitly explain to participant, then move to 7 filters
+ currentIntensityNum = 0; % Start calibrations from the bottom up
+elseif results.setup.taskType == 2
+ results.practice.intensity = 7; % Start practice at 7 filters
+ currentIntensityNum = 1; % Start calibrations from the bottom up
+end
+
+% Specify prompt questions to ask during task
+if results.setup.taskType == 1
+ prompt_answer = 'ANSWER: (Yes = 1 No = 0) ';
+elseif results.setup.taskType == 2
+ prompt_answer = 'ANSWER: (1st = 1 2nd = 2) ';
+end
+prompt_confidence = sprintf('CONFIDENCE: (%d - %d) ', results.setup.confidenceLower, results.setup.confidenceUpper);
+prompt_confirm_trial = '-->CONFIRM TRIAL: (Yes = 1 No = 0) ';
+prompt_filters = 'ENTER FILTERS = ';
+
+% Display start on screen
+fprintf('_______________________________________\n_______________________________________\n\n FILTER DETECTION TASK\n_______________________________________\n_______________________________________\n');
+
+% Print reminder to turn on pink noise
+pinkNoise = 0;
+while pinkNoise ~= 1
+ try
+ pinkNoise = input('PINK NOISE ON? (Yes = 1)? '); % Prompt reminder about pink noise
+ if pinkNoise ~= 1
+ disp('CAUTION! Pink noise required')
+ end
+ catch
+ disp('CAUTION! Pink noise required')
+ end
+end
+fprintf('\nStarting task...\n_______________________________________\n');
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RUN PRACTICE TRIAL(S) IF SPECIFIED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Run practice trial(s) starting with a dummy and then 7 filters (specified above), can add filters if perception not reported
+if practice == 1
+ for n = 1:length(results.practice.intensity)
+ if n == 1 && results.setup.taskType == 1
+ fprintf('_______________________________________\nPRACTICE TRIAL: EXPLICIT DUMMY\n'); % Print the trial type
+ fprintf('\nFILTERS = DUMMY\n'); % Print the number of filters
+ else
+ fprintf('_______________________________________\nPRACTICE TRIAL: LARGE LOAD\n'); % Print the trial type
+ if results.setup.taskType == 1
+ fprintf('\nFILTERS (%d) = PRESENT\n', results.practice.intensity(n)); % Print the number of filters
+ elseif results.setup.taskType == 2
+ r = randi([1, 2], 1);
+ fprintf('\nFILTERS (%d) = INTERVAL %d\n', results.practice.intensity(n), r); % Print the number of filters and presentation interval
+ results.practice.interval(n) = r;
+ end
+ end
+ a = 0;
+ while a < 1
+ try
+ response = input(prompt_answer); % Input response from participant
+ if response == 1 || (response == 0 && results.setup.taskType == 1) || (response == 2 && results.setup.taskType == 2)
+ results.practice.response(n) = response;
+ b = 0;
+ while b < 1
+ try
+ confidence = input(prompt_confidence); % Ask for confidence
+ if confidence >= results.setup.confidenceLower && confidence <= results.setup.confidenceUpper
+ results.practice.confidence(n) = confidence;
+ c = 0;
+ while c < 1
+ try
+ confirm = input(prompt_confirm_trial); % Ask for confirmation
+ if results.setup.taskType == 1 && n == 1 && response == 1 && confirm == 1 % If they incorrectly reported the dummy trial, repeat the trial
+ fprintf('_______________________________________\n\n REPEAT PRACTICE DUMMY TRIAL\n_______________________________________\n');
+ fprintf('_______________________________________\nPRACTICE TRIAL: EXPLICIT DUMMY\n'); % Print the trial type
+ fprintf('\nFILTERS = DUMMY\n'); % Print the number of filters
+ c = 1; % Exit the confirm loop
+ b = 1; % Exit the confidence loop
+ elseif results.setup.taskType == 1 && n == 1 && response == 0 && confirm == 1 % If they correctly reported the dummy trial, move to the next trial
+ c = 1; % Exit the confirm loop
+ b = 1; % Exit the confidence loop
+ a = 1; % Exit the response loop
+ elseif (results.setup.taskType == 1 && n > 1 && response == 0 && confirm == 1) || (results.setup.taskType == 2 && response ~= results.practice.interval(n) && confirm == 1) % If they were incorrect on the filter practice trial, repeat the practice with one additional filter
+ c = 1; % Exit the confirm loop
+ b = 1; % Exit the confidence loop
+ results.practice.intensity(n) = results.practice.intensity(n) + 1; % Add a filter to the practice intensity
+ fprintf('_______________________________________\n\n ADD FILTER (NOW = %d FILTERS)\n + REPEAT PRACTICE TRIAL\n_______________________________________\n', results.practice.intensity(n));
+ fprintf('_______________________________________\nPRACTICE TRIAL: LARGE LOAD\n'); % Print the trial type
+ if results.setup.taskType == 1
+ fprintf('\nFILTERS (%d) = PRESENT\n', results.practice.intensity(n)); % Print the number of filters
+ elseif results.setup.taskType == 2
+ r = randi([1, 2], 1);
+ fprintf('\nFILTERS (%d) = INTERVAL %d\n', results.practice.intensity(n), r); % Print the number of filters and presentation interval
+ results.practice.interval(n) = r;
+ end
+ elseif (results.setup.taskType == 1 && n > 1 && response == 1 && confirm == 1) || (results.setup.taskType == 2 && response == results.practice.interval(n) && confirm == 1) % If they correctly reported the filter practice trial, move to the next trial
+ c = 1; % Exit the confirm loop
+ b = 1; % Exit the confidence loop
+ a = 1; % Exit the response loop
+ elseif confirm == 0
+ c = 1; % Exit the confirm loop
+ b = 1; % Exit the confidence loop
+ end
+ catch
+ end
+ end
+ end
+ catch
+ end
+ end
+ end
+ catch
+ end
+ end
+ end
+end
+
+% Save practice trials to results file
+save(resultsFile, 'results');
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RUN CALIBRATION TRIALS IF SPECIFIED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Run calibration check to find starting point, starting with number of filters specified above
+if calibration == 1
+ fprintf('_______________________________________\n_______________________________________\n\n START CALIBRATION TRIALS\n_______________________________________\n');
+ for n = 1:10 % Max of 10 counted calibration trials
+ results.calibration.trial(n) = n;
+ results.calibration.intensity(n) = currentIntensityNum; % Start calibration with filter number specified above
+ fprintf('_______________________________________\nCALIBRATION TRIAL %d\n',n); % Print the trial type and number
+ if results.calibration.intensity(n) == 0
+ fprintf('\nFILTERS = DUMMY\n'); % First calibration trial is a dummy --> No filters present
+ results.calibration.filters(n) = 0;
+ elseif results.calibration.intensity(n) > 0 && results.setup.taskType == 1
+ fprintf('\nFILTERS (%d) = PRESENT\n', currentIntensityNum); % Print number of filters for all other calibration trials with Yes/No
+ results.calibration.filters(n) = 1; % Filters present for all calibration trials (except dummy)
+ elseif results.calibration.intensity(n) > 0 && results.setup.taskType == 2
+ r = randi([1, 2], 1);
+ fprintf('\nFILTERS (%d) = INTERVAL %d\n', currentIntensityNum, r); % Print the number of filters and presentation interval for all calibration trials with 2IFC
+ results.calibration.interval(n) = r;
+ end
+ a = 0;
+ while a < 1
+ try
+ response = input(prompt_answer); % Input response from participant
+ if response == 1 || (response == 0 && results.setup.taskType == 1) || (response == 2 && results.setup.taskType == 2)
+ results.calibration.response(n) = response;
+ b = 0;
+ while b < 1
+ try
+ confidence = input(prompt_confidence); % Ask for confidence
+ if confidence >= results.setup.confidenceLower && confidence <= results.setup.confidenceUpper
+ results.calibration.confidence(n) = confidence;
+ c = 0;
+ while c < 1
+ try
+ confirm = input(prompt_confirm_trial); % Ask for confirmation
+ if confirm == 1 && response == 1 && results.calibration.intensity(n) == 0 % If they report something on the dummy, repeat the dummy trial
+ fprintf('_______________________________________\n\n REPEAT DUMMY TRIAL\n_______________________________________\n');
+ c = 1; % Exit the confirmation loop
+ b = 1; % Exit the confidence loop
+ elseif confirm == 1
+ c = 1; % Exit the confirmation loop
+ b = 1; % Exit the confidence loop
+ a = 1; % Exit the response loop
+ elseif confirm == 0
+ c = 1; % Exit the confirmation loop
+ b = 1; % Exit the confidence loop
+ end
+ catch
+ end
+ end
+ end
+ catch
+ end
+ end
+ end
+ catch
+ end
+ end
+
+ % Score trials if 2IFC task running
+ if results.setup.taskType == 2 && results.calibration.response(n) == results.calibration.interval(n)
+ results.calibration.score(n) = 1;
+ elseif results.setup.taskType == 2 && results.calibration.response(n) ~= results.calibration.interval(n)
+ results.calibration.score(n) = 0;
+ end
+
+ % Initially keep changing up every step until first report yes
+ if (results.setup.taskType == 1 && sum(results.calibration.response(1:n)) == 0) || (results.setup.taskType == 2 && sum(results.calibration.score(1:n)) == 0) % If no filter perception has been reported so far during calibration
+ currentIntensityNum = currentIntensityNum+1; % Add a filter
+ if currentIntensityNum == 1
+ fprintf('_______________________________________\n\n ADD ONE FILTER (NOW = %d FILTER)\n', currentIntensityNum);
+ else
+ fprintf('_______________________________________\n\n ADD ONE FILTER (NOW = %d FILTERS)\n', currentIntensityNum);
+ end
+ elseif (results.setup.taskType == 1 && results.calibration.response(n-1) == 0 && results.calibration.response(n) == 1) || (results.setup.taskType == 2 && results.calibration.score(n-1) == 0 && results.calibration.score(n) == 1) % When they first report feeling the resistance, add a filter and check for yes again
+ currentIntensityNum = currentIntensityNum+1; % Add a filter
+ if currentIntensityNum == 1
+ fprintf('_______________________________________\n\n ADD ONE FILTER (NOW = %d FILTER)\n', currentIntensityNum);
+ else
+ fprintf('_______________________________________\n\n ADD ONE FILTER (NOW = %d FILTERS)\n', currentIntensityNum);
+ end
+ elseif (results.setup.taskType == 1 && (results.calibration.response(n) + results.calibration.response(n-1)) == 2 && results.calibration.response(n-2) == 0) || (results.setup.taskType == 2 && (results.calibration.score(n) + results.calibration.score(n-1)) == 2 && results.calibration.score(n-2) == 0) % If two trials at ascending filters have 'yes' response
+ currentIntensityNum = currentIntensityNum-1; % Remove a filter for a confirmation trial
+ if currentIntensityNum == 1
+ fprintf('_______________________________________\n\n REMOVE ONE FILTER (NOW = %d FILTER)\n', currentIntensityNum);
+ else
+ fprintf('_______________________________________\n\n REMOVE ONE FILTER (NOW = %d FILTERS)\n', currentIntensityNum);
+ end
+ elseif (results.setup.taskType == 1 && (results.calibration.response(n-1) + results.calibration.response(n-2)) == 2) || (results.setup.taskType == 2 && (results.calibration.score(n-1) + results.calibration.score(n-2)) == 2) % Once two trials at ascending filters have a 'yes' response and confirmation trial conducted
+ if (results.setup.taskType == 1 && results.calibration.response(n) == 1) || (results.setup.taskType == 2 && results.calibration.score(n) == 1) % If confirmation trial at lower filter is 'yes' / correct
+ break; % Filter number stays at lower intensity, calibration complete
+ elseif (results.setup.taskType == 1 && results.calibration.response(n) == 0) || (results.setup.taskType == 2 && results.calibration.score(n) == 0) % If confirmation trial at lower filter is 'no' / incorrect
+ currentIntensityNum = currentIntensityNum + 1; % Filter number goes up one
+ break; % Calibration complete
+ end
+ elseif results.calibration.response(n) == 0 || results.calibration.score(n) == 0 % Otherwise, if they get one wrong
+ currentIntensityNum = currentIntensityNum+1; % Add a filter
+ if currentIntensityNum == 1
+ fprintf('_______________________________________\n\n ADD ONE FILTER (NOW = %d FILTER)\n', currentIntensityNum);
+ else
+ fprintf('_______________________________________\n\n ADD ONE FILTER (NOW = %d FILTERS)\n', currentIntensityNum);
+ end
+ end
+ end
+ fprintf('_______________________________________\n\n CALIBRATION COMPLETE\n');
+elseif calibration == 0
+ currentIntensityNum = start_filters;
+end
+
+% Save results so far
+save(resultsFile, 'results');
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% RUN MAIN TASK
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Set running counters
+n = 1;
+trialCount = 1;
+trialsInARow = 1;
+totalTrials = 1;
+
+% Create a dummy vector to shuffle every 10 trials for stimulus order
+if results.setup.taskType == 1
+ stimulus_order = [1 1 1 1 1 0 0 0 0 0];
+elseif results.setup.taskType == 2
+ stimulus_order = [1 1 1 1 1 2 2 2 2 2];
+end
+
+% Print starting value
+if currentIntensityNum == 1
+ fprintf('_______________________________________\n_______________________________________\n\n STARTING VALUE = %d FILTER\n_______________________________________\n',currentIntensityNum);
+else
+ fprintf('_______________________________________\n_______________________________________\n\n STARTING VALUE = %d FILTERS\n_______________________________________\n',currentIntensityNum);
+end
+
+% Run full set of trials, with adjustment after 10 trials as necessary
+while totalTrials <= results.trials % Run this loop until specified number of trials have been completed
+
+ % Specify trial number, trial count and intensity (number of filters)
+ results.allTrials.trial(n) = n;
+ results.allTrials.trialCount(n) = trialCount;
+ results.allTrials.intensity(n) = currentIntensityNum;
+
+ % Shuffle order of stimuli every 10 trials
+ if n == 1 || mod(n,10) == 0 % If n is 1 or a multiple of 10
+ if results.setup.taskType == 1
+ results.allTrials.filters(n:n+9) = stimulus_order(randperm(length(stimulus_order))); % Initiate filter presence / absence for the next 10 trials
+ elseif results.setup.taskType == 2
+ results.allTrials.interval(n:n+9) = stimulus_order(randperm(length(stimulus_order))); % Initiate next filter interval for the next 10 trials
+ end
+ end
+
+ % Present the stimulus and enter the participant's answers
+ fprintf('_______________________________________\nTRIAL %d\n',totalTrials); % Print the trial type and number
+ if results.setup.taskType == 1
+ filters = results.allTrials.filters(n);
+ if filters == 1
+ fprintf('\nFILTERS (%d) = PRESENT\n', currentIntensityNum); % Print the number of filters
+ elseif filters == 0
+ fprintf('\nFILTERS = ABSENT\n');
+ end
+ elseif results.setup.taskType == 2
+ interval = results.allTrials.interval(n);
+ fprintf('\nFILTERS (%d) = INTERVAL %d\n', currentIntensityNum, interval); % Print the number of filters and presentation interval
+ end
+ a = 0;
+ while a < 1
+ try
+ response = input(prompt_answer); % Input response from participant
+ if response == 1 || response == 0 && results.setup.taskType == 1 || response == 2 && results.setup.taskType == 2
+ results.allTrials.response(n) = response;
+ b = 0;
+ while b < 1
+ try
+ confidence = input(prompt_confidence); % Ask for confidence
+ if confidence >= results.setup.confidenceLower && confidence <= results.setup.confidenceUpper
+ results.allTrials.confidence(n) = confidence;
+ c = 0;
+ while c < 1
+ try
+ confirm = input(prompt_confirm_trial); % Ask for confirmation
+ if confirm == 1
+ c = 1; % Exit the confirmation loop
+ b = 1; % Exit the confidence loop
+ a = 1; % Exit the response loop
+ elseif confirm == 0
+ c = 1; % Exit the confirmation loop
+ b = 1; % Exit the confidence loop
+ end
+ catch
+ end
+ end
+ end
+ catch
+ end
+ end
+ end
+ catch
+ end
+ end
+ save(resultsFile, 'results');
+
+ % Score trials
+ if (results.setup.taskType == 1 && results.allTrials.filters(n) == results.allTrials.response(n)) || (results.setup.taskType == 2 && results.allTrials.interval(n) == results.allTrials.response(n))
+ results.allTrials.score(n) = 1;
+ elseif (results.setup.taskType == 1 && results.allTrials.filters(n) ~= results.allTrials.response(n)) || (results.setup.taskType == 2 && results.allTrials.interval(n) ~= results.allTrials.response(n))
+ results.allTrials.score(n) = 0;
+ end
+
+ % Pull out threshold trials that will be used for staircase
+ results.thresholdTrials.filterNum = currentIntensityNum;
+ results.thresholdTrials.trialNum(trialCount) = results.allTrials.trialCount(n);
+ results.thresholdTrials.response(trialCount) = results.allTrials.response(n);
+ results.thresholdTrials.confidence(trialCount) = results.allTrials.confidence(n);
+ results.thresholdTrials.score(trialCount) = results.allTrials.score(n);
+ if results.setup.taskType == 1
+ results.thresholdTrials.filters(trialCount) = results.allTrials.filters(n);
+ elseif results.setup.taskType == 2
+ results.thresholdTrials.interval(trialCount) = results.allTrials.interval(n);
+ end
+
+ % Calculate cumulative and running accuracy
+ results.thresholdTrials.cumulativeAccuracy(trialCount) = round(mean(results.thresholdTrials.score(1,1:trialCount)) * 100);
+ results.thresholdTrials.accuracyTotal = results.thresholdTrials.cumulativeAccuracy(trialCount);
+ results.allTrials.cumulativeAccuracy(n) = results.thresholdTrials.cumulativeAccuracy(trialCount);
+ results.allTrials.accuracyTotal(n) = round(mean(results.allTrials.score * 100));
+ if trialCount >= 10
+ results.thresholdTrials.runningAccuracy(trialCount) = round(mean(results.thresholdTrials.score((end-9):end)) * 100);
+ results.allTrials.runningAccuracy(n) = results.thresholdTrials.runningAccuracy(trialCount);
+ end
+
+ % Plot 10-trial running accuracy and cumulative accuracy after 10 trials
+ if (results.setup.staircaseType == 1 && trialCount > 10) || (results.setup.staircaseType == 2)
+ if results.setup.staircaseType == 1
+ x = area(results.thresholdTrials.cumulativeAccuracy, 'FaceAlpha', 0.4);
+ x.FaceColor = [0.5843 0.8157 0.9882]; % Make the shaded area light blue
+ hold on
+ title(sprintf('\nACCURACY FOR %d FILTERS\n', currentIntensityNum))
+ plot(results.thresholdTrials.trialNum, results.thresholdTrials.runningAccuracy, '-ok', 'MarkerFaceColor', 'k'); % Plot results for visualisation plot(x,y,'-o')
+ legend('Total accuracy', '10-trial accuracy')
+ xlim([10 results.trials])
+ elseif results.setup.staircaseType == 2
+ x = area(results.allTrials.accuracyTotal, 'FaceAlpha', 0.4);
+ x.FaceColor = [0.5843 0.8157 0.9882]; % Make the shaded area light blue
+ hold on
+ title('CUMULATIVE ACCURACY')
+ xlim([1 results.trials])
+ end
+ ylim([0 100])
+ ylabel('Percentage correct')
+ xlabel('Trial number')
+ print(figureFile, '-dtiff');
+ end
+
+ % Save interim results each loop
+ save(resultsFile, 'results');
+
+ % Calculate probability that underlying accuracy lies within accuracy boundaries
+ results.thresholdTrials.rightCount(trialCount) = sum(results.thresholdTrials.score(1:trialCount));
+ results.thresholdTrials.wrongCount(trialCount) = trialCount - results.thresholdTrials.rightCount(trialCount);
+ results.thresholdTrials.probBand(trialCount) = betacdf(results.setup.upperBand,2+results.thresholdTrials.rightCount(trialCount),1+results.thresholdTrials.wrongCount(trialCount)) - betacdf(results.setup.lowerBand,2+results.thresholdTrials.rightCount(trialCount),1+results.thresholdTrials.wrongCount(trialCount));
+ results.allTrials.rightCount(n) = results.thresholdTrials.rightCount(trialCount);
+ results.allTrials.wrongCount(n) = results.thresholdTrials.wrongCount(trialCount);
+ results.allTrials.probBand(n) = results.thresholdTrials.probBand(trialCount);
+
+ % Exit main loop here if number of trials is complete
+ if totalTrials == results.trials
+ % Clean up extra trials
+ if results.setup.taskType == 1
+ results.allTrials.filters = results.allTrials.filters(1:length(results.allTrials.trialCount));
+ elseif results.setup.taskType == 2
+ results.allTrials.interval = results.allTrials.interval(1:length(results.allTrials.trialCount));
+ end
+ % Clean up threshold trials if using a roving staircase
+ if results.setup.staircaseType == 2
+ results.runningTrials = results.thresholdTrials;
+ results.thresholdTrials = results.allTrials;
+ results.thresholdTrials.filterNum = results.allTrials.intensity;
+ results.thresholdTrials.accuracyTotal = round(mean(results.allTrials.score * 100));
+ end
+ break;
+ end
+
+ % Suggest changes based on probable accuracy (if staircase type is constant, only when trialCount is between 5 and 30 trials)
+ if trialCount >= 5 && trialsInARow >= 3 && (results.setup.staircaseType == 2 || (results.setup.staircaseType == 1 && trialCount < 30)) && ((results.setup.taskType == 1 && sum(results.allTrials.filters((n - trialsInARow + 1):n)) >= 1) || results.setup.taskType == 2) % If trialCount is between 5-30, with at least 3 trials in a row at the same filter intensity with at least one filter presented
+ if results.thresholdTrials.cumulativeAccuracy(trialCount) > 72.5 && results.thresholdTrials.probBand(trialCount) <= results.setup.errorRisk % If accuracy is above upper bound
+ suggestedIntensityNum = currentIntensityNum-1; % Make it harder
+ if currentIntensityNum == 1
+ fprintf('_______________________________________\n_______________________________________\n\n ACCURACY = %d PERCENT AT %d FILTER\n',results.thresholdTrials.cumulativeAccuracy(trialCount), currentIntensityNum);
+ elseif currentIntensityNum > 1
+ fprintf('_______________________________________\n_______________________________________\n\n ACCURACY = %d PERCENT AT %d FILTERS\n',results.thresholdTrials.cumulativeAccuracy(trialCount), currentIntensityNum);
+ end
+ if suggestedIntensityNum == 0 % Avoid zero, continue on 1 filter instead
+ fprintf('\n STAY ON 1 FILTER\n_______________________________________\n');
+ suggestedIntensityNum = 1;
+ else
+ fprintf('\n CHANGE TO %d FILTERS?\n\n',suggestedIntensityNum);
+ end
+ elseif results.thresholdTrials.cumulativeAccuracy(trialCount) < 72.5 && results.thresholdTrials.probBand(trialCount) <= results.setup.errorRisk % If accuracy is less than lower bound
+ suggestedIntensityNum = currentIntensityNum+1; % Make it easier
+ if currentIntensityNum == 1
+ fprintf('_______________________________________\n_______________________________________\n\n ACCURACY = %d PERCENT AT %d FILTER\n',results.thresholdTrials.cumulativeAccuracy(trialCount), currentIntensityNum);
+ elseif currentIntensityNum > 1
+ fprintf('_______________________________________\n_______________________________________\n\n ACCURACY = %d PERCENT AT %d FILTERS\n',results.thresholdTrials.cumulativeAccuracy(trialCount), currentIntensityNum);
+ end
+ fprintf('\n CHANGE TO %d FILTERS?\n\n',suggestedIntensityNum);
+ else
+ suggestedIntensityNum = currentIntensityNum;
+ newIntensityNum = currentIntensityNum;
+ end
+ else % If outside of staircase trials, keep intensity number
+ suggestedIntensityNum = currentIntensityNum;
+ end
+
+ % If staircase type is contant, add a check every 10 trials for 30 and above, and display accuracy above and below if cumulative accuracy has fallen outside 60-85%
+ if results.setup.staircaseType == 1 && trialCount >= 30 && (mod(trialCount,10) == 0) % If trial count is 30 or above, and a multiple of 10
+ fprintf('_______________________________________\n_______________________________________\n\n TRIAL COUNT = %d (%d FILTERS)\n',trialCount, currentIntensityNum);
+ fprintf('\n CURRENT ACCURACY = %d PERCENT\n',results.thresholdTrials.cumulativeAccuracy(trialCount));
+ if (results.thresholdTrials.cumulativeAccuracy(trialCount) > 85) || results.thresholdTrials.cumulativeAccuracy(trialCount) < 60
+ accuracyAbove = round(sum(results.allTrials.score(results.allTrials.intensity == (currentIntensityNum + 1)))/length(results.allTrials.score(results.allTrials.intensity == (currentIntensityNum + 1))) * 100);
+ accuracyBelow = round(sum(results.allTrials.score(results.allTrials.intensity == (currentIntensityNum - 1)))/length(results.allTrials.score(results.allTrials.intensity == (currentIntensityNum - 1))) * 100);
+ if isnan(accuracyAbove) == 1
+ fprintf('\n ACCURACY AT %d FILTERS = UNKNOWN\n',(currentIntensityNum + 1));
+ else
+ fprintf('\n ACCURACY AT %d FILTERS = %d PERCENT\n',(currentIntensityNum + 1), accuracyAbove);
+ end
+ if isnan(accuracyBelow) == 1
+ fprintf('\n ACCURACY AT %d FILTERS = UNKNOWN\n',(currentIntensityNum - 1));
+ else
+ fprintf('\n ACCURACY AT %d FILTERS = %d PERCENT\n',(currentIntensityNum - 1), accuracyBelow);
+ end
+ end
+ fprintf('_______________________________________\n\n CONTINUE WITH %d FILTERS?\n\n',currentIntensityNum);
+ suggestedIntensityNum = currentIntensityNum;
+ end
+
+ % Confirm filter changes and reset counters if needed after 5 trials
+ if trialCount >= 5 && ((suggestedIntensityNum ~= currentIntensityNum && (results.setup.staircaseType == 2 || (results.setup.staircaseType == 1 && trialCount < 30))) || (results.setup.staircaseType == 1 && trialCount >= 30 && mod(trialCount,10) == 0)) % If trialCount is greater than 5 and suggested intensity number changes
+ % Confirm new filter intensity
+ a = 0;
+ while a < 1
+ try
+ prompt_confirm_filters = sprintf('CONFIRM %d FILTERS: (Yes = 1 No = 0) ', suggestedIntensityNum);
+ confirm = input(prompt_confirm_filters);
+ if confirm == 1
+ newIntensityNum = suggestedIntensityNum;
+ a = 1;
+ elseif confirm == 0
+ b = 0;
+ while b < 1
+ try
+ newIntensityNum = input(prompt_filters);
+ if newIntensityNum <= 10 && newIntensityNum >= 1
+ prompt_confirm_filters = sprintf('CONFIRM %d FILTERS: (Yes = 1 No = 0) ', newIntensityNum);
+ reconfirm = input(prompt_confirm_filters);
+ if reconfirm == 1
+ b = 1;
+ a = 1;
+ elseif reconfirm == 0
+ b = 0;
+ end
+ end
+ catch
+ end
+ end
+ end
+ catch
+ end
+ end
+ fprintf('_______________________________________\n');
+
+ % Reset counters as needed (overall trial count reset only for constant staircase)
+ if newIntensityNum == currentIntensityNum % If filter number has not changed
+ trialCount = trialCount + 1; % Leave overall counter running
+ if suggestedIntensityNum ~= newIntensityNum % Reset trialsInARow if suggestion has been overridden
+ trialsInARow = 1;
+ else
+ trialsInARow = trialsInARow + 1;
+ end
+ elseif newIntensityNum ~= currentIntensityNum
+ currentIntensityNum = newIntensityNum; % Update filter number
+ field = 'thresholdTrials';
+ results = rmfield(results,field);
+ results.thresholdTrials.filterNum = currentIntensityNum;
+ results.thresholdTrials.trialNum = results.allTrials.trialCount(results.allTrials.intensity == results.thresholdTrials.filterNum);
+ results.thresholdTrials.response = results.allTrials.response(results.allTrials.intensity == results.thresholdTrials.filterNum);
+ results.thresholdTrials.confidence = results.allTrials.confidence(results.allTrials.intensity == results.thresholdTrials.filterNum);
+ results.thresholdTrials.score = results.allTrials.score(results.allTrials.intensity == results.thresholdTrials.filterNum);
+ if results.setup.taskType == 1
+ results.thresholdTrials.filters = results.allTrials.filters(results.allTrials.intensity == results.thresholdTrials.filterNum);
+ elseif results.setup.taskType == 2
+ results.thresholdTrials.interval = results.allTrials.interval(results.allTrials.intensity == results.thresholdTrials.filterNum);
+ end
+ if isempty(results.thresholdTrials.trialNum) == 1 % If no previous intensities recorded, start trials again from 1
+ trialCount = 1;
+ else
+ trialCount = results.thresholdTrials.trialNum(end) + 1; % Continue trial counter from previous trials at this intensity
+ results.thresholdTrials.cumulativeAccuracy = results.allTrials.cumulativeAccuracy(results.allTrials.intensity == results.thresholdTrials.filterNum);
+ if trialCount > 10
+ results.thresholdTrials.runningAccuracy = results.allTrials.runningAccuracy(results.allTrials.intensity == results.thresholdTrials.filterNum);
+ end
+ end
+ trialsInARow = 1; % Re-set trials in a row counter
+ if results.setup.staircaseType == 1
+ close; % Close the current figure
+ end
+ end
+ else
+ trialCount = trialCount + 1;
+ trialsInARow = trialsInARow + 1;
+ end
+
+ % Save interim results each loop
+ save(resultsFile, 'results');
+
+ % Update running total
+ n = n + 1;
+
+ % Update total trial counter
+ if results.setup.staircaseType == 1
+ totalTrials = trialCount;
+ elseif results.setup.staircaseType == 2
+ totalTrials = n;
+ end
+end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% SAVE OUT FINAL RESULTS FOR ANALYSIS
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% Save final results
+save(resultsFile, 'results');
+
+% Print outcome to screen
+fprintf('_______________________________________\n\n ACCURACY = %d PERCENT\n',results.thresholdTrials.accuracyTotal);
+fprintf('_______________________________________\n\n FILTER TASK COMPLETE\n_______________________________________\n');
+
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
diff --git a/task/FDT/scripts/tapas_filter_detection_task_fix.m b/task/FDT/scripts/tapas_filter_detection_task_fix.m
new file mode 100644
index 00000000..b216e702
--- /dev/null
+++ b/task/FDT/scripts/tapas_filter_detection_task_fix.m
@@ -0,0 +1,194 @@
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%% FIX FOR BREATHING FILTER DETECTION TASK %%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+% -------------------------------------------------------------------------
+% Author: Olivia Harrison
+% Created: 14/08/2018
+%
+% This software is free software: you can redistribute it and/or modify it
+% under the terms of the GNU General Public License as published by the
+% Free Software Foundation, either version 3 of the License, or (at your
+% option) any later version. This software is distributed in the hope that
+% it will be useful, but WITHOUT ANY WARRANTY; without even the implied
+% warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+% GNU General Public License for more details: http://www.gnu.org/licenses/
+% -------------------------------------------------------------------------
+
+% This function is provided to fix any input mistakes made whilst
+% performing the FDT, or for combining two files from the same participant
+% into one file for analysis.
+
+% To call the function, type tapas_filter_detection_task_fix into the
+% matlab terminal from the main FDT folder.
+
+% The use of this scripts is for the following scenarios:
+% 1) If any trials were incorrectly entered by the experimenter during
+% the task, use the option 'fix' when prompted by this function. This
+% will allow you to over-write specified trial results for either one
+% or both of the perception response given or the confidence score.
+% Call the function separately for each trial you wish to correct.
+% 3) If the task is exited for any reason, it can be restarted (without
+% practice and calibration trials), with filter number and remaining
+% trials specified by the experimenter. Once the task is complete, the
+% two sets of results can be combined using the option 'combine' when
+% prompted by this function. In this cade, the original data files
+% will be moved and saved into a directory called 'original_files'
+% within the results directory, and a new (combined) file will be
+% created.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CALL THE FUNCTION
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+function tapas_filter_detection_task_fix()
+
+% Display function on screen
+fprintf('\n______________________________________\n\n FIX FILTER TASK RESULTS\n______________________________________\n\n');
+
+% Check folder location is main FDT folder
+[~,dir_name] = fileparts(pwd);
+if ~strcmp(dir_name,'FDT')
+ error('Not currently in main FDT folder. Please move to FDT folder and try again.');
+end
+
+% Ask for option to fix results or combine trial sets
+option = input('Option (fix or combine) = ','s'); % Get option
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% FIX RESPONSES OR CONFIDENCE SCORES
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+try
+if strcmp(option,'fix') == 1
+ % Load results to alter
+ PPID = input('PPID = ','s'); % Get subject ID
+ resultsFile = fullfile('results', ['filter_task_results_', PPID, '.mat']); % Create results file name
+ load(resultsFile); % Load results
+ % Choose trials to override
+ a = 0;
+ while a < 1
+ changeTrialNum = input('Trial number to change = '); % Get trial number
+ if results.setup.taskType == 1 && results.thresholdTrials.filters(changeTrialNum) == 1
+ fprintf('______________________________________\n\nFilters were present for trial %d\n______________________________________\n\n', changeTrialNum);
+ elseif results.setup.taskType == 1 && results.thresholdTrials.filters(changeTrialNum) == 0
+ fprintf('______________________________________\n\nFilters were absent for trial %d\n______________________________________\n\n', changeTrialNum);
+ elseif results.setup.taskType == 2
+ fprintf('______________________________________\n\nFilters were presented in interval %d for trial %d\n______________________________________\n\n', results.thresholdTrials.interval(changeTrialNum), changeTrialNum);
+ end
+ changeResponse = input('Response = '); % Change response
+ changeConfidence = input('Confidence = '); % Change confidence score
+ % Ask for confirmation
+ confirm = input('Confirm (Yes = 1, No = 0) = '); % Get confirmation
+ if confirm == 1
+ results.thresholdTrials.response(changeTrialNum) = changeResponse;
+ results.thresholdTrials.confidence(changeTrialNum) = changeConfidence;
+ results.thresholdTrials.adjustmentDateAndTime = datestr(now, 'yyyy_mm_dd_HHMMSS'); % Mark the date the results were manually adjusted
+ % Re-score replaced trials
+ if (results.setup.taskType == 1 && results.thresholdTrials.filters(changeTrialNum) == results.thresholdTrials.response(changeTrialNum)) || (results.setup.taskType == 2 && results.thresholdTrials.interval(changeTrialNum) == results.thresholdTrials.response(changeTrialNum))
+ results.thresholdTrials.score(changeTrialNum) = 1;
+ elseif (results.setup.taskType == 1 && results.thresholdTrials.filters(changeTrialNum) ~= results.thresholdTrials.response(changeTrialNum)) || (results.setup.taskType == 2 && results.thresholdTrials.interval(changeTrialNum) ~= results.thresholdTrials.response(changeTrialNum))
+ results.thresholdTrials.score(changeTrialNum) = 0;
+ end
+ results.thresholdTrials.accuracyTotal = round(mean(results.thresholdTrials.score) * 100); % Re-calculate total accuracy
+ fprintf('______________________________________\n\nTrial %d adjusted\n______________________________________\n\n', changeTrialNum);
+ else
+ fprintf('______________________________________\n\nTrial %d NOT adjusted\n______________________________________\n\n', changeTrialNum);
+ end
+ % Ask for further trials
+ try
+ more = input('Change another trial (Yes = 1, No = 0) = '); % Get confirmation
+ catch
+ end
+ if more == 0
+ outputDir = exist(fullfile('results', 'original_files')); % Check if folder for old files already exists
+ if outputDir == 0
+ mkdir results original_files % Make the folder if it does not exist
+ elseif outputDir == 7
+ end
+ resultsFile_orig = fullfile('results', 'original_files', ['filter_task_results_', PPID, '_orig.mat']);
+ movefile(resultsFile, resultsFile_orig); % Save a copy of the original results
+ save(resultsFile, 'results'); % Save results
+ fprintf('______________________________________\n\nFINISHED!\n______________________________________\n\n');
+ a = 1;
+ end
+ end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% COMBINE THRESHOLD TRIALS IN TWO FILES TO CREATE NEW OUTPUT
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+elseif strcmp(option,'combine') == 1
+ % Load results to alter
+ file1 = input('File 1 PPID = ','s'); % Get subject ID for first file
+ resultsFile1 = load(fullfile('results', ['filter_task_results_', file1, '.mat'])); % Create and load results file 1
+ file2 = input('File 2 PPID = ','s'); % Get subject ID for second file
+ resultsFile2 = load(fullfile('results', ['filter_task_results_', file2, '.mat'])); % Create and load results file 2
+ output = input('Output PPID = ','s'); % Get output ID for final results
+ outputFile = fullfile('results', ['filter_task_results_', output, '.mat']); % Create output file and location
+ fprintf('\nConcatenating File 1 + File 2 into Output file \n');
+ % Make compatible with previous versions with set staircase
+ if ~isfield('staircaseType', resultsFile1.results.setup)
+ resultsFile1.results.setup.staircaseType = 1;
+ end
+ if ~isfield('staircaseType', resultsFile2.results.setup)
+ resultsFile1.results.setup.staircaseType = 1;
+ end
+ % Concatenate all variables
+ if (resultsFile1.results.setup.staircaseType == 1 && resultsFile2.results.setup.staircaseType == 1 && resultsFile1.results.thresholdTrials.filterNum == resultsFile2.results.thresholdTrials.filterNum) || (resultsFile1.results.setup.staircaseType == 2 && resultsFile2.results.setup.staircaseType == 2)
+ if resultsFile1.results.setup.staircaseType == 1 && resultsFile2.results.setup.staircaseType == 1
+ results.setup.staircaseType = 1;
+ results.thresholdTrials.filterNum = resultsFile1.results.thresholdTrials.filterNum;
+ elseif resultsFile1.results.setup.staircaseType == 2 && resultsFile1.results.setup.staircaseType == 2
+ results.setup.staircaseType = 2;
+ results.thresholdTrials.filterNum = [resultsFile1.results.thresholdTrials.filterNum, resultsFile2.results.thresholdTrials.filterNum];
+ end
+ file1Trials = length(resultsFile1.results.thresholdTrials.trialNum);
+ file2Trials = length(resultsFile2.results.thresholdTrials.trialNum);
+ results.thresholdTrials.trialNum(1:file1Trials) = resultsFile1.results.thresholdTrials.trialNum; % Load in first trials
+ results.thresholdTrials.trialNum((file1Trials + 1):(file1Trials + file2Trials)) = (resultsFile1.results.thresholdTrials.trialNum(end) + 1):(file1Trials+file2Trials); % Load in second trials
+ results.thresholdTrials.filters(1:file1Trials) = resultsFile1.results.thresholdTrials.filters; % Load in first trials
+ results.thresholdTrials.filters((file1Trials + 1):(file1Trials + file2Trials)) = resultsFile2.results.thresholdTrials.filters; % Load in second trials
+ results.thresholdTrials.response(1:file1Trials) = resultsFile1.results.thresholdTrials.response; % Load in first trials
+ results.thresholdTrials.response((file1Trials + 1):(file1Trials + file2Trials)) = resultsFile2.results.thresholdTrials.response; % Load in second trials
+ results.thresholdTrials.confidence(1:file1Trials) = resultsFile1.results.thresholdTrials.confidence; % Load in first trials
+ results.thresholdTrials.confidence((file1Trials + 1):(file1Trials + file2Trials)) = resultsFile2.results.thresholdTrials.confidence; % Load in second trials
+ results.thresholdTrials.score(1:file1Trials) = resultsFile1.results.thresholdTrials.score; % Load in first trials
+ results.thresholdTrials.score((file1Trials + 1):(file1Trials + file2Trials)) = resultsFile2.results.thresholdTrials.score; % Load in second trials
+ results.thresholdTrials.accuracyTotal = round(mean(results.thresholdTrials.score) * 100); % Re-calculate total accuracy
+ results.thresholdTrials.adjustmentDateAndTime = datestr(now, 'yyyy_mm_dd_HHMMSS'); % Mark the date the results were manually adjusted
+ outputDir = exist(fullfile('results', 'original_files')); % Check if folder for old files already exists
+ if outputDir == 0
+ mkdir results original_files % Make the folder if it does not exist
+ elseif outputDir == 7
+ end
+ resultsFile1SaveName = fullfile('results', 'original_files', ['filter_task_results_', file1, '_orig', '.mat']); % Create output file and location
+ resultsFile2SaveName = fullfile('results', 'original_files', ['filter_task_results_', file2, '_orig', '.mat']); % Create output file and location
+ save(resultsFile1SaveName, '-struct', 'resultsFile1'); % Save original results
+ save(resultsFile2SaveName, '-struct', 'resultsFile2'); % Save original results
+ save(outputFile, 'results'); % Save new results
+ delete (fullfile('results', ['filter_task_results_', file1, '.mat'])); % Remove old file from main results folder
+ delete (fullfile('results', ['filter_task_results_', file2, '.mat'])); % Remove old file from main results folder
+ else
+ fprintf('\nERROR: FILTER NUMBERS DO NOT MATCH\n______________________________________\n');
+ end
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% CATCH IF INCORRECT OPTION SPECIFIED
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+
+else
+ fprintf('\nOption does not exist, please try again.\n');
+end
+catch
+ fprintf('\n______________________________________\n')
+end
+
+
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\ No newline at end of file
diff --git a/task/FDT/scripts/tapas_fit_meta_d_MLE.m b/task/FDT/scripts/tapas_fit_meta_d_MLE.m
new file mode 100644
index 00000000..8fefd98d
--- /dev/null
+++ b/task/FDT/scripts/tapas_fit_meta_d_MLE.m
@@ -0,0 +1,436 @@
+
+% -------------------------------------------------------------------------
+% Downloaded 10.08.2018 from:
+% http://www.columbia.edu/~bsm2105/type2sdt/archive/index.html
+% Author: Brian Maniscalco
+% Contact: brian@psych.columbia.edu
+
+% 10.08.2018: OKH added calculation for type 1 c to the results
+
+% NOTE FROM WEBPAGE:
+% If you use this analysis file, please reference the Consciousness &
+% Cognition paper:
+% Maniscalco, B., & Lau, H. (2012). A signal detection
+% theoretic approach for estimating metacognitive sensitivity from
+% confidence ratings. Consciousness and Cognition, 21(1), 422–430.
+% doi:10.1016/j.concog.2011.09.021)
+% And the website:
+% http://www.columbia.edu/~bsm2105/type2sdt/archive/index.html
+% -------------------------------------------------------------------------
+
+function fit = tapas_fit_meta_d_MLE(nR_S1, nR_S2, s, fncdf, fninv)
+
+% fit = fit_meta_d_MLE(nR_S1, nR_S2, s, fncdf, fninv)
+%
+% Given data from an experiment where an observer discriminates between two
+% stimulus alternatives on every trial and provides confidence ratings,
+% provides a type 2 SDT analysis of the data.
+%
+% INPUTS
+%
+% * nR_S1, nR_S2
+% these are vectors containing the total number of responses in
+% each response category, conditional on presentation of S1 and S2.
+%
+% e.g. if nR_S1 = [100 50 20 10 5 1], then when stimulus S1 was
+% presented, the subject had the following response counts:
+% responded S1, rating=3 : 100 times
+% responded S1, rating=2 : 50 times
+% responded S1, rating=1 : 20 times
+% responded S2, rating=1 : 10 times
+% responded S2, rating=2 : 5 times
+% responded S2, rating=3 : 1 time
+%
+% The ordering of response / rating counts for S2 should be the same as it
+% is for S1. e.g. if nR_S2 = [3 7 8 12 27 89], then when stimulus S2 was
+% presented, the subject had the following response counts:
+% responded S1, rating=3 : 3 times
+% responded S1, rating=2 : 7 times
+% responded S1, rating=1 : 8 times
+% responded S2, rating=1 : 12 times
+% responded S2, rating=2 : 27 times
+% responded S2, rating=3 : 89 times
+%
+% N.B. if nR_S1 or nR_S2 contain zeros, this may interfere with estimation of
+% meta-d'.
+%
+% Some options for dealing with response cell counts containing zeros are:
+%
+% (1) Add a small adjustment factor, e.g. adj_f = 1/(length(nR_S1), to each
+% input vector:
+%
+% adj_f = 1/length(nR_S1);
+% nR_S1_adj = nR_S1 + adj_f;
+% nR_S2_adj = nR_S2 + adj_f;
+%
+% This is a generalization of the correction for similar estimation issues of
+% type 1 d' as recommended in
+%
+% Hautus, M. J. (1995). Corrections for extreme proportions and their biasing
+% effects on estimated values of d'. Behavior Research Methods, Instruments,
+% & Computers, 27, 46-51.
+%
+% When using this correction method, it is recommended to add the adjustment
+% factor to ALL data for all subjects, even for those subjects whose data is
+% not in need of such correction, in order to avoid biases in the analysis
+% (cf Snodgrass & Corwin, 1988).
+%
+% (2) Collapse across rating categories.
+%
+% e.g. if your data set has 4 possible confidence ratings such that length(nR_S1)==8,
+% defining new input vectors
+%
+% nR_S1_new = [sum(nR_S1(1:2)), sum(nR_S1(3:4)), sum(nR_S1(5:6)), sum(nR_S1(7:8))];
+% nR_S2_new = [sum(nR_S2(1:2)), sum(nR_S2(3:4)), sum(nR_S2(5:6)), sum(nR_S2(7:8))];
+%
+% might be sufficient to eliminate zeros from the input without using an adjustment.
+%
+% * s
+% this is the ratio of standard deviations for type 1 distributions, i.e.
+%
+% s = sd(S1) / sd(S2)
+%
+% if not specified, s is set to a default value of 1.
+% For most purposes, we recommend setting s = 1.
+% See http://www.columbia.edu/~bsm2105/type2sdt for further discussion.
+%
+% * fncdf
+% a function handle for the CDF of the type 1 distribution.
+% if not specified, fncdf defaults to @normcdf (i.e. CDF for normal
+% distribution)
+%
+% * fninv
+% a function handle for the inverse CDF of the type 1 distribution.
+% if not specified, fninv defaults to @norminv
+%
+% OUTPUT
+%
+% Output is packaged in the struct "fit."
+% In the following, let S1 and S2 represent the distributions of evidence
+% generated by stimulus classes S1 and S2.
+% Then the fields of "fit" are as follows:
+%
+% fit.d1 = mean(S2) - mean(S1), in room-mean-square(sd(S1),sd(S2)) units
+% fit.c1 = type 1 criterion
+% fit.s = sd(S1) / sd(S2)
+% fit.meta_d = meta-d' in RMS units
+% fit.M_diff = meta_da - da
+% fit.M_ratio = meta_da / da
+% fit.meta_c1 = type 1 criterion for meta-d' fit, RMS units
+% fit.t2ca_rS1 = type 2 criteria of "S1" responses for meta-d' fit, RMS units
+% fit.t2ca_rS2 = type 2 criteria of "S2" responses for meta-d' fit, RMS units
+%
+% fit.S1units = contains same parameters in sd(S1) units.
+% these may be of use since the data-fitting is conducted
+% using parameters specified in sd(S1) units.
+%
+% fit.logL = log likelihood of the data fit
+%
+% fit.est_HR2_rS1 = estimated (from meta-d' fit) type 2 hit rates for S1 responses
+% fit.obs_HR2_rS1 = actual type 2 hit rates for S1 responses
+% fit.est_FAR2_rS1 = estimated type 2 false alarm rates for S1 responses
+% fit.obs_FAR2_rS1 = actual type 2 false alarm rates for S1 responses
+%
+% fit.est_HR2_rS2 = estimated type 2 hit rates for S2 responses
+% fit.obs_HR2_rS2 = actual type 2 hit rates for S2 responses
+% fit.est_FAR2_rS2 = estimated type 2 false alarm rates for S2 responses
+% fit.obs_FAR2_rS2 = actual type 2 false alarm rates for S2 responses
+%
+% If there are N ratings, then there will be N-1 type 2 hit rates and false
+% alarm rates.
+
+% 2015/07/23 - fixed bug for output fit.meta_ca and fit.S1units.meta_c1.
+% - added comments to help section as well as a warning output
+% for nR_S1 or nR_S2 inputs containing zeros
+% 2014/10/14 - updated discussion of "s" input in the help section above.
+% 2010/09/07 - created
+
+
+%% parse inputs
+
+% check inputs
+if ~mod(length(nR_S1),2)==0, error('input arrays must have an even number of elements'); end
+if length(nR_S1)~=length(nR_S2), error('input arrays must have the same number of elements'); end
+
+if any(nR_S1 == 0) || any(nR_S2 == 0)
+ disp(' ')
+ disp('WARNING!!')
+ disp('---------')
+ disp('Your inputs')
+ disp(' ')
+ disp(['nR_S1 = [' num2str(nR_S1) ']'])
+ disp(['nR_S2 = [' num2str(nR_S2) ']'])
+ disp(' ')
+ disp('contain zeros! This may interfere with proper estimation of meta-d''.')
+ disp('See ''help fit_meta_d_MLE'' for more information.')
+ disp(' ')
+ disp(' ')
+end
+
+% assign input default values
+if ~exist('s','var') || isempty(s)
+ s = 1;
+end
+
+if ~exist('fncdf','var') || isempty(fncdf)
+ fncdf = @normcdf;
+end
+
+if ~exist('fninv','var') || isempty(fninv)
+ fninv = @norminv;
+end
+
+nRatings = length(nR_S1) / 2;
+nCriteria = 2*nRatings - 1;
+
+
+%% set up constraints for MLE estimation
+
+% parameters
+% meta-d' - 1
+% t2c - nCriteria-1
+
+A = [];
+b = [];
+
+% constrain type 2 criteria values,
+% such that t2c(i) is always <= t2c(i+1)
+% want t2c(i) <= t2c(i+1)
+% --> t2c(i+1) >= c(i) + 1e-5 (i.e. very small deviation from equality)
+% --> t2c(i) - t2c(i+1) <= -1e-5
+for i = 2 : nCriteria-1
+
+ A(end+1,[i i+1]) = [1 -1];
+ b(end+1) = -1e-5;
+
+end
+
+% lower bounds on parameters
+LB = [];
+LB = [LB -10]; % meta-d'
+LB = [LB -20*ones(1,(nCriteria-1)/2)]; % criteria lower than t1c
+LB = [LB zeros(1,(nCriteria-1)/2)]; % criteria higher than t1c
+
+% upper bounds on parameters
+UB = [];
+UB = [UB 10]; % meta-d'
+UB = [UB zeros(1,(nCriteria-1)/2)]; % criteria lower than t1c
+UB = [UB 20*ones(1,(nCriteria-1)/2)]; % criteria higher than t1c
+
+
+%% select constant criterion type
+
+constant_criterion = 'meta_d1 * (t1c1 / d1)'; % relative criterion
+
+
+%% set up initial guess at parameter values
+
+ratingHR = [];
+ratingFAR = [];
+for c = 2:nRatings*2
+ ratingHR(end+1) = sum(nR_S2(c:end)) / sum(nR_S2);
+ ratingFAR(end+1) = sum(nR_S1(c:end)) / sum(nR_S1);
+end
+
+t1_index = nRatings;
+t2_index = setdiff(1:2*nRatings-1, t1_index);
+
+d1 = (1/s) * fninv( ratingHR(t1_index) ) - fninv( ratingFAR(t1_index) );
+meta_d1 = d1;
+c = -0.5 .* (fninv(ratingHR(t1_index)) + fninv(ratingFAR(t1_index)));
+c1 = (-1/(1+s)) * ( fninv( ratingHR ) + fninv( ratingFAR ) );
+t1c1 = c1(t1_index);
+t2c1 = c1(t2_index);
+
+guess = [meta_d1 t2c1 - eval(constant_criterion)];
+
+
+
+%% find the best fit for type 2 hits and FAs
+
+% save fit_meta_d_MLE.mat nR_S1 nR_S2 t2FAR_rS2 t2HR_rS2 t2FAR_rS1 t2HR_rS1 nRatings t1c1 s d1 fncdf constant_criterion
+save fit_meta_d_MLE.mat nR_S1 nR_S2 nRatings d1 t1c1 s constant_criterion fncdf fninv
+
+op = optimset(@fmincon);
+op = optimset(op,'MaxFunEvals',100000);
+
+[x f] = fmincon(@fit_meta_d_logL,guess,A,b,[],[],LB,UB,[],op);
+
+meta_d1 = x(1);
+t2c1 = x(2:end) + eval(constant_criterion);
+logL = -f;
+
+
+%% data is fit, now to package it...
+
+%% find observed t2FAR and t2HR
+
+% I_nR and C_nR are rating trial counts for incorrect and correct trials
+% element i corresponds to # (in)correct w/ rating i
+I_nR_rS2 = nR_S1(nRatings+1:end);
+I_nR_rS1 = nR_S2(nRatings:-1:1);
+
+C_nR_rS2 = nR_S2(nRatings+1:end);
+C_nR_rS1 = nR_S1(nRatings:-1:1);
+
+for i = 2:nRatings
+ obs_FAR2_rS2(i-1) = sum( I_nR_rS2(i:end) ) / sum(I_nR_rS2);
+ obs_HR2_rS2(i-1) = sum( C_nR_rS2(i:end) ) / sum(C_nR_rS2);
+
+ obs_FAR2_rS1(i-1) = sum( I_nR_rS1(i:end) ) / sum(I_nR_rS1);
+ obs_HR2_rS1(i-1) = sum( C_nR_rS1(i:end) ) / sum(C_nR_rS1);
+end
+
+
+%% find estimated t2FAR and t2HR
+
+S1mu = -meta_d1/2; S1sd = 1;
+S2mu = meta_d1/2; S2sd = S1sd/s;
+
+mt1c1 = eval(constant_criterion);
+
+C_area_rS2 = 1-fncdf(mt1c1,S2mu,S2sd);
+I_area_rS2 = 1-fncdf(mt1c1,S1mu,S1sd);
+
+C_area_rS1 = fncdf(mt1c1,S1mu,S1sd);
+I_area_rS1 = fncdf(mt1c1,S2mu,S2sd);
+
+for i=1:nRatings-1
+
+ t2c1_lower = t2c1(nRatings-i);
+ t2c1_upper = t2c1(nRatings-1+i);
+
+ I_FAR_area_rS2 = 1-fncdf(t2c1_upper,S1mu,S1sd);
+ C_HR_area_rS2 = 1-fncdf(t2c1_upper,S2mu,S2sd);
+
+ I_FAR_area_rS1 = fncdf(t2c1_lower,S2mu,S2sd);
+ C_HR_area_rS1 = fncdf(t2c1_lower,S1mu,S1sd);
+
+
+ est_FAR2_rS2(i) = I_FAR_area_rS2 / I_area_rS2;
+ est_HR2_rS2(i) = C_HR_area_rS2 / C_area_rS2;
+
+ est_FAR2_rS1(i) = I_FAR_area_rS1 / I_area_rS1;
+ est_HR2_rS1(i) = C_HR_area_rS1 / C_area_rS1;
+
+end
+
+
+%% package output
+
+fit.d1 = sqrt(2/(1+s^2)) * s * d1;
+fit.c1 = c;
+fit.s = s;
+fit.meta_d = sqrt(2/(1+s^2)) * s * meta_d1;
+fit.M_diff = fit.meta_d - fit.d1;
+fit.M_ratio = fit.meta_d / fit.d1;
+
+mt1c1 = eval(constant_criterion);
+fit.meta_c1 = ( sqrt(2).*s ./ sqrt(1+s.^2) ) .* mt1c1;
+
+t2ca = ( sqrt(2).*s ./ sqrt(1+s.^2) ) .* t2c1;
+fit.t2ca_rS1 = t2ca(1:nRatings-1);
+fit.t2ca_rS2 = t2ca(nRatings:end);
+
+fit.S1units.d1 = d1;
+fit.S1units.meta_d1 = meta_d1;
+fit.S1units.s = s;
+fit.S1units.meta_c1 = mt1c1;
+fit.S1units.t2c1_rS1 = t2c1(1:nRatings-1);
+fit.S1units.t2c1_rS2 = t2c1(nRatings:end);
+
+fit.logL = logL;
+
+fit.est_HR2_rS1 = est_HR2_rS1;
+fit.obs_HR2_rS1 = obs_HR2_rS1;
+
+fit.est_FAR2_rS1 = est_FAR2_rS1;
+fit.obs_FAR2_rS1 = obs_FAR2_rS1;
+
+fit.est_HR2_rS2 = est_HR2_rS2;
+fit.obs_HR2_rS2 = obs_HR2_rS2;
+
+fit.est_FAR2_rS2 = est_FAR2_rS2;
+fit.obs_FAR2_rS2 = obs_FAR2_rS2;
+
+
+%% clean up
+delete fit_meta_d_MLE.mat
+
+end
+
+
+%% function to find the likelihood of parameter values, given observed data
+function logL = fit_meta_d_logL(parameters)
+
+% set up parameters
+meta_d1 = parameters(1);
+t2c1 = parameters(2:end);
+
+% loads:
+% nR_S1 nR_S2 nRatings d1 t1c1 s constant_criterion fncdf fninv
+load fit_meta_d_MLE.mat
+
+
+% define mean and SD of S1 and S2 distributions
+S1mu = -meta_d1/2; S1sd = 1;
+S2mu = meta_d1/2; S2sd = S1sd/s;
+
+
+% adjust so that the type 1 criterion is set at 0
+% (this is just to work with optimization toolbox constraints...
+% to simplify defining the upper and lower bounds of type 2 criteria)
+S1mu = S1mu - eval(constant_criterion);
+S2mu = S2mu - eval(constant_criterion);
+
+t1c1 = 0;
+
+
+
+%%% set up MLE analysis
+
+% get type 2 response counts
+for i = 1:nRatings
+
+ % S1 responses
+ nC_rS1(i) = nR_S1(i);
+ nI_rS1(i) = nR_S2(i);
+
+ % S2 responses
+ nC_rS2(i) = nR_S2(nRatings+i);
+ nI_rS2(i) = nR_S1(nRatings+i);
+
+end
+
+% get type 2 probabilities
+C_area_rS1 = fncdf(t1c1,S1mu,S1sd);
+I_area_rS1 = fncdf(t1c1,S2mu,S2sd);
+
+C_area_rS2 = 1-fncdf(t1c1,S2mu,S2sd);
+I_area_rS2 = 1-fncdf(t1c1,S1mu,S1sd);
+
+t2c1x = [-Inf t2c1(1:nRatings-1) t1c1 t2c1(nRatings:end) Inf];
+
+for i = 1:nRatings
+ prC_rS1(i) = ( fncdf(t2c1x(i+1),S1mu,S1sd) - fncdf(t2c1x(i),S1mu,S1sd) ) / C_area_rS1;
+ prI_rS1(i) = ( fncdf(t2c1x(i+1),S2mu,S2sd) - fncdf(t2c1x(i),S2mu,S2sd) ) / I_area_rS1;
+
+ prC_rS2(i) = ( (1-fncdf(t2c1x(nRatings+i),S2mu,S2sd)) - (1-fncdf(t2c1x(nRatings+i+1),S2mu,S2sd)) ) / C_area_rS2;
+ prI_rS2(i) = ( (1-fncdf(t2c1x(nRatings+i),S1mu,S1sd)) - (1-fncdf(t2c1x(nRatings+i+1),S1mu,S1sd)) ) / I_area_rS2;
+end
+
+
+% calculate logL
+logL = 0;
+for i = 1:nRatings
+
+ logL = logL + nC_rS1(i)*log(prC_rS1(i)) + nI_rS1(i)*log(prI_rS1(i)) + ...
+ nC_rS2(i)*log(prC_rS2(i)) + nI_rS2(i)*log(prI_rS2(i));
+
+end
+
+if isnan(logL), logL=-Inf; end
+
+logL = -logL;
+
+end
\ No newline at end of file
diff --git a/tools/tapas_huge_psrf.m b/tools/tapas_huge_psrf.m
new file mode 100644
index 00000000..09175e06
--- /dev/null
+++ b/tools/tapas_huge_psrf.m
@@ -0,0 +1,131 @@
+function [ psrf, neff, tau, thin ] = tapas_huge_psrf( samples, nChains, rBurnIn )
+% Calculate the Potential Scale Reduction Factor
+%
+% INPUTS:
+% samples - array containing samples from MCMC. 1st dimension: samples,
+% 2nd dimension: parameters, 3rd dimension: chains.
+%
+% OPTIONAL INPUTS:
+% nChains - number of chains. If supplied 3rd dimension of samples is
+% interpreted as parameters.
+% rBurnIn - ratio of samples to discard for burn-in.
+%
+% OUTPUTS:
+% psrf - array containing Potential Scale Reduction Factor
+% neff - effective sample size
+% tau - autocorrelation time
+% thin - length of initial positive sequence
+%
+
+% REFERENCE:
+% Stephen P. Brooks & Andrew Gelman (1998) General Methods for
+% Monitoring Convergence of Iterative Simulations, Journal of
+% Computational and Graphical Statistics, 7:4, 434-455, DOI:
+% 10.1080/10618600.1998.10474787
+
+% Author: Yu Yao (yao@biomed.ee.ethz.ch)
+% Copyright (C) 2020 Translational Neuromodeling Unit
+% Institute for Biomedical Engineering,
+% University of Zurich and ETH Zurich.
+%
+% This file is part of TAPAS, which is released under the terms of the GNU
+% General Public Licence (GPL), version 3. For further details, see
+% .
+%
+% This software is provided "as is", without warranty of any kind, express
+% or implied, including, but not limited to the warranties of
+% merchantability, fitness for a particular purpose and non-infringement.
+%
+% This software is intended for research only. Do not use for clinical
+% purpose. Please note that this toolbox is under active development.
+% Considerable changes may occur in future releases. For support please
+% refer to:
+% https://github.com/translationalneuromodeling/tapas/issues
+%
+
+
+[N, P, M] = size(samples);
+if nargin < 2
+ M = 1;
+end
+if nargin < 3
+ rBurnIn = 0; % ratio of samples to discard for burn-in
+end
+psrf = zeros(P, M);
+if nargout > 1
+ neff = zeros(P, M);
+ tau = zeros(P, M);
+ thin = zeros(P, M);
+end
+
+for p = 1:P
+ for m = 1:M
+ if nargin < 2 % treat 3rd dimension as chains
+ tmp = squeeze(samples(:, p, :));
+ else % subdivide 1st dimension into pseudo-chains
+ tmp = reshape(samples(end-fix(N/nChains)*nChains+1:end, p, m), ...
+ fix(N/nChains), nChains);
+ end
+ psrf(p, m) = calculate_psrf( tmp, rBurnIn );
+ if nargout > 1
+ [ neff(p, m), tau(p, m), thin(p, m) ] = calculate_neff( tmp, rBurnIn );
+ end
+ end
+end
+
+end
+
+function [ psrf ] = calculate_psrf( samples, bi )
+
+[N, M] = size(samples);
+assert(M > 1, 'TAPAS:HUGE:noChains', 'Not enough chains.')
+
+% discard first part of each chain as burn-in
+samples = samples(max(1, fix(N*bi)):end, :);
+N = size(samples, 1);
+assert(N > 9, 'TAPAS:HUGE:noSamples', 'Not enough samples.')
+
+% within-chain mean and variance
+x_bar = mean(samples);
+s2 = var(samples);
+
+B = var(x_bar);
+W = mean(s2);
+
+% across-chain mean and variance
+sigma_hat2 = (N - 1)/N*W + B;
+
+V_hat = sigma_hat2 + B/M;
+psrf = sqrt(V_hat/W);
+
+% % correction based on t-distribution
+% mu_hat = mean(samples(:));
+% var_V_hat = (N - 1)^2/N^2/M*var(s2) + 2*(M + 1)^2/M^2/(M-1)*B^2 ...
+% + 2*(M + 1)*(N - 1)/M^2/N* ...
+% (xcov(s2, x_bar.^2, 0) - 2*mu_hat*xcov(s2, x_bar, 0));
+% df = 2*V_hat^2/var_V_hat;
+% psrf = sqrt(V_hat/W*(df + 3)/(df + 1));
+
+end
+
+function [ neff, tau, thin ] = calculate_neff( samples, bi )
+
+% discard first part of each chain as burn-in
+[N,M] = size(samples);
+samples = samples(max(1, fix(N*bi)):end, :);
+N = size(samples, 1);
+K = 2*floor(N/2) - 1;
+% autocovariance
+rho = zeros(2*N-1,1);
+for m = 1:M
+ rho = rho + xcov(samples(:,m),'coeff');
+end
+thin = 2*(find(rho(N:2:N+K)+rho(N+1:2:N+K)<0,1,'first') - 1) - 1;
+if isempty(thin)
+ thin = K;
+end
+thin = max(thin,1);
+tau = sum(rho(N-thin:N+thin))/M; % Autocorrelation time estimation
+neff = M*N/tau; % effective sample size
+
+end