diff --git a/ArrayOperations.c b/ArrayOperations.c
new file mode 100644
index 0000000..00a8324
--- /dev/null
+++ b/ArrayOperations.c
@@ -0,0 +1,288 @@
+/*******************************************************************************
+** ArrayOperations.cpp
+** Part of the mutual information toolbox
+**
+** Contains functions to floor arrays, and to merge arrays into a joint
+** state.
+**
+** Author: Adam Pocock
+** Created 17/2/2010
+**
+** Copyright 2010 Adam Pocock, The University Of Manchester
+** www.cs.manchester.ac.uk
+**
+** This file is part of MIToolbox.
+**
+** MIToolbox is free software: you can redistribute it and/or modify
+** it under the terms of the GNU Lesser General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** MIToolbox 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 Lesser General Public License for more details.
+**
+** You should have received a copy of the GNU Lesser General Public License
+** along with MIToolbox. If not, see .
+**
+*******************************************************************************/
+
+#include "MIToolbox.h"
+#include "ArrayOperations.h"
+
+void printDoubleVector(double *vector, int vectorLength)
+{
+ int i;
+ for (i = 0; i < vectorLength; i++)
+ {
+ if (vector[i] > 0)
+ printf("Val at i=%d, is %f\n",i,vector[i]);
+ }/*for number of items in vector*/
+}/*printDoubleVector(double*,int)*/
+
+void printIntVector(int *vector, int vectorLength)
+{
+ int i;
+ for (i = 0; i < vectorLength; i++)
+ {
+ printf("Val at i=%d, is %d\n",i,vector[i]);
+ }/*for number of items in vector*/
+}/*printIntVector(int*,int)*/
+
+int numberOfUniqueValues(double *featureVector, int vectorLength)
+{
+ int uniqueValues = 0;
+ double *valuesArray = (double *) CALLOC_FUNC(vectorLength,sizeof(double));
+
+ int found = 0;
+ int j = 0;
+ int i;
+
+ for (i = 0; i < vectorLength; i++)
+ {
+ found = 0;
+ j = 0;
+ while ((j < uniqueValues) && (found == 0))
+ {
+ if (valuesArray[j] == featureVector[i])
+ {
+ found = 1;
+ featureVector[i] = (double) (j+1);
+ }
+ j++;
+ }
+ if (!found)
+ {
+ valuesArray[uniqueValues] = featureVector[i];
+ uniqueValues++;
+ featureVector[i] = (double) uniqueValues;
+ }
+ }/*for vectorlength*/
+
+ FREE_FUNC(valuesArray);
+ valuesArray = NULL;
+
+ return uniqueValues;
+}/*numberOfUniqueValues(double*,int)*/
+
+/*******************************************************************************
+** normaliseArray takes an input vector and writes an output vector
+** which is a normalised version of the input, and returns the number of states
+** A normalised array has min value = 0, max value = number of states
+** and all values are integers
+**
+** length(inputVector) == length(outputVector) == vectorLength otherwise there
+** is a memory leak
+*******************************************************************************/
+int normaliseArray(double *inputVector, int *outputVector, int vectorLength)
+{
+ int minVal = 0;
+ int maxVal = 0;
+ int currentValue;
+ int i;
+
+ if (vectorLength > 0)
+ {
+ minVal = (int) floor(inputVector[0]);
+ maxVal = (int) floor(inputVector[0]);
+
+ for (i = 0; i < vectorLength; i++)
+ {
+ currentValue = (int) floor(inputVector[i]);
+ outputVector[i] = currentValue;
+
+ if (currentValue < minVal)
+ {
+ minVal = currentValue;
+ }
+
+ if (currentValue > maxVal)
+ {
+ maxVal = currentValue;
+ }
+ }/*for loop over vector*/
+
+ for (i = 0; i < vectorLength; i++)
+ {
+ outputVector[i] = outputVector[i] - minVal;
+ }
+
+ maxVal = (maxVal - minVal) + 1;
+ }
+
+ return maxVal;
+}/*normaliseArray(double*,double*,int)*/
+
+
+/*******************************************************************************
+** mergeArrays takes in two arrays and writes the joint state of those arrays
+** to the output vector, returning the number of joint states
+**
+** the length of the vectors must be the same and equal to vectorLength
+** outputVector must be malloc'd before calling this function
+*******************************************************************************/
+int mergeArrays(double *firstVector, double *secondVector, double *outputVector, int vectorLength)
+{
+ int *firstNormalisedVector;
+ int *secondNormalisedVector;
+ int firstNumStates;
+ int secondNumStates;
+ int i;
+ int *stateMap;
+ int stateCount;
+ int curIndex;
+
+ firstNormalisedVector = (int *) CALLOC_FUNC(vectorLength,sizeof(int));
+ secondNormalisedVector = (int *) CALLOC_FUNC(vectorLength,sizeof(int));
+
+ firstNumStates = normaliseArray(firstVector,firstNormalisedVector,vectorLength);
+ secondNumStates = normaliseArray(secondVector,secondNormalisedVector,vectorLength);
+
+ /*
+ ** printVector(firstNormalisedVector,vectorLength);
+ ** printVector(secondNormalisedVector,vectorLength);
+ */
+ stateMap = (int *) CALLOC_FUNC(firstNumStates*secondNumStates,sizeof(int));
+ stateCount = 1;
+ for (i = 0; i < vectorLength; i++)
+ {
+ curIndex = firstNormalisedVector[i] + (secondNormalisedVector[i] * firstNumStates);
+ if (stateMap[curIndex] == 0)
+ {
+ stateMap[curIndex] = stateCount;
+ stateCount++;
+ }
+ outputVector[i] = stateMap[curIndex];
+ }
+
+ FREE_FUNC(firstNormalisedVector);
+ FREE_FUNC(secondNormalisedVector);
+ FREE_FUNC(stateMap);
+
+ firstNormalisedVector = NULL;
+ secondNormalisedVector = NULL;
+ stateMap = NULL;
+
+ /*printVector(outputVector,vectorLength);*/
+ return stateCount;
+}/*mergeArrays(double *,double *,double *, int, bool)*/
+
+int mergeArraysArities(double *firstVector, int numFirstStates, double *secondVector, int numSecondStates, double *outputVector, int vectorLength)
+{
+ int *firstNormalisedVector;
+ int *secondNormalisedVector;
+ int i;
+ int totalStates;
+ int firstStateCheck, secondStateCheck;
+
+ firstNormalisedVector = (int *) CALLOC_FUNC(vectorLength,sizeof(int));
+ secondNormalisedVector = (int *) CALLOC_FUNC(vectorLength,sizeof(int));
+
+ firstStateCheck = normaliseArray(firstVector,firstNormalisedVector,vectorLength);
+ secondStateCheck = normaliseArray(secondVector,secondNormalisedVector,vectorLength);
+
+ if ((firstStateCheck <= numFirstStates) && (secondStateCheck <= numSecondStates))
+ {
+ for (i = 0; i < vectorLength; i++)
+ {
+ outputVector[i] = firstNormalisedVector[i] + (secondNormalisedVector[i] * numFirstStates) + 1;
+ }
+ totalStates = numFirstStates * numSecondStates;
+ }
+ else
+ {
+ totalStates = -1;
+ }
+
+ FREE_FUNC(firstNormalisedVector);
+ FREE_FUNC(secondNormalisedVector);
+
+ firstNormalisedVector = NULL;
+ secondNormalisedVector = NULL;
+
+ return totalStates;
+}/*mergeArraysArities(double *,int,double *,int,double *,int)*/
+
+int mergeMultipleArrays(double *inputMatrix, double *outputVector, int matrixWidth, int vectorLength)
+{
+ int i = 0;
+ int currentIndex;
+ int currentNumStates;
+ int *normalisedVector;
+
+ if (matrixWidth > 1)
+ {
+ currentNumStates = mergeArrays(inputMatrix, (inputMatrix + vectorLength), outputVector,vectorLength);
+ for (i = 2; i < matrixWidth; i++)
+ {
+ currentIndex = i * vectorLength;
+ currentNumStates = mergeArrays(outputVector,(inputMatrix + currentIndex),outputVector,vectorLength);
+ }
+ }
+ else
+ {
+ normalisedVector = (int *) CALLOC_FUNC(vectorLength,sizeof(int));
+ currentNumStates = normaliseArray(inputMatrix,normalisedVector,vectorLength);
+ for (i = 0; i < vectorLength; i++)
+ {
+ outputVector[i] = inputMatrix[i];
+ }
+ }
+
+ return currentNumStates;
+}/*mergeMultipleArrays(double *, double *, int, int, bool)*/
+
+
+int mergeMultipleArraysArities(double *inputMatrix, double *outputVector, int matrixWidth, int *arities, int vectorLength)
+{
+ int i = 0;
+ int currentIndex;
+ int currentNumStates;
+ int *normalisedVector;
+
+ if (matrixWidth > 1)
+ {
+ currentNumStates = mergeArraysArities(inputMatrix, arities[0], (inputMatrix + vectorLength), arities[1], outputVector,vectorLength);
+ for (i = 2; i < matrixWidth; i++)
+ {
+ currentIndex = i * vectorLength;
+ currentNumStates = mergeArraysArities(outputVector,currentNumStates,(inputMatrix + currentIndex),arities[i],outputVector,vectorLength);
+ if (currentNumStates == -1)
+ break;
+ }
+ }
+ else
+ {
+ normalisedVector = (int *) CALLOC_FUNC(vectorLength,sizeof(int));
+ currentNumStates = normaliseArray(inputMatrix,normalisedVector,vectorLength);
+ for (i = 0; i < vectorLength; i++)
+ {
+ outputVector[i] = inputMatrix[i];
+ }
+ }
+
+ return currentNumStates;
+}/*mergeMultipleArraysArities(double *, double *, int, int, bool)*/
+
+
diff --git a/ArrayOperations.h b/ArrayOperations.h
new file mode 100644
index 0000000..3cc9025
--- /dev/null
+++ b/ArrayOperations.h
@@ -0,0 +1,88 @@
+/*******************************************************************************
+** ArrayOperations.h
+** Part of the mutual information toolbox
+**
+** Contains functions to floor arrays, and to merge arrays into a joint
+** state.
+**
+** Author: Adam Pocock
+** Created 17/2/2010
+**
+** Copyright 2010 Adam Pocock, The University Of Manchester
+** www.cs.manchester.ac.uk
+**
+** This file is part of MIToolbox.
+**
+** MIToolbox is free software: you can redistribute it and/or modify
+** it under the terms of the GNU Lesser General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** MIToolbox 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 Lesser General Public License for more details.
+**
+** You should have received a copy of the GNU Lesser General Public License
+** along with MIToolbox. If not, see .
+**
+*******************************************************************************/
+
+#ifndef __ArrayOperations_H
+#define __ArrayOperations_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*******************************************************************************
+** Simple print function for debugging
+*******************************************************************************/
+void printDoubleVector(double *vector, int vectorLength);
+
+void printIntVector(int *vector, int vectorLength);
+
+/*******************************************************************************
+** numberOfUniqueValues finds the number of unique values in an array by
+** repeatedly iterating through the array and checking if a value has been
+** seen previously
+*******************************************************************************/
+int numberOfUniqueValues(double *featureVector, int vectorLength);
+
+/*******************************************************************************
+** normaliseArray takes an input vector and writes an output vector
+** which is a normalised version of the input, and returns the number of states
+** A normalised array has min value = 0, max value = number of states
+** and all values are integers
+**
+** length(inputVector) == length(outputVector) == vectorLength otherwise there
+** is a memory leak
+*******************************************************************************/
+int normaliseArray(double *inputVector, int *outputVector, int vectorLength);
+
+/*******************************************************************************
+** mergeArrays takes in two arrays and writes the joint state of those arrays
+** to the output vector
+**
+** the length of the vectors must be the same and equal to vectorLength
+*******************************************************************************/
+int mergeArrays(double *firstVector, double *secondVector, double *outputVector, int vectorLength);
+int mergeArraysArities(double *firstVector, int numFirstStates, double *secondVector, int numSecondStates, double *outputVector, int vectorLength);
+
+/*******************************************************************************
+** mergeMultipleArrays takes in a matrix and repeatedly merges the matrix using
+** merge arrays and writes the joint state of that matrix
+** to the output vector
+**
+** the length of the vectors must be the same and equal to vectorLength
+** matrixWidth = the number of columns in the matrix
+*******************************************************************************/
+int mergeMultipleArrays(double *inputMatrix, double *outputVector, int matrixWidth, int vectorLength);
+int mergeMultipleArraysArities(double *inputMatrix, double *outputVector, int matrixWidth, int *arities, int vectorLength);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..94a9ed0
--- /dev/null
+++ b/COPYING
@@ -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/COPYING.LESSER b/COPYING.LESSER
new file mode 100644
index 0000000..cca7fc2
--- /dev/null
+++ b/COPYING.LESSER
@@ -0,0 +1,165 @@
+ GNU LESSER 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.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser 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
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
diff --git a/CalculateProbability.c b/CalculateProbability.c
new file mode 100644
index 0000000..6d4f19b
--- /dev/null
+++ b/CalculateProbability.c
@@ -0,0 +1,184 @@
+/*******************************************************************************
+** CalculateProbability.cpp
+** Part of the mutual information toolbox
+**
+** Contains functions to calculate the probability of each state in the array
+** and to calculate the probability of the joint state of two arrays
+**
+** Author: Adam Pocock
+** Created 17/2/2010
+**
+** Copyright 2010 Adam Pocock, The University Of Manchester
+** www.cs.manchester.ac.uk
+**
+** This file is part of MIToolbox.
+**
+** MIToolbox is free software: you can redistribute it and/or modify
+** it under the terms of the GNU Lesser General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** MIToolbox 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 Lesser General Public License for more details.
+**
+** You should have received a copy of the GNU Lesser General Public License
+** along with MIToolbox. If not, see .
+**
+*******************************************************************************/
+
+#include "MIToolbox.h"
+#include "ArrayOperations.h"
+#include "CalculateProbability.h"
+
+JointProbabilityState calculateJointProbability(double *firstVector, double *secondVector, int vectorLength)
+{
+ int *firstNormalisedVector;
+ int *secondNormalisedVector;
+ int *firstStateCounts;
+ int *secondStateCounts;
+ int *jointStateCounts;
+ double *firstStateProbs;
+ double *secondStateProbs;
+ double *jointStateProbs;
+ int firstNumStates;
+ int secondNumStates;
+ int jointNumStates;
+ int i;
+ double length = vectorLength;
+ JointProbabilityState state;
+
+ firstNormalisedVector = (int *) CALLOC_FUNC(vectorLength,sizeof(int));
+ secondNormalisedVector = (int *) CALLOC_FUNC(vectorLength,sizeof(int));
+
+ firstNumStates = normaliseArray(firstVector,firstNormalisedVector,vectorLength);
+ secondNumStates = normaliseArray(secondVector,secondNormalisedVector,vectorLength);
+ jointNumStates = firstNumStates * secondNumStates;
+
+ firstStateCounts = (int *) CALLOC_FUNC(firstNumStates,sizeof(int));
+ secondStateCounts = (int *) CALLOC_FUNC(secondNumStates,sizeof(int));
+ jointStateCounts = (int *) CALLOC_FUNC(jointNumStates,sizeof(int));
+
+ firstStateProbs = (double *) CALLOC_FUNC(firstNumStates,sizeof(double));
+ secondStateProbs = (double *) CALLOC_FUNC(secondNumStates,sizeof(double));
+ jointStateProbs = (double *) CALLOC_FUNC(jointNumStates,sizeof(double));
+
+ /* optimised version, less numerically stable
+ double fractionalState = 1.0 / vectorLength;
+
+ for (i = 0; i < vectorLength; i++)
+ {
+ firstStateProbs[firstNormalisedVector[i]] += fractionalState;
+ secondStateProbs[secondNormalisedVector[i]] += fractionalState;
+ jointStateProbs[secondNormalisedVector[i] * firstNumStates + firstNormalisedVector[i]] += fractionalState;
+ }
+ */
+
+ /* Optimised for number of FP operations now O(states) instead of O(vectorLength) */
+ for (i = 0; i < vectorLength; i++)
+ {
+ firstStateCounts[firstNormalisedVector[i]] += 1;
+ secondStateCounts[secondNormalisedVector[i]] += 1;
+ jointStateCounts[secondNormalisedVector[i] * firstNumStates + firstNormalisedVector[i]] += 1;
+ }
+
+ for (i = 0; i < firstNumStates; i++)
+ {
+ firstStateProbs[i] = firstStateCounts[i] / length;
+ }
+
+ for (i = 0; i < secondNumStates; i++)
+ {
+ secondStateProbs[i] = secondStateCounts[i] / length;
+ }
+
+ for (i = 0; i < jointNumStates; i++)
+ {
+ jointStateProbs[i] = jointStateCounts[i] / length;
+ }
+
+ FREE_FUNC(firstNormalisedVector);
+ FREE_FUNC(secondNormalisedVector);
+ FREE_FUNC(firstStateCounts);
+ FREE_FUNC(secondStateCounts);
+ FREE_FUNC(jointStateCounts);
+
+ firstNormalisedVector = NULL;
+ secondNormalisedVector = NULL;
+ firstStateCounts = NULL;
+ secondStateCounts = NULL;
+ jointStateCounts = NULL;
+
+ /*
+ **typedef struct
+ **{
+ ** double *jointProbabilityVector;
+ ** int numJointStates;
+ ** double *firstProbabilityVector;
+ ** int numFirstStates;
+ ** double *secondProbabilityVector;
+ ** int numSecondStates;
+ **} JointProbabilityState;
+ */
+
+ state.jointProbabilityVector = jointStateProbs;
+ state.numJointStates = jointNumStates;
+ state.firstProbabilityVector = firstStateProbs;
+ state.numFirstStates = firstNumStates;
+ state.secondProbabilityVector = secondStateProbs;
+ state.numSecondStates = secondNumStates;
+
+ return state;
+}/*calculateJointProbability(double *,double *, int)*/
+
+ProbabilityState calculateProbability(double *dataVector, int vectorLength)
+{
+ int *normalisedVector;
+ int *stateCounts;
+ double *stateProbs;
+ int numStates;
+ /*double fractionalState;*/
+ ProbabilityState state;
+ int i;
+ double length = vectorLength;
+
+ normalisedVector = (int *) CALLOC_FUNC(vectorLength,sizeof(int));
+
+ numStates = normaliseArray(dataVector,normalisedVector,vectorLength);
+
+ stateCounts = (int *) CALLOC_FUNC(numStates,sizeof(int));
+ stateProbs = (double *) CALLOC_FUNC(numStates,sizeof(double));
+
+ /* optimised version, may have floating point problems
+ fractionalState = 1.0 / vectorLength;
+
+ for (i = 0; i < vectorLength; i++)
+ {
+ stateProbs[normalisedVector[i]] += fractionalState;
+ }
+ */
+
+ /* Optimised for number of FP operations now O(states) instead of O(vectorLength) */
+ for (i = 0; i < vectorLength; i++)
+ {
+ stateCounts[normalisedVector[i]] += 1;
+ }
+
+ for (i = 0; i < numStates; i++)
+ {
+ stateProbs[i] = stateCounts[i] / length;
+ }
+
+ FREE_FUNC(stateCounts);
+ FREE_FUNC(normalisedVector);
+
+ stateCounts = NULL;
+ normalisedVector = NULL;
+
+ state.probabilityVector = stateProbs;
+ state.numStates = numStates;
+
+ return state;
+}/*calculateProbability(double *,int)*/
+
diff --git a/CalculateProbability.h b/CalculateProbability.h
new file mode 100644
index 0000000..d5e9d3e
--- /dev/null
+++ b/CalculateProbability.h
@@ -0,0 +1,80 @@
+/*******************************************************************************
+** CalculateProbability.h
+** Part of the mutual information toolbox
+**
+** Contains functions to calculate the probability of each state in the array
+** and to calculate the probability of the joint state of two arrays
+**
+** Author: Adam Pocock
+** Created 17/2/2010
+**
+** Copyright 2010 Adam Pocock, The University Of Manchester
+** www.cs.manchester.ac.uk
+**
+** This file is part of MIToolbox.
+**
+** MIToolbox is free software: you can redistribute it and/or modify
+** it under the terms of the GNU Lesser General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** MIToolbox 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 Lesser General Public License for more details.
+**
+** You should have received a copy of the GNU Lesser General Public License
+** along with MIToolbox. If not, see .
+**
+*******************************************************************************/
+
+#ifndef __CalculateProbability_H
+#define __CalculateProbability_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct jpState
+{
+ double *jointProbabilityVector;
+ int numJointStates;
+ double *firstProbabilityVector;
+ int numFirstStates;
+ double *secondProbabilityVector;
+ int numSecondStates;
+} JointProbabilityState;
+
+typedef struct pState
+{
+ double *probabilityVector;
+ int numStates;
+} ProbabilityState;
+
+/*******************************************************************************
+** calculateJointProbability returns the joint probability vector of two vectors
+** and the marginal probability vectors in a struct.
+** It is the base operation for all information theory calculations involving
+** two or more variables.
+**
+** length(firstVector) == length(secondVector) == vectorLength otherwise there
+** will be a segmentation fault
+*******************************************************************************/
+JointProbabilityState calculateJointProbability(double *firstVector, double *secondVector, int vectorLength);
+
+/*******************************************************************************
+** calculateProbability returns the probability vector from one vector.
+** It is the base operation for all information theory calculations involving
+** one variable
+**
+** length(dataVector) == vectorLength otherwise there
+** will be a segmentation fault
+*******************************************************************************/
+ProbabilityState calculateProbability(double *dataVector, int vectorLength);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/CompileScript.m b/CompileScript.m
new file mode 100644
index 0000000..a8d9e92
--- /dev/null
+++ b/CompileScript.m
@@ -0,0 +1,4 @@
+% Compiles the MIToolbox functions
+
+mex MIToolboxMex.c MutualInformation.c Entropy.c CalculateProbability.c ArrayOperations.c
+mex RenyiMIToolboxMex.c RenyiMutualInformation.c RenyiEntropy.c CalculateProbability.c ArrayOperations.c
diff --git a/Entropy.c b/Entropy.c
new file mode 100644
index 0000000..3f37cc1
--- /dev/null
+++ b/Entropy.c
@@ -0,0 +1,130 @@
+/*******************************************************************************
+** Entropy.cpp
+** Part of the mutual information toolbox
+**
+** Contains functions to calculate the entropy of a single variable H(X),
+** the joint entropy of two variables H(X,Y), and the conditional entropy
+** H(X|Y)
+**
+** Author: Adam Pocock
+** Created 19/2/2010
+**
+** Copyright 2010 Adam Pocock, The University Of Manchester
+** www.cs.manchester.ac.uk
+**
+** This file is part of MIToolbox.
+**
+** MIToolbox is free software: you can redistribute it and/or modify
+** it under the terms of the GNU Lesser General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** MIToolbox 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 Lesser General Public License for more details.
+**
+** You should have received a copy of the GNU Lesser General Public License
+** along with MIToolbox. If not, see .
+**
+*******************************************************************************/
+
+#include "MIToolbox.h"
+#include "CalculateProbability.h"
+#include "Entropy.h"
+
+double calculateEntropy(double *dataVector, int vectorLength)
+{
+ double entropy = 0.0;
+ double tempValue = 0.0;
+ int i;
+ ProbabilityState state = calculateProbability(dataVector,vectorLength);
+
+ /*H(X) = - sum p(x) log p(x)*/
+ for (i = 0; i < state.numStates; i++)
+ {
+ tempValue = state.probabilityVector[i];
+
+ if (tempValue > 0)
+ {
+ entropy -= tempValue * log(tempValue);
+ }
+ }
+
+ entropy /= log(2.0);
+
+ FREE_FUNC(state.probabilityVector);
+ state.probabilityVector = NULL;
+
+ return entropy;
+}/*calculateEntropy(double *,int)*/
+
+double calculateJointEntropy(double *firstVector, double *secondVector, int vectorLength)
+{
+ double jointEntropy = 0.0;
+ double tempValue = 0.0;
+ int i;
+ JointProbabilityState state = calculateJointProbability(firstVector,secondVector,vectorLength);
+
+ /*H(XY) = - sumx sumy p(xy) log p(xy)*/
+ for (i = 0; i < state.numJointStates; i++)
+ {
+ tempValue = state.jointProbabilityVector[i];
+ if (tempValue > 0)
+ {
+ jointEntropy -= tempValue * log(tempValue);
+ }
+ }
+
+ jointEntropy /= log(2.0);
+
+ FREE_FUNC(state.firstProbabilityVector);
+ state.firstProbabilityVector = NULL;
+ FREE_FUNC(state.secondProbabilityVector);
+ state.secondProbabilityVector = NULL;
+ FREE_FUNC(state.jointProbabilityVector);
+ state.jointProbabilityVector = NULL;
+
+ return jointEntropy;
+}/*calculateJointEntropy(double *, double *, int)*/
+
+double calculateConditionalEntropy(double *dataVector, double *conditionVector, int vectorLength)
+{
+ /*
+ ** Conditional entropy
+ ** H(X|Y) = - sumx sumy p(xy) log p(xy)/p(y)
+ */
+
+ double condEntropy = 0.0;
+ double jointValue = 0.0;
+ double condValue = 0.0;
+ int i;
+ JointProbabilityState state = calculateJointProbability(dataVector,conditionVector,vectorLength);
+
+ /*H(X|Y) = - sumx sumy p(xy) log p(xy)/p(y)*/
+ /* to index by numFirstStates use modulus of i
+ ** to index by numSecondStates use integer division of i by numFirstStates
+ */
+ for (i = 0; i < state.numJointStates; i++)
+ {
+ jointValue = state.jointProbabilityVector[i];
+ condValue = state.secondProbabilityVector[i / state.numFirstStates];
+ if ((jointValue > 0) && (condValue > 0))
+ {
+ condEntropy -= jointValue * log(jointValue / condValue);
+ }
+ }
+
+ condEntropy /= log(2.0);
+
+ FREE_FUNC(state.firstProbabilityVector);
+ state.firstProbabilityVector = NULL;
+ FREE_FUNC(state.secondProbabilityVector);
+ state.secondProbabilityVector = NULL;
+ FREE_FUNC(state.jointProbabilityVector);
+ state.jointProbabilityVector = NULL;
+
+ return condEntropy;
+
+}/*calculateConditionalEntropy(double *, double *, int)*/
+
diff --git a/Entropy.h b/Entropy.h
new file mode 100644
index 0000000..4bdd697
--- /dev/null
+++ b/Entropy.h
@@ -0,0 +1,71 @@
+/*******************************************************************************
+** Entropy.h
+** Part of the mutual information toolbox
+**
+** Contains functions to calculate the entropy of a single variable H(X),
+** the joint entropy of two variables H(X,Y), and the conditional entropy
+** H(X|Y)
+**
+** Author: Adam Pocock
+** Created 19/2/2010
+**
+** Copyright 2010 Adam Pocock, The University Of Manchester
+** www.cs.manchester.ac.uk
+**
+** This file is part of MIToolbox.
+**
+** MIToolbox is free software: you can redistribute it and/or modify
+** it under the terms of the GNU Lesser General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** MIToolbox 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 Lesser General Public License for more details.
+**
+** You should have received a copy of the GNU Lesser General Public License
+** along with MIToolbox. If not, see .
+**
+*******************************************************************************/
+
+#ifndef __Entropy_H
+#define __Entropy_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*******************************************************************************
+** calculateEntropy returns the entropy in log base 2 of dataVector
+** H(X)
+**
+** length(dataVector) == vectorLength otherwise there
+** will be a segmentation fault
+*******************************************************************************/
+double calculateEntropy(double *dataVector, int vectorLength);
+
+/*******************************************************************************
+** calculateJointEntropy returns the entropy in log base 2 of the joint
+** variable of firstVector and secondVector H(XY)
+**
+** length(firstVector) == length(secondVector) == vectorLength otherwise there
+** will be a segmentation fault
+*******************************************************************************/
+double calculateJointEntropy(double *firstVector, double *secondVector, int vectorLength);
+
+/*******************************************************************************
+** calculateConditionalEntropy returns the entropy in log base 2 of dataVector
+** conditioned on conditionVector, H(X|Y)
+**
+** length(dataVector) == length(conditionVector) == vectorLength otherwise there
+** will be a segmentation fault
+*******************************************************************************/
+double calculateConditionalEntropy(double *dataVector, double *conditionVector, int vectorLength);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/MIToolbox.h b/MIToolbox.h
new file mode 100644
index 0000000..bba6284
--- /dev/null
+++ b/MIToolbox.h
@@ -0,0 +1,53 @@
+/*******************************************************************************
+**
+** MIToolbox.h
+** Provides the header files and #defines to ensure compatibility with MATLAB
+** and C/C++. Uncomment the correct lines to setup the correct memory
+** allocation and freeing operations.
+**
+** Author: Adam Pocock
+** Created 17/2/2010
+**
+**
+** Copyright 2010 Adam Pocock, The University Of Manchester
+** www.cs.manchester.ac.uk
+**
+** This file is part of MIToolbox.
+**
+** MIToolbox is free software: you can redistribute it and/or modify
+** it under the terms of the GNU Lesser General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** MIToolbox 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 Lesser General Public License for more details.
+**
+** You should have received a copy of the GNU Lesser General Public License
+** along with MIToolbox. If not, see .
+**
+*******************************************************************************/
+
+#ifndef __MIToolbox_H
+#define __MIToolbox_H
+
+#include
+#include
+
+#ifdef COMPILE_C
+ #define C_IMPLEMENTATION
+ #include
+ #include
+ #define CALLOC_FUNC calloc
+ #define FREE_FUNC free
+#else
+ #define MEX_IMPLEMENTATION
+ #include "mex.h"
+ #define CALLOC_FUNC mxCalloc
+ #define FREE_FUNC mxFree
+ #define printf mexPrintf /*for Octave-3.2*/
+#endif
+
+#endif
+
diff --git a/MIToolbox.m b/MIToolbox.m
new file mode 100644
index 0000000..880924a
--- /dev/null
+++ b/MIToolbox.m
@@ -0,0 +1,83 @@
+function [varargout] = MIToolbox(functionName, varargin)
+%function [varargout] = MIToolbox(functionName, varargin)
+%
+%Provides access to the functions in MIToolboxMex
+%
+%Expects column vectors, will not work with row vectors
+%
+%Function list
+%"joint" = joint variable of the matrix
+%"entropy" or "h" = H(X)
+%"ConditionalEntropy" or "condh" = H(X|Y)
+%"mi" = I(X;Y)
+%"ConditionalMI" or "cmi" = I(X;Y|Z)
+%
+%Arguments and returned values
+%[jointVariable] = joint(matrix)
+%[entropy] = H(X) = H(vector)
+%[entropy] = H(X|Y) = H(vector,condition)
+%[mi] = I(X;Y) = I(vector,target)
+%[mi] = I(X;Y|Z) = I(vector,target,condition)
+%
+%Internal MIToolbox function number
+%Joint = 3
+%Entropy = 4
+%Conditional Entropy = 6
+%Mutual Information = 7
+%Conditional MI = 8
+
+if (strcmpi(functionName,'Joint') || strcmpi(functionName,'Merge'))
+ [varargout{1}] = MIToolboxMex(3,varargin{1});
+elseif (strcmpi(functionName,'Entropy') || strcmpi(functionName,'h'))
+ %disp('Calculating Entropy');
+ if (size(varargin{1},2)>1)
+ mergedVector = MIToolboxMex(3,varargin{1});
+ else
+ mergedVector = varargin{1};
+ end
+ [varargout{1}] = MIToolboxMex(4,mergedVector);
+elseif ((strcmpi(functionName,'ConditionalEntropy')) || strcmpi(functionName,'condh'))
+ if (size(varargin{1},2)>1)
+ mergedFirst = MIToolboxMex(3,varargin{1});
+ else
+ mergedFirst = varargin{1};
+ end
+ if (size(varargin{2},2)>1)
+ mergedSecond = MIToolboxMex(3,varargin{2});
+ else
+ mergedSecond = varargin{2};
+ end
+ [varargout{1}] = MIToolboxMex(6,mergedFirst,mergedSecond);
+elseif (strcmpi(functionName,'mi'))
+ if (size(varargin{1},2)>1)
+ mergedFirst = MIToolboxMex(3,varargin{1});
+ else
+ mergedFirst = varargin{1};
+ end
+ if (size(varargin{2},2)>1)
+ mergedSecond = MIToolboxMex(3,varargin{2});
+ else
+ mergedSecond = varargin{2};
+ end
+ [varargout{1}] = MIToolboxMex(7,mergedFirst,mergedSecond);
+elseif (strcmpi(functionName,'ConditionalMI') || strcmpi(functionName,'cmi'))
+ if (size(varargin{1},2)>1)
+ mergedFirst = MIToolboxMex(3,varargin{1});
+ else
+ mergedFirst = varargin{1};
+ end
+ if (size(varargin{2},2)>1)
+ mergedSecond = MIToolboxMex(3,varargin{2});
+ else
+ mergedSecond = varargin{2};
+ end
+ if (size(varargin{3},2)>1)
+ mergedThird = MIToolboxMex(3,varargin{3});
+ else
+ mergedThird = varargin{3};
+ end
+ [varargout{1}] = MIToolboxMex(8,mergedFirst,mergedSecond,mergedThird);
+else
+ varargout{1} = 0;
+ disp(['Unrecognised functionName ' functionName]);
+end
diff --git a/MIToolboxMex.c b/MIToolboxMex.c
new file mode 100644
index 0000000..e27009f
--- /dev/null
+++ b/MIToolboxMex.c
@@ -0,0 +1,494 @@
+/*******************************************************************************
+**
+** MIToolboxMex.cpp
+** is the MATLAB entry point for the MIToolbox functions when called from
+** a MATLAB/OCTAVE script.
+**
+** Copyright 2010 Adam Pocock, The University Of Manchester
+** www.cs.manchester.ac.uk
+**
+** This file is part of MIToolbox.
+**
+** MIToolbox is free software: you can redistribute it and/or modify
+** it under the terms of the GNU Lesser General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** MIToolbox 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 Lesser General Public License for more details.
+**
+** You should have received a copy of the GNU Lesser General Public License
+** along with MIToolbox. If not, see .
+**
+*******************************************************************************/
+#include "MIToolbox.h"
+#include "ArrayOperations.h"
+#include "CalculateProbability.h"
+#include "Entropy.h"
+#include "MutualInformation.h"
+
+/*******************************************************************************
+**entry point for the mex call
+**nlhs - number of outputs
+**plhs - pointer to array of outputs
+**nrhs - number of inputs
+**prhs - pointer to array of inputs
+*******************************************************************************/
+void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
+{
+ /*****************************************************************************
+ ** this function takes a flag and a variable number of arguments
+ ** depending on the value of the flag and returns either a construct
+ ** containing probability estimates, a merged vector or a double value
+ ** representing an entropy or mutual information
+ *****************************************************************************/
+
+ int flag, i, numberOfSamples, checkSamples, thirdCheckSamples, numberOfFeatures, checkFeatures, thirdCheckFeatures;
+ int numArities, errorTest;
+ double *dataVector, *condVector, *targetVector, *firstVector, *secondVector, *output, *numStates;
+ double *matrix, *mergedVector, *arities;
+ int *outputIntVector, *intArities;
+
+ double *jointOutput, *numJointStates, *firstOutput, *numFirstStates, *secondOutput, *numSecondStates;
+
+ ProbabilityState state;
+ JointProbabilityState jointState;
+
+ /*if (nlhs != 1)
+ {
+ printf("Incorrect number of output arguments\n");
+ }//if not 1 output
+ */
+ if (nrhs == 2)
+ {
+ /*printf("Must be H(X), calculateProbability(X), merge(X), normaliseArray(X)\n");*/
+ }
+ else if (nrhs == 3)
+ {
+ /*printf("Must be H(XY), H(X|Y), calculateJointProbability(XY), I(X;Y)\n");*/
+ }
+ else if (nrhs == 4)
+ {
+ /*printf("Must be I(X;Y|Z)\n");*/
+ }
+ else
+ {
+ printf("Incorrect number of arguments, format is MIToolbox(\"FLAG\",varargin)\n");
+ }
+
+ /* number to function map
+ ** 1 = calculateProbability
+ ** 2 = calculateJointProbability
+ ** 3 = mergeArrays
+ ** 4 = H(X)
+ ** 5 = H(XY)
+ ** 6 = H(X|Y)
+ ** 7 = I(X;Y)
+ ** 8 = I(X;Y|Z)
+ ** 9 = normaliseArray
+ */
+
+ flag = *mxGetPr(prhs[0]);
+
+ switch (flag)
+ {
+ case 1:
+ {
+ /*
+ **calculateProbability
+ */
+ numberOfSamples = mxGetM(prhs[1]);
+ dataVector = (double *) mxGetPr(prhs[1]);
+
+ /*ProbabilityState calculateProbability(double *dataVector, int vectorLength);*/
+ state = calculateProbability(dataVector,numberOfSamples);
+
+ plhs[0] = mxCreateDoubleMatrix(state.numStates,1,mxREAL);
+ plhs[1] = mxCreateDoubleMatrix(1,1,mxREAL);
+ output = (double *)mxGetPr(plhs[0]);
+ numStates = (double *) mxGetPr(plhs[1]);
+
+ *numStates = state.numStates;
+
+ for (i = 0; i < state.numStates; i++)
+ {
+ output[i] = state.probabilityVector[i];
+ }
+
+ break;
+ }/*case 1 - calculateProbability*/
+ case 2:
+ {
+ /*
+ **calculateJointProbability
+ */
+ numberOfSamples = mxGetM(prhs[1]);
+ firstVector = (double *) mxGetPr(prhs[1]);
+ secondVector = (double *) mxGetPr(prhs[2]);
+
+ /*JointProbabilityState calculateJointProbability(double *firstVector, double *secondVector int vectorLength);*/
+ jointState = calculateJointProbability(firstVector,secondVector,numberOfSamples);
+
+ plhs[0] = mxCreateDoubleMatrix(jointState.numJointStates,1,mxREAL);
+ plhs[1] = mxCreateDoubleMatrix(1,1,mxREAL);
+ plhs[2] = mxCreateDoubleMatrix(jointState.numFirstStates,1,mxREAL);
+ plhs[3] = mxCreateDoubleMatrix(1,1,mxREAL);
+ plhs[4] = mxCreateDoubleMatrix(jointState.numSecondStates,1,mxREAL);
+ plhs[5] = mxCreateDoubleMatrix(1,1,mxREAL);
+ jointOutput = (double *)mxGetPr(plhs[0]);
+ numJointStates = (double *) mxGetPr(plhs[1]);
+ firstOutput = (double *)mxGetPr(plhs[2]);
+ numFirstStates = (double *) mxGetPr(plhs[3]);
+ secondOutput = (double *)mxGetPr(plhs[4]);
+ numSecondStates = (double *) mxGetPr(plhs[5]);
+
+ *numJointStates = jointState.numJointStates;
+ *numFirstStates = jointState.numFirstStates;
+ *numSecondStates = jointState.numSecondStates;
+
+ for (i = 0; i < jointState.numJointStates; i++)
+ {
+ jointOutput[i] = jointState.jointProbabilityVector[i];
+ }
+ for (i = 0; i < jointState.numFirstStates; i++)
+ {
+ firstOutput[i] = jointState.firstProbabilityVector[i];
+ }
+ for (i = 0; i < jointState.numSecondStates; i++)
+ {
+ secondOutput[i] = jointState.secondProbabilityVector[i];
+ }
+
+ break;
+ }/*case 2 - calculateJointProbability */
+ case 3:
+ {
+ /*
+ **mergeArrays
+ */
+ numberOfSamples = mxGetM(prhs[1]);
+ numberOfFeatures = mxGetN(prhs[1]);
+
+ numArities = 0;
+ if (nrhs > 2)
+ {
+ numArities = mxGetN(prhs[2]);
+ /*printf("arities = %d, features = %d, samples = %d\n",numArities,numberOfFeatures,numberOfSamples);*/
+ }
+
+ plhs[0] = mxCreateDoubleMatrix(0,0,mxREAL);
+
+ if (numArities == 0)
+ {
+ /*
+ **no arities therefore compress output
+ */
+ if ((numberOfFeatures > 0) && (numberOfSamples > 0))
+ {
+ matrix = (double *) mxGetPr(prhs[1]);
+ mergedVector = (double *) mxCalloc(numberOfSamples,sizeof(double));
+
+ plhs[0] = mxCreateDoubleMatrix(numberOfSamples,1,mxREAL);
+ output = (double *)mxGetPr(plhs[0]);
+
+ /*int mergeMultipleArrays(double *inputMatrix, double *outputVector, int matrixWidth, int vectorLength)*/
+ mergeMultipleArrays(matrix, mergedVector, numberOfFeatures, numberOfSamples);
+ for (i = 0; i < numberOfSamples; i++)
+ {
+ output[i] = mergedVector[i];
+ }
+
+ mxFree(mergedVector);
+ mergedVector = NULL;
+ }
+ }
+ else if (numArities == numberOfFeatures)
+ {
+ if ((numberOfFeatures > 0) && (numberOfSamples > 0))
+ {
+
+ matrix = (double *) mxGetPr(prhs[1]);
+ mergedVector = (double *) mxCalloc(numberOfSamples,sizeof(double));
+
+ arities = (double *) mxGetPr(prhs[2]);
+ intArities = (int *) mxCalloc(numberOfFeatures,sizeof(int));
+ for (i = 0; i < numArities; i++)
+ {
+ intArities[i] = (int) floor(arities[i]);
+ }
+
+ /*int mergeMultipleArrays(double *inputMatrix, double *outputVector, int matrixWidth, int *arities, int vectorLength);*/
+ errorTest = mergeMultipleArraysArities(matrix, mergedVector, numberOfFeatures, intArities, numberOfSamples);
+
+ if (errorTest != -1)
+ {
+ plhs[0] = mxCreateDoubleMatrix(numberOfSamples,1,mxREAL);
+ output = (double *)mxGetPr(plhs[0]);
+ for (i = 0; i < numberOfSamples; i++)
+ {
+ output[i] = mergedVector[i];
+ }
+ }
+ else
+ {
+ printf("Incorrect arities supplied. More states in data than specified\n");
+ }
+
+ mxFree(mergedVector);
+ mergedVector = NULL;
+ }
+ }
+ else
+ {
+ printf("Number of arities does not match number of features, arities should be a row vector\n");
+ }
+
+ break;
+ }/*case 3 - mergeArrays*/
+ case 4:
+ {
+ /*
+ **H(X)
+ */
+ numberOfSamples = mxGetM(prhs[1]);
+ numberOfFeatures = mxGetN(prhs[1]);
+
+ dataVector = (double *) mxGetPr(prhs[1]);
+
+ plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
+ output = (double *)mxGetPr(plhs[0]);
+
+ if (numberOfFeatures == 1)
+ {
+ /*double calculateEntropy(double *dataVector, int vectorLength);*/
+ *output = calculateEntropy(dataVector,numberOfSamples);
+ }
+ else
+ {
+ printf("No columns in input\n");
+ *output = -1.0;
+ }
+
+ break;
+ }/*case 4 - H(X)*/
+ case 5:
+ {
+ /*
+ **H(XY)
+ */
+ numberOfSamples = mxGetM(prhs[1]);
+ checkSamples = mxGetM(prhs[2]);
+
+ numberOfFeatures = mxGetN(prhs[1]);
+ checkFeatures = mxGetN(prhs[2]);
+
+ firstVector = mxGetPr(prhs[1]);
+ secondVector = mxGetPr(prhs[2]);
+
+ plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
+ output = (double *)mxGetPr(plhs[0]);
+
+
+ if ((numberOfFeatures == 1) && (checkFeatures == 1))
+ {
+ if ((numberOfSamples == 0) && (checkSamples == 0))
+ {
+ *output = 0.0;
+ }
+ else if (numberOfSamples == 0)
+ {
+ *output = calculateEntropy(secondVector,numberOfSamples);
+ }
+ else if (checkSamples == 0)
+ {
+ *output = calculateEntropy(firstVector,numberOfSamples);
+ }
+ else if (numberOfSamples == checkSamples)
+ {
+ /*double calculateJointEntropy(double *firstVector, double *secondVector, int vectorLength);*/
+ *output = calculateJointEntropy(firstVector,secondVector,numberOfSamples);
+ }
+ else
+ {
+ printf("Vector lengths do not match, they must be the same length\n");
+ *output = -1.0;
+ }
+ }
+ else
+ {
+ printf("No columns in input\n");
+ *output = -1.0;
+ }
+
+ break;
+ }/*case 5 - H(XY)*/
+ case 6:
+ {
+ /*
+ **H(X|Y)
+ */
+ numberOfSamples = mxGetM(prhs[1]);
+ checkSamples = mxGetM(prhs[2]);
+
+ numberOfFeatures = mxGetN(prhs[1]);
+ checkFeatures = mxGetN(prhs[2]);
+
+ dataVector = mxGetPr(prhs[1]);
+ condVector = mxGetPr(prhs[2]);
+
+ plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
+ output = (double *)mxGetPr(plhs[0]);
+
+ if ((numberOfFeatures == 1) && (checkFeatures == 1))
+ {
+ if (numberOfSamples == 0)
+ {
+ *output = 0.0;
+ }
+ else if (checkSamples == 0)
+ {
+ *output = calculateEntropy(dataVector,numberOfSamples);
+ }
+ else if (numberOfSamples == checkSamples)
+ {
+ /*double calculateConditionalEntropy(double *dataVector, double *condVector, int vectorLength);*/
+ *output = calculateConditionalEntropy(dataVector,condVector,numberOfSamples);
+ }
+ else
+ {
+ printf("Vector lengths do not match, they must be the same length\n");
+ *output = -1.0;
+ }
+ }
+ else
+ {
+ printf("No columns in input\n");
+ *output = -1.0;
+ }
+ break;
+ }/*case 6 - H(X|Y)*/
+ case 7:
+ {
+ /*
+ **I(X;Y)
+ */
+ numberOfSamples = mxGetM(prhs[1]);
+ checkSamples = mxGetM(prhs[2]);
+
+ numberOfFeatures = mxGetN(prhs[1]);
+ checkFeatures = mxGetN(prhs[2]);
+
+ firstVector = mxGetPr(prhs[1]);
+ secondVector = mxGetPr(prhs[2]);
+
+ plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
+ output = (double *)mxGetPr(plhs[0]);
+
+ if ((numberOfFeatures == 1) && (checkFeatures == 1))
+ {
+ if ((numberOfSamples == 0) || (checkSamples == 0))
+ {
+ *output = 0.0;
+ }
+ else if (numberOfSamples == checkSamples)
+ {
+ /*double calculateMutualInformation(double *firstVector, double *secondVector, int vectorLength);*/
+ *output = calculateMutualInformation(firstVector,secondVector,numberOfSamples);
+ }
+ else
+ {
+ printf("Vector lengths do not match, they must be the same length\n");
+ *output = -1.0;
+ }
+ }
+ else
+ {
+ printf("No columns in input\n");
+ *output = -1.0;
+ }
+ break;
+ }/*case 7 - I(X;Y)*/
+ case 8:
+ {
+ /*
+ **I(X;Y|Z)
+ */
+ numberOfSamples = mxGetM(prhs[1]);
+ checkSamples = mxGetM(prhs[2]);
+ thirdCheckSamples = mxGetM(prhs[3]);
+
+ numberOfFeatures = mxGetN(prhs[1]);
+ checkFeatures = mxGetN(prhs[2]);
+ thirdCheckFeatures = mxGetN(prhs[3]);
+
+ firstVector = mxGetPr(prhs[1]);
+ targetVector = mxGetPr(prhs[2]);
+ condVector = mxGetPr(prhs[3]);
+
+ plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
+ output = (double *)mxGetPr(plhs[0]);
+
+ if ((numberOfFeatures == 1) && (checkFeatures == 1))
+ {
+ if ((numberOfSamples == 0) || (checkSamples == 0))
+ {
+ *output = 0.0;
+ }
+ else if ((thirdCheckSamples == 0) || (thirdCheckFeatures != 1))
+ {
+ *output = calculateMutualInformation(firstVector,targetVector,numberOfSamples);
+ }
+ else if ((numberOfSamples == checkSamples) && (numberOfSamples == thirdCheckSamples))
+ {
+ /*double calculateConditionalMutualInformation(double *firstVector, double *targetVector, double *condVector, int vectorLength);*/
+ *output = calculateConditionalMutualInformation(firstVector,targetVector,condVector,numberOfSamples);
+ }
+ else
+ {
+ printf("Vector lengths do not match, they must be the same length\n");
+ *output = -1.0;
+ }
+ }
+ else
+ {
+ printf("No columns in input\n");
+ *output = -1.0;
+ }
+ break;
+ }/*case 8 - I(X;Y|Z)*/
+ case 9:
+ {
+ /*
+ **normaliseArray
+ */
+ numberOfSamples = mxGetM(prhs[1]);
+ dataVector = (double *) mxGetPr(prhs[1]);
+
+ outputIntVector = (int *) mxCalloc(numberOfSamples,sizeof(int));
+
+ plhs[0] = mxCreateDoubleMatrix(numberOfSamples,1,mxREAL);
+ plhs[1] = mxCreateDoubleMatrix(1,1,mxREAL);
+ output = (double *)mxGetPr(plhs[0]);
+ numStates = (double *) mxGetPr(plhs[1]);
+
+ /*int normaliseArray(double *inputVector, int *outputVector, int vectorLength);*/
+ *numStates = normaliseArray(dataVector, outputIntVector, numberOfSamples);
+
+ for (i = 0; i < numberOfSamples; i++)
+ {
+ output[i] = outputIntVector[i];
+ }
+
+ break;
+ }/*case 9 - normaliseArray*/
+ default:
+ {
+ printf("Unrecognised flag\n");
+ break;
+ }/*default*/
+ }/*switch(flag)*/
+
+ return;
+}/*mexFunction()*/
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..0135410
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,84 @@
+#makefile for MIToolbox
+#Author: Adam Pocock, apocock@cs.man.ac.uk
+#Created 11/3/2010
+#
+#
+#Copyright 2010 Adam Pocock, The University Of Manchester
+#www.cs.manchester.ac.uk
+#
+#This file is part of MIToolbox.
+#
+#MIToolbox is free software: you can redistribute it and/or modify
+#it under the terms of the GNU Lesser General Public License as published by
+#the Free Software Foundation, either version 3 of the License, or
+#(at your option) any later version.
+#
+#MIToolbox 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 Lesser General Public License for more details.
+#
+#You should have received a copy of the GNU Lesser General Public License
+#along with MIToolbox. If not, see .
+
+CXXFLAGS = -O3 -fPIC
+COMPILER = gcc
+objects = ArrayOperations.o CalculateProbability.o Entropy.o \
+ MutualInformation.o RenyiEntropy.o RenyiMutualInformation.o
+
+libMIToolbox.so : $(objects)
+ $(COMPILER) $(CXXFLAGS) -shared -o libMIToolbox.so $(objects)
+
+RenyiMutualInformation.o: RenyiMutualInformation.c MIToolbox.h ArrayOperations.h \
+ CalculateProbability.h RenyiEntropy.h
+ $(COMPILER) $(CXXFLAGS) -DCOMPILE_C -c RenyiMutualInformation.c
+
+RenyiEntropy.o: RenyiEntropy.c MIToolbox.h ArrayOperations.h \
+ CalculateProbability.h
+ $(COMPILER) $(CXXFLAGS) -DCOMPILE_C -c RenyiEntropy.c
+
+MutualInformation.o: MutualInformation.c MIToolbox.h ArrayOperations.h \
+ CalculateProbability.h Entropy.h MutualInformation.h
+ $(COMPILER) $(CXXFLAGS) -DCOMPILE_C -c MutualInformation.c
+
+Entropy.o: Entropy.c MIToolbox.h ArrayOperations.h CalculateProbability.h \
+ Entropy.h
+ $(COMPILER) $(CXXFLAGS) -DCOMPILE_C -c Entropy.c
+
+CalculateProbability.o: CalculateProbability.c MIToolbox.h ArrayOperations.h \
+ CalculateProbability.h
+ $(COMPILER) $(CXXFLAGS) -DCOMPILE_C -c CalculateProbability.c
+
+ArrayOperations.o: ArrayOperations.c MIToolbox.h ArrayOperations.h
+ $(COMPILER) $(CXXFLAGS) -DCOMPILE_C -c ArrayOperations.c
+
+.PHONY : debug
+debug:
+ $(MAKE) libMIToolbox.so "CXXFLAGS = -g -DDEBUG -fPIC"
+
+.PHONY : x86
+x86:
+ $(MAKE) libMIToolbox.so "CXXFLAGS = -O3 -fPIC -m32"
+
+.PHONY : x64
+x64:
+ $(MAKE) libMIToolbox.so "CXXFLAGS = -O3 -fPIC -m64"
+
+.PHONY : matlab
+matlab:
+ mex MIToolboxMex.c MutualInformation.c Entropy.c CalculateProbability.c ArrayOperations.c
+ mex RenyiMIToolboxMex.c RenyiMutualInformation.c RenyiEntropy.c CalculateProbability.c ArrayOperations.c
+
+.PHONY : matlab-debug
+matlab-debug:
+ mex -g MIToolboxMex.c MutualInformation.c Entropy.c CalculateProbability.c ArrayOperations.c
+ mex -g RenyiMIToolboxMex.c RenyiMutualInformation.c RenyiEntropy.c CalculateProbability.c ArrayOperations.c
+
+.PHONY : intel
+intel:
+ $(MAKE) libMIToolbox.so "COMPILER = icc" "CXXFLAGS = -O2 -fPIC -xHost"
+
+.PHONY : clean
+clean:
+ rm *.o libMIToolbox.so
+
diff --git a/MutualInformation.c b/MutualInformation.c
new file mode 100644
index 0000000..0fb4766
--- /dev/null
+++ b/MutualInformation.c
@@ -0,0 +1,95 @@
+/*******************************************************************************
+** MutualInformation.cpp
+** Part of the mutual information toolbox
+**
+** Contains functions to calculate the mutual information of
+** two variables X and Y, I(X;Y), to calculate the joint mutual information
+** of two variables X & Z on the variable Y, I(XZ;Y), and the conditional
+** mutual information I(x;Y|Z)
+**
+** Author: Adam Pocock
+** Created 19/2/2010
+**
+** Copyright 2010 Adam Pocock, The University Of Manchester
+** www.cs.manchester.ac.uk
+**
+** This file is part of MIToolbox.
+**
+** MIToolbox is free software: you can redistribute it and/or modify
+** it under the terms of the GNU Lesser General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** MIToolbox 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 Lesser General Public License for more details.
+**
+** You should have received a copy of the GNU Lesser General Public License
+** along with MIToolbox. If not, see .
+**
+*******************************************************************************/
+
+#include "MIToolbox.h"
+#include "ArrayOperations.h"
+#include "CalculateProbability.h"
+#include "Entropy.h"
+#include "MutualInformation.h"
+
+double calculateMutualInformation(double *dataVector, double *targetVector, int vectorLength)
+{
+ double mutualInformation = 0.0;
+ int firstIndex,secondIndex;
+ int i;
+ JointProbabilityState state = calculateJointProbability(dataVector,targetVector,vectorLength);
+
+ /*
+ ** I(X;Y) = sum sum p(xy) * log (p(xy)/p(x)p(y))
+ */
+ for (i = 0; i < state.numJointStates; i++)
+ {
+ firstIndex = i % state.numFirstStates;
+ secondIndex = i / state.numFirstStates;
+
+ if ((state.jointProbabilityVector[i] > 0) && (state.firstProbabilityVector[firstIndex] > 0) && (state.secondProbabilityVector[secondIndex] > 0))
+ {
+ /*double division is probably more stable than multiplying two small numbers together
+ ** mutualInformation += state.jointProbabilityVector[i] * log(state.jointProbabilityVector[i] / (state.firstProbabilityVector[firstIndex] * state.secondProbabilityVector[secondIndex]));
+ */
+ mutualInformation += state.jointProbabilityVector[i] * log(state.jointProbabilityVector[i] / state.firstProbabilityVector[firstIndex] / state.secondProbabilityVector[secondIndex]);
+ }
+ }
+
+ mutualInformation /= log(2.0);
+
+ FREE_FUNC(state.firstProbabilityVector);
+ state.firstProbabilityVector = NULL;
+ FREE_FUNC(state.secondProbabilityVector);
+ state.secondProbabilityVector = NULL;
+ FREE_FUNC(state.jointProbabilityVector);
+ state.jointProbabilityVector = NULL;
+
+ return mutualInformation;
+}/*calculateMutualInformation(double *,double *,int)*/
+
+double calculateConditionalMutualInformation(double *dataVector, double *targetVector, double *conditionVector, int vectorLength)
+{
+ double mutualInformation = 0.0;
+ double firstCondition, secondCondition;
+ double *mergedVector = (double *) CALLOC_FUNC(vectorLength,sizeof(double));
+
+ mergeArrays(targetVector,conditionVector,mergedVector,vectorLength);
+
+ /* I(X;Y|Z) = H(X|Z) - H(X|YZ) */
+ /* double calculateConditionalEntropy(double *dataVector, double *conditionVector, int vectorLength); */
+ firstCondition = calculateConditionalEntropy(dataVector,conditionVector,vectorLength);
+ secondCondition = calculateConditionalEntropy(dataVector,mergedVector,vectorLength);
+
+ mutualInformation = firstCondition - secondCondition;
+
+ FREE_FUNC(mergedVector);
+ mergedVector = NULL;
+
+ return mutualInformation;
+}/*calculateConditionalMutualInformation(double *,double *,double *,int)*/
+
diff --git a/MutualInformation.h b/MutualInformation.h
new file mode 100644
index 0000000..1045912
--- /dev/null
+++ b/MutualInformation.h
@@ -0,0 +1,64 @@
+/*******************************************************************************
+** MutualInformation.h
+** Part of the mutual information toolbox
+**
+** Contains functions to calculate the mutual information of
+** two variables X and Y, I(X;Y), to calculate the joint mutual information
+** of two variables X & Z on the variable Y, I(XZ;Y), and the conditional
+** mutual information I(x;Y|Z)
+**
+** Author: Adam Pocock
+** Created 19/2/2010
+**
+** Copyright 2010 Adam Pocock, The University Of Manchester
+** www.cs.manchester.ac.uk
+**
+** This file is part of MIToolbox.
+**
+** MIToolbox is free software: you can redistribute it and/or modify
+** it under the terms of the GNU Lesser General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** MIToolbox 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 Lesser General Public License for more details.
+**
+** You should have received a copy of the GNU Lesser General Public License
+** along with MIToolbox. If not, see .
+**
+*******************************************************************************/
+
+#ifndef __MutualInformation_H
+#define __MutualInformation_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*******************************************************************************
+** calculateMutualInformation returns the log base 2 mutual information between
+** dataVector and targetVector, I(X;Y)
+**
+** length(dataVector) == length(targetVector) == vectorLength otherwise there
+** will be a segmentation fault
+*******************************************************************************/
+double calculateMutualInformation(double *dataVector, double *targetVector, int vectorLength);
+
+/*******************************************************************************
+** calculateConditionalMutualInformation returns the log base 2
+** mutual information between dataVector and targetVector, conditioned on
+** conditionVector, I(X;Y|Z)
+**
+** length(dataVector) == length(targetVector) == length(condtionVector) == vectorLength
+** otherwise it will error with a segmentation fault
+*******************************************************************************/
+double calculateConditionalMutualInformation(double *dataVector, double *targetVector, double *conditionVector, int vectorLength);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/README b/README
new file mode 100644
index 0000000..dfa4fce
--- /dev/null
+++ b/README
@@ -0,0 +1,32 @@
+This is the MIToolbox v1.02 for C/C++ and MATLAB/OCTAVE
+
+It provides a series of functions for working with information theory and
+Renyi's extension to information theory. It also contains some variable
+manipulation functions to preprocess discrete/categorical variables to generate
+information theoretic values from the variables.
+
+These functions are targeted for use with feature selection algorithms rather
+than communication channels and so expect all the data to be available before
+execution and sample their own probability distributions from the data.
+
+Functions contained:
+ - Entropy
+ - Conditional Entropy
+ - Mutual Information
+ - Conditional Mutual Information
+ - generating a joint variable
+ - generating a probability distribution from a discrete random variable
+ - Renyi's Entropy
+ - Renyi's Mutual Information
+
+To compile the library for use in MATLAB/OCTAVE, execute CompileScript.m
+from within MATLAB, or run 'make matlab' from a linux terminal.
+
+The C source files are licensed under the LGPL v3. The MATLAB wrappers and
+demonstration feature selection algorithms are provided as is with no warranty
+as examples of how to use the library in MATLAB.
+
+Update History
+07/07/2010 - v1.0 - Initial Release
+02/09/2010 - v1.01 - Updated CMIM.m in demonstration_algorithms, due to a bug where the last feature would not be selected first if it had the highest MI
+15/10/2010 - v1.02 - Fixed bug where MIToolbox would cause a segmentation fault if a x by 0 empty matrix was passed in. Now prints an error message and returns gracefully
diff --git a/RenyiEntropy.c b/RenyiEntropy.c
new file mode 100644
index 0000000..32c5ff9
--- /dev/null
+++ b/RenyiEntropy.c
@@ -0,0 +1,191 @@
+/*******************************************************************************
+** RenyiEntropy.cpp
+** Part of the mutual information toolbox
+**
+** Contains functions to calculate the Renyi alpha entropy of a single variable
+** H_\alpha(X), the Renyi joint entropy of two variables H_\alpha(X,Y), and the
+** conditional Renyi entropy H_\alpha(X|Y)
+**
+** Author: Adam Pocock
+** Created 26/3/2010
+**
+** Copyright 2010 Adam Pocock, The University Of Manchester
+** www.cs.manchester.ac.uk
+**
+** This file is part of MIToolbox.
+**
+** MIToolbox is free software: you can redistribute it and/or modify
+** it under the terms of the GNU Lesser General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** MIToolbox 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 Lesser General Public License for more details.
+**
+** You should have received a copy of the GNU Lesser General Public License
+** along with MIToolbox. If not, see .
+**
+*******************************************************************************/
+
+#include "MIToolbox.h"
+#include "ArrayOperations.h"
+#include "CalculateProbability.h"
+#include "Entropy.h"
+
+double calculateRenyiEntropy(double alpha, double *dataVector, int vectorLength)
+{
+ double entropy = 0.0;
+ double tempValue = 0.0;
+ int i;
+ ProbabilityState state = calculateProbability(dataVector,vectorLength);
+
+ /*H_\alpha(X) = 1/(1-alpha) * log(2)(sum p(x)^alpha)*/
+ for (i = 0; i < state.numStates; i++)
+ {
+ tempValue = state.probabilityVector[i];
+
+ if (tempValue > 0)
+ {
+ entropy += pow(tempValue,alpha);
+ /*printf("Entropy = %f, i = %d\n", entropy,i);*/
+ }
+ }
+
+ /*printf("Entropy = %f\n", entropy);*/
+
+ entropy = log(entropy);
+
+ entropy /= log(2.0);
+
+ entropy /= (1.0-alpha);
+
+ /*printf("Entropy = %f\n", entropy);*/
+ FREE_FUNC(state.probabilityVector);
+ state.probabilityVector = NULL;
+
+ return entropy;
+}/*calculateRenyiEntropy(double,double*,int)*/
+
+double calculateJointRenyiEntropy(double alpha, double *firstVector, double *secondVector, int vectorLength)
+{
+ double jointEntropy = 0.0;
+ double tempValue = 0.0;
+ int i;
+ JointProbabilityState state = calculateJointProbability(firstVector,secondVector,vectorLength);
+
+ /*H_\alpha(XY) = 1/(1-alpha) * log(2)(sum p(xy)^alpha)*/
+ for (i = 0; i < state.numJointStates; i++)
+ {
+ tempValue = state.jointProbabilityVector[i];
+ if (tempValue > 0)
+ {
+ jointEntropy += pow(tempValue,alpha);
+ }
+ }
+
+ jointEntropy = log(jointEntropy);
+
+ jointEntropy /= log(2.0);
+
+ jointEntropy /= (1.0-alpha);
+
+ FREE_FUNC(state.firstProbabilityVector);
+ state.firstProbabilityVector = NULL;
+ FREE_FUNC(state.secondProbabilityVector);
+ state.secondProbabilityVector = NULL;
+ FREE_FUNC(state.jointProbabilityVector);
+ state.jointProbabilityVector = NULL;
+
+ return jointEntropy;
+}/*calculateJointRenyiEntropy(double,double*,double*,int)*/
+
+double calcCondRenyiEnt(double alpha, double *dataVector, double *conditionVector, int uniqueInCondVector, int vectorLength)
+{
+ /*uniqueInCondVector = is the number of unique values in the cond vector.*/
+
+ /*condEntropy = sum p(y) * sum p(x|y)^alpha(*/
+
+ /*
+ ** first generate the seperate variables
+ */
+
+ double *seperateVectors = (double *) CALLOC_FUNC(uniqueInCondVector*vectorLength,sizeof(double));
+ int *seperateVectorCount = (int *) CALLOC_FUNC(uniqueInCondVector,sizeof(int));
+ double seperateVectorProb = 0.0;
+ int i,j;
+ double entropy = 0.0;
+ double tempValue = 0.0;
+ int currentValue;
+ double tempEntropy;
+ ProbabilityState state;
+
+ double **seperateVectors2D = (double **) CALLOC_FUNC(uniqueInCondVector,sizeof(double*));
+ for(j=0; j < uniqueInCondVector; j++)
+ seperateVectors2D[j] = seperateVectors + (int)j*vectorLength;
+
+ for (i = 0; i < vectorLength; i++)
+ {
+ currentValue = (int) (conditionVector[i] - 1.0);
+ /*printf("CurrentValue = %d\n",currentValue);*/
+ seperateVectors2D[currentValue][seperateVectorCount[currentValue]] = dataVector[i];
+ seperateVectorCount[currentValue]++;
+ }
+
+
+
+ for (j = 0; j < uniqueInCondVector; j++)
+ {
+ tempEntropy = 0.0;
+ seperateVectorProb = ((double)seperateVectorCount[j]) / vectorLength;
+ state = calculateProbability(seperateVectors2D[j],seperateVectorCount[j]);
+
+ /*H_\alpha(X) = 1/(1-alpha) * log(2)(sum p(x)^alpha)*/
+ for (i = 0; i < state.numStates; i++)
+ {
+ tempValue = state.probabilityVector[i];
+
+ if (tempValue > 0)
+ {
+ tempEntropy += pow(tempValue,alpha);
+ /*printf("Entropy = %f, i = %d\n", entropy,i);*/
+ }
+ }
+
+ /*printf("Entropy = %f\n", entropy);*/
+
+ tempEntropy = log(tempEntropy);
+
+ tempEntropy /= log(2.0);
+
+ tempEntropy /= (1.0-alpha);
+
+ entropy += tempEntropy;
+
+ FREE_FUNC(state.probabilityVector);
+ }
+
+ FREE_FUNC(seperateVectors2D);
+ seperateVectors2D = NULL;
+
+ FREE_FUNC(seperateVectors);
+ FREE_FUNC(seperateVectorCount);
+
+ seperateVectors = NULL;
+ seperateVectorCount = NULL;
+
+ return entropy;
+}/*calcCondRenyiEnt(double *,double *,int)*/
+
+double calculateConditionalRenyiEntropy(double alpha, double *dataVector, double *conditionVector, int vectorLength)
+{
+ /*calls this:
+ **double calculateConditionalRenyiEntropy(double alpha, double *firstVector, double *condVector, int uniqueInCondVector, int vectorLength)
+ **after determining uniqueInCondVector
+ */
+ int numUnique = numberOfUniqueValues(conditionVector, vectorLength);
+
+ return calcCondRenyiEnt(alpha, dataVector, conditionVector, numUnique, vectorLength);
+}/*calculateConditionalRenyiEntropy(double,double*,double*,int)*/
+
diff --git a/RenyiEntropy.h b/RenyiEntropy.h
new file mode 100644
index 0000000..296bc4b
--- /dev/null
+++ b/RenyiEntropy.h
@@ -0,0 +1,68 @@
+/*******************************************************************************
+** RenyiEntropy.h
+** Part of the mutual information toolbox
+**
+** Contains functions to calculate the Renyi alpha entropy of a single variable
+** H_\alpha(X), the Renyi joint entropy of two variables H_\alpha(X,Y), and the
+** conditional Renyi entropy H_\alpha(X|Y)
+**
+** Author: Adam Pocock
+** Created 26/3/2010
+**
+** Copyright 2010 Adam Pocock, The University Of Manchester
+** www.cs.manchester.ac.uk
+**
+** This file is part of MIToolbox.
+**
+** MIToolbox is free software: you can redistribute it and/or modify
+** it under the terms of the GNU Lesser General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** MIToolbox 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 Lesser General Public License for more details.
+**
+** You should have received a copy of the GNU Lesser General Public License
+** along with MIToolbox. If not, see .
+**
+*******************************************************************************/
+
+#ifndef __Renyi_Entropy_H
+#define __Renyi_Entropy_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*******************************************************************************
+** calculateRenyiEntropy returns the Renyi entropy in log base 2 of dataVector
+** H_{\alpha}(X), for \alpha != 1
+**
+** length(dataVector) == vectorLength otherwise there
+** will be a segmentation fault
+*******************************************************************************/
+double calculateRenyiEntropy(double alpha, double *dataVector, int vectorLength);
+
+/*******************************************************************************
+** calculateJointRenyiEntropy returns the Renyi entropy in log base 2 of the
+** joint variable of firstVector and secondVector H_{\alpha}(XY),
+** for \alpha != 1
+**
+** length(firstVector) == length(secondVector) == vectorLength otherwise there
+** will be a segmentation fault
+*******************************************************************************/
+double calculateJointRenyiEntropy(double alpha, double *firstVector, double *secondVector, int vectorLength);
+
+/* This function does not return a valid conditonal entropy as it has no
+** meaning in Renyi's extension of entropy
+double calculateConditionalRenyiEntropy(double alpha, double *dataVector, double *conditionVector, int vectorLength);
+*/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/RenyiMIToolbox.m b/RenyiMIToolbox.m
new file mode 100644
index 0000000..cd235e9
--- /dev/null
+++ b/RenyiMIToolbox.m
@@ -0,0 +1,48 @@
+function [varargout] = RenyiMIToolbox(functionName, alpha, varargin)
+%function [varargout] = RenyiMIToolbox(functionName, alpha, varargin)
+%
+%Provides access to the functions in RenyiMIToolboxMex
+%
+%Expects column vectors, will not work with row vectors
+%
+%Function list
+%"Entropy" = H_{\alpha}(X) = 1
+%"MI" = I_{\alpha}(X;Y) = 3
+%
+%Arguments and returned values
+%[entropy] = H_\alpha(X) = H(alpha,vector)
+%[mi] = I_\alpha(X;Y) = I(alpha,vector,target)
+%
+%Internal RenyiMIToolbox function number
+%Renyi Entropy = 1;
+%Renyi MI = 3;
+
+if (alpha ~= 1)
+ if (strcmpi(functionName,'Entropy') || strcmpi(functionName,'h'))
+ %disp('Calculating Entropy');
+ if (size(varargin{1},2)>1)
+ mergedVector = MIToolboxMex(3,varargin{1});
+ else
+ mergedVector = varargin{1};
+ end
+ [varargout{1}] = RenyiMIToolboxMex(1,alpha,mergedVector);
+ elseif (strcmpi(functionName,'MI'))
+ if (size(varargin{1},2)>1)
+ mergedFirst = MIToolboxMex(3,varargin{1});
+ else
+ mergedFirst = varargin{1};
+ end
+ if (size(varargin{2},2)>1)
+ mergedSecond = MIToolboxMex(3,varargin{2});
+ else
+ mergedSecond = varargin{2};
+ end
+ [varargout{1}] = RenyiMIToolboxMex(3,alpha,mergedFirst,mergedSecond);
+ else
+ varargout{1} = 0;
+ disp(['Unrecognised functionName ' functionName]);
+ end
+else
+ disp('For alpha = 1 use functions in MIToolbox.m');
+ disp('as those functions are the implementation of Shannon''s Information Theory');
+end
diff --git a/RenyiMIToolboxMex.c b/RenyiMIToolboxMex.c
new file mode 100644
index 0000000..03ab076
--- /dev/null
+++ b/RenyiMIToolboxMex.c
@@ -0,0 +1,197 @@
+/*******************************************************************************
+**
+** RenyiMIToolboxMex.cpp
+** is the MATLAB entry point for the Renyi Entropy and MI MIToolbox functions
+** when called from a MATLAB/OCTAVE script.
+**
+** Copyright 2010 Adam Pocock, The University Of Manchester
+** www.cs.manchester.ac.uk
+**
+** This file is part of MIToolbox.
+**
+** MIToolbox is free software: you can redistribute it and/or modify
+** it under the terms of the GNU Lesser General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** MIToolbox 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 Lesser General Public License for more details.
+**
+** You should have received a copy of the GNU Lesser General Public License
+** along with MIToolbox. If not, see .
+**
+*******************************************************************************/
+#include "MIToolbox.h"
+#include "RenyiEntropy.h"
+#include "RenyiMutualInformation.h"
+
+/*******************************************************************************
+**entry point for the mex call
+**nlhs - number of outputs
+**plhs - pointer to array of outputs
+**nrhs - number of inputs
+**prhs - pointer to array of inputs
+*******************************************************************************/
+void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
+{
+ /*****************************************************************************
+ ** this function takes a flag and 2 or 3 other arguments
+ ** the first is a scalar alpha value, and the remainder are
+ ** arrays. It returns a Renyi entropy or mutual information using the
+ ** alpha divergence.
+ *****************************************************************************/
+
+ int flag, numberOfSamples, checkSamples, numberOfFeatures, checkFeatures;
+ double alpha;
+ double *dataVector, *firstVector, *secondVector, *output;
+
+ /*if (nlhs != 1)
+ {
+ printf("Incorrect number of output arguments\n");
+ }//if not 1 output
+ */
+ if (nrhs == 3)
+ {
+ /*printf("Must be H(X)\n");*/
+ }
+ else if (nrhs == 4)
+ {
+ /*printf("Must be H(XY), I(X;Y)\n");*/
+ }
+ else
+ {
+ printf("Incorrect number of arguments, format is RenyiMIToolbox(\"FLAG\",varargin)\n");
+ }
+
+ /* number to function map
+ ** 1 = H(X)
+ ** 2 = H(XY)
+ ** 3 = I(X;Y)
+ */
+
+ flag = *mxGetPr(prhs[0]);
+
+ switch (flag)
+ {
+ case 1:
+ {
+ /*
+ **H_{\alpha}(X)
+ */
+ alpha = mxGetScalar(prhs[1]);
+ numberOfSamples = mxGetM(prhs[2]);
+ numberOfFeatures = mxGetN(prhs[2]);
+ dataVector = (double *) mxGetPr(prhs[2]);
+
+ plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
+ output = (double *) mxGetPr(plhs[0]);
+
+ if (numberOfFeatures == 1)
+ {
+ /*double calculateRenyiEntropy(double alpha, double *dataVector, long vectorLength);*/
+ *output = calculateRenyiEntropy(alpha,dataVector,numberOfSamples);
+ }
+ else
+ {
+ printf("No columns in input\n");
+ *output = -1.0;
+ }
+ break;
+ }/*case 1 - H_{\alpha}(X)*/
+ case 2:
+ {
+ /*
+ **H_{\alpha}(XY)
+ */
+ alpha = mxGetScalar(prhs[1]);
+
+ numberOfSamples = mxGetM(prhs[2]);
+ checkSamples = mxGetM(prhs[3]);
+
+ numberOfFeatures = mxGetN(prhs[2]);
+ checkFeatures = mxGetN(prhs[3]);
+
+ firstVector = mxGetPr(prhs[2]);
+ secondVector = mxGetPr(prhs[3]);
+
+ plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
+ output = (double *)mxGetPr(plhs[0]);
+
+ if ((numberOfFeatures == 1) && (checkFeatures == 1))
+ {
+ if ((numberOfSamples == 0) || (checkSamples == 0))
+ {
+ *output = 0.0;
+ }
+ else if (numberOfSamples == checkSamples)
+ {
+ /*double calculateJointRenyiEntropy(double alpha, double *firstVector, double *secondVector, long vectorLength);*/
+ *output = calculateJointRenyiEntropy(alpha,firstVector,secondVector,numberOfSamples);
+ }
+ else
+ {
+ printf("Vector lengths do not match, they must be the same length");
+ *output = -1.0;
+ }
+ }
+ else
+ {
+ printf("No columns in input\n");
+ *output = -1.0;
+ }
+ break;
+ }/*case 2 - H_{\alpha}(XY)*/
+ case 3:
+ {
+ /*
+ **I_{\alpha}(X;Y)
+ */
+ alpha = mxGetScalar(prhs[1]);
+
+ numberOfSamples = mxGetM(prhs[2]);
+ checkSamples = mxGetM(prhs[3]);
+
+ numberOfFeatures = mxGetN(prhs[2]);
+ checkFeatures = mxGetN(prhs[3]);
+
+ firstVector = mxGetPr(prhs[2]);
+ secondVector = mxGetPr(prhs[3]);
+
+ plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
+ output = (double *)mxGetPr(plhs[0]);
+
+ if ((numberOfFeatures == 1) && (checkFeatures == 1))
+ {
+ if ((numberOfSamples == 0) || (checkSamples == 0))
+ {
+ *output = 0.0;
+ }
+ else if (numberOfSamples == checkSamples)
+ {
+ /*double calculateRenyiMIDivergence(double alpha, double *dataVector, double *targetVector, long vectorLength);*/
+ *output = calculateRenyiMIDivergence(alpha,firstVector,secondVector,numberOfSamples);
+ }
+ else
+ {
+ printf("Vector lengths do not match, they must be the same length");
+ *output = -1.0;
+ }
+ }
+ else
+ {
+ printf("No columns in input\n");
+ *output = -1.0;
+ }
+ break;
+ }/*case 3 - I_{\alpha}(X;Y)*/
+ default:
+ {
+ printf("Unrecognised flag\n");
+ break;
+ }/*default*/
+ }/*switch(flag)*/
+
+ return;
+}/*mexFunction()*/
diff --git a/RenyiMutualInformation.c b/RenyiMutualInformation.c
new file mode 100644
index 0000000..dc6fd51
--- /dev/null
+++ b/RenyiMutualInformation.c
@@ -0,0 +1,95 @@
+/*******************************************************************************
+** RenyiMutualInformation.cpp
+** Part of the mutual information toolbox
+**
+** Contains functions to calculate the Renyi mutual information of
+** two variables X and Y, I_\alpha(X;Y), using the Renyi alpha divergence and
+** the joint entropy difference
+**
+** Author: Adam Pocock
+** Created 26/3/2010
+**
+** Copyright 2010 Adam Pocock, The University Of Manchester
+** www.cs.manchester.ac.uk
+**
+** This file is part of MIToolbox.
+**
+** MIToolbox is free software: you can redistribute it and/or modify
+** it under the terms of the GNU Lesser General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** MIToolbox 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 Lesser General Public License for more details.
+**
+** You should have received a copy of the GNU Lesser General Public License
+** along with MIToolbox. If not, see .
+**
+*******************************************************************************/
+
+#include "MIToolbox.h"
+#include "CalculateProbability.h"
+#include "RenyiEntropy.h"
+#include "RenyiMutualInformation.h"
+
+double calculateRenyiMIDivergence(double alpha, double *dataVector, double *targetVector, int vectorLength)
+{
+ double mutualInformation = 0.0;
+ int firstIndex,secondIndex;
+ int i;
+ double jointTemp = 0.0;
+ double seperateTemp = 0.0;
+ double invAlpha = 1.0 - alpha;
+ JointProbabilityState state = calculateJointProbability(dataVector,targetVector,vectorLength);
+
+ /* standard MI is D_KL(p(x,y)||p(x)p(y))
+ ** which expands to
+ ** D_KL(p(x,y)||p(x)p(y)) = sum(p(x,y) * log(p(x,y)/(p(x)p(y))))
+ **
+ ** Renyi alpha divergence D_alpha(p(x,y)||p(x)p(y))
+ ** expands to
+ ** D_alpha(p(x,y)||p(x)p(y)) = 1/(alpha-1) * log(sum((p(x,y)^alpha)*((p(x)p(y))^(1-alpha))))
+ */
+
+ for (i = 0; i < state.numJointStates; i++)
+ {
+ firstIndex = i % state.numFirstStates;
+ secondIndex = i / state.numFirstStates;
+
+ if ((state.jointProbabilityVector[i] > 0) && (state.firstProbabilityVector[firstIndex] > 0) && (state.secondProbabilityVector[secondIndex] > 0))
+ {
+ jointTemp = pow(state.jointProbabilityVector[i],alpha);
+ seperateTemp = state.firstProbabilityVector[firstIndex] * state.secondProbabilityVector[secondIndex];
+ seperateTemp = pow(seperateTemp,invAlpha);
+ mutualInformation += (jointTemp * seperateTemp);
+ }
+ }
+
+ mutualInformation = log(mutualInformation);
+ mutualInformation /= log(2.0);
+ mutualInformation /= (alpha-1.0);
+
+ FREE_FUNC(state.firstProbabilityVector);
+ state.firstProbabilityVector = NULL;
+ FREE_FUNC(state.secondProbabilityVector);
+ state.secondProbabilityVector = NULL;
+ FREE_FUNC(state.jointProbabilityVector);
+ state.jointProbabilityVector = NULL;
+
+ return mutualInformation;
+}/*calculateRenyiMIDivergence(double, double *, double *, int)*/
+
+double calculateRenyiMIJoint(double alpha, double *dataVector, double *targetVector, int vectorLength)
+{
+ double hY = calculateRenyiEntropy(alpha, targetVector, vectorLength);
+ double hX = calculateRenyiEntropy(alpha, dataVector, vectorLength);
+
+ double hXY = calculateJointRenyiEntropy(alpha, dataVector, targetVector, vectorLength);
+
+ double answer = hX + hY - hXY;
+
+ return answer;
+}/*calculateRenyiMIJoint(double, double*, double*, int)*/
+
diff --git a/RenyiMutualInformation.h b/RenyiMutualInformation.h
new file mode 100644
index 0000000..07eff09
--- /dev/null
+++ b/RenyiMutualInformation.h
@@ -0,0 +1,60 @@
+/*******************************************************************************
+** RenyiMutualInformation.h
+** Part of the mutual information toolbox
+**
+** Contains functions to calculate the Renyi mutual information of
+** two variables X and Y, I_\alpha(X;Y), using the Renyi alpha divergence and
+** the joint entropy difference
+**
+** Author: Adam Pocock
+** Created 26/3/2010
+**
+** Copyright 2010 Adam Pocock, The University Of Manchester
+** www.cs.manchester.ac.uk
+**
+** This file is part of MIToolbox.
+**
+** MIToolbox is free software: you can redistribute it and/or modify
+** it under the terms of the GNU Lesser General Public License as published by
+** the Free Software Foundation, either version 3 of the License, or
+** (at your option) any later version.
+**
+** MIToolbox 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 Lesser General Public License for more details.
+**
+** You should have received a copy of the GNU Lesser General Public License
+** along with MIToolbox. If not, see .
+**
+*******************************************************************************/
+
+#ifndef __Renyi_MutualInformation_H
+#define __Renyi_MutualInformation_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*******************************************************************************
+** calculateRenyiMIDivergence returns the log base 2 Renyi mutual information
+** between dataVector and targetVector, I_{\alpha}(X;Y), for \alpha != 1
+** This uses Renyi's generalised alpha divergence as the difference measure
+** instead of the KL-divergence as in Shannon's Mutual Information
+**
+** length(dataVector) == length(targetVector) == vectorLength otherwise there
+** will be a segmentation fault
+*******************************************************************************/
+double calculateRenyiMIDivergence(double alpha, double *dataVector, double *targetVector, int vectorLength);
+
+/* This function returns a different value to the alpha divergence mutual
+** information, and thus is not a correct mutual information
+double calculateRenyiMIJoint(double alpha, double *dataVector, double *targetVector, int vectorLength);
+*/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/cmi.m b/cmi.m
new file mode 100644
index 0000000..30e4bb0
--- /dev/null
+++ b/cmi.m
@@ -0,0 +1,31 @@
+function output = cmi(X,Y,Z)
+%function output = cmi(X,Y,Z)
+%X, Y & Z can be matrices which are converted into a joint variable
+%before computation
+%
+%expects variables to be column-wise
+%
+%returns the mutual information between X and Y conditioned on Z, I(X;Y|Z)
+
+if nargin == 3
+ if (size(X,2)>1)
+ mergedFirst = MIToolboxMex(3,X);
+ else
+ mergedFirst = X;
+ end
+ if (size(Y,2)>1)
+ mergedSecond = MIToolboxMex(3,Y);
+ else
+ mergedSecond = Y;
+ end
+ if (size(Z,2)>1)
+ mergedThird = MIToolboxMex(3,Z);
+ else
+ mergedThird = Z;
+ end
+ [output] = MIToolboxMex(8,mergedFirst,mergedSecond,mergedThird);
+elseif nargin == 2
+ output = mi(X,Y);
+else
+ output = 0;
+end
diff --git a/condh.m b/condh.m
new file mode 100644
index 0000000..9f966db
--- /dev/null
+++ b/condh.m
@@ -0,0 +1,26 @@
+function output = condh(X,Y)
+%function output = condh(X,Y)
+%X & Y can be matrices which are converted into a joint variable
+%before computation
+%
+%expects variables to be column-wise
+%
+%returns the conditional entropy of X given Y, H(X|Y)
+
+if nargin == 2
+ if (size(X,2)>1)
+ mergedFirst = MIToolboxMex(3,X);
+ else
+ mergedFirst = X;
+ end
+ if (size(Y,2)>1)
+ mergedSecond = MIToolboxMex(3,Y);
+ else
+ mergedSecond = Y;
+ end
+ [output] = MIToolboxMex(6,mergedFirst,mergedSecond);
+elseif nargin == 1
+ output = h(X);
+else
+ output = 0;
+end
diff --git a/demonstration_algorithms/CMIM.m b/demonstration_algorithms/CMIM.m
new file mode 100644
index 0000000..8ae1f7c
--- /dev/null
+++ b/demonstration_algorithms/CMIM.m
@@ -0,0 +1,49 @@
+function selectedFeatures = CMIM(k, featureMatrix, classColumn)
+%function selectedFeatures = CMIM(k, featureMatrix, classColumn)
+%Computes conditional mutual information maximisation algorithm from
+%"Fast Binary Feature Selection with Conditional Mutual Information"
+%by F. Fleuret (2004)
+
+%Computes the top k features from
+%a dataset featureMatrix with n training examples and m features
+%with the classes held in classColumn.
+
+noOfTraining = size(classColumn,1);
+noOfFeatures = size(featureMatrix,2);
+
+partialScore = zeros(noOfFeatures,1);
+m = zeros(noOfFeatures,1);
+score = 0;
+answerFeatures = zeros(k,1);
+highestMI = 0;
+highestMICounter = 0;
+
+for n = 1 : noOfFeatures
+ partialScore(n) = mi(featureMatrix(:,n),classColumn);
+ if partialScore(n) > highestMI
+ highestMI = partialScore(n);
+ highestMICounter = n;
+ end
+end
+
+answerFeatures(1) = highestMICounter;
+
+for i = 2 : k
+ score = 0;
+ limitI = i - 1;
+ for n = 1 : noOfFeatures
+ while ((partialScore(n) >= score) && (m(n) < limitI))
+ m(n) = m(n) + 1;
+ conditionalInfo = cmi(featureMatrix(:,n),classColumn,featureMatrix(:,answerFeatures(m(n))));
+ if partialScore(n) > conditionalInfo
+ partialScore(n) = conditionalInfo;
+ end
+ end
+ if partialScore(n) >= score
+ score = partialScore(n);
+ answerFeatures(i) = n;
+ end
+ end
+end
+
+selectedFeatures = answerFeatures;
diff --git a/demonstration_algorithms/CMIM_Mex.c b/demonstration_algorithms/CMIM_Mex.c
new file mode 100644
index 0000000..daacb34
--- /dev/null
+++ b/demonstration_algorithms/CMIM_Mex.c
@@ -0,0 +1,158 @@
+/*******************************************************************************
+** Demonstration feature selection algorithm - MATLAB r2009a
+**
+** Initial Version - 13/06/2008
+** Updated - 07/07/2010
+** based on CMIM.m
+**
+** Conditional Mutual Information Maximisation
+** in
+** "Fast Binary Feature Selection using Conditional Mutual Information Maximisation
+** F. Fleuret (2004)
+**
+** Author - Adam Pocock
+** Demonstration code for MIToolbox
+*******************************************************************************/
+
+#include "mex.h"
+#include "MutualInformation.h"
+
+void CMIMCalculation(int k, int noOfSamples, int noOfFeatures,double *featureMatrix, double *classColumn, double *outputFeatures)
+{
+ /*holds the class MI values
+ **the class MI doubles as the partial score from the CMIM paper
+ */
+ double *classMI = (double *)mxCalloc(noOfFeatures,sizeof(double));
+ /*in the CMIM paper, m = lastUsedFeature*/
+ int *lastUsedFeature = (int *)mxCalloc(noOfFeatures,sizeof(int));
+
+ double score, conditionalInfo;
+ int iMinus, currentFeature;
+
+ double maxMI = 0.0;
+ int maxMICounter = -1;
+
+ int j,i;
+
+ double **feature2D = (double**) mxCalloc(noOfFeatures,sizeof(double*));
+
+ for(j = 0; j < noOfFeatures; j++)
+ {
+ feature2D[j] = featureMatrix + (int)j*noOfSamples;
+ }
+
+ for (i = 0; i < noOfFeatures;i++)
+ {
+ classMI[i] = calculateMutualInformation(feature2D[i], classColumn, noOfSamples);
+
+ if (classMI[i] > maxMI)
+ {
+ maxMI = classMI[i];
+ maxMICounter = i;
+ }/*if bigger than current maximum*/
+ }/*for noOfFeatures - filling classMI*/
+
+ outputFeatures[0] = maxMICounter;
+
+ /*****************************************************************************
+ ** We have populated the classMI array, and selected the highest
+ ** MI feature as the first output feature
+ ** Now we move into the CMIM algorithm
+ *****************************************************************************/
+
+ for (i = 1; i < k; i++)
+ {
+ score = 0.0;
+ iMinus = i-1;
+
+ for (j = 0; j < noOfFeatures; j++)
+ {
+ while ((classMI[j] > score) && (lastUsedFeature[j] < i))
+ {
+ /*double calculateConditionalMutualInformation(double *firstVector, double *targetVector, double *conditionVector, int vectorLength);*/
+ currentFeature = (int) outputFeatures[lastUsedFeature[j]];
+ conditionalInfo = calculateConditionalMutualInformation(feature2D[j],classColumn,feature2D[currentFeature],noOfSamples);
+ if (classMI[j] > conditionalInfo)
+ {
+ classMI[j] = conditionalInfo;
+ }/*reset classMI*/
+ /*moved due to C indexing from 0 rather than 1*/
+ lastUsedFeature[j] += 1;
+ }/*while partial score greater than score & not reached last feature*/
+ if (classMI[j] > score)
+ {
+ score = classMI[j];
+ outputFeatures[i] = j;
+ }/*if partial score still greater than score*/
+ }/*for number of features*/
+ }/*for the number of features to select*/
+
+
+ for (i = 0; i < k; i++)
+ {
+ outputFeatures[i] += 1; /*C indexes from 0 not 1*/
+ }/*for number of selected features*/
+
+}/*CMIMCalculation*/
+
+/*entry point for the mex call
+**nlhs - number of outputs
+**plhs - pointer to array of outputs
+**nrhs - number of inputs
+**prhs - pointer to array of inputs
+*/
+void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
+{
+ /*************************************************************
+ ** this function takes 3 arguments:
+ ** k = number of features to select,
+ ** featureMatrix[][] = matrix of features
+ ** classColumn[] = targets
+ ** the arguments should all be discrete integers.
+ ** and has one output:
+ ** selectedFeatures[] of size k
+ *************************************************************/
+
+ int k, numberOfFeatures, numberOfSamples, numberOfTargets;
+ double *featureMatrix, *targets, *output;
+
+
+ if (nlhs != 1)
+ {
+ printf("Incorrect number of output arguments");
+ }/*if not 1 output*/
+ if (nrhs != 3)
+ {
+ printf("Incorrect number of input arguments");
+ }/*if not 3 inputs*/
+
+ /*get the number of features to select, cast out as it is a double*/
+ k = (int) mxGetScalar(prhs[0]);
+
+ numberOfFeatures = mxGetN(prhs[1]);
+ numberOfSamples = mxGetM(prhs[1]);
+
+ numberOfTargets = mxGetM(prhs[2]);
+
+ if (numberOfTargets != numberOfSamples)
+ {
+ printf("Number of targets must match number of samples\n");
+ printf("Number of targets = %d, Number of Samples = %d, Number of Features = %d\n",numberOfTargets,numberOfSamples,numberOfFeatures);
+
+ plhs[0] = mxCreateDoubleMatrix(0,0,mxREAL);
+ }/*if size mismatch*/
+ else
+ {
+
+ featureMatrix = mxGetPr(prhs[1]);
+ targets = mxGetPr(prhs[2]);
+
+ plhs[0] = mxCreateDoubleMatrix(k,1,mxREAL);
+ output = (double *)mxGetPr(plhs[0]);
+
+ /*void CMIMCalculation(int k, int noOfSamples, int noOfFeatures,double *featureMatrix, double *classColumn, double *outputFeatures)*/
+ CMIMCalculation(k,numberOfSamples,numberOfFeatures,featureMatrix,targets,output);
+ }
+
+ return;
+}/*mexFunction()*/
diff --git a/demonstration_algorithms/CMIM_Mex.mexa64 b/demonstration_algorithms/CMIM_Mex.mexa64
new file mode 100644
index 0000000..e6718b1
Binary files /dev/null and b/demonstration_algorithms/CMIM_Mex.mexa64 differ
diff --git a/demonstration_algorithms/CMIM_Mex.mexglx b/demonstration_algorithms/CMIM_Mex.mexglx
new file mode 100644
index 0000000..bb27db3
Binary files /dev/null and b/demonstration_algorithms/CMIM_Mex.mexglx differ
diff --git a/demonstration_algorithms/CMIM_Mex.mexw32 b/demonstration_algorithms/CMIM_Mex.mexw32
new file mode 100644
index 0000000..88bb52a
Binary files /dev/null and b/demonstration_algorithms/CMIM_Mex.mexw32 differ
diff --git a/demonstration_algorithms/DISR.m b/demonstration_algorithms/DISR.m
new file mode 100644
index 0000000..c8f5669
--- /dev/null
+++ b/demonstration_algorithms/DISR.m
@@ -0,0 +1,73 @@
+function selectedFeatures = DISR(k, featureMatrix, classColumn)
+%function selectedFeatures = DISR(k, featureMatrix, classColumn)
+%
+%Computers optimal features according to DISR algorithm from
+%On the Use of variable "complementarity for feature selection"
+%by P Meyer, G Bontempi (2006)
+%
+%Computes the top k features from
+%a dataset featureMatrix with n training examples and m features
+%with the classes held in classColumn.
+%
+%DISR - arg(Xi) max(sum(Xj mem XS)(SimRel(Xij,Y)))
+%where SimRel = MI(Xij,Y) / H(Xij,Y)
+
+totalFeatures = size(featureMatrix,2);
+classMI = zeros(totalFeatures,1);
+unselectedFeatures = ones(totalFeatures,1);
+score = 0;
+currentScore = 0;
+innerScore = 0;
+iMinus = 0;
+answerFeatures = zeros(k,1);
+highestMI = 0;
+highestMICounter = 0;
+currentHighestFeature = 0;
+
+%create a matrix to hold the SRs of a feature pair.
+%initialised to -1 as you can't get a negative SR.
+featureSRMatrix = -(ones(k,totalFeatures));
+
+for n = 1 : totalFeatures
+ classMI(n) = mi(featureMatrix(:,n),classColumn);
+ if classMI(n) > highestMI
+ highestMI = classMI(n);
+ highestMICounter = n;
+ end
+end
+
+answerFeatures(1) = highestMICounter;
+unselectedFeatures(highestMICounter) = 0;
+
+for i = 2 : k
+ score = 0;
+ currentHighestFeature = 0;
+ iMinus = i-1;
+ for j = 1 : totalFeatures
+ if unselectedFeatures(j) == 1
+ %DISR - arg(Xi) max(sum(Xj mem XS)(SimRel(Xij,Y)))
+ %where SimRel = MI(Xij,Y) / H(Xij,Y)
+ currentScore = 0;
+ for m = 1 : iMinus
+ if featureSRMatrix(m,j) == -1
+ unionedFeatures = joint([featureMatrix(:,answerFeatures(m)),featureMatrix(:,j)]);
+ tempUnionMI = mi(unionedFeatures,classColumn);
+ tempTripEntropy = h([unionedFeatures,classColumn]);
+ featureSRMatrix(m,j) = tempUnionMI/tempTripEntropy;
+ end
+
+ currentScore = currentScore + featureSRMatrix(m,j);
+ end
+ if (currentScore > score)
+ score = currentScore;
+ currentHighestFeature = j;
+ end
+ end
+ end
+ %now highest feature is selected in currentHighestFeature
+ %store it
+ unselectedFeatures(currentHighestFeature) = 0;
+ answerFeatures(i) = currentHighestFeature;
+end
+
+selectedFeatures = answerFeatures;
diff --git a/demonstration_algorithms/DISR_Mex.c b/demonstration_algorithms/DISR_Mex.c
new file mode 100644
index 0000000..617ca81
--- /dev/null
+++ b/demonstration_algorithms/DISR_Mex.c
@@ -0,0 +1,199 @@
+/*******************************************************************************
+** Demonstration feature selection algorithm - MATLAB r2009a
+**
+** Initial Version - 13/06/2008
+** Updated - 07/07/2010
+** based on DISR.m
+**
+** Double Input Symmetrical Relevance
+** in
+** "On the Use of Variable Complementarity for Feature Selection in Cancer Classification"
+** P. Meyer and G. Bontempi (2006)
+**
+** Author - Adam Pocock
+** Demonstration code for MIToolbox
+*******************************************************************************/
+
+#include "mex.h"
+#include "MutualInformation.h"
+#include "Entropy.h"
+#include "ArrayOperations.h"
+
+void DISRCalculation(int k, int noOfSamples, int noOfFeatures,double *featureMatrix, double *classColumn, double *outputFeatures)
+{
+ /*holds the class MI values*/
+ double *classMI = (double *)mxCalloc(noOfFeatures,sizeof(double));
+
+ char *selectedFeatures = (char *)mxCalloc(noOfFeatures,sizeof(char));
+
+ /*holds the intra feature MI values*/
+ int sizeOfMatrix = k*noOfFeatures;
+ double *featureMIMatrix = (double *)mxCalloc(sizeOfMatrix,sizeof(double));
+
+ double maxMI = 0.0;
+ int maxMICounter = -1;
+
+ double **feature2D = (double**) mxCalloc(noOfFeatures,sizeof(double*));
+
+ double score, currentScore, totalFeatureMI;
+ int currentHighestFeature;
+
+ double *mergedVector = (double *) mxCalloc(noOfSamples,sizeof(double));
+
+ int arrayPosition;
+ double mi, tripEntropy;
+
+ int i,j,x;
+
+ for(j = 0; j < noOfFeatures; j++)
+ {
+ feature2D[j] = featureMatrix + (int)j*noOfSamples;
+ }
+
+ for (i = 0; i < sizeOfMatrix;i++)
+ {
+ featureMIMatrix[i] = -1;
+ }/*for featureMIMatrix - blank to -1*/
+
+
+ for (i = 0; i < noOfFeatures;i++)
+ {
+ /*calculate mutual info
+ **double calculateMutualInformation(double *firstVector, double *secondVector, int vectorLength);
+ */
+ classMI[i] = calculateMutualInformation(feature2D[i], classColumn, noOfSamples);
+
+ if (classMI[i] > maxMI)
+ {
+ maxMI = classMI[i];
+ maxMICounter = i;
+ }/*if bigger than current maximum*/
+ }/*for noOfFeatures - filling classMI*/
+
+ selectedFeatures[maxMICounter] = 1;
+ outputFeatures[0] = maxMICounter;
+
+ /*****************************************************************************
+ ** We have populated the classMI array, and selected the highest
+ ** MI feature as the first output feature
+ ** Now we move into the DISR algorithm
+ *****************************************************************************/
+
+ for (i = 1; i < k; i++)
+ {
+ score = 0.0;
+ currentHighestFeature = 0;
+ currentScore = 0.0;
+ totalFeatureMI = 0.0;
+
+ for (j = 0; j < noOfFeatures; j++)
+ {
+ /*if we haven't selected j*/
+ if (selectedFeatures[j] == 0)
+ {
+ currentScore = 0.0;
+ totalFeatureMI = 0.0;
+
+ for (x = 0; x < i; x++)
+ {
+ arrayPosition = x*noOfFeatures + j;
+ if (featureMIMatrix[arrayPosition] == -1)
+ {
+ /*
+ **double calculateMutualInformation(double *firstVector, double *secondVector, int vectorLength);
+ **double calculateJointEntropy(double *firstVector, double *secondVector, int vectorLength);
+ */
+
+ mergeArrays(feature2D[(int) outputFeatures[x]], feature2D[j],mergedVector,noOfSamples);
+ mi = calculateMutualInformation(mergedVector, classColumn, noOfSamples);
+ tripEntropy = calculateJointEntropy(mergedVector, classColumn, noOfSamples);
+
+ featureMIMatrix[arrayPosition] = mi / tripEntropy;
+ }/*if not already known*/
+ currentScore += featureMIMatrix[arrayPosition];
+ }/*for the number of already selected features*/
+
+ if (currentScore > score)
+ {
+ score = currentScore;
+ currentHighestFeature = j;
+ }
+ }/*if j is unselected*/
+ }/*for number of features*/
+
+ selectedFeatures[currentHighestFeature] = 1;
+ outputFeatures[i] = currentHighestFeature;
+
+ }/*for the number of features to select*/
+
+ mxFree(mergedVector);
+ mergedVector = NULL;
+
+ for (i = 0; i < k; i++)
+ {
+ outputFeatures[i] += 1; /*C indexes from 0 not 1*/
+ }/*for number of selected features*/
+
+}/*DISRCalculation(double[][],double[])*/
+
+/*entry point for the mex call
+**nlhs - number of outputs
+**plhs - pointer to array of outputs
+**nrhs - number of inputs
+**prhs - pointer to array of inputs
+*/
+void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
+{
+ /*************************************************************
+ ** this function takes 3 arguments:
+ ** k = number of features to select,
+ ** featureMatrix[][] = matrix of features
+ ** classColumn[] = targets
+ ** the arguments should all be discrete integers.
+ ** and has one output:
+ ** selectedFeatures[] of size k
+ *************************************************************/
+
+ int k, numberOfFeatures, numberOfSamples, numberOfTargets;
+ double *featureMatrix, *targets, *output;
+
+
+ if (nlhs != 1)
+ {
+ printf("Incorrect number of output arguments");
+ }/*if not 1 output*/
+ if (nrhs != 3)
+ {
+ printf("Incorrect number of input arguments");
+ }/*if not 3 inputs*/
+
+ /*get the number of features to select, cast out as it is a double*/
+ k = (int) mxGetScalar(prhs[0]);
+
+ numberOfFeatures = mxGetN(prhs[1]);
+ numberOfSamples = mxGetM(prhs[1]);
+
+ numberOfTargets = mxGetM(prhs[2]);
+
+ if (numberOfTargets != numberOfSamples)
+ {
+ printf("Number of targets must match number of samples\n");
+ printf("Number of targets = %d, Number of Samples = %d, Number of Features = %d\n",numberOfTargets,numberOfSamples,numberOfFeatures);
+
+ plhs[0] = mxCreateDoubleMatrix(0,0,mxREAL);
+ }/*if size mismatch*/
+ else
+ {
+
+ featureMatrix = mxGetPr(prhs[1]);
+ targets = mxGetPr(prhs[2]);
+
+ plhs[0] = mxCreateDoubleMatrix(k,1,mxREAL);
+ output = (double *)mxGetPr(plhs[0]);
+
+ /*void DISRCalculation(int k, int noOfSamples, int noOfFeatures,double *featureMatrix, double *classColumn, double *outputFeatures)*/
+ DISRCalculation(k,numberOfSamples,numberOfFeatures,featureMatrix,targets,output);
+ }
+
+ return;
+}/*mexFunction()*/
diff --git a/demonstration_algorithms/DISR_Mex.mexa64 b/demonstration_algorithms/DISR_Mex.mexa64
new file mode 100644
index 0000000..694fc9b
Binary files /dev/null and b/demonstration_algorithms/DISR_Mex.mexa64 differ
diff --git a/demonstration_algorithms/DISR_Mex.mexglx b/demonstration_algorithms/DISR_Mex.mexglx
new file mode 100644
index 0000000..dda5aee
Binary files /dev/null and b/demonstration_algorithms/DISR_Mex.mexglx differ
diff --git a/demonstration_algorithms/DISR_Mex.mexw32 b/demonstration_algorithms/DISR_Mex.mexw32
new file mode 100644
index 0000000..9565f82
Binary files /dev/null and b/demonstration_algorithms/DISR_Mex.mexw32 differ
diff --git a/demonstration_algorithms/IAMB.m b/demonstration_algorithms/IAMB.m
new file mode 100644
index 0000000..1011260
--- /dev/null
+++ b/demonstration_algorithms/IAMB.m
@@ -0,0 +1,56 @@
+function [cmb association] = IAMB( data, targetindex, THRESHOLD)
+%function [cmb association] = IAMB( data, targetindex, THRESHOLD)
+%
+%Performs the IAMB algorithm of Tsmardinos et al. (2003)
+%from "Towards principled feature selection: Relevancy, filters and wrappers"
+
+if (nargin == 2)
+ THRESHOLD = 0.02;
+end
+
+numf = size(data,2);
+targets = data(:,targetindex);
+data(:,targetindex) = -10;
+
+cmb = [];
+
+finished = false;
+while ~finished
+ for n = 1:numf
+ cmbVector = joint(data(:,cmb));
+ if isempty(cmb)
+ association(n) = mi( data(:,n), targets );
+ end
+
+ if ismember(n,cmb)
+ association(n) = -10; %arbtirary large negative constant
+ else
+ association(n) = cmi( data(:,n), targets, cmbVector);
+ end
+ end
+
+ [maxval maxidx] = max(association);
+ if maxval < THRESHOLD
+ finished = true;
+ else
+ cmb = [ cmb maxidx ];
+ end
+end
+
+finished = false;
+while ~finished && ~isempty(cmb)
+ association = [];
+ for n = 1:length(cmb)
+ cmbwithoutn = cmb;
+ cmbwithoutn(n)=[];
+ association(n) = cmi( data(:,cmb(n)), targets, data(:,cmbwithoutn) );
+ end
+
+ [minval minidx] = min(association);
+ if minval > THRESHOLD
+ finished = true;
+ else
+ cmb(minidx) = [];
+ end
+end
+
diff --git a/demonstration_algorithms/compile_demos.m b/demonstration_algorithms/compile_demos.m
new file mode 100644
index 0000000..65464b3
--- /dev/null
+++ b/demonstration_algorithms/compile_demos.m
@@ -0,0 +1,3 @@
+mex -I.. CMIM_Mex.c ../MutualInformation.c ../Entropy.c ../CalculateProbability.c ../ArrayOperations.c
+mex -I.. DISR_Mex.c ../MutualInformation.c ../Entropy.c ../CalculateProbability.c ../ArrayOperations.c
+mex -I.. mRMR_D_Mex.c ../MutualInformation.c ../Entropy.c ../CalculateProbability.c ../ArrayOperations.c
\ No newline at end of file
diff --git a/demonstration_algorithms/mRMR_D.m b/demonstration_algorithms/mRMR_D.m
new file mode 100644
index 0000000..50b14bc
--- /dev/null
+++ b/demonstration_algorithms/mRMR_D.m
@@ -0,0 +1,69 @@
+function selectedFeatures = mRMR_D(k, featureMatrix, classColumn)
+%function selectedFeatures = mRMR_D(k, featureMatrix, classColumn)
+%
+%Selects optimal features according to the mRMR-D algorithm from
+%"Feature Selection Based on Mutual Information: Criteria of Max-Dependency, Max-Relevance, and Min-Redundancy"
+%by H. Peng et al. (2005)
+%
+%Calculates the top k features
+%a dataset featureMatrix with n training examples and m features
+%with the classes held in classColumn (an n x 1 vector)
+
+noOfTraining = size(classColumn,1);
+noOfFeatures = size(featureMatrix,2);
+unselectedFeatures = ones(noOfFeatures,1);
+
+classMI = zeros(noOfFeatures,1);
+answerFeatures = zeros(k,1);
+highestMI = 0;
+highestMICounter = 0;
+currentHighestFeature = 0;
+
+featureMIMatrix = -(ones(k,noOfFeatures));
+
+%setup the mi against the class
+for n = 1 : noOfFeatures
+ classMI(n) = mi(featureMatrix(:,n),classColumn);
+ if classMI(n) > highestMI
+ highestMI = classMI(n);
+ highestMICounter = n;
+ end
+end
+
+answerFeatures(1) = highestMICounter;
+unselectedFeatures(highestMICounter) = 0;
+
+%iterate over the number of features to select
+for i = 2:k
+ score = -100;
+ currentHighestFeature = 0;
+ iMinus = i-1;
+ for j = 1 : noOfFeatures
+ if unselectedFeatures(j) == 1
+ currentMIScore = 0;
+ for m = 1 : iMinus
+ if featureMIMatrix(m,j) == -1
+ featureMIMatrix(m,j) = mi(featureMatrix(:,j),featureMatrix(:,answerFeatures(m)));
+ end
+ currentMIScore = currentMIScore + featureMIMatrix(m,j);
+ end
+ currentScore = classMI(j) - (currentMIScore/iMinus);
+
+ if (currentScore > score)
+ score = currentScore;
+ currentHighestFeature = j;
+ end
+ end
+ end
+
+ if score < 0
+ disp(['at selection ' int2str(j) ' mRMRD is negative with value ' num2str(score)]);
+ end
+
+ %now highest feature is selected in currentHighestFeature
+ %store it
+ unselectedFeatures(currentHighestFeature) = 0;
+ answerFeatures(i) = currentHighestFeature;
+end
+
+selectedFeatures = answerFeatures;
diff --git a/demonstration_algorithms/mRMR_D_Mex.c b/demonstration_algorithms/mRMR_D_Mex.c
new file mode 100644
index 0000000..8d7b074
--- /dev/null
+++ b/demonstration_algorithms/mRMR_D_Mex.c
@@ -0,0 +1,184 @@
+/*******************************************************************************
+** Demonstration feature selection algorithm - MATLAB r2009a
+**
+** Initial Version - 13/06/2008
+** Updated - 07/07/2010
+** based on mRMR_D.m
+**
+** Minimum Relevance Maximum Redundancy
+** in
+** "Feature Selection Based on Mutual Information: Criteria of Max-Dependency, Max-Relevance, and Min-Redundancy"
+** H. Peng et al. (2005)
+**
+** Author - Adam Pocock
+** Demonstration code for MIToolbox
+*******************************************************************************/
+
+#include "mex.h"
+#include "MutualInformation.h"
+
+void mRMRCalculation(int k, int noOfSamples, int noOfFeatures,double *featureMatrix, double *classColumn, double *outputFeatures)
+{
+ double **feature2D = (double**) mxCalloc(noOfFeatures,sizeof(double*));
+ /*holds the class MI values*/
+ double *classMI = (double *)mxCalloc(noOfFeatures,sizeof(double));
+ int *selectedFeatures = (int *)mxCalloc(noOfFeatures,sizeof(int));
+ /*holds the intra feature MI values*/
+ int sizeOfMatrix = k*noOfFeatures;
+ double *featureMIMatrix = (double *)mxCalloc(sizeOfMatrix,sizeof(double));
+
+ double maxMI = 0.0;
+ int maxMICounter = -1;
+
+ /*init variables*/
+
+ double score, currentScore, totalFeatureMI;
+ int currentHighestFeature;
+
+ int arrayPosition, i, j, x;
+
+ for(j = 0; j < noOfFeatures; j++)
+ {
+ feature2D[j] = featureMatrix + (int)j*noOfSamples;
+ }
+
+ for (i = 0; i < sizeOfMatrix;i++)
+ {
+ featureMIMatrix[i] = -1;
+ }/*for featureMIMatrix - blank to -1*/
+
+
+ for (i = 0; i < noOfFeatures;i++)
+ {
+ classMI[i] = calculateMutualInformation(feature2D[i], classColumn, noOfSamples);
+ if (classMI[i] > maxMI)
+ {
+ maxMI = classMI[i];
+ maxMICounter = i;
+ }/*if bigger than current maximum*/
+ }/*for noOfFeatures - filling classMI*/
+
+ selectedFeatures[maxMICounter] = 1;
+ outputFeatures[0] = maxMICounter;
+
+ /*************
+ ** Now we have populated the classMI array, and selected the highest
+ ** MI feature as the first output feature
+ ** Now we move into the mRMR-D algorithm
+ *************/
+
+ for (i = 1; i < k; i++)
+ {
+ /*to ensure it selects some features
+ **if this is zero then it will not pick features where the redundancy is greater than the
+ **relevance
+ */
+ score = -1000.0;
+ currentHighestFeature = 0;
+ currentScore = 0.0;
+ totalFeatureMI = 0.0;
+
+ for (j = 0; j < noOfFeatures; j++)
+ {
+ /*if we haven't selected j*/
+ if (selectedFeatures[j] == 0)
+ {
+ currentScore = classMI[j];
+ totalFeatureMI = 0.0;
+
+ for (x = 0; x < i; x++)
+ {
+ arrayPosition = x*noOfFeatures + j;
+ if (featureMIMatrix[arrayPosition] == -1)
+ {
+ /*work out intra MI*/
+
+ /*double calculateMutualInformation(double *firstVector, double *secondVector, int vectorLength);*/
+ featureMIMatrix[arrayPosition] = calculateMutualInformation(feature2D[(int) outputFeatures[x]], feature2D[j], noOfSamples);
+ }
+
+ totalFeatureMI += featureMIMatrix[arrayPosition];
+ }/*for the number of already selected features*/
+
+ currentScore -= (totalFeatureMI/i);
+ if (currentScore > score)
+ {
+ score = currentScore;
+ currentHighestFeature = j;
+ }
+ }/*if j is unselected*/
+ }/*for number of features*/
+
+ selectedFeatures[currentHighestFeature] = 1;
+ outputFeatures[i] = currentHighestFeature;
+
+ }/*for the number of features to select*/
+
+ for (i = 0; i < k; i++)
+ {
+ outputFeatures[i] += 1; /*C indexes from 0 not 1*/
+ }/*for number of selected features*/
+
+}/*mRMRCalculation(double[][],double[])*/
+
+/*entry point for the mex call
+**nlhs - number of outputs
+**plhs - pointer to array of outputs
+**nrhs - number of inputs
+**prhs - pointer to array of inputs
+*/
+void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
+{
+ /*************************************************************
+ ** this function takes 3 arguments:
+ ** k = number of features to select,
+ ** featureMatrix[][] = matrix of features
+ ** classColumn[] = targets
+ ** the arguments should all be discrete integers.
+ ** and has one output:
+ ** selectedFeatures[] of size k
+ *************************************************************/
+
+ int k, numberOfFeatures, numberOfSamples, numberOfTargets;
+ double *featureMatrix, *targets, *output;
+
+
+ if (nlhs != 1)
+ {
+ printf("Incorrect number of output arguments");
+ }/*if not 1 output*/
+ if (nrhs != 3)
+ {
+ printf("Incorrect number of input arguments");
+ }/*if not 3 inputs*/
+
+ /*get the number of features to select, cast out as it is a double*/
+ k = (int) mxGetScalar(prhs[0]);
+
+ numberOfFeatures = mxGetN(prhs[1]);
+ numberOfSamples = mxGetM(prhs[1]);
+
+ numberOfTargets = mxGetM(prhs[2]);
+
+ if (numberOfTargets != numberOfSamples)
+ {
+ printf("Number of targets must match number of samples\n");
+ printf("Number of targets = %d, Number of Samples = %d, Number of Features = %d\n",numberOfTargets,numberOfSamples,numberOfFeatures);
+
+ plhs[0] = mxCreateDoubleMatrix(0,0,mxREAL);
+ }/*if size mismatch*/
+ else
+ {
+
+ featureMatrix = mxGetPr(prhs[1]);
+ targets = mxGetPr(prhs[2]);
+
+ plhs[0] = mxCreateDoubleMatrix(k,1,mxREAL);
+ output = (double *)mxGetPr(plhs[0]);
+
+ /*void mRMRCalculation(int k, int noOfSamples, int noOfFeatures,double *featureMatrix, double *classColumn, double *outputFeatures)*/
+ mRMRCalculation(k,numberOfSamples,numberOfFeatures,featureMatrix,targets,output);
+ }
+
+ return;
+}/*mexFunction()*/
diff --git a/demonstration_algorithms/mRMR_D_Mex.mexa64 b/demonstration_algorithms/mRMR_D_Mex.mexa64
new file mode 100644
index 0000000..8b15a92
Binary files /dev/null and b/demonstration_algorithms/mRMR_D_Mex.mexa64 differ
diff --git a/demonstration_algorithms/mRMR_D_Mex.mexglx b/demonstration_algorithms/mRMR_D_Mex.mexglx
new file mode 100644
index 0000000..e9b3d04
Binary files /dev/null and b/demonstration_algorithms/mRMR_D_Mex.mexglx differ
diff --git a/demonstration_algorithms/mRMR_D_Mex.mexw32 b/demonstration_algorithms/mRMR_D_Mex.mexw32
new file mode 100644
index 0000000..4c0f833
Binary files /dev/null and b/demonstration_algorithms/mRMR_D_Mex.mexw32 differ
diff --git a/h.m b/h.m
new file mode 100644
index 0000000..8fd8999
--- /dev/null
+++ b/h.m
@@ -0,0 +1,13 @@
+function output = h(X)
+%function output = h(X)
+%X can be a matrix which is converted into a joint variable before calculation
+%expects variables to be column-wise
+%
+%returns the entropy of X, H(X)
+
+if (size(X,2)>1)
+ mergedVector = MIToolboxMex(3,X);
+else
+ mergedVector = X;
+end
+[output] = MIToolboxMex(4,mergedVector);
diff --git a/joint.m b/joint.m
new file mode 100644
index 0000000..f40ff25
--- /dev/null
+++ b/joint.m
@@ -0,0 +1,16 @@
+function output = joint(X,arities)
+%function output = joint(X,arities)
+%returns the joint random variable of the matrix X
+%assuming the variables are in columns
+%
+%if passed a vector of the arities then it produces a correct
+%joint variable, otherwise it may not include all states
+%
+%if the joint variable is only compared with variables using the same samples,
+%then arity information is not required
+
+if (nargin == 2)
+ [output] = MIToolboxMex(3,X,arities);
+else
+ [output] = MIToolboxMex(3,X);
+end
diff --git a/mi.m b/mi.m
new file mode 100644
index 0000000..2fd8766
--- /dev/null
+++ b/mi.m
@@ -0,0 +1,20 @@
+function output = mi(X,Y)
+%function output = mi(X,Y)
+%X & Y can be matrices which are converted into a joint variable
+%before computation
+%
+%expects variables to be column-wise
+%
+%returns the mutual information between X and Y, I(X;Y)
+
+if (size(X,2)>1)
+ mergedFirst = MIToolboxMex(3,X);
+else
+ mergedFirst = X;
+end
+if (size(Y,2)>1)
+ mergedSecond = MIToolboxMex(3,Y);
+else
+ mergedSecond = Y;
+end
+[output] = MIToolboxMex(7,mergedFirst,mergedSecond);